diff --git "a/6449.jsonl" "b/6449.jsonl" new file mode 100644--- /dev/null +++ "b/6449.jsonl" @@ -0,0 +1,740 @@ +{"seq_id":"390270254","text":"\r\n\r\ndef test_function(list1, list2, position):\r\n outlist1 = []\r\n outlist2 = []\r\n\r\n for outer_index, grouping in enumerate(list2):\r\n possible_combinators = []\r\n for number in grouping:\r\n if number >= position:\r\n possible_combinators.append(number)\r\n\r\n if len(list1) > 0:\r\n for number in possible_combinators:\r\n temp1 = list1[outer_index].copy()\r\n temp2 = list2[outer_index].copy()\r\n\r\n temp1.append(number)\r\n temp2.remove(number)\r\n\r\n outlist1.append(temp1)\r\n outlist2.append(temp2)\r\n else:\r\n for number in possible_combinators:\r\n temp1 = []\r\n temp2 = list2[outer_index].copy()\r\n\r\n temp1.append(number)\r\n temp2.remove(number)\r\n\r\n outlist1.append(temp1)\r\n outlist2.append(temp2)\r\n\r\n outpos = position -1\r\n\r\n return outlist1, outlist2, outpos\r\n\r\n\r\ngrand_total = 0\r\nlargest = 4\r\nfor size in range(largest, 0, -1):\r\n start_set = [[n for n in range(largest,0,-1)]]\r\n\r\n all_combos = []\r\n leftovers = start_set\r\n position = size\r\n\r\n while position > 0:\r\n all_combos, leftovers, position = test_function(all_combos,leftovers,position)\r\n\r\n grand_total +=len(all_combos)\r\n\r\nprint(grand_total)\r\n\r\n","sub_path":"scratch_1.py","file_name":"scratch_1.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"493330277","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n # main books home (library)\n url(r'^$', views.library, name='library'),\n\n # add to books form\n url(r'add$', views.add_book, name='add_book'),\n\n # create new book record\n url(r'create$', views.create, name='create'),\n\n #view individual book\n url(r'^(?P\\d+$)', views.individual_book, name='view_book')\n]\n","sub_path":"django/belt_review/apps/books/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"446771462","text":"\nimport wx\nimport os\nimport sys\nimport time\nimport logging\nimport plistlib\nimport traceback\nimport threading\nimport subprocess\n\nfrom pathlib import Path\n\nfrom resources import (\n constants,\n kdk_handler,\n)\nfrom resources.sys_patch import (\n sys_patch,\n sys_patch_detect\n)\nfrom resources.wx_gui import (\n gui_main_menu,\n gui_support,\n gui_download,\n)\nfrom data import os_data\n\n\nclass SysPatchFrame(wx.Frame):\n \"\"\"\n Create a frame for root patching\n Uses a Modal Dialog for smoother transition from other frames\n \"\"\"\n def __init__(self, parent: wx.Frame, title: str, global_constants: constants.Constants, screen_location: tuple = None, patches: dict = {}):\n self.frame = parent\n self.initiated_with_parent = False\n if not self.frame and patches == {}:\n super(SysPatchFrame, self).__init__(parent, title=title, size=(350, 200), style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))\n self.frame = self\n self.frame.Centre()\n else:\n self.initiated_with_parent = True\n\n self.title = title\n self.constants: constants.Constants = global_constants\n self.frame_modal: wx.Dialog = None\n self.return_button: wx.Button = None\n self.available_patches: bool = False\n\n self.frame_modal = wx.Dialog(self.frame, title=title, size=(360, 200))\n\n if patches:\n return\n\n self._generate_elements_display_patches(self.frame_modal, patches)\n self.frame_modal.ShowWindowModal()\n\n if self.constants.update_stage != gui_support.AutoUpdateStages.INACTIVE:\n if self.available_patches is False:\n gui_support.RestartHost(self.frame).restart(message=\"No root patch updates needed!\\n\\nWould you like to reboot to apply the new OpenCore build?\")\n\n\n def _kdk_download(self, frame: wx.Frame = None) -> bool:\n frame = self if not frame else frame\n\n logging.info(\"KDK missing, generating KDK download frame\")\n\n header = wx.StaticText(frame, label=\"Downloading Kernel Debug Kit\", pos=(-1,5))\n header.SetFont(wx.Font(19, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False, \".AppleSystemUIFont\"))\n header.Centre(wx.HORIZONTAL)\n\n subheader = wx.StaticText(frame, label=\"Fetching KDK database...\", pos=(-1, header.GetPosition()[1] + header.GetSize()[1] + 5))\n subheader.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n subheader.Centre(wx.HORIZONTAL)\n\n progress_bar = wx.Gauge(frame, range=100, pos=(-1, subheader.GetPosition()[1] + subheader.GetSize()[1] + 5), size=(250, 20))\n progress_bar.Centre(wx.HORIZONTAL)\n\n progress_bar_animation = gui_support.GaugePulseCallback(self.constants, progress_bar)\n progress_bar_animation.start_pulse()\n\n # Set size of frame\n frame.SetSize((-1, progress_bar.GetPosition()[1] + progress_bar.GetSize()[1] + 35))\n frame.Show()\n\n # Generate KDK object\n self.kdk_obj: kdk_handler.KernelDebugKitObject = None\n def _kdk_thread_spawn():\n self.kdk_obj = kdk_handler.KernelDebugKitObject(self.constants, self.constants.detected_os_build, self.constants.detected_os_version)\n\n kdk_thread = threading.Thread(target=_kdk_thread_spawn)\n kdk_thread.start()\n\n while kdk_thread.is_alive():\n wx.Yield()\n\n if self.kdk_obj.success is False:\n progress_bar_animation.stop_pulse()\n progress_bar.SetValue(0)\n wx.MessageBox(f\"KDK download failed: {self.kdk_obj.error_msg}\", \"Error\", wx.OK | wx.ICON_ERROR)\n return False\n\n kdk_download_obj = self.kdk_obj.retrieve_download()\n if not kdk_download_obj:\n # KDK is already downloaded\n return True\n\n gui_download.DownloadFrame(\n self,\n title=self.title,\n global_constants=self.constants,\n download_obj=kdk_download_obj,\n item_name=f\"KDK Build {self.kdk_obj.kdk_url_build}\"\n )\n if kdk_download_obj.download_complete is False:\n return False\n\n header.SetLabel(f\"Validating KDK: {self.kdk_obj.kdk_url_build}\")\n header.Centre(wx.HORIZONTAL)\n\n subheader.SetLabel(\"Checking if checksum is valid...\")\n subheader.Centre(wx.HORIZONTAL)\n wx.Yield()\n\n progress_bar_animation.stop_pulse()\n\n if self.kdk_obj.validate_kdk_checksum() is False:\n progress_bar.SetValue(0)\n logging.error(\"KDK checksum validation failed\")\n logging.error(self.kdk_obj.error_msg)\n msg = wx.MessageDialog(frame, f\"KDK checksum validation failed: {self.kdk_obj.error_msg}\", \"Error\", wx.OK | wx.ICON_ERROR)\n msg.ShowModal()\n return False\n\n progress_bar.SetValue(100)\n\n logging.info(\"KDK download complete\")\n return True\n\n\n def _generate_elements_display_patches(self, frame: wx.Frame = None, patches: dict = {}) -> None:\n \"\"\"\n Generate UI elements for root patching frame\n\n Format:\n - Title label: Post-Install Menu\n - Label: Available patches:\n - Labels: {patch name}\n - Button: Start Root Patching\n - Button: Revert Root Patches\n - Button: Return to Main Menu\n \"\"\"\n frame = self if not frame else frame\n\n title_label = wx.StaticText(frame, label=\"Post-Install Menu\", pos=(-1, 10))\n title_label.SetFont(wx.Font(19, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False, \".AppleSystemUIFont\"))\n title_label.Centre(wx.HORIZONTAL)\n\n # Label: Available patches:\n available_label = wx.StaticText(frame, label=\"Available patches for your system:\", pos=(-1, title_label.GetPosition()[1] + title_label.GetSize()[1] + 10))\n available_label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False, \".AppleSystemUIFont\"))\n available_label.Centre(wx.HORIZONTAL)\n\n # Labels: {patch name}\n patches: dict = sys_patch_detect.DetectRootPatch(self.constants.computer.real_model, self.constants).detect_patch_set() if not patches else patches\n can_unpatch: bool = patches[\"Validation: Unpatching Possible\"]\n\n if not any(not patch.startswith(\"Settings\") and not patch.startswith(\"Validation\") and patches[patch] is True for patch in patches):\n logging.info(\"- No applicable patches available\")\n patches = []\n\n # Check if OCLP has already applied the same patches\n no_new_patches = not self._check_if_new_patches_needed(patches) if patches else False\n\n if not patches:\n # Prompt user with no patches found\n patch_label = wx.StaticText(frame, label=\"No patches required\", pos=(-1, available_label.GetPosition()[1] + 20))\n patch_label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n patch_label.Centre(wx.HORIZONTAL)\n\n else:\n # Add Label for each patch\n i = 0\n if no_new_patches is True:\n patch_label = wx.StaticText(frame, label=\"All applicable patches already installed\", pos=(-1, available_label.GetPosition()[1] + 20))\n patch_label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n patch_label.Centre(wx.HORIZONTAL)\n i = i + 20\n else:\n longest_patch = \"\"\n for patch in patches:\n if (not patch.startswith(\"Settings\") and not patch.startswith(\"Validation\") and patches[patch] is True):\n if len(patch) > len(longest_patch):\n longest_patch = patch\n anchor = wx.StaticText(frame, label=longest_patch, pos=(-1, available_label.GetPosition()[1] + 20))\n anchor.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n anchor.Centre(wx.HORIZONTAL)\n anchor.Hide()\n\n for patch in patches:\n if (not patch.startswith(\"Settings\") and not patch.startswith(\"Validation\") and patches[patch] is True):\n i = i + 20\n logging.info(f\"- Adding patch: {patch} - {patches[patch]}\")\n patch_label = wx.StaticText(frame, label=f\"- {patch}\", pos=(anchor.GetPosition()[0], available_label.GetPosition()[1] + i))\n patch_label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n\n if i == 20:\n patch_label.SetLabel(patch_label.GetLabel().replace(\"-\", \"\"))\n patch_label.Centre(wx.HORIZONTAL)\n\n if patches[\"Validation: Patching Possible\"] is False:\n # Cannot patch due to the following reasons:\n patch_label = wx.StaticText(frame, label=\"Cannot patch due to the following reasons:\", pos=(-1, patch_label.GetPosition()[1] + 25))\n patch_label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False, \".AppleSystemUIFont\"))\n patch_label.Centre(wx.HORIZONTAL)\n\n longest_patch = \"\"\n for patch in patches:\n if not patch.startswith(\"Validation\"):\n continue\n if patches[patch] is False:\n continue\n if patch == \"Validation: Unpatching Possible\":\n continue\n\n if len(patch) > len(longest_patch):\n longest_patch = patch\n anchor = wx.StaticText(frame, label=longest_patch.split('Validation: ')[1], pos=(-1, patch_label.GetPosition()[1] + 20))\n anchor.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n anchor.Centre(wx.HORIZONTAL)\n anchor.Hide()\n\n i = 0\n for patch in patches:\n if not patch.startswith(\"Validation\"):\n continue\n if patches[patch] is False:\n continue\n if patch == \"Validation: Unpatching Possible\":\n continue\n\n patch_label = wx.StaticText(frame, label=f\"- {patch.split('Validation: ')[1]}\", pos=(anchor.GetPosition()[0], anchor.GetPosition()[1] + i))\n patch_label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n i = i + 20\n\n if i == 20:\n patch_label.SetLabel(patch_label.GetLabel().replace(\"-\", \"\"))\n patch_label.Centre(wx.HORIZONTAL)\n\n else:\n if self.constants.computer.oclp_sys_version and self.constants.computer.oclp_sys_date:\n date = self.constants.computer.oclp_sys_date.split(\" @\")\n date = date[0] if len(date) == 2 else \"\"\n\n patch_text = f\"{self.constants.computer.oclp_sys_version}, {date}\"\n\n patch_label = wx.StaticText(frame, label=\"Root Volume last patched:\", pos=(-1, patch_label.GetPosition().y + 25))\n patch_label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False, \".AppleSystemUIFont\"))\n patch_label.Centre(wx.HORIZONTAL)\n\n patch_label = wx.StaticText(frame, label=patch_text, pos=(available_label.GetPosition().x - 10, patch_label.GetPosition().y + 20))\n patch_label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n patch_label.Centre(wx.HORIZONTAL)\n\n\n # Button: Start Root Patching\n start_button = wx.Button(frame, label=\"Start Root Patching\", pos=(10, patch_label.GetPosition().y + 25), size=(170, 30))\n start_button.Bind(wx.EVT_BUTTON, lambda event: self.start_root_patching(patches))\n start_button.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n start_button.Centre(wx.HORIZONTAL)\n\n # Button: Revert Root Patches\n revert_button = wx.Button(frame, label=\"Revert Root Patches\", pos=(10, start_button.GetPosition().y + start_button.GetSize().height - 5), size=(170, 30))\n revert_button.Bind(wx.EVT_BUTTON, lambda event: self.revert_root_patching(patches))\n revert_button.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n revert_button.Centre(wx.HORIZONTAL)\n\n # Button: Return to Main Menu\n return_button = wx.Button(frame, label=\"Return to Main Menu\", pos=(10, revert_button.GetPosition().y + revert_button.GetSize().height), size=(150, 30))\n return_button.Bind(wx.EVT_BUTTON, self.on_return_dismiss if self.initiated_with_parent else self.on_return_to_main_menu)\n return_button.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n return_button.Centre(wx.HORIZONTAL)\n self.return_button = return_button\n\n # Disable buttons if unsupported\n if not patches:\n start_button.Disable()\n else:\n self.available_patches = True\n if patches[\"Validation: Patching Possible\"] is False:\n start_button.Disable()\n elif no_new_patches is False:\n start_button.SetDefault()\n else:\n self.available_patches = False\n if can_unpatch is False:\n revert_button.Disable()\n\n # Relaunch as root if not root\n uid = os.geteuid()\n if uid != 0:\n start_button.Bind(wx.EVT_BUTTON, gui_support.RelaunchApplicationAsRoot(frame, self.constants).relaunch)\n revert_button.Bind(wx.EVT_BUTTON, gui_support.RelaunchApplicationAsRoot(frame, self.constants).relaunch)\n\n # Set frame size\n frame.SetSize((-1, return_button.GetPosition().y + return_button.GetSize().height + 35))\n\n\n def _generate_modal(self, patches: dict = {}, variant: str = \"Root Patching\"):\n \"\"\"\n Create UI for root patching/unpatching\n \"\"\"\n supported_variants = [\"Root Patching\", \"Revert Root Patches\"]\n if variant not in supported_variants:\n logging.error(f\"Unsupported variant: {variant}\")\n return\n\n self.frame_modal.Close() if self.frame_modal else None\n\n dialog = wx.Dialog(self, title=self.title, size=(400, 200))\n\n # Title\n title = wx.StaticText(dialog, label=variant, pos=(-1, 10))\n title.SetFont(wx.Font(19, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False, \".AppleSystemUIFont\"))\n title.Centre(wx.HORIZONTAL)\n\n if variant == \"Root Patching\":\n # Label\n label = wx.StaticText(dialog, label=\"Root Patching will patch the following:\", pos=(-1, title.GetPosition()[1] + 30))\n label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n label.Centre(wx.HORIZONTAL)\n\n\n # Get longest patch label, then create anchor for patch labels\n longest_patch = \"\"\n for patch in patches:\n if (not patch.startswith(\"Settings\") and not patch.startswith(\"Validation\") and patches[patch] is True):\n if len(patch) > len(longest_patch):\n longest_patch = patch\n\n anchor = wx.StaticText(dialog, label=longest_patch, pos=(label.GetPosition()[0], label.GetPosition()[1] + 20))\n anchor.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n anchor.Centre(wx.HORIZONTAL)\n anchor.Hide()\n\n # Labels\n i = 0\n for patch in patches:\n if (not patch.startswith(\"Settings\") and not patch.startswith(\"Validation\") and patches[patch] is True):\n logging.info(f\"- Adding patch: {patch} - {patches[patch]}\")\n patch_label = wx.StaticText(dialog, label=f\"- {patch}\", pos=(anchor.GetPosition()[0], label.GetPosition()[1] + 20 + i))\n patch_label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False, \".AppleSystemUIFont\"))\n i = i + 20\n\n if i == 20:\n patch_label.SetLabel(patch_label.GetLabel().replace(\"-\", \"\"))\n patch_label.Centre(wx.HORIZONTAL)\n\n elif i == 0:\n patch_label = wx.StaticText(dialog, label=\"No patches to apply\", pos=(label.GetPosition()[0], label.GetPosition()[1] + 20))\n patch_label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False, \".AppleSystemUIFont\"))\n patch_label.Centre(wx.HORIZONTAL)\n else:\n patch_label = wx.StaticText(dialog, label=\"Reverting to last sealed snapshot\", pos=(-1, title.GetPosition()[1] + 30))\n patch_label.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n patch_label.Centre(wx.HORIZONTAL)\n\n\n # Text box\n text_box = wx.TextCtrl(dialog, pos=(10, patch_label.GetPosition()[1] + 30), size=(400, 400), style=wx.TE_READONLY | wx.TE_MULTILINE | wx.TE_RICH2)\n text_box.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n text_box.Centre(wx.HORIZONTAL)\n self.text_box = text_box\n\n # Button: Return to Main Menu\n return_button = wx.Button(dialog, label=\"Return to Main Menu\", pos=(10, text_box.GetPosition()[1] + text_box.GetSize()[1] + 5), size=(150, 30))\n return_button.Bind(wx.EVT_BUTTON, self.on_return_to_main_menu)\n return_button.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, \".AppleSystemUIFont\"))\n return_button.Centre(wx.HORIZONTAL)\n self.return_button = return_button\n\n # Set frame size\n dialog.SetSize((-1, return_button.GetPosition().y + return_button.GetSize().height + 33))\n self.frame_modal = dialog\n dialog.ShowWindowModal()\n\n\n def start_root_patching(self, patches: dict):\n self.frame.Close() if self.frame else None\n super(SysPatchFrame, self).__init__(None, title=self.title, size=(350, 260), style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))\n gui_support.GenerateMenubar(self, self.constants).generate()\n self.Centre()\n self.return_button.Bind(wx.EVT_BUTTON, self.on_return_to_main_menu) if self.return_button else None\n\n logging.info(\"Starting root patching\")\n\n while gui_support.PayloadMount(self.constants, self).is_unpack_finished() is False:\n wx.Yield()\n\n if patches[\"Settings: Kernel Debug Kit missing\"] is True:\n if self._kdk_download(self) is False:\n self.on_return_to_main_menu()\n return\n\n self._generate_modal(patches, \"Root Patching\")\n self.return_button.Disable()\n\n thread = threading.Thread(target=self._start_root_patching, args=(patches,))\n thread.start()\n\n while thread.is_alive():\n wx.Yield()\n\n self._post_patch()\n self.return_button.Enable()\n\n\n def _start_root_patching(self, patches: dict):\n logger = logging.getLogger()\n logger.addHandler(gui_support.ThreadHandler(self.text_box))\n try:\n sys_patch.PatchSysVolume(self.constants.computer.real_model, self.constants, patches).start_patch()\n except:\n logging.error(\"- An internal error occurred while running the Root Patcher:\\n\")\n logging.error(traceback.format_exc())\n logger.removeHandler(logger.handlers[2])\n\n\n def revert_root_patching(self, patches: dict):\n self.frame.Close() if self.frame else None\n super(SysPatchFrame, self).__init__(None, title=self.title, size=(350, 260), style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))\n gui_support.GenerateMenubar(self, self.constants).generate()\n self.Centre()\n self.return_button.Bind(wx.EVT_BUTTON, self.on_return_to_main_menu) if self.return_button else None\n\n logging.info(\"Reverting root patches\")\n self._generate_modal(patches, \"Revert Root Patches\")\n self.return_button.Disable()\n\n thread = threading.Thread(target=self._revert_root_patching, args=(patches,))\n thread.start()\n\n while thread.is_alive():\n wx.Yield()\n\n self._post_patch()\n self.return_button.Enable()\n\n\n def _revert_root_patching(self, patches: dict):\n logger = logging.getLogger()\n logger.addHandler(gui_support.ThreadHandler(self.text_box))\n try:\n sys_patch.PatchSysVolume(self.constants.computer.real_model, self.constants, patches).start_unpatch()\n except:\n logging.error(\"- An internal error occurred while running the Root Patcher:\\n\")\n logging.error(traceback.format_exc())\n logger.removeHandler(logger.handlers[2])\n\n\n def on_return_to_main_menu(self, event: wx.Event = None):\n # Get frame from event\n frame_modal: wx.Dialog = event.GetEventObject().GetParent()\n frame: wx.Frame = frame_modal.Parent\n frame_modal.Hide()\n frame.Hide()\n\n main_menu_frame = gui_main_menu.MainFrame(\n None,\n title=self.title,\n global_constants=self.constants,\n )\n main_menu_frame.Show()\n frame.Destroy()\n\n\n def on_return_dismiss(self, event: wx.Event = None):\n self.frame_modal.Hide()\n self.frame_modal.Destroy()\n\n\n def _post_patch(self):\n if self.constants.root_patcher_succeeded is False:\n return\n\n if self.constants.needs_to_open_preferences is False:\n gui_support.RestartHost(self.frame_modal).restart(message=\"Root Patcher finished successfully!\\n\\nWould you like to reboot now?\")\n return\n\n if self.constants.detected_os >= os_data.os_data.ventura:\n gui_support.RestartHost(self.frame_modal).restart(message=\"Root Patcher finished successfully!\\nIf you were prompted to open System Settings to authorize new kexts, this can be ignored. Your system is ready once restarted.\\n\\nWould you like to reboot now?\")\n return\n\n # Create dialog box to open System Preferences -> Security and Privacy\n self.popup = wx.MessageDialog(\n self.frame_modal,\n \"We just finished installing the patches to your Root Volume!\\n\\nHowever, Apple requires users to manually approve the kernel extensions installed before they can be used next reboot.\\n\\nWould you like to open System Preferences?\",\n \"Open System Preferences?\",\n wx.YES_NO | wx.ICON_INFORMATION\n )\n self.popup.SetYesNoLabels(\"Open System Preferences\", \"Ignore\")\n answer = self.popup.ShowModal()\n if answer == wx.ID_YES:\n output =subprocess.run(\n [\n \"osascript\", \"-e\",\n 'tell app \"System Preferences\" to activate',\n \"-e\", 'tell app \"System Preferences\" to reveal anchor \"General\" of pane id \"com.apple.preference.security\"',\n ],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n if output.returncode != 0:\n # Some form of fallback if unaccelerated state errors out\n subprocess.run([\"open\", \"-a\", \"System Preferences\"])\n time.sleep(5)\n sys.exit(0)\n\n\n def _check_if_new_patches_needed(self, patches: dict) -> bool:\n \"\"\"\n Checks if any new patches are needed for the user to install\n Newer users will assume the root patch menu will present missing patches.\n Thus we'll need to see if the exact same OCLP build was used already\n \"\"\"\n\n if self.constants.commit_info[0] in [\"Running from source\", \"Built from source\"]:\n return True\n\n if self.constants.computer.oclp_sys_url != self.constants.commit_info[2]:\n # If commits are different, assume patches are as well\n return True\n\n oclp_plist = \"/System/Library/CoreServices/OpenCore-Legacy-Patcher.plist\"\n if not Path(oclp_plist).exists():\n # If it doesn't exist, no patches were ever installed\n # ie. all patches applicable\n return True\n\n oclp_plist_data = plistlib.load(open(oclp_plist, \"rb\"))\n for patch in patches:\n if (not patch.startswith(\"Settings\") and not patch.startswith(\"Validation\") and patches[patch] is True):\n # Patches should share the same name as the plist key\n # See sys_patch_dict.py for more info\n patch_installed = False\n for key in oclp_plist_data:\n if isinstance(oclp_plist_data[key], (bool, int)):\n continue\n if \"Display Name\" not in oclp_plist_data[key]:\n continue\n if oclp_plist_data[key][\"Display Name\"] == patch:\n patch_installed = True\n break\n\n if patch_installed is False:\n logging.info(f\"- Patch {patch} not installed\")\n return True\n\n logging.info(\"- No new patches detected for system\")\n return False","sub_path":"resources/wx_gui/gui_sys_patch.py","file_name":"gui_sys_patch.py","file_ext":"py","file_size_in_byte":26273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"157959231","text":"from flask import (Blueprint, abort, flash, g, redirect, render_template,\n request, url_for)\n\nfrom checklist_app import db\nfrom checklist_app.auth import login_required\nfrom checklist_app.forms import AddItemForm, CreateListForm, EditListForm\nfrom checklist_app.models import Checklist, ChecklistItem\n\nbp = Blueprint('checklist', __name__, url_prefix='/checklist')\n\n\ndef get_checklist(id):\n \"\"\"Gets the checklist identified by the id.\"\"\"\n checklist = Checklist.query.filter_by(id=id).first_or_404()\n return checklist\n\n\n@bp.route('/create', methods=('GET', 'POST'))\n@login_required\ndef create():\n form = CreateListForm()\n\n if form.validate_on_submit():\n checklist = Checklist(\n title=form.list_title.data,\n description=form.list_description.data,\n created_by=g.user,\n assigned_to=g.user\n )\n db.session.add(checklist)\n db.session.commit()\n\n return redirect(url_for('checklist.view', id=checklist.id))\n\n return render_template('checklist/create.html', header=None, form=form)\n\n\n@bp.route('/edit/', methods=('GET', 'POST'))\n@login_required\ndef edit(id):\n \"\"\"Edit the checklist header with primary key matchig the id.\"\"\"\n form = EditListForm()\n\n checklist = get_checklist(id)\n\n if form.validate_on_submit():\n checklist.title = form.list_title.data\n checklist.description = form.list_description.data\n db.session.add(checklist)\n db.session.commit()\n\n return redirect(url_for('checklist.view', id=id))\n\n form.list_title.data = checklist.title\n form.list_description.data = checklist.description\n return render_template('checklist/create.html', form=form)\n\n\n@bp.route('/delete/', methods=('GET', 'POST'))\n@login_required\ndef delete(id):\n \"\"\"Mark the checklist identified by the id as deleted.\"\"\"\n checklist = get_checklist(id)\n\n if request.method == 'POST':\n # Check that the confirmation has been given and return.\n confirm_delete = request.form['confirm_delete']\n\n if not confirm_delete:\n abort(401)\n\n checklist.is_deleted = True\n db.session.add(checklist)\n db.session.commit()\n\n # redirect the user to their list of checklists.\n return redirect(url_for('checklist.index'))\n\n # Create a little confirmation form and return it as a message\n flash(render_template('checklist/partial/delete.html', id=id))\n return redirect(url_for('checklist.view', id=id))\n\n\n@bp.route('/')\n@bp.route('')\n@login_required\ndef index():\n checklists = Checklist.query.filter_by(\n created_by=g.user,\n is_deleted=False\n ).all()\n return render_template('checklist/index.html', lists=checklists)\n\n\n@bp.route('/')\n@login_required\ndef view(id):\n checklist = get_checklist(id)\n form = AddItemForm()\n return render_template('checklist/view_list.html', checklist=checklist, form=form)\n\n\n@bp.route('//check/')\n@login_required\ndef toggle_item(id, item_id):\n get_checklist(id)\n item = ChecklistItem.query.filter_by(id=item_id).first_or_404()\n\n if item.checklist_id == id:\n item.toggle(g.user)\n db.session.commit()\n\n return redirect(url_for('checklist.view', id=id))\n\n\n@bp.route('//check/all')\n@login_required\ndef toggle_all(id):\n checklist = get_checklist(id)\n\n [i.toggle(g.user) for i in checklist.items if i.done is False]\n db.session.commit()\n\n return redirect(url_for('checklist.view', id=id))\n\n\n@bp.route('//add', methods=('GET', 'POST'))\n@login_required\ndef add_item(id):\n checklist = get_checklist(id)\n form = AddItemForm()\n\n if form.validate_on_submit():\n checklist.add_item(form.item_text.data, g.user)\n db.session.add(checklist)\n db.session.commit()\n return redirect(url_for('checklist.view', id=id))\n\n return render_template('checklist/view_list.html', checklist=checklist, form=form)\n\n\n@bp.route('//edit/')\n@login_required\ndef edit_item(id, item_id):\n get_checklist(id)\n ChecklistItem.query.filter_by(id=item_id).first_or_404()\n\n return redirect(url_for('checklist.view', id=id))\n\n\n@bp.route('//delete/')\n@login_required\ndef delete_item(id, item_id):\n checklist = get_checklist(id)\n item = ChecklistItem.query.filter_by(id=item_id).first_or_404()\n\n if item.checklist_id == id:\n checklist.delete_item(item, g.user)\n db.session.commit()\n\n return redirect(url_for('checklist.view', id=id))\n","sub_path":"checklist_app/checklist.py","file_name":"checklist.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"150985434","text":"from commandparser import CommandParser\nfrom maillist_factory import MailListFactory\nfrom maillist_file_adapter import MailListFileAdapter\nfrom glob import glob\nfrom os.path import basename\nimport sys\nimport sqlite3\n\n\nclass MailListProgram():\n \"\"\"docstring for MailListProgram\"\"\"\n def __init__(self):\n self.factory = MailListFactory()\n self.cp = CommandParser()\n self.lists = {}\n self.db_path = \"lists/\"\n\n self._load_initial_state()\n self._init_callbacks()\n self._loop()\n\n def create_list_callback(self, arguments):\n if len(str(arguments)) == 4:\n print(\"Invalid listname!\")\n else:\n used_names = self.show_lists_callback(\"1\")\n new_args = str(arguments)\n if new_args[2:-2] in used_names:\n print (\"There is already a list with that name!\")\n else:\n conn = sqlite3.connect(\"mail_list_database.db\")\n cursor = conn.cursor()\n result = cursor.execute('''INSERT INTO maillist(name)\n VALUES (?)''', (arguments))\n conn.commit()\n conn.close()\n\n\n def add_subscriber_callback(self, arguments):\n list_id = arguments[0]\n conn = sqlite3.connect(\"mail_list_database.db\")\n cursor = conn.cursor()\n name = input(\"name>\")\n email = input(\"email>\")\n result1 = cursor.execute('''SELECT subs_id\n FROM subscribers\n WHERE name = ? and email = ?''', (name, email))\n final_res = cursor.fetchone()\n if final_res is None:\n print(cursor.fetchone())\n result2 = cursor.execute('''INSERT INTO subscribers(name, email)\n VALUES(?, ?)''', (name, email))\n\n result3 = cursor.execute('''SELECT subs_id\n FROM subscribers\n WHERE name = ? and email = ?''', (name, email))\n result_from_3rd_query = cursor.fetchone()\n res3 = int(result_from_3rd_query[0])\n\n result4 = cursor.execute(''' INSERT INTO maillist_to_subscribers(list_id, subscribesr_id)\n VALUES (?, ?)''', (list_id, res3))\n else:\n result_from_1st_query = final_res\n res1 = int(result_from_1st_query[0])\n result5 = cursor.execute('''SELECT list_id\n FROM maillist_to_subscribers\n WHERE subscribesr_id = (?)''', str(res1))\n lists = []\n for row in result5:\n lists.append(int(row[0]))\n if int(list_id) in lists:\n print (\"The subscriber is already in that list\")\n else:\n result6 = cursor.execute('''INSERT INTO maillist_to_subscribers(list_id, subscribesr_id)\n VALUES (?,?)''', (list_id, res1) )\n conn.commit()\n conn.close()\n\n def show_lists_callback(self, want_return=0):\n conn = sqlite3.connect(\"mail_list_database.db\")\n cursor = conn.cursor()\n list_names = []\n list_ids = []\n result = cursor.execute(\"SELECT * FROM maillist\")\n for row in result:\n list_ids.append(row[0])\n list_names.append(row[1])\n conn.close()\n the_wish = len(want_return)\n if the_wish == 0:\n for row in range(0, len(list_ids)):\n print(\"{\" + str(list_ids[row]) + \"} \" + list_names[row])\n else:\n return(list_names)\n\n\n def show_list_callback(self, arguments):\n conn = sqlite3.connect(\"mail_list_database.db\")\n cursor = conn.cursor()\n\n used_names = self.show_lists_callback(\"1\")\n integer_argument = int(arguments[0])\n if integer_argument > len(used_names):\n print (\"There is no list with this identifier!\")\n else:\n result = cursor.execute('''SELECT DISTINCT subscribers.name, subscribers.email\n FROM subscribers INNER JOIN maillist_to_subscribers ON subscribers.subs_id = maillist_to_subscribers.subscribesr_id\n INNER JOIN maillist ON maillist_to_subscribers.list_id = ?''', (arguments))\n counter = 1\n for row in result:\n print(\"{\" + str(counter) + \"} \" + str(row[0]) + \" - \" + str(row[1]) )\n counter += 1\n conn.commit()\n conn.close()\n\n\n def exit_callback(self, arguments):\n sys.exit(0)\n\n def _load_initial_state(self):\n dir_lists = map(basename, glob(self.db_path + \"*\"))\n\n for list_file in dir_lists:\n adapter = MailListFileAdapter(self.db_path)\n parsed_list = adapter.load(list_file)\n\n maillist_adapter = MailListFileAdapter(self.db_path, parsed_list)\n\n self.lists[parsed_list.get_id()] = (parsed_list, maillist_adapter)\n\n def _init_callbacks(self):\n self.cp.on(\"create\", self.create_list_callback)\n self.cp.on(\"add\", self.add_subscriber_callback)\n self.cp.on(\"show_lists\", self.show_lists_callback)\n self.cp.on(\"show_list\", self.show_list_callback)\n self.cp.on(\"exit\", self.exit_callback)\n # TODO - implement the rest of the callbacks\n\n def _notify_save(self, list_id):\n self.lists[list_id][1].save()\n\n def _loop(self):\n while True:\n command = input(\">\")\n self.cp.take_command(command)\n\n\nif __name__ == '__main__':\n MailListProgram()\n","sub_path":"mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":5643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"106096306","text":"import logging\nimport sys\nimport time\n\nimport pygame\nimport pygcurse\nfrom pygame.locals import *\n\nimport coloredlogs\nfrom gamecomp import Game\n\nLOGGER = logging.getLogger(__name__)\n\nWINWIDTH = 50\nWINHEIGHT = 50\n\nFPS = 60\n\n\ndef main():\n log_fmt = \"%(asctime)s %(name)s[%(lineno)d] %(levelname)s %(message)s\"\n coloredlogs.install(level=logging.DEBUG, fmt=log_fmt)\n win = pygcurse.PygcurseWindow(WINWIDTH, WINHEIGHT + 4, fullscreen=False)\n pygame.display.set_caption(\"Window Title\")\n win.autoupdate = False\n clock = pygame.time.Clock()\n\n game = Game(WINWIDTH, WINHEIGHT)\n # print(game.maze())\n\n while True:\n win.fill(bgcolor=\"blue\")\n # time.sleep(0.01)\n if game.endstate == True:\n time.sleep(1)\n terminate()\n game.find_move_a_star(win)\n # game.terminate()\n # handle_events(game)\n handle_exit(game)\n game.check()\n game.draw(win)\n # print(game.snake)\n win.update()\n clock.tick(FPS)\n\n\n# def handle_events(game):\n# for event in pygame.event.get():\n# LOGGER.log(5, 'event: {0}'.format(event))\n# if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):\n# terminate()\n# if event.type == KEYDOWN and (event.key == K_UP or event.key == K_w):\n# game.move_up()\n# if event.type == KEYDOWN and (event.key == K_DOWN or event.key == K_s):\n# game.move_down()\n# if event.type == KEYDOWN and (event.key == K_LEFT or event.key == K_a):\n# game.move_left()\n# if event.type == KEYDOWN and (event.key == K_RIGHT or event.key == K_d):\n# game.move_right()\n# if event.type == KEYDOWN:\n# if game.check() == 10:\n# terminate()\n\n\ndef handle_exit(game):\n for event in pygame.event.get():\n LOGGER.log(5, \"event: {0}\".format(event))\n if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):\n terminate()\n if event.type == KEYDOWN:\n if game.check() == 10:\n terminate()\n\n\ndef terminate():\n pygame.quit()\n sys.exit()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"guicomp.py","file_name":"guicomp.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"570984290","text":"import sys\ndef input(): return sys.stdin.readline().rstrip()\n\ndef main():\n H, W, K = map(int, input().split())\n S = [tuple(map(int, list(input()))) for _ in range(H)]\n\n ans = 10 ** 9\n for bit in range(1 << (H-1)):\n canSolve = True\n order = [0] * (H + 1)\n tmp_ans = 0\n for i in range(H):\n if bit & 1 << i:\n order[i+1] = order[i] + 1\n tmp_ans += 1\n else:\n order[i+1] = order[i]\n sum_block = [0] * (H + 1)\n for w in range(W):\n one_block = [0] * (H + 1)\n overK = False\n for h in range(H):\n h_index = order[h]\n one_block[h_index] += S[h][w]\n sum_block[h_index] += S[h][w]\n if one_block[h_index] > K:\n canSolve = False\n if sum_block[h_index] > K:\n overK = True\n if not canSolve:\n break\n if overK:\n tmp_ans += 1\n sum_block = one_block\n if tmp_ans >= ans:\n canSolve = False\n break\n if canSolve:\n ans = tmp_ans\n print(ans)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python_codes/p02733/s244239681.py","file_name":"s244239681.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"16765048","text":"'''\n\nThis script takes two input arguments:\n--input - input file to be evaluated\n--output - path where the output will be stored\n\n\nThe format of the input file should be as following:\n**************************************\nKun\nTurun\nakatemian\nensimmäinen\nfysiikan\nja\nkasvitieteen\nprofessori\nGeorgius\nAlanus\nsiirtyi\nteologiseen\ntiedekuntaan\n\nKolmen\nehdokkaan\njoukosta\npätevimmäksi\nkatsottiin\nThauvonius\n,\nja\nhän\nsaikin\nnimityksen\ntähän\nvirkaan\n1649\n.\n**************************************\n\nThe output will be in the following format:\n\n**************************************\nKun\tO\nTurun\tB-ORG\nakatemian\tI-ORG\nensimmäinen\tO\nfysiikan\tO\nja\tO\nkasvitieteen\tO\nprofessori\tO\nGeorgius\tB-PER\nAlanus\tI-PER\nsiirtyi\tO\nteologiseen\tO\ntiedekuntaan\tO\n\nKolmen\tO\nehdokkaan\tO\njoukosta\tO\npätevimmäksi\tO\nkatsottiin\tO\nThauvonius\tB-PER\n,\tO\nja\tO\nhän\tO\nsaikin\tO\nnimityksen\tO\ntähän\tO\nvirkaan\tO\n1649\tB-DATE\n.\n**************************************\n\n'''\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nimport torch.autograd as autograd\n\nimport numpy as np\nfrom argparse import ArgumentParser\n\nfrom model import NERModel\nfrom train import train\nimport utils.evaluate as evaluate\nimport utils.prepare_data as prepare_data\nfrom utils import radam\nfrom config.params import *\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument(\"-i\", \"--input\", dest=\"input\",\n help=\"input document to be evaluated\", metavar=\"INPUT\", required=True)\n parser.add_argument(\"-o\", \"--output\", dest=\"output\",\n help=\"output path\", metavar=\"OUTPUT\", required=True)\n\n args = parser.parse_args()\n\n\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n torch.manual_seed(0)\n\n print(device)\n\n document_path = args.input\n output_path = args.output\n\n\n def load_data(data_path):\n words = []\n data = []\n with open(data_path, 'r', encoding='utf-8') as f:\n lines = f.readlines()\n for line in lines:\n if line != '\\n':\n words.append(line.rstrip())\n else:\n words.insert(0, '')\n words.append('')\n data.append(words)\n words = []\n\n return data\n \n target_data = load_data(document_path)\n\n\n def combine_data(indexed_data, indexed_char_train, indexed_morph_train, MAX_SEQ_LENGTH):\n res = []\n for seq in range(len(indexed_data)):\n if len(indexed_data[seq]) <= MAX_SEQ_LENGTH:\n res.append((indexed_data[seq], indexed_char_train[seq], indexed_morph_train[seq]))\n return res\n\n\n def prepare_sequence(seq, to_ix):\n res = []\n for w in seq:\n res.append([to_ix[w]])\n return autograd.Variable(torch.LongTensor(res))\n\n def prepare_char_sequence(word, to_ix):\n res = []\n for char in word:\n res.append(to_ix[char])\n return autograd.Variable(torch.LongTensor(res))\n\n\n def prepare_morph_sequence(word, to_morph, to_idx):\n res = []\n morphs = to_morph[word]\n\n for morph in morphs.split(' '):\n res.append(to_idx[morph])\n return autograd.Variable(torch.LongTensor(res))\n\n\n def data_to_idx(data, word2idx):\n res = []\n for seq in range(len(data)):\n res.append(prepare_sequence(data[seq], word2idx))\n return res\n\n def char_to_idx(data, char2idx):\n res = []\n for seq in range(len(data)):\n temp = []\n for w in data[seq]:\n temp.append(prepare_char_sequence(w, char2idx))\n res.append(temp)\n return res\n\n\n def morph_to_idx(data, morph2idx, word2morph):\n res = []\n for seq in range(len(data)):\n temp = []\n for w in data[seq]:\n temp.append(prepare_morph_sequence(w, word2morph, morph2idx))\n res.append(temp)\n return res\n\n\n def evaluate_document(file, word_num_layers, char_num_layers, morph_num_layers, word_hidden_size, char_hidden_size, morph_hidden_size, batch_size, data, model, idx2word, idx2tag, device):\n with open (file, 'w', encoding='utf-8') as f:\n for sent in data:\n test_sentence = sent[0].to(device)\n chars = sent[1]\n morphs = sent[2]\n\n word_hidden = model.init_hidden(word_num_layers, word_hidden_size, batch_size, device)\n char_hidden = model.init_hidden(char_num_layers, char_hidden_size, batch_size, device)\n morph_hidden = model.init_hidden(morph_num_layers, morph_hidden_size, batch_size, device)\n\n pad_char_seqs = prepare_data.pad_subwords(chars).to(device)\n pad_morph_seqs = prepare_data.pad_subwords(morphs).to(device)\n\n emissions = model(test_sentence, [len(test_sentence)], pad_char_seqs.to(device), [pad_char_seqs.size(0)], pad_morph_seqs.to(device), [pad_morph_seqs.size(0)], word_hidden, char_hidden, morph_hidden, batch_size)\n\n for i in range(len(test_sentence)):\n word = idx2word[test_sentence[i].item()]\n tag = torch.argmax(emissions[i]).item()\n tag = idx2tag[torch.argmax(emissions[i]).item()]\n \n if word != '' and word != '':\n f.write(word + '\\t' + tag + '\\n')\n f.write('\\n')\n\n\n embeddings_path_ft = 'data/embeddings/cc.fi.300.bin'\n\n\n # LOAD INDICES\n word2idx = prepare_data.load_obj('weights/indices/word2idx')\n idx2word = prepare_data.load_obj('weights/indices/idx2word')\n tag2idx = prepare_data.load_obj('weights/indices/tag2idx')\n idx2tag = prepare_data.load_obj('weights/indices/idx2tag')\n char2idx = prepare_data.load_obj('weights/indices/char2idx')\n morph2idx = prepare_data.load_obj('weights/indices/morph2idx')\n idx2morph = prepare_data.load_obj('weights/indices/idx2morph')\n word2morph = prepare_data.load_obj('weights/indices/word2morph')\n\n # load embedding matrix\n weights_matrix = np.load('weights/embedding_weights_matrix_ft.npy')\n\n \n def remove_oov(target_data, idx2word, word2morph):\n data = []\n temp = []\n for sent in target_data:\n for word in sent:\n if word in idx2word.values() and word in word2morph.keys():\n temp.append(word)\n data.append(temp)\n temp = []\n return data\n\n target_data = remove_oov(target_data, idx2word, word2morph)\n\n indexed_data_target = data_to_idx(target_data, word2idx)\n indexed_char_target = char_to_idx(target_data, char2idx)\n indexed_morph_target = morph_to_idx(target_data, morph2idx, word2morph)\n data_target = combine_data(indexed_data_target, indexed_char_target, indexed_morph_target, MAX_SEQ_LENGTH)\n\n\n # initialize the model\n model = NERModel(word_embedding_dim, char_embedding_dim, morph_embedding_dim, word_hidden_size, char_hidden_size, morph_hidden_size, len(word2idx), \n len(char2idx), len(morph2idx), len(tag2idx)+1, word_num_layers, char_num_layers, morph_num_layers, weights_matrix, dropout_prob).to(device)\n\n # load the model\n model.load_state_dict(torch.load('weights/model.pt'))\n\n model.eval()\n\n batch_size = 1\n\n print('Processing the document')\n evaluate_document(output_path, word_num_layers, char_num_layers, morph_num_layers, word_hidden_size, char_hidden_size, morph_hidden_size, batch_size, data_target, model, idx2word, idx2tag, device)\n print('Done')","sub_path":"evaluate_document.py","file_name":"evaluate_document.py","file_ext":"py","file_size_in_byte":7679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"94997015","text":"\n\nfrom xai.brain.wordbase.verbs._swindle import _SWINDLE\n\n#calss header\nclass _SWINDLING(_SWINDLE, ):\n\tdef __init__(self,): \n\t\t_SWINDLE.__init__(self)\n\t\tself.name = \"SWINDLING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"swindle\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_swindling.py","file_name":"_swindling.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"273900610","text":"import torch\nimport argparse\nimport numpy as np\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='')\n\n parser.add_argument('--model', choices=['lenet', 'resnet'], help='name of model')\n parser.add_argument('--epochs', default=160, type=int, help='number of epoch')\n parser.add_argument('--batch-size', default=128, type=int, help='number of batch')\n parser.add_argument('--binaly', action='store_true', help='Binalization')\n parser.add_argument('--hist', action='store_true', help='Histogram Equalization')\n parser.add_argument('--img-size', default=32, type=int, help='size of image')\n parser.add_argument('--lr', default=0.1, type=float, help='learning rate(default:0.1')\n parser.add_argument('--weight-decay', default=1e-6, type=float, help='weight decay(default:1e-6)')\n parser.add_argument('--step', default=40, type=int, help='frequency of updating learning rate, given in epochs')\n parser.add_argument('--lr-decay', default=0.1, type=float, help='learning rate decay(default:0.1)')\n parser.add_argument('--momentum', default=0.9, type=float, help='sgd momentum(default:0.9')\n parser.add_argument('--num-classes', default=43, type=int, help='number of classes')\n \n \n\n args = parser.parse_args()\n\n args.val_split = .2\n args.random_seed = 416\n\n args.mean = np.array([0.3337, 0.3064, 0.3171])\n args.std = np.array([0.2672, 0.2564, 0.2629])\n\n args.cuda = torch.cuda.is_available()\n args.device = 'cuda:0' if args.cuda else 'cpu'\n\n args.train_dir = '/home/Osakana4/Binalization/GTSRB/Final_Training/Images'\n args.test_dir = '/home/Osakana4/Binalization/GTSRB/Final_Test/Images'\n args.save_dir = '/home/Osakana4/Binalization_v2/results'\n args.model_dir = '/home/Osakana4/Binalization_v2/trained_model'\n\n return args\n","sub_path":"functions/args.py","file_name":"args.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"447599754","text":"from my_dict import load_dict\nimport sys\n\ndictionary = load_dict(\"books/unismoothdict.txt\")\n\nmax_word_length = 20\n\n \n# Dynamic programming algorithm that actually inserts spaces into an\n# inputted space-less text block, and then prints the result\ndef insert_spaces(text_block, filename):\n array = [0]\n array1 = [0]\n \n for i in range(1, len(text_block)):\n array.append(float(\"inf\"))\n array1.append(0)\n word = \"\"\n for j in range(0,50):\n prevval = float(\"inf\")\n if (i - j >= 0):\n word = text_block[i-j] + word\n if word in dictionary:\n if (i - j - 1 >= 0):\n prevval = array[i-j-1]\n newval = (dictionary[word] + prevval)\n if (newval < array[i]):\n \n array[i] = newval\n if (i-j-1 >= 0):\n array1[i] = i-j-1\n else:\n array1[i] = 0\n spaces = []\n i = array1[len(array1)-1]\n while (i > 0):\n spaces.append(i)\n i = array1[i]\n spaces.reverse()\n results = open (\"output/\" + filename + \"_3.txt\", 'w')\n j = 0\n for i in range(0, len(text_block)):\n results.write(text_block[i])\n if (i == spaces[j]):\n results.write(' ')\n if (j + 1 < len(spaces)):\n j += 1\n results.close()\n\n spaces.sort()\n return spaces\n\n","sub_path":"corpus_dp.py","file_name":"corpus_dp.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"18533691","text":"__author__ = 'student'\nimport turtle as trt\ntrt.speed(20)\n\ndef draw(l,n):\n if n==0:\n trt.forward(l)\n return\n draw(l/3,n-1)\n trt.left(60)\n draw(l / 3, n - 1)\n trt.right(120)\n draw(l / 3, n - 1)\n trt.left(60)\n draw(l / 3, n - 1)\n\ndef draw2(l, n):\n for i in range(3):\n draw(l, n)\n trt.right(120)\n\ndraw2(360, 4)\ntrt.done()\ninput()","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"426138482","text":"import pygame\r\nimport config\r\nimport math\r\nfrom random import randint,uniform\r\nfrom polygon import Polygon\r\nfrom point import Point\r\n\r\nclass Ship(Polygon):\r\n def __init__(self,surface):\r\n ship_points = [Point(25,0), Point(-20,8), Point(-25,0), Point(-20,-8)]\r\n Polygon.__init__(self, ship_points, Point(config.SCREEN_X/2,config.SCREEN_Y/2), config.SHIP_INITIAL_DIRECTION, config.SHIP_COLOR)\r\n self.pull = Point(0,0)\r\n self.rotation +=360\r\n self.rotation = self.rotation%360\r\n self.shield = 5\r\n self.screen = surface\r\n## def __init__(self, position, rotation, color):\r\n## self.position = position\r\n## self.rotation = rotation\r\n## self.points = []\r\n## self.color = color\r\n## outline = [(4,0),(3,1),(2,0),(0,1),(-3,2),(0,-1),(1,0),(4,0)]\r\n## for i in outline:\r\n## self.points.append(Point(i[0], i[1]))\r\n## Polygon.__init__(self.outline, self.position, self.rotation, self.color)\r\n\r\n\r\n## def paint(self, surface):\r\n## outline = []\r\n## points = self.getPoints();\r\n## for i in points:\r\n## outline.append(i.pair())\r\n## pygame.draw.polygon(surface,Polygon.color, outline, width=0)\r\n\r\n def acceleration(self, pos):\r\n x = self.pull.x + pos * math.cos(math.radians(self.rotation))\r\n y = self.pull.y + pos * math.sin(math.radians(self.rotation))\r\n\r\n self.pull = Point(x,y)\r\n \r\n\r\n def game_logic(self, keys, newkeys):\r\n if pygame.K_LEFT in keys:\r\n self.rotate(-config.SHIP_ROTATION_RATE)\r\n if pygame.K_RIGHT in keys:\r\n self.rotate(config.SHIP_ROTATION_RATE)\r\n if pygame.K_UP in keys:\r\n self.acceleration(config.SHIP_ACCELERATION_RATE)\r\n if pygame.K_DOWN in keys:\r\n self.acceleration(-config.SHIP_ACCELERATION_RATE)\r\n\r\n self.move()\r\n","sub_path":"old_classes/cs/cs1410/astro/asteroids_pt1/ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"11898578","text":"import os\nfrom unittest import TestCase\n\nfrom lxml import html\n\nfrom basketball_reference_web_scraper.html import DailyBoxScoresPage\n\njanuary_01_2017_html = os.path.join(os.path.dirname(__file__), './01_01_2017_box_scores.html')\n\n\nclass TestDailyBoxScoresPage(TestCase):\n def setUp(self):\n self.january_01_2017_box_scores_file = open(january_01_2017_html)\n self.january_01_2017_box_scores = self.january_01_2017_box_scores_file.read()\n\n def tearDown(self):\n self.january_01_2017_box_scores_file.close()\n\n def test_game_url_paths_query(self):\n page = DailyBoxScoresPage(html=html.fromstring(self.january_01_2017_box_scores))\n self.assertEqual(page.game_url_paths_query, '//td[contains(@class, \"gamelink\")]/a')\n\n def test_parse_urls(self):\n page = DailyBoxScoresPage(html=html.fromstring(self.january_01_2017_box_scores))\n urls = page.game_url_paths\n self.assertEqual(len(urls), 5)\n self.assertEqual(urls[0], '/boxscores/201701010ATL.html')\n self.assertEqual(urls[1], '/boxscores/201701010IND.html')\n self.assertEqual(urls[2], '/boxscores/201701010LAL.html')\n self.assertEqual(urls[3], '/boxscores/201701010MIA.html')\n self.assertEqual(urls[4], '/boxscores/201701010MIN.html')\n","sub_path":"tests/test_daily_box_scores_page.py","file_name":"test_daily_box_scores_page.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"417200677","text":"from random import randint\r\nimport numpy as np\r\nN, M = 5, 8\r\nA = [[randint(1, 10) for j in range(M)] for i in range(N)]\r\nA = np.array(A)\r\nprint(\"Матрица:\\r\\n{}\".format(A))\r\n\r\nAverage = A.mean(axis=1)\r\nindex = Average.argmax(axis=0)\r\nmax = Average.max(axis=0)\r\n\r\nprint(\"Наибольшее среднее значение: {}\".format(max))","sub_path":"2 часть/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"205205149","text":"from imports import *\n\n\ndef maximum_distinct_elements(nums, K):\n\n freq_counter = Counter(nums)\n min_heap = []\n distinct = 0\n\n for k, v in freq_counter.items():\n if v == 1:\n distinct += 1\n else:\n heappush(min_heap, (v, k))\n\n while k > 0 and min_heap:\n freq, item = heappop(min_heap)\n K = K - freq + 1\n if K >= 0:\n distinct += 1\n\n if K > 0:\n distinct -= K\n return distinct\n","sub_path":"revise-daily/arjuna-vishwamitra-abhimanyu/educative/3-heap-related/top-largest-elements/8_maximum_distinct_elements.py","file_name":"8_maximum_distinct_elements.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"479957012","text":"#from pynput.mouse import Button, Controller\n#mouse = Controller()\n\nimport pyautogui, time, threading\na=pyautogui\npyautogui.FAILSAFE = True\n\n#simulates wait\ndef wait(sec):\n time.sleep(sec)\n\n#function to reset resolution\ndef resetsolution():\n resolution= a.size()\n a.hotkey('win','d')#minimizes any open windows for sefty protocol\n wait(0.5)\n a.hotkey('win','i')#opens Windows settings with hotkey(shortcut)\n wait(3)\n a.press('tab')#chooses System option\n a.press('enter')#presses enter to open system settings\n wait(2)\n #navigates to menu according to resolution\n res=a.size()\n if (res[0] == 1366) and (res[1] == 768):\n a.press('tab',8)#goes to resolution dropdown menu\n elif (res[0] == 1360) and (res[1] == 768):\n a.press('tab', 8)#goes to resolution dropdown menu\n elif(res[0] == 1280) and (res[1] == 768):\n a.press('tab',8)#goes to resolution dropdown menu\n elif (res[0] == 1280) and (res[1] == 720) :\n a.press('tab',7)#goes to resolution dropdown menu\n elif (res[0] == 1024) and (res[1] == 768) :\n a.press('tab',8)#goes to resolution dropdown menu\n else : #elif (res[0] == 800) and (res[1] == 600):\n a.press('tab',7)#goes to resolution dropdown menu\n \n wait(1)\n a.press('enter',2,3)#choose other resolution than the recommended (3 seconds)\n a.press('tab')#navigates to keep res settings option when resolution changed\n wait(0.5)\n a.press('enter')#presses enter to keep resolution\n resolution = a.size()\n wait(1)\n\n res=a.size()\n if (res[0] == 1366) and (res[1] == 768) :\n a.press('tab',9)#Renavigates to resolution menu\n elif (res[0] == 1360) and (res[1] == 768) :\n a.press('tab', 9)#Renavigates to resolution menu\n elif (res[0] == 1280) and (res[1] == 768) :\n a.press('tab',9)#Renavigates to resolution menu\n elif (res[0] == 1280) and (res[1] == 720) :\n a.press('tab',8)#Renavigates to resolution menu\n elif (res[0] == 1024) and (res[1] == 768) :\n a.press('tab',9)#Renavigates to resolution menu\n else : #elif (res[0] == 800) and (res[1] == 600):\n a.press('tab',8)#Renavigates to resolution menu\n\n wait(1)\n a.press('enter',2,3)#gives you only 3 seconds to choose recommended resolution\n wait(0.5)\n a.press('tab')#navigates to keep res settings\n a.press('enter')#presses enter to keep resolution which was recommended\n a.hotkey('win','i')#opens exsting settings window\n a.hotkey('alt','f4')#closes existing \n \ndef main():\n pyautogui.FAILSAFE = True\n resetsolution()\n status=(a.confirm(text='Did it Worked?',title='Run Again?', buttons=['Worked','Retry']))\n if status == 'Retry':\n resetsolution()\n else:\n pyautogui.alert(text='Thanks',Title='See You Later', button='OK')\ndef failsure():\n a = True\n while (a==True):\n loc = pyautogui.position()\n if ((loc[0] == 0) or (loc[0] == 1365)):\n if((loc[1] == 0) or (loc[1] == 767)):\n exit()\n\nfailsafe = threading.Thread(target=failsure)\nchief = threading.Thread(target=main)\n\nif __name__ == '__main__':\n failsafe.start()\n chief.start()\n","sub_path":"Tests/Test_.py","file_name":"Test_.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"344668363","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 14 16:31:47 2020\n\n@author: AEGEAN\n\"\"\"\n\nimport cv2\nimport os\n\ndef create_video_from_images(image_folder, video_name):\n os.chdir(\"C:\\\\Users\\\\AEGEAN\\\\Desktop\\\\Projects\\\\parking_lot_detection_deep_learning\")\n images = [img for img in os.listdir(image_folder) if img.endswith(\".jpg\")]\n frame = cv2.imread(os.path.join(image_folder, images[0]))\n height, width, layers = frame.shape\n \n video = cv2.VideoWriter(video_name, 0, 1, (width,height))\n \n for image in images:\n video.write(cv2.imread(os.path.join(image_folder, image)))\n \n cv2.destroyAllWindows()\n video.release()\n\n\ndef convert_avi_to_mp4(avi_file_path, output_name):\n os.popen(\"ffmpeg -i '{input}' -ac 2 -b:v 2000k -c:a aac -c:v libx264 -b:a 160k -vprofile high -bf 0 -strict experimental -f mp4 '{output}.mp4'\".format(input = avi_file_path, output = output_name))\n return True\n\n\n\n##Main\nimage_folder = 'video_data'\nvideo_name = 'video.avi'\n","sub_path":"classifier/helpers/video_creator.py","file_name":"video_creator.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"186619435","text":"\"\"\"\nWhat is the 10 001st prime number?\n\"\"\"\n\n\n\ndef is_prime(n):\n start = int(n/2)\n for i in range(start, 1, -1):\n if n%i == 0:\n return False\n return True\n\n\ndef is_prime_from_list(n, prime_list):\n if len(prime_list) == 0:\n return True\n for p in prime_list:\n if n%p == 0:\n return False\n return True\n\n\ntope = 10001\nprime_list = []\nprime_number = 0\nn = 1\nwhile prime_number < tope:\n n += 1\n if is_prime_from_list(n,prime_list):\n prime_list.append(n)\n prime_number += 1\n #print(f'Prime {prime_number}: {n}')\n\nprint(prime_list)\nprint(f'{tope} prime number is: {n}')\n\n\n\n\n\n","sub_path":"Problem_007/problem_7.py","file_name":"problem_7.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"290793624","text":"\"\"\"urlconf for the base application\"\"\"\n\nfrom django.conf.urls import url, patterns\n\n# Notes\nurlpatterns = patterns('api.cases.views',\n\n url(r'^$', 'notes_root', name='notes_root'),\n url(r'^create/$', 'notes_create', name='notes_create'),\n url(r'^update/$', 'notes_update', name='notes_update'),\n url(r'^info/$', 'notes_info', name='notes_info'),\n url(r'^info/(?P[a-zA-Z0-9_.-]+)/$', 'notes_info', name='notes_info'),\n url(r'^search/$', 'notes_search', name='notes_search'),\n url(r'^delete/$', 'notes_delete', name='notes_delete'),\n\n)\n","sub_path":"api/cases/note_urls.py","file_name":"note_urls.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"90822848","text":"# Download the Python helper library from twilio.com/docs/python/install\nimport os\nfrom twilio.rest import Client\n\n# Your Account Sid and Auth Token from twilio.com/user/account\n# To set up environmental variables, see http://twil.io/secure\naccount_sid = os.environ['TWILIO_ACCOUNT_SID']\nauth_token = os.environ['TWILIO_AUTH_TOKEN']\nclient = Client(account_sid, auth_token)\n\nmap_items = client.sync \\\n .services(\"ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\") \\\n .sync_maps(\"Players\") \\\n .sync_map_items \\\n .list(from_=\"steph_curry\", order=\"asc\")\n\nfor map_item in map_items:\n print(map_item.data)\n","sub_path":"sync/rest/maps/query-map/query-map.8.x.py","file_name":"query-map.8.x.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"264535184","text":"#_*_coding:utf-8_*_\r\n__author__ = 'Leonyan'\r\nimport os,sys,platform\r\n\r\n#for linux\r\nif platform.system() == \"Windows\":\r\n BASE_DIR = '\\\\'.join(os.path.abspath(os.path.dirname(__file__)).split('\\\\')[:-1])\r\n print(BASE_DIR)\r\nelse:\r\n BASE_DIR = '/'.join(os.path.abspath(os.path.dirname(__file__)).split('/')[:-1])\r\nsys.path.append(BASE_DIR)\r\n\r\nfrom core import HouseStark\r\n\r\n\r\nif __name__ == '__main__':\r\n #sys.argv:命令行参数List,第一个元素是程序本身路径,第二个就是运行文本后的第一个位置参数\r\n HouseStark.ArgvHandler(sys.argv)","sub_path":"MadKingClient/bin/NedStark.py","file_name":"NedStark.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"20303405","text":"#!/usr/bin/python3\n\"\"\"matrix_divided\"\"\"\n\n\ndef matrix_divided(matrix, div):\n \"\"\"Used for divide each element of a matrix\n\n Arguments:\n matrix {list [int, float]} -- the matrix to be divided\n div {[int]} -- divisor\n\n Raises:\n TypeError: \"matrix must be a matrix (list of lists) of integers/floats\"\n ZeroDivisionError: \"division by zero\"\n TypeError: \"Each row of the matrix must have the same size\")\n\n Returns:\n [list] -- New matrix divided\n \"\"\"\n TypeErr = \"matrix must be a matrix (list of lists) of integers/floats\"\n if not isinstance(div, (int, float)):\n raise TypeError(\"div must be a number\")\n elif div == 0:\n raise ZeroDivisionError(\"division by zero\")\n new_matrix = []\n if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0:\n raise TypeError(TypeErr)\n\n len_item = len(matrix[0])\n for item in matrix:\n if len(item) != len_item:\n raise TypeError(\"Each row of the matrix must have the same size\")\n for inside in item:\n if not isinstance(inside, (int, float)):\n raise TypeError(TypeErr)\n for item in matrix:\n new_matrix.append(list(map(lambda i: round(i / div, 2), item)))\n return new_matrix\n","sub_path":"0x07-python-test_driven_development/2-matrix_divided.py","file_name":"2-matrix_divided.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"152093078","text":"import pathlib\nimport pprint\n\nfrom .util import _write_circuit_graph, max_connectivity\nfrom .read_netlist import SpiceParser\nfrom .match_graph import read_inputs, read_setup,_mapped_graph_list,preprocess_stack,reduce_graph,define_SD,check_nodes,add_parallel_caps,add_series_res\nfrom .write_verilog_lef import WriteVerilog, WriteSpice, print_globals,print_header,generate_lef\nfrom .write_verilog_lef import WriteConst, FindArray, WriteCap, check_common_centroid, CopyConstFile\nfrom .read_lef import read_lef\n\nimport logging\nlogger = logging.getLogger(__name__)\n\ndef generate_hierarchy(netlist, subckt, output_dir, flatten_heirarchy, unit_size_mos , unit_size_cap):\n updated_ckt,library = compiler(netlist, subckt, flatten_heirarchy)\n return compiler_output(netlist, library, updated_ckt, subckt, output_dir, unit_size_mos , unit_size_cap)\n\ndef compiler(input_ckt:pathlib.Path, design_name:str, flat=0,Debug=False):\n logger.info(\"Starting topology identification...\")\n input_dir=input_ckt.parents[0]\n logger.debug(f\"Reading subckt {input_ckt}\")\n sp = SpiceParser(input_ckt, design_name, flat)\n circuit = sp.sp_parser()[0]\n\n design_setup=read_setup(input_dir / f'{input_ckt.stem}.setup')\n logger.debug(f\"template parent path: {pathlib.Path(__file__).parent}\")\n lib_path=pathlib.Path(__file__).resolve().parent.parent / 'config' / 'basic_template.sp'\n logger.debug(f\"template library path: {lib_path}\")\n basic_lib = SpiceParser(lib_path)\n library = basic_lib.sp_parser()\n lib_path=pathlib.Path(__file__).resolve().parent.parent / 'config' / 'user_template.sp'\n user_lib = SpiceParser(lib_path)\n library += user_lib.sp_parser()\n library=sorted(library, key=lambda k: max_connectivity(k[\"graph\"]), reverse=True)\n logger.info(f\"dont use cells: {design_setup['DONT_USE_CELLS']}\")\n if len(design_setup['DONT_USE_CELLS'])>0:\n library=[lib_ele for lib_ele in library if lib_ele['name'] not in design_setup['DONT_USE_CELLS']]\n\n if Debug==True:\n _write_circuit_graph(circuit[\"name\"], circuit[\"graph\"],\n \"./circuit_graphs/\")\n for lib_circuit in library:\n _write_circuit_graph(lib_circuit[\"name\"], lib_circuit[\"graph\"],\n \"./circuit_graphs/\")\n hier_graph_dict=read_inputs(circuit[\"name\"],circuit[\"graph\"])\n\n UPDATED_CIRCUIT_LIST = []\n for circuit_name, circuit in hier_graph_dict.items():\n logger.debug(f\"START MATCHING in circuit: {circuit_name}\")\n G1 = circuit[\"graph\"]\n if circuit_name in design_setup['DIGITAL']:\n mapped_graph_list = _mapped_graph_list(G1, library, design_setup['CLOCK'], True )\n else:\n define_SD(G1,design_setup['POWER'],design_setup['GND'], design_setup['CLOCK'])\n logger.debug(f\"no of nodes: {len(G1)}\")\n add_parallel_caps(G1)\n add_series_res(G1)\n preprocess_stack(G1)\n initial_size=len(G1)\n delta =1\n while delta > 0:\n logger.debug(\"CHECKING stacked transistors\")\n preprocess_stack(G1)\n delta = initial_size - len(G1)\n initial_size = len(G1)\n mapped_graph_list = _mapped_graph_list(G1, library, design_setup['CLOCK'], False )\n updated_circuit, Grest = reduce_graph(G1, mapped_graph_list, library)\n check_nodes(updated_circuit)\n UPDATED_CIRCUIT_LIST.extend(updated_circuit)\n\n UPDATED_CIRCUIT_LIST.append({\n \"name\": circuit_name,\n \"graph\": Grest,\n \"ports\":circuit[\"ports\"],\n \"ports_match\": circuit[\"connection\"],\n \"size\": len(Grest.nodes())\n })\n return UPDATED_CIRCUIT_LIST, library\n\ndef compiler_output(input_ckt, library, updated_ckt, design_name, result_dir, unit_size_mos=12, unit_size_cap=12):\n if not result_dir.exists():\n result_dir.mkdir()\n logger.debug(f\"Writing results in dir: {result_dir}\")\n input_dir=input_ckt.parents[0]\n VERILOG_FP = open(result_dir / f'{design_name}.v', 'w')\n\n logger.debug(\"writing spice file for cell generator\")\n\n ## File pointer for spice generator\n SP_FP = open(result_dir / (design_name + '_blocks.sp'), 'w')\n print_header(VERILOG_FP, design_name)\n design_setup=read_setup(input_dir / (input_ckt.stem + '.setup'))\n try:\n POWER_PINS = [design_setup['POWER'][0],design_setup['GND'][0]]\n except (IndexError, ValueError):\n POWER_PINS=[]\n logger.error(\"no power and gnd defination, correct setup file\")\n\n #read lef to not write those modules as macros\n lef_path = pathlib.Path(__file__).resolve().parent.parent / 'config'\n ALL_LEF = read_lef(lef_path)\n logger.debug(f\"Available library cells: {', '.join(ALL_LEF)}\")\n # local hack for deisgn vco_dtype,\n #there requirement is different size for nmos and pmos\n if 'vco_dtype_12' in design_name:\n unit_size_mos=37\n generated_module=[]\n primitives = {}\n duplicate_modules =[]\n for members in updated_ckt:\n #print(members)\n name = members[\"name\"]\n if name in duplicate_modules:\n continue\n else:\n duplicate_modules.append(name)\n logger.debug(f\"Found module: {name}\")\n inoutpin = []\n logger.debug(f'found ports match: {members[\"ports_match\"]}')\n floating_ports=[]\n if members[\"ports_match\"]:\n for key in members[\"ports_match\"].keys():\n if key not in POWER_PINS:\n inoutpin.append(key)\n if members[\"ports\"]:\n logger.debug(f'Found module ports kk: {members[\"ports\"]}')\n floating_ports = list(set(inoutpin) - set(members[\"ports\"]) - set(design_setup['POWER']) -set(design_setup['GND']))\n if len(floating_ports)> 0:\n logger.error(f\"floating ports found: {name} {floating_ports}\")\n raise SystemExit('Please remove floating ports')\n else:\n inoutpin = members[\"ports\"]\n\n graph = members[\"graph\"].copy()\n logger.debug(f\"Reading nodes from graph: {graph}\")\n for node, attr in graph.nodes(data=True):\n #lef_name = '_'.join(attr['inst_type'].split('_')[0:-1])\n if 'net' in attr['inst_type']: continue\n #Dropping floating ports\n #if attr['ports'\n lef_name = attr['inst_type']\n if \"values\" in attr and (lef_name in ALL_LEF):\n block_name, block_args = generate_lef(\n lef_name, attr[\"values\"],\n primitives, unit_size_mos, unit_size_cap)\n block_name_ext = block_name.replace(lef_name,'')\n logger.debug(f\"Created new lef for: {block_name}\")\n # Only unit caps are generated\n if block_name.lower().startswith('cap'):\n graph.nodes[node]['inst_type'] = block_args['primitive']\n block_args['primitive']=block_name\n else:\n graph.nodes[node]['inst_type'] = block_name\n\n if block_name in primitives:\n assert block_args == primitives[block_name]\n else:\n primitives[block_name] = block_args\n else:\n logger.info(f\"No physical information found for: {name}\")\n\n if name in ALL_LEF:\n logger.debug(f\"writing spice for block: {name}\")\n ws = WriteSpice(graph, name+block_name_ext, inoutpin, updated_ckt)\n ws.print_subckt(SP_FP)\n continue\n\n logger.debug(f\"generated data for {name} : {pprint.pformat(primitives, indent=4)}\")\n if name not in ALL_LEF:\n logger.debug(f\"call verilog writer for block: {name}\")\n wv = WriteVerilog(graph, name, inoutpin, updated_ckt, POWER_PINS)\n logger.debug(f\"call array finder for block: {name}\")\n all_array=FindArray(graph, input_dir, name )\n logger.debug(f\"Copy const file for: {name}\")\n const_file = CopyConstFile(name, input_dir, result_dir)\n logger.debug(f\"cap constraint gen for block: {name}\")\n WriteCap(graph, result_dir, name, unit_size_cap,all_array)\n check_common_centroid(graph,const_file,inoutpin)\n ##Removinf constraints to fix cascoded cmc\n lib_names=[lib_ele['name'] for lib_ele in library]\n if name not in design_setup['DIGITAL'] and name not in lib_names:\n logger.debug(f\"call constraint generator writer for block: {name}\")\n stop_points=design_setup['DIGITAL']+design_setup['CLOCK']\n WriteConst(graph, result_dir, name, inoutpin, stop_points)\n wv.print_module(VERILOG_FP)\n generated_module.append(name)\n if len(POWER_PINS)>0:\n print_globals(VERILOG_FP,POWER_PINS)\n SP_FP.close()\n\n logger.info(\"Topology identification done !!!\")\n logger.info(f\"OUTPUT verilog netlist at: {result_dir}/{design_name}.v\")\n logger.info(f\"OUTPUT spice netlist at: {result_dir}/{design_name}_blocks.sp\")\n logger.info(f\"OUTPUT const file at: {result_dir}/{design_name}.const\")\n\n return primitives\n","sub_path":"align/compiler/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":9242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"382362848","text":"\"\"\"CMPT 370 Group 5 Project: NAME (Nearly Analogous Music Engine)\n Summary: is a piece of software to compare songs using the Spotify API.\n NAME will help the user find other similar songs to the ones they\n are interested in, as well as detailed info about their favorite\n songs.\n\"\"\"\nimport os\nimport name.gui as gui\nimport tkinter as tk\nfrom tkinter import Grid\n\nfrom name.backend_classes.user import User\n\n\nclass Name(tk.Tk):\n \"\"\"Main entry point for the app basically wraps the GUI\n set up a finite state machine to flip between frames in a more controlled\n fashion\n Args:\n tk (Tk): a tk application object\n \"\"\"\n\n\n max_songs = 6 # need to set a maximum number of songs that can show up in\n # the search\n active_frame = 9 # the frame that is currently shown to the user\n previous_frame = 9\n\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n\n self.title(\"Nearly Analagous Music Engine\")\n self.iconbitmap(\"name\\\\resources\\\\ravencon.ico\")\n\n Grid.rowconfigure(self, 0, weight=1)\n Grid.columnconfigure(self, 0, weight=1)\n\n # container frame\n container = tk.Frame(self)\n container.grid(row=0, column=0, sticky=\"nsew\")\n container.grid_rowconfigure(1, weight=1)\n container.grid_columnconfigure(0, weight=1)\n container.grid(padx=\"10\", pady=\"10\")\n\n # working list of songs (displayed in the song_treeview widgets)\n self.song_object_list = []\n\n # instantiate frame array\n self.frames = {}\n\n # instantiate the user\n self.user = User()\n\n # instantiate the frames\n self.frames[0] = gui.CompareSongsFrame(self, container, self.user)\n self.frames[1] = gui.SongInfoSearchFrame(self, container, self.user)\n self.frames[2] = gui.SongInfoFrame(self, container, self.user)\n self.frames[3] = gui.SongStatsFrame(self, container, self.user)\n self.frames[4] = gui.MemberHomeFrame(self, container, self.user)\n self.frames[5] = gui.PlaylistEditFrame(self, container, self.user)\n self.frames[6] = gui.AllPlaylistsFrame(self, container, self.user)\n self.frames[7] = gui.SavePlaylistFrame(self, container, self.user)\n self.frames[8] = gui.ListeningHabitsFrame(self, container, self.user)\n self.frames[9] = gui.HomePageFrame(self, container, self.user)\n\n #instantiate group frames\n self.frames[10] = gui.EditGroupFrame(self, container, self.user)\n self.frames[11] = gui.EditGroupPlaylistFrame(self, container, self.user)\n self.frames[12] = gui.GroupHomeFrame(self, container, self.user)\n self.frames[13] = gui.SongInfoMemberFrame(self, container, self.user)\n\n for i in self.frames:\n self.frames[i].grid_unmap()\n\n self.frames[self.get_frame_id(\"Home Page\")].grid_init()\n\n def switch_frame(self, old_id, new_id):\n \"\"\" This will switch the state in the finite state machine to the next state based on\n some event\n\n Args:\n old_id (int): The previously active frame\n new_id (int): THe frame being switched too\n \"\"\"\n self.frames[old_id].grid_unmap()\n self.frames[new_id].grid_remember()\n self.previous_frame = old_id\n self.active_frame = new_id\n\n def switch_to_previous_frame(self):\n \"\"\" switch to the previously active frame \"\"\"\n self.switch_frame(self.active_frame, self.previous_frame)\n\n def get_frame_id(self, name):\n \"\"\" get the frame id based on the given name see GUI FSM diagram in wiki\n maybe not the best way to do this but its fine for now\n\n Args:\n name (string): the name of desired frame id\n\n Returns:\n integer: the corresponding frame_id of given name\n \"\"\"\n if name == \"Compare Songs\":\n return 0\n elif name == \"Song Info Search\":\n return 1\n elif name == \"Song Info\":\n return 2\n elif name == \"Song Stats\":\n return 3\n elif name == \"Member Home\":\n return 4\n elif name == \"Playlist Edit\":\n return 5\n elif name == \"All Playlists\":\n return 6\n elif name == \"Save Playlist\":\n return 7\n elif name == \"Listening Habits\":\n return 8\n elif name == \"Home Page\":\n return 9\n elif name == \"Edit Group\":\n return 10\n elif name == \"Edit Group Playlist\":\n return 11\n elif name == \"Group Home\":\n return 12\n elif name == \"Song Info Member\":\n return 13\n else:\n print(\"ERROR NO SUCH FRAME\")\n exit()\n\ndef main():\n \"\"\" main entry point \"\"\"\n app = Name()\n app.mainloop()\n if os.path.exists(\".cache\"):\n os.remove(\".cache\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"name.py","file_name":"name.py","file_ext":"py","file_size_in_byte":4963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"477681674","text":"# -*- coding:ascii -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1428446922.800181\n_enable_loop = True\n_template_filename = '/Users/jamesdayhuff/Documents/Programming/Frameworks/Python.framework/Versions/3.4/bin/test_dmp1/homepage/templates/rental_catalog.html'\n_template_uri = 'rental_catalog.html'\n_source_encoding = 'ascii'\nimport os, os.path, re\n_exports = ['content']\n\n\ndef _mako_get_namespace(context, name):\n try:\n return context.namespaces[(__name__, name)]\n except KeyError:\n _mako_generate_namespaces(context)\n return context.namespaces[(__name__, name)]\ndef _mako_generate_namespaces(context):\n pass\ndef _mako_inherit(template, context):\n _mako_generate_namespaces(context)\n return runtime._inherit_from(context, 'base.htm', _template_uri)\ndef render_body(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n items = context.get('items', UNDEFINED)\n def content():\n return render_content(context._locals(__M_locals))\n __M_writer = context.writer()\n __M_writer('\\n\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'content'):\n context['self'].content(**pageargs)\n \n\n __M_writer('\\n\\n\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_content(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n items = context.get('items', UNDEFINED)\n def content():\n return render_content(context)\n __M_writer = context.writer()\n __M_writer('\\n

Rental Catalog

\\n \\n \\n
\\n
\\n
\\n
\\n \\n \\n \\n \\n
\\n
\\n \\n
\\n
\\n
\\n')\n for item in items:\n __M_writer('
\\n
')\n __M_writer(str(item.name))\n __M_writer(\"
\\n
\\n \\n \\n \\n
$')\n __M_writer(str(item.STP))\n __M_writer(' / day
\\n')\n __M_writer(' \\n
\\n\\n')\n __M_writer('
\\n\\n\\n
\\n
\\n
\\n
\\n \\n

Rental Cart

\\n
\\n
\\n \\n
\\n
\\n')\n __M_writer('
\\n
\\n
\\n
\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n\"\"\"\n__M_BEGIN_METADATA\n{\"uri\": \"rental_catalog.html\", \"line_map\": {\"64\": 30, \"65\": 30, \"66\": 30, \"35\": 1, \"68\": 49, \"40\": 53, \"74\": 68, \"46\": 3, \"59\": 25, \"67\": 34, \"53\": 3, \"54\": 21, \"55\": 22, \"56\": 23, \"57\": 23, \"58\": 25, \"27\": 0, \"60\": 26, \"61\": 26, \"62\": 28, \"63\": 28}, \"filename\": \"/Users/jamesdayhuff/Documents/Programming/Frameworks/Python.framework/Versions/3.4/bin/test_dmp1/homepage/templates/rental_catalog.html\", \"source_encoding\": \"ascii\"}\n__M_END_METADATA\n\"\"\"\n","sub_path":"homepage/cached_templates/templates/rental_catalog.html.py","file_name":"rental_catalog.html.py","file_ext":"py","file_size_in_byte":4423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"434663817","text":"import numpy as np\r\nimport scipy.stats\r\nimport json\r\n\r\ndef create_similarity_matrix_weight(steiner_trees):\r\n with open('../util/api_weight_label_vec.json', 'r') as fp:\r\n data = json.load(fp)\r\n api_vec = np.array(data['api_vec'])\r\n\r\n weight_vector = []\r\n candidate_num = len(steiner_trees)\r\n candidate_vec = np.zeros((candidate_num, api_vec.shape[1]))\r\n Gram_matrix = np.zeros((candidate_num, candidate_num))\r\n for (i, steiner) in enumerate(steiner_trees):\r\n vec = np.zeros((len(steiner.nodes), api_vec.shape[1]))\r\n for (v, node) in enumerate(steiner.nodes):\r\n vec[v, :] = api_vec[node]\r\n\r\n candidate_vec[i] = np.sum(vec, axis=0)\r\n weight_vector.append(1 + steiner.weight)\r\n\r\n a = np.exp(1 / np.array(weight_vector))\r\n compatibility_vector = a /(np.sum(a))\r\n candidate_vec /= np.linalg.norm(candidate_vec, axis=1, keepdims=True)\r\n Gram_matrix = np.dot(candidate_vec, candidate_vec.T)\r\n\r\n return compatibility_vector, Gram_matrix\r\n\r\n","sub_path":"src/util/create_similarity_matrix_weight.py","file_name":"create_similarity_matrix_weight.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"86724085","text":"from discord import Client, Message\nfrom policy import AccessControl\nimport re\n\nSHORT_HELP_TEXT = '$$$say [mensagem] - Faz-me dizer uma mensagem'\n\ndef help(**kwargs):\n return SHORT_HELP_TEXT\n\n@AccessControl(roles=['Staff'], relax_in=['justabunchofspam'], relax_pm=True)\nasync def run(client: Client, message: Message, **kwargs):\n msg_content = str.join(' ', kwargs['args'])\n p = re.compile('@\\\\w+#\\\\d{4}') # regex expression for mention\n user_mentions = p.findall(msg_content)\n if not user_mentions == []:\n for usr in user_mentions:\n msg_content.replace(usr, '<@%s>' % usr[1:]) # fix mentions\n\n await message.channel.send(content=msg_content)\n\n if 'sch_orig_channel' in kwargs:\n await kwargs['sch_orig_channel'].send(content='Feito')\n","sub_path":"hooks/commands/say.py","file_name":"say.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"186046537","text":"\nimport pickle\nimport numpy as np\n\nimport keras\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense, Dropout, Activation, Flatten\n\n\n\n\n\nclass predictor:\n def __init__(self):\n self.data = None\n self.model = None\n \n def readdata(self, data_name = 'draft_win.txt'):\n f = open(data_name,'rb') \n self.data = pickle.load(f) \n f.close()\n np.random.shuffle(self.data)\n N = len(self.data)\n print(N)\n self.x_train = self.data[:int(0.7*N), :-1] / 130\n self.x_test = self.data[int(0.7*N):, :-1] / 130\n self.y_train = self.data[:int(0.7*N), -1]\n self.y_test = self.data[int(0.7*N):, -1]\n \n def build(self):\n self.model = Sequential()\n self.model.add(Dense(64, activation='relu', input_shape=self.x_train.shape[1:]))\n self.model.add(Dense(128, activation='relu'))\n self.model.add(Dense(32, activation='relu'))\n self.model.add(Dense(16, activation='relu'))\n self.model.add(Dense(1, activation='sigmoid'))\n opt = keras.optimizers.rmsprop(lr=0.001, decay=1e-7)\n self.model.compile(optimizer=opt,\n loss='binary_crossentropy',\n metrics=['accuracy'])\n \n def train(self, batch_size = 64, epochs = 100):\n self.model.fit(self.x_train, self.y_train, epochs=epochs, batch_size=batch_size)\n \n def save(self):\n self.model.save('predictor.h5')\n \n def evaluate(self):\n eva = self.model.evaluate(self.x_test, self.y_test)\n print(eva)\n \n def do_all(self):\n self.readdata()\n self.build()\n self.train()\n self.evaluate()\n self.save()\n ","sub_path":"predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"571512148","text":"from django.urls import path\nfrom . import views\n\napp_name = 'trading'\nurlpatterns = [\n path('', views.buy, name='index'),\n path('buy/', views.buy, name='buy'),\n path('buy/poli', views.buy_poli, name='buy_poli'),\n path('buy/poli/breakout',\n views.buy_poli_breakout,\n name='buy_poli_breakout'),\n path('buy//done', views.buy_done, name='buy_done'),\n path('test/500', views.test_500, name='test_500'),\n]\n","sub_path":"web/trading/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"5296077","text":"from bifrost.db.base import BaseDBException\nfrom bifrost.connections import create_bifrost, create_oracle\nfrom bifrost.utils import ObjectNotSavedException\n\n\nclass BaseObject(object):\n \"\"\" Base class for all objects that involves databases. \"\"\"\n\n def __init__(self, db_fields, obj_fields, db_table, no_id=False):\n self._id = 0\n self._db_fields = db_fields\n self._fields = obj_fields\n self._table_name = db_table\n self.qry_init_part = ''\n self.no_id = no_id\n self.create_connection = create_bifrost\n\n self.build_query()\n\n def build_query(self):\n \"\"\" Build the query string for select. \"\"\"\n if self.no_id:\n self.qry_init_part = 'SELECT {} FROM {} WHERE '.format(\n '\"{}\"'.format('\", \"'.join(self.db_fields)), self._table_name)\n else:\n self.qry_init_part = 'SELECT {}, id FROM {} WHERE '.format(\n '\"{}\"'.format('\", \"'.join(self.db_fields)), self._table_name)\n\n def is_new(self):\n \"\"\" Return True if this is a new object. \"\"\"\n\n return self.id == 0 or self.no_id\n\n def load(self, pk):\n\n \"\"\"\n Load a object from id = pk.\n :param pk:\n \"\"\"\n\n connection = self.create_connection()\n result = connection.query(\n '{} \"id\" = %(_id)s'.format(self.qry_init_part),\n {'_id': pk})\n if len(result) > 0:\n self.load_data(result[0])\n connection.close()\n self.on_load()\n\n def load_data(self, data):\n\n \"\"\" Fill object with your data .\n :param data:\n \"\"\"\n\n count = 0\n if abs(len(data) - len(self._db_fields)) > 1:\n raise IndexError('Invalid numbers of fields')\n for key in self._fields:\n if key not in self.__dict__:\n raise IndexError(\n 'Instance attribute not found: \"\"'.format(key))\n self.__dict__[key] = data[count]\n count += 1\n if not self.no_id:\n self._id = data[count]\n self.on_load()\n\n @staticmethod\n def normalize_column(column_name):\n \"\"\"\nNormalize column according with your database.\n :param column_name:\n :return:\n \"\"\"\n if column_name.startswith('('):\n exp = column_name.split(' ')\n name = exp.pop(-1)\n return ' '.join(exp) + ' \"{}\"'.format(name)\n return '\"{}\"'.format(column_name)\n\n @staticmethod\n def normalize_columns(columns_name):\n \"\"\"\nNormalize an array of columns depending with your database,\n :param columns_name:\n :return:\n \"\"\"\n to_return = ''\n for column_name in columns_name:\n if column_name.startswith('('):\n exp = column_name.split(' ')\n name = exp.pop(-1)\n to_return += ' '.join(exp) + ' \"{}\", '.format(name)\n else:\n to_return += '\"{}\", '.format(column_name)\n return to_return.rstrip(', ')\n\n def save(self):\n \"\"\"\n Save data to the database.\n :raise ObjectNotSavedException:\n \"\"\"\n connection = self.create_connection()\n command = self._save_string()\n data = self._save_dict()\n try:\n connection.command(command, data)\n except BaseDBException as err:\n if str(err).startswith('DUPLICATE KEY'):\n raise ObjectNotSavedException('Duplicated Item.')\n connection.close()\n if self.is_new() and not self.no_id:\n self._load_id_by_all_fields()\n self.on_save()\n\n def on_load(self):\n \"\"\"\n\n Execute that functions when the object is loaded.\n \"\"\"\n pass\n\n def on_save(self):\n \"\"\"\n\n Execute that functions when the object is saved.\n \"\"\"\n pass\n\n def _insert_string(self):\n\n \"\"\" Return the insert string. \"\"\"\n\n return 'INSERT INTO {} ({}) VALUES ({})'.format(\n self._table_name,\n '\"{}\"'.format('\", \"'.join(self.db_fields)),\n '%({})s'.format(')s, %('.join(self._fields)))\n\n def _load_id_by_all_fields(self):\n\n \"\"\"\n Load a id with the same data of this object Used to get id when new\n object is saved.\n \"\"\"\n\n count = 0\n connection = self.create_connection()\n command = 'SELECT id FROM {} WHERE'.format(self._table_name)\n data = self._save_dict()\n while count < len(self._db_fields):\n if data[self._fields[count]] is None:\n command += ' \"{}\" is %({})s AND'.format(self._db_fields[count],\n self._fields[count])\n else:\n command += ' \"{}\" = %({})s AND'.format(self._db_fields[count],\n self._fields[count])\n count += 1\n result = connection.query(command.strip(' AND'), data)\n if len(result) > 0:\n self._id = result[0][0]\n connection.close()\n else:\n connection.close()\n raise IndexError('Id not found in search by all fields')\n\n def _load_id_by_unique(self, **obj_data):\n \"\"\"\n Load a id with the same data of this object. Used to get id when new\n object is saved.\n \"\"\"\n\n count = 0\n connection = self.create_connection()\n command = 'SELECT id FROM {} WHERE'.format(self._table_name)\n for data in obj_data.keys():\n if obj_data[data] is None:\n command += ' \"{0}\" is %({0})s AND'.format(data)\n else:\n command += ' \"{0}\" = %({0})s AND'.format(data)\n count += 1\n result = connection.query(command.strip(' AND'), obj_data)\n if len(result) > 0:\n self._id = result[0][0]\n connection.close()\n return True\n return False\n\n def _save_dict(self):\n \"\"\" Return adictionary with values of bind variables. \"\"\"\n new_dict = {}\n if not self.no_id:\n new_dict['_id'] = self._id\n for key in self._fields:\n if key not in self.__dict__:\n print('Instance attribute not found: {}'.format(key))\n raise IndexError(\n 'Instance attribute not found: {}'.format(key))\n new_dict[key] = self.__dict__[key]\n return new_dict\n\n def _save_string(self):\n\n \"\"\" Return the save [insert or update] string. \"\"\"\n\n if len(self._fields) < len(self._db_fields):\n print('Invalid numbers of fields')\n raise IndexError('Invalid numbers of fields')\n if self.is_new():\n return self._insert_string()\n else:\n return self._update_string()\n\n def _update_string(self):\n\n \"\"\" Return the update string. \"\"\"\n\n count = 0\n cmd = 'UPDATE {} SET'.format(self._table_name)\n while count < len(self._db_fields):\n cmd += ' \"{}\"=%({})s,'.format(self._db_fields[count],\n self._fields[count])\n count += 1\n cmd = '{} WHERE \"id\" = %(_id)s'.format(cmd.strip(','))\n return cmd\n\n @property\n def db_fields(self):\n return self._db_fields\n\n @property\n def fields(self):\n return self._fields()\n\n @property\n def id(self):\n return None if self.no_id else self._id\n\n @property\n def table_name(self):\n return self._table_name\n\n\nclass OracleObject(BaseObject):\n \"\"\" Base class for all objects that involves Oracle databases. \"\"\"\n\n def __init__(self, db_fields, obj_fields, db_table):\n BaseObject.__init__(self, db_fields, obj_fields, db_table)\n self.create_connection = create_oracle\n\n def build_query(self):\n \"\"\" Build the query string for select. \"\"\"\n if self.no_id:\n self.qry_init_part = 'SELECT {} FROM {} WHERE '.format(\n ', '.join(self.db_fields), self._table_name)\n else:\n self.qry_init_part = 'SELECT {}, id FROM {} WHERE '.format(\n ', '.join(self.db_fields), self._table_name)\n\n def load(self, pk):\n\n \"\"\" Load a object from id = pk. \"\"\"\n\n connection = self.create_connection()\n result = connection.query(\n '{} \"id\" = :_id'.format(self.qry_init_part),\n {'_id': pk})\n if len(result) > 0:\n self.load_data(result[0])\n connection.close()\n self.on_load()\n\n @staticmethod\n def normalize_column(column_name):\n return column_name\n\n @staticmethod\n def normalize_columns(columns_name):\n return ', '.join(columns_name)\n\n def _insert_string(self):\n\n \"\"\" Return the insert string. \"\"\"\n\n return 'INSERT INTO {} ({}) VALUES ({})'.format(\n self._table_name, ', '.join(self.db_fields),\n ':{}'.format(', :'.join(self._fields)))\n\n def _load_id_by_all_fields(self):\n\n \"\"\"\nLoad a id with the same data of this object.\nUsed to get id when new object is saved.\n \"\"\"\n\n count = 0\n connection = self.create_connection()\n command = 'SELECT id FROM {} WHERE'.format(self._table_name)\n data = self._save_dict()\n while count < len(self._db_fields):\n if data[self._fields[count]] is None:\n command += ' {} is :{} AND'.format(self._db_fields[count],\n self._fields[count])\n else:\n command += ' {} = :{} AND'.format(self._db_fields[count],\n self._fields[count])\n count += 1\n result = connection.query(command.strip(' AND'), data)\n if len(result) > 0:\n self._id = result[0][0]\n connection.close()\n else:\n connection.close()\n raise IndexError('Id not found in search by all fields')\n\n def _load_id_by_unique(self, **obj_data):\n\n \"\"\"\nLoad a id with the same data of this object.\nUsed to get id when new object is saved.\n \"\"\"\n\n count = 0\n connection = self.create_connection()\n command = 'SELECT id FROM {} WHERE'.format(self._table_name)\n for data in obj_data.keys():\n if obj_data[data] is None:\n command += ' {0} is :{0} AND'.format(data)\n else:\n command += ' {0} = :{0} AND'.format(data)\n count += 1\n result = connection.query(command.strip(' AND'), obj_data)\n if len(result) > 0:\n self._id = result[0][0]\n connection.close()\n return True\n return False\n\n def _update_string(self):\n\n \"\"\" Return the update string. \"\"\"\n\n count = 0\n cmd = 'UPDATE {} SET'.format(self._table_name)\n while count < len(self._db_fields):\n cmd += ' {}=:{},'.format(self._db_fields[count],\n self._fields[count])\n count += 1\n cmd = '{} WHERE id = :_id'.format(cmd.strip(','))\n return cmd\n","sub_path":"bifrost/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":11110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"625257590","text":"import pickle\r\nimport socket\r\nimport struct\r\n\r\nimport cv2\r\n\r\nHOST = ''\r\nPORT = 8089\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nprint('Socket created')\r\n\r\ns.bind((HOST, PORT))\r\nprint('Socket bind complete')\r\ns.listen(10)\r\nprint('Socket now listening')\r\n\r\nconn, addr = s.accept()\r\n\r\ndata = b'' ### CHANGED\r\npayload_size = struct.calcsize(\"L\") ### CHANGED\r\n\r\nwhile True:\r\n\r\n # Retrieve message size\r\n while len(data) < payload_size:\r\n data += conn.recv(4096)\r\n\r\n packed_msg_size = data[:payload_size]\r\n data = data[payload_size:]\r\n msg_size = struct.unpack(\"L\", packed_msg_size)[0] ### CHANGED\r\n\r\n # Retrieve all data based on message size\r\n while len(data) < msg_size:\r\n data += conn.recv(4096)\r\n\r\n frame_data = data[:msg_size]\r\n data = data[msg_size:]\r\n\r\n # Extract frame\r\n frame = pickle.loads(frame_data)\r\n\r\n # Display\r\n cv2.imshow('frame', frame)\r\n cv2.waitKey(1)\r\n\r\n\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport glob\r\nimport random\r\n\r\n\r\n# Load Yolo\r\n#net = cv2.dnn.readNet(\"yolov3_training_last.weights\", \"yolov3_testing.cfg\")\r\nnet = cv2.dnn.readNet(\"yolov3_custom_last.weights\", \"yolov3_custom.cfg\")\r\n\r\n# Name custom object\r\nclasses = [\"cocacola\",\"pepsi\"]\r\n\r\n# Images path\r\nimages_path = glob.glob(r\"C:\\Users\\hiwbr\\Documents\\9o semestre\\TCC\\Teste\\dataset\\*.jpg\")\r\n\r\n\r\n\r\nlayer_names = net.getLayerNames()\r\noutput_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]\r\ncolors = np.random.uniform(0, 255, size=(len(classes), 3))\r\n\r\n# Insert here the path of your images\r\nrandom.shuffle(images_path)\r\n\r\n# Loading image\r\nimg = cv2.imread(img_path)\r\nimg = cv2.resize(img, None, fx=0.4, fy=0.4)\r\nheight, width, channels = img.shape\r\n\r\n# Detecting objects\r\nblob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)\r\n\r\nnet.setInput(blob)\r\nouts = net.forward(output_layers)\r\n\r\n# Showing informations on the screen\r\nclass_ids = []\r\nconfidences = []\r\nboxes = []\r\nfor out in outs:\r\n for detection in out:\r\n scores = detection[5:]\r\n class_id = np.argmax(scores)\r\n confidence = scores[class_id]\r\n if confidence > 0.3:\r\n # Object detected\r\n print(class_id)\r\n center_x = int(detection[0] * width)\r\n center_y = int(detection[1] * height)\r\n w = int(detection[2] * width)\r\n h = int(detection[3] * height)\r\n\r\n # Rectangle coordinates\r\n x = int(center_x - w / 2)\r\n y = int(center_y - h / 2)\r\n\r\n boxes.append([x, y, w, h])\r\n confidences.append(float(confidence))\r\n class_ids.append(class_id)\r\n\r\nindexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)\r\nprint(indexes)\r\nfont = cv2.FONT_HERSHEY_PLAIN\r\nfor i in range(len(boxes)):\r\n if i in indexes:\r\n x, y, w, h = boxes[i]\r\n label = str(classes[class_ids[i]])\r\n color = colors[class_ids[i]]\r\n cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)\r\n cv2.putText(img, label, (x, y + 30), font, 3, color, 2)\r\n\r\n\r\ncv2.imshow(\"Image\", img)\r\nkey = cv2.waitKey(0)\r\n\r\ncv2.destroyAllWindows()\r\n","sub_path":"server_yolo.py","file_name":"server_yolo.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"384335661","text":"import numpy as np\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\nfrom sklearn import decomposition\nfrom sklearn import datasets\n\nnp.random.seed(5)\n\ncenters = [[1, 1], [-1, -1], [1, -1]]\niris = datasets.load_iris()\nX = iris.data\ny = iris.target\n\nfig = plt.figure(1, figsize=(4, 3))\nplt.clf()\nax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)\n\nplt.cla()\n\nprint(X.shape)\nnormalized=X-np.mean(X,axis=0)\nprint('**',normalized.shape)\nprint(np.mean(X,axis=0))\ncov_matrix=np.cov(normalized.T)\nprint('**',cov_matrix.shape)\neigen_values,eigen_vectors=np.linalg.eig(cov_matrix)\nprint(eigen_vectors.shape)\neigen_vectors=eigen_vectors[:,0:3]\nprint(eigen_vectors.shape)\nprint(cov_matrix.shape)\nprint()\nprint()\nprint(eigen_values)\nconv_data=np.dot(eigen_vectors.T,normalized.T).T\nX=conv_data\n\n\n\n\nfor name, label in [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]:\n ax.text3D(X[y == label, 0].mean(),\n X[y == label, 1].mean() + 1.5,\n X[y == label, 2].mean(), name,\n horizontalalignment='center',\n bbox=dict(alpha=.5, edgecolor='w', facecolor='w'))\n# Reorder the labels to have colors matching the cluster results\ny = np.choose(y, [1, 2, 0]).astype(np.float)\nax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=plt.cm.spectral,\n edgecolor='k')\n\nax.w_xaxis.set_ticklabels([])\nax.w_yaxis.set_ticklabels([])\nax.w_zaxis.set_ticklabels([])\n\nplt.show()\n","sub_path":"ML assignments/PCA.py","file_name":"PCA.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"586006808","text":"from typing import List\n\nfrom game_config.houses import HousesConfig\nfrom game_config.influence_tracks import InfluenceTracksConfig\nfrom game_config.map import GameMapConfig\nfrom game_config.tokens import TokensConfig\nfrom game_config.unit_types import UnitTypesConfig\n\n\nclass PlayerConfig(object):\n \"\"\" Configuration of a single player (that does not change during a game_play) \"\"\"\n def __init__(self, name: str, house_name: str):\n self.name = name\n self.house_name = house_name\n\n\nclass GameConfig(object):\n \"\"\" Configuration of a single game_play (that does not change during the game_play) \"\"\"\n def __init__(self,\n players: List[PlayerConfig],\n game_map: GameMapConfig,\n houses: HousesConfig,\n tokens: TokensConfig,\n unit_types: UnitTypesConfig,\n influence_tracks: InfluenceTracksConfig):\n self.players = players\n self.game_map = game_map\n self.houses = houses\n self.tokens = tokens\n self.unit_types = unit_types\n self.influence_tracks = influence_tracks\n","sub_path":"game_config/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"482839001","text":"# Goes through a CSV an build a JSON out of it. \n\nimport csv\nimport json\n\n# create a json file (with write access)\njsonfile = open('file.json', 'w')\n\n# hold components\ncomp = []\n\n# open and load the csv\nwith open('updated2.csv') as csvfile:\n readCSV = csv.reader(csvfile, delimiter=',')\n # iterates through all the rows from the csv\n for row in readCSV:\n # row[0] = component\n # row[1] = version\n # row[2] = package manager\n print(row)\n temp = {'component':{row[2]:{'name':row[0], 'version':row[1]}}} \n print(temp) \n comp.append(temp)\n json_string = json.dumps(temp)\n print(json_string) \nprint(\"##########\")\njson.dump(comp, jsonfile, sort_keys=True, indent=4, separators=(',', ': '))\nprint(jsonfile)\n\n\n# \"component\": {\n# \"nuget.org\": {\n# \"name\": \"EntityFramework\",\n# \"version\": \"6.1.3\"\n# }\n# } \n\n\n \n","sub_path":"pymongo/csvtojson-master/create_json_from_csv.py","file_name":"create_json_from_csv.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"441291624","text":"\"\"\"\nqueue_link.py\n\"\"\"\nclass Node:\n def __init__(self, value,next=None):\n self.value=value\n self.next=next\nclass Lkqueue:\n def __init__(self):\n self.head=self.tail=Node(None)\n def add(self,value):\n #建立一个中间变量,隔离\n self.tail.next=Node(value)\n if not self.head.value:\n self.head=self.tail.next\n self.tail=self.tail.next\n def pop(self):\n val=self.head.value\n self.head=self.head.next\n return val\nl1=Lkqueue()\nl1.add(8)\nl1.add(7)\nl1.add(6)\nl1.add(5)\nl1.add(4)\nprint(l1.pop())\nprint(l1.pop())\nprint(l1.pop())\n\n\n\n","sub_path":"queue_link.py","file_name":"queue_link.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"572019165","text":"# Copyright 2022 The KerasCV Authors\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# https://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.\nimport tensorflow as tf\n\nfrom keras_cv import bounding_box\nfrom keras_cv.layers import preprocessing\n\nclasses = 10\n\n\nclass RandomShearTest(tf.test.TestCase):\n def test_aggressive_shear_fills_at_least_some_pixels(self):\n img_shape = (50, 50, 3)\n xs = tf.stack(\n [2 * tf.ones(img_shape), tf.ones(img_shape)],\n axis=0,\n )\n xs = tf.cast(xs, tf.float32)\n\n fill_value = 0.0\n layer = preprocessing.RandomShear(\n x_factor=(3, 3), seed=0, fill_mode=\"constant\", fill_value=fill_value\n )\n xs = layer(xs)\n\n # Some pixels should be replaced with fill value\n self.assertTrue(tf.math.reduce_any(xs[0] == fill_value))\n self.assertTrue(tf.math.reduce_any(xs[0] == 2.0))\n self.assertTrue(tf.math.reduce_any(xs[1] == fill_value))\n self.assertTrue(tf.math.reduce_any(xs[1] == 1.0))\n\n def test_return_shapes(self):\n \"\"\"test return dict keys and value pairs\"\"\"\n xs = tf.ones((2, 512, 512, 3))\n # randomly sample labels\n ys_labels = tf.random.categorical(tf.math.log([[0.5, 0.5]]), 2)\n ys_labels = tf.squeeze(ys_labels)\n ys_labels = tf.one_hot(ys_labels, classes)\n\n # randomly sample bounding boxes\n ys_bounding_boxes = tf.random.uniform((2, 3, 7), 0, 1)\n\n layer = preprocessing.RandomShear(\n x_factor=(0.1, 0.3),\n y_factor=(0.1, 0.3),\n seed=0,\n fill_mode=\"constant\",\n bounding_box_format=\"rel_xyxy\",\n )\n # mixup on labels\n outputs = layer(\n {\"images\": xs, \"labels\": ys_labels, \"bounding_boxes\": ys_bounding_boxes}\n )\n xs, ys_labels, ys_bounding_boxes = (\n outputs[\"images\"],\n outputs[\"labels\"],\n outputs[\"bounding_boxes\"],\n )\n self.assertEqual(xs.shape, [2, 512, 512, 3])\n self.assertEqual(ys_labels.shape, [2, 10])\n self.assertEqual(ys_bounding_boxes.shape, [2, 3, 7])\n\n def test_single_image_input(self):\n \"\"\"test for single image input\"\"\"\n xs = tf.ones((512, 512, 3))\n ys = tf.ones(shape=(5, 5))\n inputs = {\"images\": xs, \"bounding_boxes\": ys}\n layer = preprocessing.RandomShear(\n x_factor=(3, 3),\n seed=0,\n fill_mode=\"constant\",\n bounding_box_format=\"rel_xyxy\",\n )\n outputs = layer(inputs)\n xs, ys_bounding_boxes = (\n outputs[\"images\"],\n outputs[\"bounding_boxes\"],\n )\n self.assertEqual(xs.shape, [512, 512, 3])\n self.assertEqual(ys_bounding_boxes.shape, [5, 5])\n\n def test_area(self):\n \"\"\"test for shear bbox transformation since new bbox will be\n greater than old bbox\"\"\"\n xs = tf.ones((512, 512, 3))\n ys = tf.constant([[0.3, 0.4, 0.5, 0.6, 2], [0.9, 0.8, 1.0, 1.0, 3]])\n inputs = {\"images\": xs, \"bounding_boxes\": ys}\n layer = preprocessing.RandomShear(\n x_factor=(0.3, 0.7),\n y_factor=(0.4, 0.7),\n seed=0,\n fill_mode=\"constant\",\n bounding_box_format=\"rel_xyxy\",\n )\n outputs = layer(inputs)\n xs, ys_bounding_boxes = (\n outputs[\"images\"],\n outputs[\"bounding_boxes\"],\n )\n new_area = tf.math.multiply(\n tf.abs(tf.subtract(ys_bounding_boxes[..., 2], ys_bounding_boxes[..., 0])),\n tf.abs(tf.subtract(ys_bounding_boxes[..., 3], ys_bounding_boxes[..., 1])),\n )\n old_area = tf.math.multiply(\n tf.abs(tf.subtract(ys[..., 2], ys[..., 0])),\n tf.abs(tf.subtract(ys[..., 3], ys[..., 1])),\n )\n tf.debugging.assert_greater_equal(new_area, old_area)\n\n def test_in_tf_function(self):\n \"\"\"test for class works with tf function\"\"\"\n xs = tf.cast(\n tf.stack(\n [2 * tf.ones((4, 4, 3)), tf.ones((4, 4, 3))],\n axis=0,\n ),\n tf.float32,\n )\n ys = tf.cast(\n tf.stack(\n [\n tf.constant([[0.3, 0.4, 0.5, 0.6], [0.9, 0.8, 1.0, 1.0]]),\n tf.constant([[0.3, 0.4, 0.5, 0.6], [0.9, 0.8, 1.0, 1.0]]),\n ],\n axis=0,\n ),\n tf.float32,\n )\n ys = bounding_box.add_class_id(ys)\n layer = preprocessing.RandomShear(\n x_factor=0.2, y_factor=0.2, bounding_box_format=\"rel_xyxy\"\n )\n\n @tf.function\n def augment(x, y):\n return layer({\"images\": x, \"bounding_boxes\": y})\n\n outputs = augment(xs, ys)\n xs, ys = outputs[\"images\"], outputs[\"bounding_boxes\"]\n\n # None of the individual values should still be close to 1 or 0\n self.assertNotAllClose(xs, 1.0)\n self.assertNotAllClose(xs, 2.0)\n\n # No labels should still be close to their originals\n self.assertNotAllClose(ys, 1.0)\n self.assertNotAllClose(ys, 0.0)\n\n def test_no_augmentation(self):\n \"\"\"test for no image and bbox augmenation when x_factor,y_factor is 0,0\"\"\"\n xs = tf.cast(\n tf.stack(\n [2 * tf.ones((4, 4, 3)), tf.ones((4, 4, 3))],\n axis=0,\n ),\n tf.float32,\n )\n ys = tf.cast(\n tf.stack(\n [\n tf.constant([[0.3, 0.4, 0.5, 0.6], [0.9, 0.8, 1.0, 1.0]]),\n tf.constant([[0.3, 0.4, 0.5, 0.6], [0.9, 0.8, 1.0, 1.0]]),\n ],\n axis=0,\n ),\n tf.float32,\n )\n ys = bounding_box.add_class_id(ys)\n layer = preprocessing.RandomShear(\n x_factor=0, y_factor=0, bounding_box_format=\"rel_xyxy\"\n )\n outputs = layer({\"images\": xs, \"bounding_boxes\": ys})\n output_xs, output_ys = outputs[\"images\"], outputs[\"bounding_boxes\"]\n self.assertAllEqual(xs, output_xs)\n self.assertAllEqual(ys, output_ys)\n\n def test_bounding_box_x_augmentation(self):\n xs = tf.cast(\n tf.stack(\n [2 * tf.ones((4, 4, 3)), tf.ones((4, 4, 3))],\n axis=0,\n ),\n tf.float32,\n )\n ys = tf.cast(\n tf.stack(\n [\n tf.constant([[0.3, 0.4, 0.5, 0.6], [0.4, 0.8, 1.0, 1.0]]),\n tf.constant([[0.3, 0.4, 0.5, 0.6], [0.4, 0.8, 1.0, 1.0]]),\n ],\n axis=0,\n ),\n tf.float32,\n )\n ys = bounding_box.add_class_id(ys)\n layer = preprocessing.RandomShear(\n x_factor=0.5, y_factor=0, bounding_box_format=\"rel_xyxy\"\n )\n outputs = layer({\"images\": xs, \"bounding_boxes\": ys})\n _, output_ys = outputs[\"images\"], outputs[\"bounding_boxes\"]\n\n # assert ys are unchanged\n self.assertAllEqual(ys[..., 1], output_ys[..., 1])\n self.assertAllEqual(ys[..., 3], output_ys[..., 3])\n\n # assert xs are changed\n self.assertNotAllClose(ys[..., 0], output_ys[..., 0])\n self.assertNotAllClose(ys[..., 2], output_ys[..., 2])\n\n def test_bounding_box_y_augmentation(self):\n xs = tf.cast(\n tf.stack(\n [2 * tf.ones((4, 4, 3)), tf.ones((4, 4, 3))],\n axis=0,\n ),\n tf.float32,\n )\n ys = tf.cast(\n tf.stack(\n [\n tf.constant([[0.3, 0.4, 0.5, 0.6], [0.9, 0.2, 1.0, 1.0]]),\n tf.constant([[0.3, 0.4, 0.5, 0.6], [0.9, 0.2, 1.0, 1.0]]),\n ],\n axis=0,\n ),\n tf.float32,\n )\n ys = bounding_box.add_class_id(ys)\n layer = preprocessing.RandomShear(\n x_factor=0, y_factor=0.5, bounding_box_format=\"rel_xyxy\"\n )\n outputs = layer({\"images\": xs, \"bounding_boxes\": ys})\n _, output_ys = outputs[\"images\"], outputs[\"bounding_boxes\"]\n self.assertAllEqual(ys[..., 0], output_ys[..., 0])\n self.assertNotAllClose(ys[..., 1], output_ys[..., 1])\n self.assertAllEqual(ys[..., 2], output_ys[..., 2])\n self.assertNotAllClose(ys[..., 3], output_ys[..., 3])\n\n def test_rel_xyxy(self):\n \"\"\"test for shear bbox augmentation for relative xyxy bbox input\"\"\"\n xs = tf.cast(\n tf.stack(\n [2 * tf.ones((4, 4, 3)), tf.ones((4, 4, 3))],\n axis=0,\n ),\n tf.float32,\n )\n ys = tf.cast(\n tf.stack(\n [\n tf.constant([[0.3, 0.4, 0.5, 0.6], [0.9, 0.8, 1.0, 1.0]]),\n tf.constant([[0.3, 0.4, 0.5, 0.6], [0.9, 0.8, 1.0, 1.0]]),\n ],\n axis=0,\n ),\n tf.float32,\n )\n ys = bounding_box.add_class_id(ys)\n layer = preprocessing.RandomShear(\n x_factor=0, y_factor=0, bounding_box_format=\"rel_xyxy\"\n )\n outputs = layer({\"images\": xs, \"bounding_boxes\": ys})\n _, output_ys = outputs[\"images\"], outputs[\"bounding_boxes\"]\n self.assertAllEqual(ys, output_ys)\n\n def test_xyxy(self):\n \"\"\"test for shear bbox augmentation for xyxy format\"\"\"\n xs = tf.cast(\n tf.stack(\n [2 * tf.ones((100, 100, 3)), tf.ones((100, 100, 3))],\n axis=0,\n ),\n tf.float32,\n )\n ys = tf.cast(\n tf.stack(\n [\n tf.constant([[10.0, 20.0, 40.0, 50.0], [12.0, 22.0, 42.0, 54.0]]),\n tf.constant([[10.0, 20.0, 40.0, 50.0], [12.0, 22.0, 42.0, 54.0]]),\n ],\n axis=0,\n ),\n tf.float32,\n )\n ys = bounding_box.add_class_id(ys)\n layer = preprocessing.RandomShear(\n x_factor=0, y_factor=0, bounding_box_format=\"xyxy\"\n )\n outputs = layer({\"images\": xs, \"bounding_boxes\": ys})\n _, output_ys = outputs[\"images\"], outputs[\"bounding_boxes\"]\n self.assertAllClose(ys, output_ys)\n\n def test_clip_bounding_box(self):\n \"\"\"test for bbox clipping to image width and height\"\"\"\n xs = tf.cast(\n tf.stack(\n [2 * tf.ones((4, 4, 3)), tf.ones((4, 4, 3))],\n axis=0,\n ),\n tf.float32,\n )\n ys = tf.cast(\n tf.stack(\n [\n tf.constant([[0.0, 0.0, 40.0, 50.0], [0.0, 0.0, 42.0, 54.0]]),\n tf.constant([[0.0, 0.0, 40.0, 50.0], [0.0, 0.0, 42.0, 54.0]]),\n ],\n axis=0,\n ),\n tf.float32,\n )\n ys = bounding_box.add_class_id(ys)\n ground_truth = tf.cast(\n tf.stack(\n [\n tf.constant([[0, 0, 4, 4, 0], [0, 0, 4, 4, 0]]),\n tf.constant([[0, 0, 4, 4, 0], [0, 0, 4, 4, 0]]),\n ],\n axis=0,\n ),\n tf.float32,\n )\n layer = preprocessing.RandomShear(\n x_factor=0, y_factor=0, bounding_box_format=\"xyxy\"\n )\n outputs = layer({\"images\": xs, \"bounding_boxes\": ys})\n _, output_ys = outputs[\"images\"], outputs[\"bounding_boxes\"]\n self.assertAllEqual(ground_truth, output_ys)\n\n def test_dtype(self):\n \"\"\"test for output dtype is returned as standardize dtype\"\"\"\n xs = tf.cast(\n tf.stack(\n [2 * tf.ones((4, 4, 3)), tf.ones((4, 4, 3))],\n axis=0,\n ),\n tf.float32,\n )\n ys = tf.cast(\n tf.stack(\n [\n tf.constant([[10.0, 20.0, 40.0, 50.0], [12.0, 22.0, 42.0, 54.0]]),\n tf.constant([[10.0, 20.0, 40.0, 50.0], [12.0, 22.0, 42.0, 54.0]]),\n ],\n axis=0,\n ),\n tf.float32,\n )\n ys = bounding_box.add_class_id(ys)\n layer = preprocessing.RandomShear(\n x_factor=0, y_factor=0, bounding_box_format=\"xyxy\"\n )\n outputs = layer({\"images\": xs, \"bounding_boxes\": ys})\n _, output_ys = outputs[\"images\"], outputs[\"bounding_boxes\"]\n self.assertEqual(layer.compute_dtype, output_ys.dtype)\n\n def test_output_values(self):\n \"\"\"test to verify augmented bounding box output coordinate\"\"\"\n xs = tf.cast(\n tf.stack(\n [2 * tf.ones((100, 100, 3)), tf.zeros((100, 100, 3))],\n axis=0,\n ),\n tf.float32,\n )\n ys = tf.cast(\n tf.stack(\n [\n tf.constant([[10.0, 20.0, 40.0, 50.0], [12.0, 22.0, 42.0, 54.0]]),\n tf.constant([[10.0, 20.0, 40.0, 50.0], [12.0, 22.0, 42.0, 54.0]]),\n ],\n axis=0,\n ),\n tf.float32,\n )\n ys = bounding_box.add_class_id(ys)\n true_ys = tf.cast(\n tf.stack(\n [\n tf.constant(\n [[7.60, 20.58, 39.04, 53.02, 0], [9.4, 22.7, 40.9, 57.1, 0]]\n ),\n tf.constant(\n [[13.6, 20.9, 49.2, 53.5, 0], [16.0, 23.1, 51.9, 57.7, 0]]\n ),\n ],\n axis=0,\n ),\n tf.float32,\n )\n layer = preprocessing.RandomShear(\n x_factor=0.2, y_factor=0.2, bounding_box_format=\"xyxy\"\n )\n outputs = layer({\"images\": xs, \"bounding_boxes\": ys})\n _, output_ys = outputs[\"images\"], outputs[\"bounding_boxes\"]\n self.assertAllClose(true_ys, output_ys, rtol=1e-02, atol=1e-03)\n","sub_path":"keras_cv/layers/preprocessing/random_shear_test.py","file_name":"random_shear_test.py","file_ext":"py","file_size_in_byte":14292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"66891402","text":"#! /usr/bin/env python\n\n# Imports\n# Flask\nfrom flask import Flask, render_template, request, redirect, jsonify\nfrom flask import url_for, flash, make_response, abort\n# session already used for database session/SQLAlchemy:\n# Note - (flask) session works like a dictionary\nfrom flask import session as login_session\n\n# Database\nfrom sqlalchemy import create_engine, asc\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, Restaurant, MenuItem, User\n\n# General\nimport httplib2\nimport json\n# Extra for nice debugging output:\nfrom pprint import pprint\n#\nimport os\nimport random\nimport requests\nimport string\n\n# OAuth\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.client import FlowExchangeError\n\n# Flask setup\napp = Flask(__name__)\n\n#Connect to Database and create database session\nengine = create_engine('sqlite:///restaurantmenuwithusers.db')\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n# OAuth setup\nCLIENT_ID = json.loads(open('client_secrets.json', 'r').read())['web']['client_id']\n## print('Debug/CLIENT_ID:')\n## pprint(CLIENT_ID)\nAPPLICATION_NAME = \"Restaurant Menu App\"\n\n\n# Debugging - show diff of two dictionaries\ndef showDictDiff(d1, d2):\n # Convert the dictionaries to lists - need to combine sorted keys and values:\n l1 = [str(k) + ': ' + str(d1[k]) for k in sorted(d1.keys())]\n l2 = [str(k) + ': ' + str(d2[k]) for k in sorted(d2.keys())]\n\n # Find the difference with sets\n result = list(set(l1) ^ set(l2)) # Symmetric difference\n # result = list(set(l1).symmetric_difference(set(l2)))\n\n # Display sorted result\n for element in sorted(result):\n print(element)\n\n\n# Create a state token to prevent request forgery\n# Store it in the session cookie for later validation\n@app.route('/login')\ndef showLogin():\n # User Auth\n print('-' * 80)\n print('Debug/showLogin entered, request = {}'.format(request))\n print('-' * 80)\n state = ''.join(random.choice(string.ascii_uppercase + string.digits)\n for x in xrange(32))\n # Flask session - we're adding the state variable to the user session cookie\n login_session['state'] = state\n\n # Testing:\n # return 'The current session state is {}'.format(login_session['state'])\n\n # Debugging\n print('Debug/showLogin/env check - login_session:')\n pprint(login_session)\n print('-=' * 10)\n\n # This template renders a Google Signin Button\n # When the user clicks the button, he is authenticated to Google\n # Google will check if the user has authorized sharing info with this app\n # Not yet = Google prompts user\n # * Note - if user declines, Google sends back error\n # Yes = Google sends authorization code to JavaScript embedded in this page,\n # JS callback function then POSTs code to /gconnect\n return render_template('login.html', STATE=state)\n\n\n@app.route('/gconnect', methods=['POST'])\ndef gconnect():\n # Handle Google auth callback\n print('-' * 80)\n print('Debug/gconnect entered, request = {}'.format(request))\n print('-' * 80)\n # Validate state token - does state query parameter match state stored in\n # session cookie?\n if request.args.get('state') != login_session['state']:\n print('Debug/State check failed!')\n response = make_response(json.dumps('Invalid state parameter.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Obtain authorization code - request.data is inbound data in a mimetype\n # flask doesn't understand delivered as a string\n # Note - not sure this is the best way to accomplish this, may want to\n # check out headers and Google code examples...\n code = request.data\n try:\n # Initialize an oauth2client flow object - goal is to upgrade\n # authorization code into a credentials object\n oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='',\n redirect_uri='postmessage')\n # Debugging\n print('Debug/gconnect/oauth_flow - OAuth2Credentials Object Attributes:\\n{}')\n showDictDiff(oauth_flow.__dict__, {})\n print('-=' * 10)\n\n # This exchanges authorization code from above for access token\n # Credentials is a flow object (same as above) and holds both the access\n # and refresh tokens - designed to be used with httplib2.Http object\n credentials = oauth_flow.step2_exchange(code)\n # Debugging - show what's changed in the flow object after this step:\n print('Debug/gconnect/credentials - OAuth2Credentials Object Attributes:\\n{}')\n showDictDiff(oauth_flow.__dict__, credentials.__dict__)\n print('-=' * 10)\n except FlowExchangeError:\n print('Debug/gconnect/obtain auth code failed!')\n response = make_response(json.dumps('Failed to upgrade the authorization code.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Check that the access token is valid\n access_token = credentials.access_token\n url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={}'.format(access_token))\n h = httplib2.Http()\n result = json.loads(h.request(url, 'GET')[1])\n # If there was an error in access token info, abort\n if result.get('error') is not None:\n print('Debug/gconnect - error retrieving access token!')\n response = make_response(json.dumps(result.get('error')), 500)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is used for the intended user\n gplus_id = credentials.id_token['sub']\n if result['user_id'] != gplus_id:\n print(\"Debug/gconnect/access token ID doesn't match given user ID!\")\n response = make_response(json.dumps(\"Token's user ID doesn't match given user ID.\"), 401)\n response.header['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is valid for this app\n if result['issued_to'] != CLIENT_ID:\n print(\"Debug/gconnect/access token ID doesn't match up with app's!\")\n response = make_response(json.dumps(\"Token's client ID doesn't match app's.\"), 401)\n print(\"Token's client ID doesn't match app's.\")\n response.headers['Content-Type'] = 'application/json'\n return response\n\n stored_credentials = login_session.get('credentials')\n stored_gplus_id = login_session.get('gplus_id')\n # Debugging - check login_session (session cookie)\n print('Debug/gconnect/env check{midpoint}- login_session:')\n pprint(login_session)\n print('-=' * 10)\n\n if stored_credentials is not None and gplus_id == stored_gplus_id:\n print('Debug/gconnect/current user already connected!')\n response = make_response(json.dumps('Current user is already connected.'), 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n \n # Store the access token in the session for later use\n # Should it be this? login_session['credentials'] = credentials.access_token\n login_session['credentials'] = credentials\n login_session['gplus_id'] = gplus_id\n\n # Get user info\n userinfo_url = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n params = {'access_token': credentials.access_token, 'alt': 'json'}\n answer = requests.get(userinfo_url, params=params)\n\n data = answer.json()\n login_session['provider'] = 'Google'\n login_session['username'] = data['name']\n login_session['picture'] = data['picture']\n login_session['email'] = data['email']\n\n # Check if user in database and add if not\n user_id = getUserId(login_session['email'])\n if not user_id:\n user_id = createUser(login_session)\n login_session['user_id'] = user_id\n\n output = '

Welcome, {}!

'.format(login_session['username'])\n output += (''.format(\n login_session['picture'])\n )\n flash(\"You are now logged in as {}\".format(login_session['username']))\n ## print('done!')\n\n # Debugging - check login_session (session cookie)\n print('Debug/gconnect/env check{end}- login_session:')\n pprint(login_session)\n print('-=' * 10)\n print('OAuth2Credentials Object Attributes:')\n pprint(credentials.__dict__)\n print('-=' * 10)\n\n return output\n\n\n# Disconnect - Revoke a current user's token and reset their login_session\n@app.route('/gdisconnect')\ndef gdisconnect():\n # User Logout\n print('-' * 80)\n print('Debug/gdisconnect entered, request = {}'.format(request))\n print('-' * 80)\n # Only disconnect a connected user\n credentials = login_session.get('credentials')\n\n # Debugging - check login_session (session cookie)\n print('Debug/gdisconnect/env check{beginning}- login_session:')\n pprint(login_session)\n print('-=' * 10)\n if credentials:\n print('OAuth2Credentials Object Attributes:')\n pprint(credentials.__dict__)\n print('-=' * 10)\n\n # Debugging\n print('User name is {}'.format(login_session['username']))\n if credentials is None:\n print('Debug/gdisconnect/current user not connected!')\n response = make_response(json.dumps('Current user not connected.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Execute HTTP GET request to revoke current token\n access_token = credentials.access_token\n url = 'https://accounts.google.com/o/oauth2/revoke?token={}'.format(access_token)\n h = httplib2.Http()\n result = h.request(url, 'GET')[0]\n\n if result['status'] == '200':\n # Reset user's session\n # print('Debug/gdisconnect/resetting user session...')\n\n # This functionality moved to /disconnect\n # del login_session['credentials']\n # From github repo but don't see this key in object\n # del login_session['access_token']\n # del login_session['gplus_id']\n # del login_session['username']\n # del login_session['email']\n # del login_session['picture']\n\n # Debugging - check login_session (session cookie)\n # print('Debug/gdisconnect/env check{end}- login_session:')\n # pprint(login_session)\n # print('-=' * 10)\n\n # response = make_response(json.dumps('Successfully disconnected user.'), 200)\n # response.headers['Content-Type'] = 'application/json'\n # return response\n\n return 'You have been logged out.'\n else:\n # For whatever reason, the given token was invalid\n print('Debug/gdisconnect/invalid token!')\n\n # Debugging - check login_session (session cookie)\n print('Debug/gdisconnect/env check{end}- login_session:')\n pprint(login_session)\n print('-=' * 10)\n\n response = make_response(json.dumps('Failed to revoke token for given user.'), 400)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n\n# Facebook Login\n@app.route('/fbconnect', methods=['POST'])\ndef fbconnect():\n if request.args.get('state') != login_session['state']:\n response = make_response(json.dumps('Invalid state parameter.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n access_token = request.data\n # Debugging:\n print('Access token received: {}'.format(access_token))\n\n # Exchange client token for long-lived server-side token with GET\n app_id = json.loads(open('fbclient_secrets.json', 'r').read())['web']['app_id']\n app_secret = json.loads(open('fbclient_secrets.json', 'r').read())['web']['app_secret']\n url = ('https://graph.facebook.com/v2.9/oauth/access_token?grant_type=fb_exchange_token'\n '&client_id={}&client_secret={}&fb_exchange_token={}'.format(app_id, app_secret,\n access_token))\n h = httplib2.Http()\n result = h.request(url, 'GET')[1]\n # Debugging:\n print('Result received from token exchange: {}'.format(result))\n\n data = json.loads(result)\n # Use token to get user info from API - including picture which is now part of the\n # public profile\n url = ('https://graph.facebook.com/v2.9/me?access_token={}&fields=name,id,email'\n ',picture'.format(data['access_token']))\n h = httplib2.Http()\n result = h.request(url, 'GET')[1]\n # Debugging\n print('URL sent for API access: {}'.format(url))\n print('API JSON result: {}'.format(result))\n\n data = json.loads(result)\n login_session['provider'] = 'Facebook'\n login_session['username'] = data['name']\n login_session['email'] = data['email']\n login_session['facebook_id'] = data['id']\n login_session['picture'] = data['picture']['data']['url']\n # The token must be stored in the login_session in order to properly logout\n login_session['access_token'] = access_token\n\n # Get user picture - requires separate API call (not anymore...)\n # url = ('https://graph.facebook.com/v2.8/me/picture?access_token={}&redirect=0&height=200'\n # '&width=200'.format(token))\n # h = httplib2.Http()\n # result = h.request(url, 'GET')[1]\n # data = json.loads(result)\n # login_session['picture'] = data['data']['url']\n\n # Check if user exists in DB and add if not\n user_id = getUserId(login_session['email'])\n if not user_id:\n user_id = createUser(login_session)\n login_session['user_id'] = user_id\n\n output = '

Welcome, {}!

'.format(login_session['username'])\n output += (''.format(\n login_session['picture']))\n\n flash('Now logged in as {}'.format(login_session['username']))\n return output\n\n\n@app.route('/fbdisconnect')\ndef fbdisconnect():\n facebook_id = login_session['facebook_id']\n\n # The access token must me included to successfully logout\n access_token = login_session['access_token']\n\n url = 'https://graph.facebook.com/{}/permissions?access_token={}'.format(facebook_id,\n access_token)\n h = httplib2.Http()\n result = h.request(url, 'DELETE')[1]\n\n # Moved to disconnect function\n # Clear login session\n # del login_session['username']\n # del login_session['email']\n # del login_session['picture']\n # del login_session['user_id']\n # del login_session['facebook_id']\n\n return 'You have been logged out'\n\n\n# Disconnect based on provider\n@app.route('/disconnect')\ndef disconnect():\n # Debug\n print('Debug/disconnect/enter - login_session object attributes:')\n pprint(login_session)\n if 'credentials' in login_session:\n print('-=' * 10)\n showDictDiff(login_session['credentials'].__dict__, {})\n print('-=' * 10)\n\n if 'provider' in login_session:\n if login_session['provider'] == 'Google':\n gdisconnect()\n del login_session['gplus_id']\n del login_session['credentials']\n elif login_session['provider'] == 'Facebook':\n fbdisconnect()\n del login_session['facebook_id']\n\n # Clear out login session\n del login_session['username']\n del login_session['email']\n del login_session['picture']\n del login_session['user_id']\n del login_session['provider']\n\n flash('You have successfully been logged out.')\n\n print('Debug/disconnect/exit - login_session object attributes:')\n pprint(login_session)\n if 'credentials' in login_session:\n print('-=' * 10)\n showDictDiff(login_session['credentials'].__dict__, {})\n print('-=' * 10)\n\n return redirect(url_for('showRestaurants'))\n else:\n flash('You were not logged in.')\n\n print('Debug/disconnect/exit - login_session object attributes:')\n pprint(login_session)\n if 'credentials' in login_session:\n print('-=' * 10)\n showDictDiff(login_session['credentials'].__dict__, {})\n print('-=' * 10)\n\n return redirect(url_for('showRestaurants'))\n\n\n#JSON APIs to view Restaurant Information\n@app.route('/restaurant//menu/JSON')\ndef restaurantMenuJSON(restaurant_id):\n # Public - authentication not required\n restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\n items = session.query(MenuItem).filter_by(restaurant_id=restaurant_id).all()\n return jsonify(MenuItems=[i.serialize for i in items])\n\n\n@app.route('/restaurant//menu//JSON')\ndef menuItemJSON(restaurant_id, menu_id):\n # Public - authentication not required\n Menu_Item = session.query(MenuItem).filter_by(id=menu_id).one()\n return jsonify(Menu_Item = Menu_Item.serialize)\n\n\n@app.route('/restaurant/JSON')\ndef restaurantsJSON():\n # Public - authentication not required\n restaurants = session.query(Restaurant).all()\n return jsonify(restaurants=[r.serialize for r in restaurants])\n\n\n#Show all restaurants\n@app.route('/')\n@app.route('/restaurant/')\ndef showRestaurants():\n # Public - authentication not required\n restaurants = session.query(Restaurant).order_by(asc(Restaurant.name))\n\n # If authenticated user present show MACD page\n if 'username' in login_session:\n return render_template('restaurants.html', restaurants=restaurants)\n else:\n # Otherwise show public page (no MACD buttons)\n return render_template('publicrestaurants.html', restaurants=restaurants)\n\n\n#Create a new restaurant\n@app.route('/restaurant/new/', methods=['GET','POST'])\ndef newRestaurant():\n # Must be authenticated\n if 'username' not in login_session:\n return redirect('/login')\n\n if request.method == 'POST':\n newRestaurant = Restaurant(name=request.form['name'], user_id=login_session['user_id'])\n session.add(newRestaurant)\n flash('New Restaurant %s Successfully Created' % newRestaurant.name)\n session.commit()\n return redirect(url_for('showRestaurants'))\n else:\n return render_template('newRestaurant.html')\n\n\n#Edit a restaurant\n@app.route('/restaurant//edit/', methods=['GET', 'POST'])\ndef editRestaurant(restaurant_id):\n # Must be authenticated\n if 'username' not in login_session:\n return redirect('/login')\n\n restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\n if getUserId(login_session.get('email')) != restaurant.user_id:\n abort(403)\n\n editedRestaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\n if request.method == 'POST':\n if request.form['name']:\n editedRestaurant.name = request.form['name']\n flash('Restaurant Successfully Edited %s' % editedRestaurant.name)\n return redirect(url_for('showRestaurants'))\n else:\n return render_template('editRestaurant.html', restaurant=editedRestaurant)\n\n\n#Delete a restaurant\n@app.route('/restaurant//delete/', methods=['GET','POST'])\ndef deleteRestaurant(restaurant_id):\n # Must be authenticated\n if 'username' not in login_session:\n return redirect('/login')\n\n restaurantToDelete = session.query(Restaurant).filter_by(id=restaurant_id).one()\n if getUserId(login_session.get('email')) != restaurantToDelete.user_id:\n # abort(403)\n # Another option:\n return '''\n \n '''.format(restaurant_id)\n\n if request.method == 'POST':\n session.delete(restaurantToDelete)\n flash('%s Successfully Deleted' % restaurantToDelete.name)\n session.commit()\n return redirect(url_for('showRestaurants', restaurant_id=restaurant_id))\n else:\n return render_template('deleteRestaurant.html',restaurant=restaurantToDelete)\n\n\n#Show a restaurant menu\n@app.route('/restaurant//')\n@app.route('/restaurant//menu/')\ndef showMenu(restaurant_id):\n # Public - authentication not required\n restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\n items = session.query(MenuItem).filter_by(restaurant_id=restaurant_id).all()\n creator = getUserInfo(restaurant.user_id)\n\n # A couple of ways to handle this\n # 1) Only restaurant creator can alter menu\n # 2) Any authenticated user can create menu items, but only item creator can do MACD stuff\n #\n # If authenticated user present and user is restaurant creator, show MACD page (option 1)\n # if 'email' in login_session and getUserId(login_session['email']) == restaurant.user_id:\n # If authenticated user, show MACD page (option 2)\n if 'username' in login_session:\n return render_template('menu.html', items=items, restaurant=restaurant, creator=creator)\n\n # Otherwise show public page (no MACD buttons)\n return render_template('publicmenu.html', items=items, restaurant=restaurant,\n creator=creator)\n \n\n# Create a new menu item\n@app.route('/restaurant//menu/new/',methods=['GET','POST'])\ndef newMenuItem(restaurant_id):\n # Must be authenticated\n if 'username' not in login_session:\n return redirect('/login')\n\n # A couple of ways to handle this\n # 1) Only restaurant creator can alter menu\n # 2) Any authenticated user can create menu items, but only item creator can do MACD stuff\n #\n # Option 1\n # restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\n # if getUserId(login_session.get('email')) != restaurant.user_id:\n # abort(403)\n\n if request.method == 'POST':\n newItem = MenuItem(name=request.form['name'], description=\n request.form['description'], price=request.form['price'],\n course=request.form['course'], restaurant_id=restaurant_id,\n user_id=restaurant.user_id)\n session.add(newItem)\n session.commit()\n flash('New Menu %s Item Successfully Created' % (newItem.name))\n return redirect(url_for('showMenu', restaurant_id=restaurant_id))\n else:\n return render_template('newmenuitem.html', restaurant_id=restaurant_id)\n\n\n#Edit a menu item\n@app.route('/restaurant//menu//edit',\n methods=['GET','POST'])\ndef editMenuItem(restaurant_id, menu_id):\n # Must be authenticated\n if 'username' not in login_session:\n return redirect('/login')\n\n # A couple of ways to handle this\n # 1) Only restaurant creator can alter menu\n # 2) Any authenticated user can create menu items, but only item creator can do MACD stuff\n #\n editedItem = session.query(MenuItem).filter_by(id=menu_id).one()\n restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\n # Option 1\n # if getUserId(login_session.get('email')) != restaurant.user_id:\n # Optioon 2\n if getUserId(login_session.get('email')) != editedItem.user_id:\n abort(403)\n\n if request.method == 'POST':\n if request.form['name']:\n editedItem.name = request.form['name']\n if request.form['description']:\n editedItem.description = request.form['description']\n if request.form['price']:\n editedItem.price = request.form['price']\n if request.form['course']:\n editedItem.course = request.form['course']\n session.add(editedItem)\n session.commit() \n flash('Menu Item Successfully Edited')\n return redirect(url_for('showMenu', restaurant_id=restaurant_id))\n else:\n return render_template('editmenuitem.html', restaurant_id=restaurant_id,\n menu_id=menu_id, item=editedItem)\n\n\n# Delete a menu item\n@app.route('/restaurant//menu//delete',\n methods=['GET','POST'])\ndef deleteMenuItem(restaurant_id, menu_id):\n # Must be authenticated\n if 'username' not in login_session:\n return redirect('/login')\n\n # A couple of ways to handle this\n # 1) Only restaurant creator can alter menu\n # 2) Any authenticated user can create menu items, but only item creator can do MACD stuff\n #\n itemToDelete = session.query(MenuItem).filter_by(id=menu_id).one() \n restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\n # Option 1\n # if getUserId(login_session.get('email')) != restaurant.user_id:\n # Option 2\n if getUserId(login_session.get('email')) != itemToDelete.user_id:\n abort(403)\n\n if request.method == 'POST':\n session.delete(itemToDelete)\n session.commit()\n flash('Menu Item Successfully Deleted')\n return redirect(url_for('showMenu', restaurant_id=restaurant_id))\n else:\n return render_template('deleteMenuItem.html', item=itemToDelete)\n\n\ndef createUser(login_session):\n newUser = User(name=login_session['username'], email=login_session['email'],\n picture=login_session['picture'])\n # Add to database\n session.add(newUser)\n session.commit()\n\n user = session.query(User).filter_by(email=login_session['email']).one()\n return user.id\n\n\ndef getUserInfo(user_id):\n user = session.query(User).filter_by(id=user_id).one()\n return user\n\n\ndef getUserId(email):\n try:\n user = session.query(User).filter_by(email=email).one()\n return user.id\n except:\n return None\n\n\n# Debugging\n# Capture initial global environment - last thing before start program so all\n# functions declared:\ninitial_globals = set(globals())\n\n\nif __name__ == '__main__':\n app.secret_key = os.urandom(30)\n app.debug = True\n app.run(host='0.0.0.0', port=5000)\n\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":26219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"536747844","text":"'''\nCreated on 04/06/2015\n\n@author Eduardo\n'''\n\n# CONSTANTs\nGLOBAL_DICT = 0\n\n#END constants\n\n\n'''***************************************************************************************\nFUNÇÃO: countWordInDictionary\nDESCRIÇÃO:\n Verifica a presen de uma palavra no dicionário global e do atual documento,\n se já estiver presente incrementa o valor, se não acrescenta aos dicionários em que não\n há a palavra como chave.\nRECEBE:\n word: String ser contabilizada e verificada\n dictionary_list: Lista de dicionários de cada documento\n curr_document_index: Iterador sobre a lista de documentos\nRETORNA: \n Por referência, retorna o a lista dicionário alterada\n***************************************************************************************'''\n'''\nExemplo para se acrescentar uma nova entrada ao dicionário: \n dicionario[ 'novachave' ] = valor \n'''\ndef countWordInDictionary( word , dictionary_list , curr_document_index ):\n #Se a palavra já estiver no dicionário incrementa se não, inicializa com 1\n if( word in dictionary_list[GLOBAL_DICT] ):\n #Incrementa a quantidade de ocorrências para aquela palavra no dicionário global\n dictionary_list[GLOBAL_DICT][ word ] += 1\n #Agora deve-se verificar se a palavra já ocorreu noo documento atual\n if( word in dictionary_list[curr_document_index] ):\n dictionary_list[curr_document_index][word] += 1\n #Se a palavra não estiver no dicionário do documento atual ela deve ser acrescentada\n else:\n dictionary_list[curr_document_index][word] = 1\n #END if( word in dictionary_list[curr_document] ):\n #END if( word in dictionary_list[GLOBAL_DICT] )\n #Caso a palavra não exista no dicionário global ela deve ser acrescentada no global e no atual\n else:\n dictionary_list[GLOBAL_DICT][word] = 1\n dictionary_list[curr_document_index][word] = 1\n #END if( word in dictionary_list[GLOBAL_DICT] )\n#END verifyWord( word in dicionario )\n\ndef start():\n list_documents = []\n dictionary_list = { } # inicializa o dicionário\n \n for document_index in range( 1 , 12500 ):\n ''' docpos(i) corresponde ao nome do documento que será contabilizado '''\n path_document = \"../../../trb_SI_dataset/part1/pos/docpos(\" + str(document_index) + \")\" #Path no formato Linux\n #path_document = \"..\\..\\..\\trb_SI_dataset/part1/pos/docpos(\" + str(document_index) + \")\" #Path no formato Windows\n list_documents.append( \"{}\" )\n try:\n with open( path_document , 'r' , encoding = 'UTF8') as document:\n #Para cada linha do documento\n for each_line in document.readlines():\n #Cada palavra da linha é separado em um elemento da lista words_line\n words_line = each_line.split()\n #Para cada palavra da linha\n for each_word in words_line:\n #DICIONÁRIOS passados como paparâmetros se mantêm alterados após retorno da função\n countWordInDictionary( each_word , dictionary_list, document_index )\n #END for each_word in words_line\n #END for each_line in document.readlines()\n #END with open( path_document , 'r' , encoding = 'UTF8') as document\n except IOError as ioerr:\n print(ioerr)\n #END try\n #END for \n#END start()\n\n\n#INÍCIO DA EXECUÇÃO DO SCRIPT\nstart()\n\n\n","sub_path":"src/training/countingWords.py","file_name":"countingWords.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"357481454","text":"import tweepy,sys,jsonpickle\nimport time\nimport json\n \nconsumer_key = 'APANIELEdB9eOX4Np68AkuSY7'\nconsumer_secret = 'ivG58O29iF0eetATQrjPwEHz4rKLu3D8C4Cod5jqtguZ4S8rrG'\n \nqry='@sandiuno'\nmaxTweets = 4000 # Isi sembarang nilai sesuai kebutuhan anda\ntweetsPerQry = 100 # Jangan isi lebih dari 100, ndak boleh oleh Twitter\nfName=qry+'_'+time.strftime('%Y%m%d-%H%M%S')+'.json' # Nama File hasil Crawling\n \nauth = tweepy.AppAuthHandler(consumer_key,consumer_secret)\napi = tweepy.API(auth, wait_on_rate_limit=True,wait_on_rate_limit_notify=True)\nif (not api):\n sys.exit('Autentikasi gagal, mohon cek \"Consumer Key\" & \"Consumer Secret\" Twitter anda')\n \nsinceId=None;max_id=-1;tweetCount=0\nprint(\"Mulai mengunduh maksimum {0} tweets\".format(maxTweets))\nwith open(fName,'w') as f:\n f.write(\"[\")\n while tweetCount < maxTweets:\n try:\n if (max_id <= 0):\n if (not sinceId):\n new_tweets=api.search(q=qry,count=tweetsPerQry)\n else:\n new_tweets=api.search(q=qry,count=tweetsPerQry,since_id=sinceId)\n else:\n if (not sinceId):\n new_tweets=api.search(q=qry,count=tweetsPerQry,max_id=str(max_id - 1))\n else:\n new_tweets=api.search(q=qry,count=tweetsPerQry,max_id=str(max_id - 1),since_id=sinceId)\n if not new_tweets:\n print('Tidak ada lagi Tweet ditemukan dengan Query=\"{0}\"'.format(qry))\n break\n\n if tweetCount > 0:\n f.write(\",\\n\")\n for i,tweet in enumerate(new_tweets):\n data_tweet = dict()\n if i>0:\n f.write(\",\\n\")\n data_tweet[\"isi\"] = tweet._json[\"text\"]\n data_tweet[\"tanggal\"] = tweet._json[\"created_at\"]\n data_tweet[\"id_user\"] = tweet._json[\"user\"][\"id\"] \n data_tweet[\"akun\"] = qry\n data_tweet[\"sentimen\"] = \"something\"\n f.write(jsonpickle.encode(data_tweet,unpicklable=False))\n tweetCount+=len(new_tweets)\n sys.stdout.write(\"\\r\");sys.stdout.write(\"Jumlah Tweets telah tersimpan: %.0f\" %tweetCount);sys.stdout.flush()\n max_id=new_tweets[-1].id\n except tweepy.TweepError as e:\n print(\"some error : \" + str(e));break # Aya error, keluar\n f.write(\"]\")\nprint ('\\nSelesai! {0} tweets tersimpan di \"{1}\"'.format(tweetCount,fName))","sub_path":"stream_sandiuno.py","file_name":"stream_sandiuno.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"333389326","text":"from tkinter import *\nimport time\nimport serial\nfrom PIL import ImageTk,Image\nfrom PIL.ImageTk import PhotoImage\nimport math\nimport random\n\nclass air_glove:\n def __init__(self):\n self.port=''\n self.x=0\n self.y=0\n self.z=0\n self.paired=False\n self.lastCoordinates=''\n \n\n #step1\n def pair_glove(self):\n self.port= serial.Serial('/dev/cu.wchusbserial1410', 9600)\n #self.port= serial.Serial('/dev/tty.HC-06-DevB', 9600)\n print('connected via USB')\n self.paired=True\n \n def read_position(self):\n if self.paired==True:\n try:\n coordinates=self.port.readline().decode('utf-8')\n x=int(re.search('x:[+,-]*(\\d)*',coordinates).group(0).strip('x:'))\n y=int(re.search('y:[+,-]*(\\d)*',coordinates).group(0).strip('y:'))\n z=int(re.search('z:[+,-]*(\\d)*',coordinates).group(0).strip('z:'))\n coordinates=[x,y,z]\n return coordinates\n except :\n print(\"crash\")\n #return self.lastCoordinates\n return [0,0,0]\n else:\n return [0,0,0]\n\n\nclass Throw:\n def __init__(self):\n self.throwCount=0\n\n def resetThowCount(self):\n self.throwCount=0\n\n def incrementthrowcount(self):\n self.throwCount+=1\n \n def can_throw_ball(self):\n if self.throwCount==0:\n return True\n else:\n return False\n \n \n \nclass air_mouse:\n def __init__(self):\n self.points=0\n self.attempts=0\n self.glove=air_glove()\n #self.glove.pair_glove()\n self.root=Tk()\n self.canvas=Canvas(master=self.root, width=1200,height=750, background='white')\n self.canvas.grid(row=0,column=0)\n self.x=500\n self.y=500\n self.z=0\n self.angle=90\n self.board = PhotoImage(file=\"board.gif\")\n self.ball = PhotoImage(file=\"handball.gif\")\n self.score=PhotoImage(file=\"score.gif\")\n self.canvas.bind('',self.coordinates)\n self.throw=Throw()\n self.next()\n\n def coordinates(self,event):\n coord='x:{} y:{}'.format(event.x,event.y)\n print(coord)\n\n def draw_circle(self,x,y,tag=''):\n radius=50\n self.point=self.canvas.create_oval(x,y,x+radius,y+radius,fill='#ff6600', tags=tag)\n \n def throw_power(self):\n force=230-self.z\n if force>=230:\n force=force-90\n self.canvas.create_rectangle(1030,30, 1040, 290, fill=\"#e88c30\",outline=\"white\")\n air_mouse.draw_circle(self,1010,force)\n \n def player_throw(self,x,y):\n if y>=560:\n self.throw. incrementthrowcount()\n return True\n else:\n return False\n\n def throw_ball(self,x,y,distance=0):\n\n if y<=40:\n self.throw.resetThowCount()\n if x>=445 and x<=735:\n self.drop_ball(x,y)\n if x>=540 and x<=625 and y<112:\n self.points+=1\n elif y>=40:\n y-=20\n air_mouse.draw_circle(self,x,y,\"ball\")\n self.root.after(1,self.throw_ball,x,y)\n\n def drop_ball(self,x,y):\n if y<=285:\n y+=20\n air_mouse.draw_circle(self,x,y,\"ball\")\n self.root.after(1,self.drop_ball,x,y)\n \n \n def update_c(self):\n self.canvas.delete(ALL)\n air_mouse.game_stats(self)\n self.throw_power()\n self.canvas.create_image(10,10, anchor=NW, image=self.score)\n self.canvas.create_line(297, 235, 89, 515, fill=\"black\")\n self.canvas.create_line(892, 235, 1084, 518, fill=\"black\")\n self.canvas.create_image(450,7, anchor=NW, image=self.board)\n if self.player_throw(self.x,self.y) and self.throw.throwCount<2:\n self.throw_power()\n self.throw_ball(self.x,self.y,500)\n self.attempts+=1\n self.canvas.create_image(self.x,self.y, anchor=NW, image=self.ball)\n\n\n def bounding_box(self,x,y):\n if x<=0:\n x=0\n if x>=1200-50:\n x=1200-50\n if y<=550:\n y=550\n if y>=750-50:\n y=750-50\n return (x,y)\n\n def glove_control(self):\n coord=self.glove.read_position()\n x=coord[0]+ self.x\n y=coord[1]+ self.y\n x_y_=air_mouse.bounding_box(self,x,y)\n self.x=x_y_[0]\n self.y=x_y_[1]\n self.z=coord[2]\n self.angle=math.degrees(math.atan2(coord[2],coord[1]))\n #print(\"Angle:\",self.angle)\n\n def game_stats(self):\n score_display=' Shots: {}'.format(self.points)\n self.canvas.create_text(31,100,text=score_display,tags='score')\n attempts_display=' Attempts: {}'.format(self.attempts)\n self.canvas.create_text(40,118,text=attempts_display,tags='attempts')\n \n def next(self):\n air_mouse.glove_control(self)\n air_mouse.update_c(self)\n self.root.after(1,air_mouse.next,self )\n\nif __name__=='__main__': \n test=air_mouse()\n test.glove.pair_glove()\n test.root.mainloop()\n \n\n","sub_path":"airball.py","file_name":"airball.py","file_ext":"py","file_size_in_byte":5173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"164897263","text":"import unittest\n\nfrom parser import parse_line\n\n\nclass NginxParserTestCase(unittest.TestCase):\n def test_parse_line(self):\n with open('nginx-access.test') as f:\n first_line = f.readline()\n line = parse_line(first_line)\n self.assertEqual('206.146.15.243', line['ip'])\n self.assertEqual('2016-03-07T13:52:51', line['datetime'])\n self.assertEqual('2016-03-07', line['date'])\n self.assertEqual('iPhone / iOS 9.2 / Mobile Safari 9', line['user-agent'].__str__())\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_nginx_parser.py","file_name":"test_nginx_parser.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"100620450","text":"import time\n\nstart_time = time.time()\n\ncount = 0\n\ndef plus_two(numerator,denominator):\n\treturn ((2*denominator+numerator),denominator)\n\n\nfor i in range(1000):\n\tfraction = (2,1)\n\tfor l in range(i):\n\t\tfraction = plus_two(fraction[1],fraction[0])\n\tfraction = ((fraction[1]+fraction[0]),fraction[0])\n\tif len(str(fraction[0]))>len(str(fraction[1])):\n\t\tcount+=1\n\nprint ('Answer: ' +str(count) + '\\t\\t\\t' +str(time.time()-start_time) +'s')\n\n","sub_path":"57.py","file_name":"57.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"192649580","text":"class Solution:\n \"\"\"\n @param graph: a 2D array\n @return: all possible paths from node 0 to node N-1\n \"\"\"\n\n def allPathsSourceTarget(self, graph):\n # Write your code here\n n = len(graph)\n\n def solve(node):\n if node == n - 1: return [[n - 1]]\n ans = []\n for nei in graph[node]:\n for path in solve(nei):\n ans.append([node] + path)\n return ans\n\n return solve(0)\n","sub_path":"lintcode/1020-all-paths-from-source-to-target.py","file_name":"1020-all-paths-from-source-to-target.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"326822956","text":"\n\n#calss header\nclass _ANORAK():\n\tdef __init__(self,): \n\t\tself.name = \"ANORAK\"\n\t\tself.definitions = [u'a short coat that protects the wearer against wind, rain, and cold weather, usually with a part for covering the head', u'a boring person who is too interested in the details of a hobby and finds it difficult to meet and spend time with other people: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_anorak.py","file_name":"_anorak.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"288067722","text":"#!/usr/bin/env python\n\n# XPC\nimport xpc.xpc as xpc \nfrom state_reader import StateReader\nfrom command_sender import CommandSender\n\n#ROS\nimport rospy \n\n\nclass XPlaneRosWrapper:\n def __init__(self, stateReader, commandSender):\n self.stateReader = stateReader\n self.commandSender = commandSender\n\n '''single function for all the information updates to avoid the issue of synchronization'''\n rospy.Timer(period=rospy.Duration(0.1), callback=self.sensor_update)\n \n def sensor_update(self, step):\n '''Extract all the useful information sequentially here'''\n if self.stateReader is not None:\n # self.stateReader.sensor_update()\n # self.stateReader.control_update()\n self.stateReader.sensor_update2()\n \n\nif __name__ == '__main__':\n # start the interface node\n rospy.init_node('xplane_ros_wrapper', anonymous=True)\n with xpc.XPlaneConnect(timeout=20000) as client:\n ''' instantiate reader and sender objects '''\n stateReader = StateReader(client)\n commandSender = CommandSender(client)\n \n '''instantiate wrapper object'''\n xplaneRosWrapper = XPlaneRosWrapper(stateReader, commandSender)\n\n rospy.spin()\n\n","sub_path":"scripts/xplane_ros_wrapper.py","file_name":"xplane_ros_wrapper.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"486241930","text":"import tensorflow as tf\nfrom tensorflow.keras.layers import Conv2D, ReLU, Concatenate, BatchNormalization\nfrom tf_utils.layers.maxout import Maxout\n\nclass CompDenseBlock(tf.keras.layers.Layer):\n\n def __init__(self, num_filters, is_input_block=False):\n super(CompDenseBlock, self).__init__()\n self.is_input_block = is_input_block\n\n self.batch_norm11 = BatchNormalization()\n self.relu1 = ReLU()\n self.conv1 = Conv2D(num_filters, kernel_size=5, padding='same')\n self.batch_norm12 = BatchNormalization()\n\n self.concat = Concatenate()\n self.max_out1 = Maxout()\n\n self.batch_norm21 = BatchNormalization()\n self.relu2 = ReLU()\n self.conv2 = Conv2D(num_filters, kernel_size=5, padding='same')\n self.batch_norm22 = BatchNormalization()\n\n self.max_out2 = Maxout()\n\n self.relu3 = ReLU()\n self.conv3 = Conv2D(num_filters, kernel_size=1, padding='same')\n\n def call(self, input_tensor, training=None, mask=None):\n\n x = input_tensor\n concat = x\n\n x = self.batch_norm11(x)\n x = self.relu1(x)\n x = self.conv1(x)\n x = self.batch_norm12(x)\n\n if self.is_input_block:\n concat = x\n x = self.concat([x, concat])\n\n else:\n x = self.max_out1([x, concat])\n concat = x\n\n x = self.batch_norm21(x)\n x = self.conv2(x)\n x = self.relu2(x)\n x = self.batch_norm22(x)\n\n x = self.max_out2([x, concat])\n\n x = self.relu3(x)\n x = self.conv3(x)\n\n return x\n\n def get_config(self):\n pass\n\n def plot_summary(self, input_shape):\n x = tf.keras.Input(shape=input_shape)\n model = tf.keras.Model(inputs=[x], outputs=self.call(x, training=False))\n tf.keras.utils.plot_model(model, to_file='CDB.png', show_shapes=True, expand_nested=True)\n model.summary(line_length=200)\n\n\nif __name__ == '__main__':\n block = CompDenseBlock(64)\n block.plot_summary((16, 16, 64))\n","sub_path":"old/tf_utils/blocks/competitive_dense_block.py","file_name":"competitive_dense_block.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"548742789","text":"import functools\nimport typing\nimport string\nimport random\nimport pytest\n\n## Lösung Teil 1.\ndef nwords(s: str) -> int:\n \"\"\"Count the number of words in a given string. Words are separated by at least one char in string.whitespace\n Args:\n s (str): A string whose words are counted\n Returns: \n int: Number of words in the given string\n \"\"\"\n letters = string.ascii\n n = 0\n words = []\n current_word = \"\"\n for ch in s:\n if ch not in string.whitespace:\n current_word += ch\n else:\n if len(current_word) > 0:\n words.append(current_word)\n current_word = \"\"\n if len(current_word) > 0:\n words.append(current_word)\n return len(words)\n \nprint(nwords(\"Hello, World!\")) \n \n \n \n \n \n# 'Hello, World'\n# 2\n## Lösung Teil 2.\n\n######################################################################\n## Lösung Teil 3. (Tests)\n\n## revert\ntry:\n word_count_iter = word_count_iter.__wrapped__\nexcept:\n pass\n\n## Lösung Teil 4.\n\n######################################################################\n","sub_path":"StudentProblem/10.21.11.36/1/1569574218.py","file_name":"1569574218.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"138226116","text":"import math\nimport random\nimport time\nfrom operator import sub\n\nfrom modules import colorutils\nfrom PIL import Image, ImageChops, ImageDraw, ImageEnhance, ImageFont, ImageOps\n\n\"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\"\n### Colorizing filter that transitions from colorA to colorB ###\n\n\nclass ColorOverlay:\n\n\tcurrentColor = [0, 0, 0, 0]\n\tcurrentColorRaw = [0, 0, 0, 0]\n\tcolorA = colorB = [0, 0, 0, 0]\n\trateOfColorChange = 0\n\trandomRange = (10.0, 100.0)\n\tcomplete = False\n\ttDelta = 0\n\ttimeTrigger = False\n\tgotoNextTransition = False\n\tautoChange = True\n\tt1 = 0\n\n\t## \"Public\" variables that can be set\n\trandomSteps = True\n\tsteps = 200\n\tstep = 1\n\ttLimit = 20\n\ttLimitBase = 20\n\n\tmaxBrightness = 1\n\n\tminValue = 0.1\n\tmaxValue = 1\n\n\tminSaturation = 0.1\n\tmaxSaturation = 1\n\n\tminHue = 1\n\tmaxHue = 360\n\n\tdropHueMin = 0\n\tdropHueMax = 0\n\n\tconfigRef = None\n\n\tdef __init__(self, randomColorInit=False):\n\t\t# self.colorTransitionSetup()\n\t\t# self.colorA = colorutils.randomColor()\n\t\t# self.colorB = colorutils.randomColor()\n\t\t# self.colorB = colorutils.getRandomRGB()\n\t\tself.t1 = time.time()\n\t\tself.timeTrigger = False\n\n\t\tif randomColorInit == True:\n\t\t\tself.currentColor = list(colorutils.randomColorAlpha(0.5, 0))\n\t\t\tself.currentColorRaw = list(colorutils.randomColorAlpha(0.5, 255))\n\t\t\tself.colorA = self.colorB = list(colorutils.randomColorAlpha(0.5, 0))\n\n\t\t\t# print(self.currentColorRaw)\n\n\tdef checkTime(self):\n\t\tt = time.time()\n\t\tself.tDelta = t - self.t1\n\n\tdef setStartColor(self):\n\t\tself.colorA = colorutils.getRandomColorHSV(\n\t\t\thMin=self.minHue,\n\t\t\thMax=self.maxHue,\n\t\t\tsMin=self.minSaturation,\n\t\t\tsMax=self.maxSaturation,\n\t\t\tvMin=self.minValue,\n\t\t\tvMax=self.maxValue,\n\t\t\tdropHueMin=self.dropHueMin,\n\t\t\tdropHueMax=self.dropHueMax,\n\t\t)\n\n\t\t\"\"\"\n\t\tprint(\"New Color A\", self.colorA)\n\t\t\"\"\"\n\n\tdef getNewColor(self):\n\t\t# self.colorB = colorutils.randomColor()\n\t\t## Vaguely more control of the color parameters ...\n\t\t# if(random.random() > .8) : self.colorB = colorutils.getRandomRGB()\n\n\t\t## LEGACY --- If the maxbrightness is being set to something other than the default\n\t\t## set the maxValue to the maxBrightness\n\t\t\"\"\"\n\t\tif(self.maxBrightness != 1 ) :\n\t\t\tself.maxValue = self.maxBrightness\n\t\t\"\"\"\n\n\t\t# print(self.minHue,self.maxHue,self.minValue,self.maxValue,self.minSaturation,self.maxSaturation)\n\n\t\tself.colorB = colorutils.getRandomColorHSV(\n\t\t\thMin=self.minHue,\n\t\t\thMax=self.maxHue,\n\t\t\tsMin=self.minSaturation,\n\t\t\tsMax=self.maxSaturation,\n\t\t\tvMin=self.minValue,\n\t\t\tvMax=self.maxValue,\n\t\t\tdropHueMin=self.dropHueMin,\n\t\t\tdropHueMax=self.dropHueMax,\n\t\t)\n\n\t\t\"\"\"\n\t\tprint(\"New Color B\", self.colorB, self.colorA)\n\t\tprint(\"New Color B\", self.minHue, self.maxHue, \n\t\t\tself.minSaturation, self.maxSaturation,\n\t\t\tself.minValue, self.maxValue)\n\t\t\"\"\"\n\n\t## Transition starts\n\tdef colorTransitionSetup(self, steps=0, newColor=None):\n\n\t\t\"\"\"\n\t\tprint(\"\\nNew transition started...\")\n\n\t\ttry :\n\t\t\tfor ii in range (0,3):\n\t\t\t\tprint(ii, \" current:\", self.currentColorRaw[ii], \" old destination:\",self.colorB[ii],\" old rate:\", self.rateOfColorChange[ii])\n\t\texcept:\n\t\t\tpass\n\t\t\"\"\"\n\n\t\tif newColor == None:\n\t\t\tself.getNewColor()\n\t\telse:\n\t\t\tself.colorB = newColor\n\n\t\tself.colorTransitionSetupValues(steps)\n\n\tdef colorTransitionSetupValues(self, steps=0):\n\t\t#### Setting up for color transitions\n\t\tself.gotoNextTransition = False\n\t\tself.colorDelta = [0, 0, 0, 0]\n\t\tself.rateOfColorChange = [0, 0, 0, 0]\n\n\t\t# config.colorDelta = [a - b for a, b in zip(config.colorA, config.colorB)]\n\n\t\tself.colorDelta = list(map(sub, list(self.colorB), self.currentColorRaw))\n\n\t\tif len(self.colorDelta) == 3:\n\t\t\tself.colorDelta.append(0.1)\n\n\t\t# print(self.colorB, self.currentColorRaw)\n\n\t\t# Create random number of transition steps\n\t\t# if(steps == 0 or self.randomSteps == True) :\n\t\tself.steps = round(random.uniform(self.randomRange[0], self.randomRange[1]))\n\n\t\tself.tLimit = (\n\t\t\tround(random.uniform(self.tLimitBase / 2, self.tLimitBase * 1.5)) + 1\n\t\t)\n\t\tself.rateOfColorChange = [x / self.steps for x in self.colorDelta]\n\t\tself.complete = False\n\t\tself.step = 1\n\t\tself.t1 = time.time()\n\n\t\trounding = 0.001\n\n\t\tif abs(self.rateOfColorChange[0]) < rounding:\n\t\t\tself.rateOfColorChange[0] = 0\n\t\tif abs(self.rateOfColorChange[1]) < rounding:\n\t\t\tself.rateOfColorChange[1] = 0\n\t\tif abs(self.rateOfColorChange[2]) < rounding:\n\t\t\tself.rateOfColorChange[2] = 0\n\t\tif abs(self.rateOfColorChange[3]) < rounding:\n\t\t\tself.rateOfColorChange[3] = 0\n\n\t\t###===========> NEED TO FIX THIS - stopping any alpha transition because\n\t\t###===========> NEED TO FIX THIS - stopping any alpha transition because\n\t\t###===========> NEED TO FIX THIS - stopping any alpha transition because\n\t\t###===========> NEED TO FIX THIS - stopping any alpha transition because\n\t\t###===========> NEED TO FIX THIS - stopping any alpha transition because\n\t\t###===========> NEED TO FIX THIS - stopping any alpha transition because\n\t\t## was throwing errors\n\t\t# self.rateOfColorChange[3] = 0\n\n\t\tself.lowerRange = list(\n\t\t\tmap(\n\t\t\t\tlambda x, y: round(x - abs(y)) - 0.5,\n\t\t\t\tself.colorB,\n\t\t\t\tself.rateOfColorChange,\n\t\t\t)\n\t\t)\n\t\tself.upperRange = list(\n\t\t\tmap(\n\t\t\t\tlambda x, y: round(x + abs(y)) + 0.5,\n\t\t\t\tself.colorB,\n\t\t\t\tself.rateOfColorChange,\n\t\t\t)\n\t\t)\n\n\t\t# print(\"New destination: \",self.colorB)\n\t\t# print(\" NEW RATE: \", self.rateOfColorChange)\n\n\t\tself.callBackStarted()\n\n\t## Transition ends\n\tdef stopTransition(self):\n\t\t# print (\"Transition stopped\")\n\t\tself.gotoNextTransition = True\n\t\tself.complete = True\n\t\tself.t1 = time.time()\n\t\t# self.callBackDone()\n\n\t\n\tdef setCallBackDoneMethod(self, method, configRef=None):\n\t\tself.callBackDoneMethod = method\n\t\tself.configRef = configRef\n\n\t\n\tdef setCallBackStartedMethod(self, method, configRef=None):\n\t\tself.callBackStartedMethod = method\n\t\tself.configRef = configRef\n\n\t\n\tdef callBackDone(self):\n\t\tif self.complete == True:\n\t\t\ttry:\n\t\t\t\tif self.configRef != None:\n\t\t\t\t\tself.callBackDoneMethod(self.configRef)\n\t\t\t\telse:\n\t\t\t\t\tself.callBackDoneMethod()\n\n\t\t\texcept AttributeError as e:\n\t\t\t\tpass\n\n\tdef callBackStarted(self):\n\t\ttry:\n\t\t\tif self.configRef != None:\n\t\t\t\tself.callBackStartedMethod(self.configRef)\n\t\t\telse:\n\t\t\t\tself.callBackStartedMethod()\n\t\texcept AttributeError as e:\n\t\t\tpass\n\n\tdef stepTransition(self, autoReset=False, alpha=255):\n\n\t\tself.currentColorRaw = [\n\t\t\tself.currentColorRaw[0] + self.rateOfColorChange[0],\n\t\t\tself.currentColorRaw[1] + self.rateOfColorChange[1],\n\t\t\tself.currentColorRaw[2] + self.rateOfColorChange[2],\n\t\t\tself.currentColorRaw[3] + self.rateOfColorChange[3],\n\t\t]\n\n\t\tif self.currentColorRaw[3] > 255:\n\t\t\tself.currentColorRaw[3] = 255\n\t\t\tself.rateOfColorChange[3] = 0\n\t\tif self.currentColorRaw[3] < 0:\n\t\t\tself.currentColorRaw[3] = 0\n\t\t\tself.rateOfColorChange[3] = 0\n\n\t\tself.currentColor = [\n\t\t\tround(self.currentColorRaw[0]),\n\t\t\tround(self.currentColorRaw[1]),\n\t\t\tround(self.currentColorRaw[2]),\n\t\t\tround(self.currentColorRaw[3]),\n\t\t]\n\n\t\tself.step += 1\n\t\tself.checkTime()\n\n\t\t## Always change to the next color based on TIME\n\t\t# if (self.tDelta > self.tLimit and self.gotoNextTransition == False) :\n\t\tif self.tDelta > self.tLimit and self.step >= self.steps:\n\t\t\tself.stopTransition()\n\t\t\tif self.autoChange == True:\n\t\t\t\tself.colorTransitionSetup(self.steps)\n\n\t\tfor i in range(0, 3):\n\n\t\t\tif (\n\t\t\t\tself.currentColor[i] >= self.lowerRange[i]\n\t\t\t\tand self.currentColor[i] <= self.upperRange[i]\n\t\t\t\tand self.rateOfColorChange[i] != 0\n\t\t\t):\n\t\t\t\tself.rateOfColorChange[i] = 0\n\t\t\t\t# print(\"Color reached\", i)\n\t\t\t\t# self.currentColor[i] = self.colorB[i]\n\t\t\t\t\"\"\"\n\t\t\t\tprint(\"Color reached\", i)\n\t\t\t\tfor ii in range (0,3):\n\t\t\t\t\tprint(ii, \" current:\", self.currentColorRaw[ii], \" destination:\",self.colorB[ii],\" rate:\", self.rateOfColorChange[ii])\n\t\t\t\t\"\"\"\n\n\t\tif (\n\t\t\tself.rateOfColorChange[0] == 0\n\t\t\tand self.rateOfColorChange[1] == 0\n\t\t\tand self.rateOfColorChange[2] == 0\n\t\t\tand self.complete == False\n\t\t):\n\t\t\tself.complete = True\n\t\t\tself.callBackDone()\n\t\t\t# print(\"Transition complete.\")\n\t\t\t# if(autoReset == True or self.gotoNextTransition == True) :\n\t\t\t# self.colorTransitionSetup(self.steps)\n\n\tdef getPercentageDone(self):\n\t\treturn self.step / self.steps\n","sub_path":"modules/coloroverlay.py","file_name":"coloroverlay.py","file_ext":"py","file_size_in_byte":8045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"586152767","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\n\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\n\nimport matplotlib.pyplot as plt\nfrom torchvision.utils import make_grid\n\n\n\nclass MyModel(nn.Module):\n def __init__(self):\n super(MyModel, self).__init__()\n self.extractor = nn.Sequential(\n nn.Conv2d(1, 3, 3, 1, 1),\n nn.MaxPool2d(2),\n nn.ReLU(inplace=True),\n nn.Conv2d(3, 6, 3, 1, 1),\n nn.MaxPool2d(2),\n nn.ReLU(inplace=True),\n )\n\n self.conv_trans1 = nn.ConvTranspose2d(6, 3, 4, 2, 1)\n self.conv_trans2 = nn.ConvTranspose2d(3, 1, 4, 2, 1)\n\n def forward(self, x):\n x = self.extractor(x)\n x = F.relu(self.conv_trans1(x))\n x = self.conv_trans2(x)\n return x\n\n\ndataset = datasets.MNIST(\n root='/home/zhenyue-qin/Research/Project-Katyusha-Multi-Label-VAE/Katyusha-CVAE/data',\n transform=transforms.ToTensor()\n)\nloader = DataLoader(\n dataset,\n num_workers=2,\n batch_size=512,\n shuffle=True\n)\n\nmodel = MyModel()\ncriterion = nn.BCEWithLogitsLoss()\noptimizer = optim.Adam(model.parameters(), lr=1e-3)\n\nepochs = 1\nfor epoch in range(epochs):\n for batch_idx, (data, target) in enumerate(loader):\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, data)\n loss.backward()\n optimizer.step()\n\n print('Epoch {}, Batch idx {}, loss {}'.format(\n epoch, batch_idx, loss.item()))\n\nactivation = {}\ndef get_activation(name):\n def hook(model, input, output):\n activation[name] = output.detach()\n return hook\n\nmodel = MyModel()\nmodel.extractor[0].register_forward_hook(get_activation('ext_conv1'))\noutput = model(data)\nprint('output shape: ', output.shape)\n\n# act = activation['ext_conv1'].squeeze()\n# num_plot = 4\n# fig, axarr = plt.subplots(min(act.size(0), num_plot))\n# for idx in range(min(act.size(0), num_plot)):\n# axarr[idx].imshow(act[idx])\n\nfrom torchvision.utils import make_grid\n\nkernels = model.extractor[3].weight.detach().clone()\nkernels = kernels - kernels.min()\nkernels = kernels / kernels.max()\nimg = make_grid(kernels)\nplt.imshow(img.permute(1, 2, 0))\n\nplt.show()\n","sub_path":"visualise_example.py","file_name":"visualise_example.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"97779518","text":"import json\nimport os\nfrom collections import defaultdict\n\npath = '/home/manuto/Documents/world_bank/bert_twitter_labor/twitter-labor-data/data/evaluation_metrics/US/expansion'\njson_list = os.listdir(path)\nfinal_dict = defaultdict(set)\n\nfor json_file in json_list:\n with open(os.path.join(path, json_file), 'r') as JSON:\n json_dict = json.load(JSON)\n for k, v in json_dict.items(): # d.items() in Python 3+\n if k not in final_dict.keys():\n final_dict[k] = dict()\n for k_2, v_2 in json_dict[k].items():\n if k_2 not in final_dict[k].keys():\n final_dict[k][k_2] = dict()\n for k_3, v_3 in json_dict[k][k_2].items():\n if k_3 not in final_dict[k][k_2].keys():\n final_dict[k][k_2][k_3] = json_dict[k][k_2][k_3]\n\nprint(final_dict['our_method'])\nprint('\\n')\nprint(final_dict['adaptive'])\nprint('\\n')\nprint(final_dict['uncertainty'])\n","sub_path":"code/2-twitter_labor/3-model_evaluation/expansion/combine_jsons.py","file_name":"combine_jsons.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"334747120","text":"#!/usr/bin/env python3\n\n# OpenBACH is a generic testbed able to control/configure multiple\n# network/physical entities (under test) and collect data from them. It is\n# composed of an Auditorium (HMIs), a Controller, a Collector and multiple\n# Agents (one for each network entity that wants to be tested).\n#\n#\n# Copyright © 2016 CNES\n#\n#\n# This file is part of the OpenBACH testbed.\n#\n#\n# OpenBACH is a free software : you can redistribute it and/or modify it under\n# the terms of the GNU General Public License as published by the Free\n# Software Foundation, either version 3 of the License, or (at your option)\n# any later version.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY, without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n# more details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program. If not, see http://www.gnu.org/licenses/.\n\n\n\"\"\"Sources of the Job iperf3\"\"\"\n\n\n__author__ = 'Viveris Technologies'\n__credits__ = '''Contributors:\n * Joaquin MUGUERZA \n * Mathias ETTINGER \n'''\n\n\nimport re\nimport sys\nimport time\nimport syslog\nimport argparse\nimport subprocess\nfrom itertools import repeat\nfrom collections import defaultdict\n\nimport collect_agent\n\n\nBRACKETS = re.compile(r'[\\[\\]]')\n\n\nclass AutoIncrementFlowNumber:\n def __init__(self):\n self.count = 0\n\n def __call__(self):\n self.count += 1\n return 'Flow{0.count}'.format(self)\n\n\ndef multiplier(unit, base):\n if unit == base:\n return 1\n if unit.startswith('G'):\n return 1024 * 1024 * 1024\n if unit.startswith('M'):\n return 1024 * 1024\n if unit.startswith('K'):\n return 1024\n if unit.startswith('m'):\n return 0.001\n collect_agent.send_log(syslog.LOG_ERR, 'Units of iperf metrics are not available/correct')\n return 1\n\n\ndef _command_build_helper(flag, value):\n if value is not None:\n yield flag\n yield str(value)\n\n\ndef client(\n client, interval, window_size, port, udp, bandwidth,\n duration, num_flows, cong_control, mss, tos):\n cmd = ['iperf3', '-c', client]\n cmd.extend(_command_build_helper('-i', interval))\n cmd.extend(_command_build_helper('-w', window_size))\n cmd.extend(_command_build_helper('-p', port))\n if udp:\n cmd.append('-u')\n cmd.extend(_command_build_helper('-b', bandwidth))\n else:\n cmd.extend(_command_build_helper('-C', cong_control))\n cmd.extend(_command_build_helper('-t', duration))\n cmd.extend(_command_build_helper('-P', num_flows))\n cmd.extend(_command_build_helper('-M', mss))\n cmd.extend(_command_build_helper('-S', tos))\n subprocess.run(cmd)\n\n\ndef server(exit, interval, port, num_flows):\n # Connect to collect_agent\n success = collect_agent.register_collect(\n '/opt/openbach/agent/jobs/iperf3/'\n 'iperf3_rstats_filter.conf')\n if not success:\n message = 'ERROR connecting to collect-agent'\n collect_agent.send_log(syslog.LOG_ERR, message)\n sys.exit(message)\n\n cmd = ['stdbuf', '-oL', 'iperf3', '-s']\n if exit:\n cmd.append('-1')\n cmd.extend(_command_build_helper('-i', interval))\n cmd.extend(_command_build_helper('-p', port))\n \n \n # Read output, and send stats\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n flow_map = defaultdict(AutoIncrementFlowNumber())\n ref = int(time.time()) \n \n for flow_number in repeat(None):\n line = p.stdout.readline().decode()\n print(line)\n tokens = BRACKETS.sub('', line).split()\n if not tokens:\n if p.poll() is not None:\n break\n continue\n \n timestamp = int(time.time() * 1000)\n \n try:\n try:\n flow, duration, _, transfer, transfer_units, bandwidth, bandwidth_units, jitter, jitter_units, packets_stats, datagrams = tokens\n jitter = float(jitter)\n datagrams = float(datagrams[1:-2])\n lost, total = map(int, packets_stats.split('/'))\n except ValueError:\n udp = False\n flow, duration, _, transfer, transfer_units, bandwidth, bandwidth_units = tokens\n else:\n udp = True\n transfer = float(transfer)\n bandwidth = float(bandwidth)\n interval_begin, interval_end = map(float, duration.split('-'))\n except ValueError:\n # filter out non-stats lines\n continue\n \n if not transfer or interval_end - interval_begin > interval:\n # filter out lines covering the whole duration\n continue\n try:\n flow_number = flow_map[int(flow)]\n except ValueError:\n if flow.upper() != \"SUM\":\n continue\n\n statistics = {\n 'sent_data': transfer * multiplier(transfer_units, 'Bytes'),\n 'throughput': bandwidth * multiplier(bandwidth_units, 'bits/sec'),\n }\n if udp:\n statistics['jitter'] = jitter * multiplier(jitter_units, 's')\n statistics['lost_pkts'] = lost\n statistics['sent_pkts'] = total\n statistics['plr'] = datagrams\n collect_agent.send_stat(timestamp, suffix=flow_number, **statistics)\n error_log = p.stderr.readline()\n if error_log:\n collect_agent.send_log(syslog.LOG_ERR, 'Error when launching iperf3: {}'.format(error_log))\n sys.exit(1)\n p.wait() \n \n\nif __name__ == \"__main__\":\n # Define Usage\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n group = parser.add_mutually_exclusive_group(required=True)\n group.add_argument(\n '-s', '--server', action='store_true',\n help='Run in server mode')\n group.add_argument(\n '-c', '--client', type=str,\n help='Run in client mode and specify server IP address')\n parser.add_argument(\n '-i', '--interval', type=float, default=1,\n help='Pause *interval* seconds between '\n 'periodic bandwidth reports')\n parser.add_argument(\n '-w', '--window-size', type=str,\n help='Socket buffer sizes. For TCP, this sets the TCP window size'\n '(specified only on client but shared to server)')\n parser.add_argument(\n '-p', '--port', type=int,\n help='Set server port to listen on/connect to '\n 'n (default 5201)')\n parser.add_argument(\n '-u', '--udp', action='store_true',\n help='Use UDP rather than TCP')\n parser.add_argument(\n '-b', '--bandwidth', type=str,\n help='Set target bandwidth to n [M/K]bits/sec (default '\n '1M). This setting requires UDP (-u).')\n parser.add_argument(\n '-t', '--time', type=float, default=10,\n help='Time in seconds to transmit for (default: 10 seconds). '\n 'This setting requires client mode.')\n parser.add_argument(\n '-1', '--exit', action='store_true',\n help='For a server, exit upon completion of one connection.')\n parser.add_argument(\n '-n', '--num-flows', type=int, default=1,\n help='For client/server, the number of parallel flows.')\n parser.add_argument(\n '-C', '--cong-control', type=str,\n help='For a client, the congestion control algorithm.')\n parser.add_argument(\n '-M', '--mss', type=str,\n help='For a client, set TCP/SCTP maximum segment size (MTU - 40 bytes)')\n parser.add_argument(\n '-S', '--tos', type=str,\n help='For a client, set the IP type of service. The usual prefixes for octal and '\n 'hex can be used, i.e. 52, 064 and 0x34 specify the same value..')\n \n # get args\n args = parser.parse_args()\n interval = args.interval\n window_size = args.window_size\n port = args.port\n udp = args.udp\n num_flows = args.num_flows\n\n if args.server:\n server(args.exit, interval, port, num_flows)\n else:\n bandwidth = args.bandwidth\n duration = args.time\n cong_control = args.cong_control\n mss = args.mss\n tos = args.tos\n client(\n args.client, interval, window_size, port, udp,\n bandwidth, duration, num_flows, cong_control, mss, tos)\n","sub_path":"src/jobs/core_jobs/metrology/iperf3/files/iperf3.py","file_name":"iperf3.py","file_ext":"py","file_size_in_byte":8619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"637764879","text":"import pytest\nfrom tests.tests_data_param import get_auth_param as td\nfrom tests import requests_operation as ro\n\nURL_REF = 'https://iii-source.github.io/public/' \\\n 'swagger_ui/tweet_news/docs/dist/'\n\n\n# 有効期限内用uuid取得\n@pytest.fixture()\n@pytest.mark.parametrize(\"inputs\", list(td.get_test_auth().values()),\n ids=list(td.get_test_auth().keys()))\ndef constant_uuid(inputs):\n result = ro.get_request_with_auth(inputs['user'], inputs['password'])\n # tokenを取得\n return max(record['token'] for record in result['records'])\n\n\n# 正常系 通常更新\n@pytest.mark.parametrize(\"inputs\", list(td.get_test_auth().values()),\n ids=list(td.get_test_auth().keys()))\ndef test_news01(inputs, constant_uuid):\n headers = {'X-Request-ID': constant_uuid}\n # リクエストAPI用jsonデータ作成\n payload = {'description': 'description_test'}\n result = ro.put_request(get_url('3'), payload, headers)\n assert result['message'] == 'Updated successfully.'\n assert result['code'] == 200\n\n\n# 正常系 更新が正しく出来ているか確認\n@pytest.mark.parametrize(\"inputs\", list(td.get_test_auth().values()),\n ids=list(td.get_test_auth().keys()))\ndef test_news02(inputs, constant_uuid):\n headers = {'X-Request-ID': constant_uuid}\n result = ro.get_request(get_url('3'), headers)\n for record in result['records']:\n assert record['newsid'] == 3\n assert record['news_date'] == '2020-08-10'\n assert record['url'] == 'https://hogehoge3'\n assert record['description'] == 'description_test'\n\n\n# 正常系 検索にヒットしなかった場合\n@pytest.mark.parametrize(\"inputs\", list(td.get_test_auth().values()),\n ids=list(td.get_test_auth().keys()))\ndef test_news03(inputs, constant_uuid):\n headers = {'X-Request-ID': constant_uuid}\n # リクエストAPI用jsonデータ作成\n result = ro.get_request(get_url('99'), headers)\n assert result['message'] == 'not found newsid'\n assert result['code'] == 404\n\n\n# 準正常系 不正なデータ型(数字型)\n@pytest.mark.parametrize(\"inputs\", list(td.get_test_auth().values()),\n ids=list(td.get_test_auth().keys()))\ndef test_news04(inputs, constant_uuid):\n headers = {'X-Request-ID': constant_uuid}\n # リクエストAPI用jsonデータ作成\n result = ro.get_request(get_url('AAAAA'), headers)\n assert result['message'] == 'Bad Request'\n assert result['errors']['code'] == 400\n assert result['errors']['url_ref'] == URL_REF\n\n\n# 準正常系 SQL インジェクション\n@pytest.mark.parametrize(\"inputs\", list(td.get_test_auth().values()),\n ids=list(td.get_test_auth().keys()))\ndef test_news05(inputs, constant_uuid):\n headers = {'X-Request-ID': constant_uuid}\n # リクエストAPI用jsonデータ作成\n result = ro.get_request(get_url('10 or 1 = 1'), headers)\n assert result['message'] == 'Bad Request'\n assert result['errors']['code'] == 400\n assert result['errors']['url_ref'] == URL_REF\n\n result = ro.get_request(get_url('0; 1 = 1'), headers)\n assert result['message'] == 'Bad Request'\n assert result['errors']['code'] == 400\n assert result['errors']['url_ref'] == URL_REF\n\n result = ro.get_request(get_url('0; select * from news'), headers)\n assert result['message'] == 'Bad Request'\n assert result['errors']['code'] == 400\n assert result['errors']['url_ref'] == URL_REF\n\n\ndef get_url(id):\n # テスト対象のURLを定義\n return 'http://localhost:5000/news/' + id\n","sub_path":"tests/test_put_news.py","file_name":"test_put_news.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"264997222","text":"from .fhirbase import fhirbase\n\n\nclass Annotation(fhirbase):\n \"\"\"\n A text note which also contains information about who made the\n statement and when.\n\n Args:\n authorReference: The individual responsible for making the annotation.\n authorString: The individual responsible for making the annotation.\n time: Indicates when this particular annotation was made.\n text: The text of the annotation.\n \"\"\"\n\n __name__ = 'Annotation'\n\n def __init__(self, dict_values=None):\n self.authorReference = None\n # reference to Reference: identifier\n\n self.authorString = None\n # type: str\n\n self.time = None\n # type: str\n\n self.text = None\n # type: str\n\n self.object_id = None\n # unique identifier for object class\n\n if dict_values:\n self.set_attributes(dict_values)\n\n def get_relationships(self):\n\n return [\n {'parent_entity': 'Reference',\n 'parent_variable': 'identifier',\n 'child_entity': 'Annotation',\n 'child_variable': 'authorReference'},\n ]\n","sub_path":"cardea/fhir/Annotation.py","file_name":"Annotation.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"591930035","text":"#%% Loading data\nimport finplot as fplt\nimport numpy as np\nimport pandas as pd\n\nsymbol = 'FUTURES BTC-USDT'\n\n#df = pd.read_csv('Binance_BTCUSDT_1m_1596240000000-1598918400000.csv')\ndf = pd.read_csv('Binance_BTCUSDT_1m_1567987200000-1598918400000.csv')\ndf = df.rename(columns={'Open_time':'time', 'Open':'open', 'Close':'close', 'High':'high', 'Low':'low', 'Volume':'volume'})\ndf\n\n#%% Calculate volatility in various timeframes\nwindows = [3, 5, 10, 30, 60, 60*4, 60*12, 60*24, 60*24*3, 60*24*7, 60*24*30]\n\nmaxim = []\nminim = []\ncenter = []\nvolatility_diff = []\nvolatility = []\n\nfor window in windows: \n ma = df['high'].rolling(window).max() # volatility box top\n mi = df['low'].rolling(window).min() # volatility box bottom}\n c = ma-mi # volatility box center\n vol = c/ma # volatility\n diff = vol.diff()\n \n volatility.append(vol)\n volatility_diff.append(diff)\n #volatility = volatility.rolling(60*6).mean()\n #open_price_position_relative_to_volatility_box = (df['open']-df['low'])/center\n#%% Plot\n\n# create two plots\nax, ax2, ax3 = fplt.create_plot(symbol, rows=3)\n\n# plot candle sticks\ncandles = df[['time','open','close','high','low']]\nfplt.candlestick_ochl(candles, ax=ax)\n\n# overlay volume on the top plot\nvolumes = df[['time','open','close','volume']]\nfplt.volume_ocv(volumes, ax=ax.overlay())\n\n# put an MA on the close price\n#fplt.plot(df['time'], df['close'].rolling(window).mean(), ax=ax, legend='ma-25')\n#fplt.plot(df['time'], maxim, ax=ax, legend='maxim')\n#fplt.plot(df['time'], minim, ax=ax, legend='minim')\n\n# draw second plot\nfor i, window in enumerate(windows): \n if(i<5):\n fplt.plot(df['time'], volatility[i], ax=ax2, legend='volatility ' + str(window))\n if(i>=5):\n fplt.plot(df['time'], volatility[i], ax=ax3, legend='volatility ' + str(window))\n#fplt.set_y_range(0, 0.005, ax=ax2) # hard-code y-axis range limitation\n\n# draw third plot\n#fplt.plot(df['time'], volatility_diff, ax=ax3, color='#927', legend='volatility_diff')\n\n# draw fourth plot\n#fplt.plot(df['time'], open_price_position_relative_to_volatility_box, ax=ax4, color='#927', legend='open_price_position_relative_to_volatility_box')\n\n# restore view (X-position and zoom) if we ever run this example again\nfplt.autoviewrestore()\n\n# we're done\nfplt.show()\n\n# %%\ni = 1","sub_path":"Examples/plotTest.py","file_name":"plotTest.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"275940665","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\winstrument\\db_connection.py\n# Compiled at: 2020-02-05 20:03:04\n# Size of source mod 2**32: 2689 bytes\nimport sqlite3\nfrom winstrument.data.module_message import ModuleMessage\nimport sys\nfrom datetime import datetime\nimport json, os, toml\n\nclass DBConnection:\n\n def __init__(self, dbpath):\n self._db = sqlite3.connect(dbpath, check_same_thread=False)\n self._dbpath = dbpath\n self._cursor = self._db.cursor()\n self._cursor.execute('CREATE TABLE IF NOT EXISTS output\\n (id INTEGER PRIMARY KEY,\\n modname TEXT NOT NULL,\\n time TEXT NOT NULL,\\n target TEXT NOT NULL,\\n message BLOB)')\n self._db.commit()\n\n def write_message(self, message):\n \"\"\"\n Insert the given message into the sqlite DB output table\n message - ModuleMessage object\n \"\"\"\n self._cursor.execute('INSERT INTO \"output\" (modname, time, target, message) VALUES (?,?,?,?)', (message.module, message.time, message.target, json.dumps(message.data)))\n self._db.commit()\n\n def clear_output(self):\n \"\"\"\n Truncates the output table\n \"\"\"\n self._cursor.execute('DELETE FROM \"output\"')\n self._db.commit()\n\n def read_messages(self, modname):\n \"\"\"\n Get a list of all messages for the given module name\n modname: str - Name of the module for which to retrieve messages\n Return: list of ModuleMessage objects\n \"\"\"\n self._cursor.execute('SELECT \"modname\", \"time\", \"target\", \"message\" FROM \"output\" where modname= ? ', (modname,))\n messages = []\n for row in self._cursor.fetchall():\n module = row[0]\n time = row[1]\n target = row[2]\n data = json.loads(row[3])\n messages.append(ModuleMessage(module, target, data, time=time))\n\n return messages\n\n def close(self):\n self._db.close()\n os.remove(self._dbpath)","sub_path":"pycfiles/winstrument-0.1.0-py3.7/db_connection.cpython-37.py","file_name":"db_connection.cpython-37.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"507320329","text":"# -*- coding: utf-8 -*-\n\nfrom . import services\n\n\nclass NotificationSenderMixin(object):\n create_notification_template = None\n update_notification_template = None\n destroy_notification_template = None\n notification_service = services.NotificationService()\n\n def _post_save_notification_sender(self, obj, created=False):\n users = obj.get_watchers_to_notify(self.request.user)\n comment = self.request.DATA.get(\"comment\", None)\n context = {'changer': self.request.user, \"comment\": comment, 'object': obj}\n\n if created:\n self.notification_service.send_notification_email(self.create_notification_template,\n users=users, context=context)\n else:\n changed_fields = obj.get_changed_fields_list(self.request.DATA)\n\n if changed_fields:\n context[\"changed_fields\"] = changed_fields\n self.notification_service.send_notification_email(self.update_notification_template,\n users=users, context=context)\n\n def post_save(self, obj, created=False):\n super().post_save(obj, created)\n self._post_save_notification_sender(obj, created)\n\n def destroy(self, request, *args, **kwargs):\n obj = self.get_object()\n users = obj.get_watchers_to_notify(self.request.user)\n\n context = {'changer': self.request.user, 'object': obj}\n self.notification_service.send_notification_email(self.destroy_notification_template,\n users=users, context=context)\n\n return super().destroy(request, *args, **kwargs)\n","sub_path":"taiga/base/notifications/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"467373836","text":"from sklearn.model_selection import train_test_split\nimport tensorflow as tf\nimport numpy as np\nimport time\nimport os\nimport struct\n\nmax_steps=1000\ndef add_layer(inputs, in_size, out_size, activation_function=None):\n Weights = tf.Variable(tf.random_normal([in_size, out_size]))\n biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)\n Wx_plus_b = tf.matmul(inputs, Weights) + biases\n if activation_function is None:\n outputs = Wx_plus_b\n else:\n outputs = activation_function(Wx_plus_b)\n return outputs\n\nfin=open('test_data.dat','rb')\nfin.seek(0,os.SEEK_END)\nlis_len=fin.tell()/4;\nfin.seek(0,os.SEEK_SET)\ndata=np.array(struct.unpack('<'+str(lis_len)+'f',fin.read()))\nfin.close()\ndata=data.reshape([-1,3])\ndata_X=data[:,:2]\ndata_y=data[:,2][:, np.newaxis]\nX_train,X_test, y_train, y_test =train_test_split(data_X,data_y, random_state=3)\n\nxs = tf.placeholder(tf.float32, [None, 2])\nys = tf.placeholder(tf.float32, [None, 1])\n# add hidden layer\nl1 = add_layer(xs, 2, 5, activation_function=tf.nn.relu)\nl2 = add_layer(l1, 5, 5, activation_function=tf.nn.relu)\nprediction = add_layer(l2, 5, 1, activation_function=None)\n\nloss = tf.reduce_mean(tf.square(ys - prediction))\ntrain_step = tf.train.GradientDescentOptimizer(0.23).minimize(loss)\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\n \nfor i in range(max_steps):\n start_time=time.time()\n sess.run(train_step, feed_dict={xs: X_train, ys: y_train})\n duration=time.time()-start_time\n if i % 50 == 0:\n example_per_sec=X_train.shape[0]/duration\n sec_pec_batch=float(duration)\n format_str=('step %d,loss=%.8f(%.1f example/sec;%.3f sec/batch)')\n loss_value=sess.run(loss, feed_dict={xs: X_train, ys: y_train})\n print(format_str%(i,loss_value,example_per_sec,sec_pec_batch))\n","sub_path":"preloaded_data.py","file_name":"preloaded_data.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"485055019","text":"__author__ = 'Jay'\n\nfrom BaseHTMLProcessor import BaseHTMLProcessor\nimport urllib\n\nparser = BaseHTMLProcessor()\n\n# Gets a file like object\nsock = urllib.urlopen(\"http://reliefweb.int/\")\n\n# read from the object, storing the pages content in htmlSource\nhtmllSource = sock.read()\n\nparser.feed(htmllSource)\nsock.close()\n\nprint(parser.output())\nparser.close()","sub_path":"Homework4/HTML_Processing/htmlScratch2.py","file_name":"htmlScratch2.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"8153063","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n'''\nUnit tests for scrapername.\n\n'''\nfrom collections import OrderedDict\nfrom os.path import join\n\nimport pytest\nfrom hdx.hdx_configuration import Configuration\nfrom hdx.hdx_locations import Locations\nfrom hdx.utilities.downloader import DownloadError\nfrom hdx.utilities.path import temp_dir\n\nfrom wfp_foodsecurity import generate_dataset_and_showcase, get_countriesdata\n\n\nclass TestScraperName:\n countrydata = {'code': '50', 'iso3': 'GIN'}\n\n @pytest.fixture(scope='function')\n def configuration(self):\n Configuration._create(hdx_read_only=True, user_agent='test',\n project_config_yaml=join('tests', 'config', 'project_configuration.yml'))\n Locations.set_validlocations([{'name': 'gin', 'title': 'Guinea'}]) # add locations used in tests\n\n @pytest.fixture(scope='function')\n def downloader(self):\n class Response:\n pass\n\n class Download:\n @staticmethod\n def setup(url, post=False, parameters=None):\n if not post:\n raise DownloadError()\n\n response = Response()\n\n if not 'page' in parameters or parameters['page'] == 0:\n response.headers = {'Content-Length': 300}\n else:\n response.headers = {'Content-Length': 100}\n if url == 'http://yyy':\n return response\n\n @staticmethod\n def get_json():\n return [OrderedDict([('RowNum', 11), ('ID', 3630), ('SvyID', 48), ('PnlID', 1), ('SvyDate', '2015-06-01T00:00:00'), ('SvyYear', 2015), ('SvyMonth', 'June'), ('SvyMonthNum', 6), ('ADM0_NAME', 'Guinea'), ('ADM1_NAME', None), ('ADM2_NAME', None), ('IndpVars', 'ADM0'), ('Variable', 'rCSI'), ('AdminStrata', 'Guinea'), ('Demographic', None), ('NumObs', 2079), ('Mean', 19.7831), ('StDev', 12.4268), ('CnfIntvHi', 20.55715), ('CnfIntvLo', 19.00906), ('Median', 19.21898), ('Pctl5', 1.0), ('Pctl25', 9.0), ('Pctl75', 30.0), ('Pctl95', 40.0), ('HLAvg', 19.0), ('ADM0_CODE', 106.0)]),\n OrderedDict([('RowNum', 169), ('ID', 3788), ('SvyID', 48), ('PnlID', 1), ('SvyDate', '2015-06-01T00:00:00'), ('SvyYear', 2015), ('SvyMonth', 'June'), ('SvyMonthNum', 6), ('ADM0_NAME', 'Guinea'), ('ADM1_NAME', None), ('ADM2_NAME', None), ('IndpVars', 'HoHSex,ToiletTypeGrp'), ('Variable', 'rCSI'), ('AdminStrata', None), ('Demographic', 'F,Bush pit latrine'), ('NumObs', 80), ('Mean', 25.79668), ('StDev', 12.32078), ('CnfIntvHi', 29.15365), ('CnfIntvLo', 22.4397), ('Median', 28.0), ('Pctl5', 1.41855), ('Pctl25', 18.0), ('Pctl75', 34.80567), ('Pctl95', 45.49957), ('HLAvg', 24.0), ('ADM0_CODE', 106.0)])]\n\n @staticmethod\n def get_tabular_rows(url, dict_rows, headers, format):\n if url == 'http://xxx/adm0code.csv':\n return [{'ADM0_CODE': '50', 'ADM0_NAME': 'Guinea'}]\n\n return Download()\n\n def test_get_countriesdata(self, downloader):\n countriesdata = get_countriesdata('http://xxx/adm0code.csv', downloader)\n assert countriesdata == [TestScraperName.countrydata]\n\n def test_generate_dataset_and_showcase(self, configuration, downloader):\n showcase_url = 'http://vam.wfp.org/sites/mvam_monitoring/%s.html'\n showcase_lookup = {'GIN': 'ebola'}\n variables = {'rCSI': 'reduced coping strategy'}\n with temp_dir('wfp-foodsecurity') as folder:\n dataset, showcase = generate_dataset_and_showcase('http://yyy', showcase_url, showcase_lookup, downloader, folder, TestScraperName.countrydata, variables)\n assert dataset == {'name': 'wfp-food-security-indicators-for-guinea', 'title': 'Guinea - Food Security Indicators',\n 'maintainer': '196196be-6037-4488-8b71-d786adf4c081', 'owner_org': '3ecac442-7fed-448d-8f78-b385ef6f84e7',\n 'data_update_frequency': '30', 'subnational': '0', 'groups': [{'name': 'gin'}],\n 'tags': [{'name': 'food security'}], 'dataset_date': '01/01/2015-12/31/2015'}\n resources = dataset.get_resources()\n assert resources == [{'name': 'pblstatssum.csv', 'description': 'pblStatsSum: Guinea - Food Security Indicators', 'format': 'csv'}]\n\n assert showcase == {'name': 'wfp-food-security-indicators-for-guinea-showcase', 'title': 'Guinea - Food Security Indicators', 'notes': 'Reports on food security for Guinea', 'url': 'http://vam.wfp.org/sites/mvam_monitoring/ebola.html', 'image_url': 'https://media.licdn.com/media/gcrc/dms/image/C5612AQHtvuWFVnGKAA/article-cover_image-shrink_423_752/0?e=2129500800&v=beta&t=00XnoAp85WXIxpygKvG7eGir_LqfxzXZz5lRGRrLUZw', 'tags': [{'name': 'food security'}]}\n\n","sub_path":"tests/test_wfp_foodsecurity.py","file_name":"test_wfp_foodsecurity.py","file_ext":"py","file_size_in_byte":4792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"378893747","text":"from collections import defaultdict\nclass Graph:\n def __init__(self,n):\n self.vertices = n\n self.graph = defaultdict(list)\n self.visited = [False]*self.vertices\n \n def addEdge(self,u,v):\n self.graph[u].append(v)\n self.graph[v].append(u)\n \n def setIdentifier(self):\n for i in range(self.vertices):\n self.graph[i].append(-1)\n \n def showGraph(self):\n for i in range(self.vertices):\n print(i,\"linked with vertices \",end=\"\")\n for j in self.graph[i]:\n if j !=-1:\n print(\"->\",j,end=\"\")\n print(\"\")\n def CheckUtils(self,u):\n self.visited[u] = True\n for v in self.graph[u]:\n if self.visited[v] == False and v !=-1:\n self.CheckUtils(v)\n \n def Check(self):\n self.setIdentifier()\n self.CheckUtils(0)\n for i in range(self.vertices):\n if not self.visited[i]:\n return True\n \ng = Graph(6)\ng.addEdge(0,1)\ng.addEdge(1,2)\ng.addEdge(2,3)\ng.addEdge(4,5)\ng.showGraph()\nif g.Check():\n print(\"Given graph is not connected\")\nelse:\n print(\"Given graph is connected\")","sub_path":"graphTheory/IsGraphConnected.py","file_name":"IsGraphConnected.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"475266380","text":"from django.core.exceptions import ObjectDoesNotExist, ValidationError\nfrom rest_framework import fields, serializers\nfrom rest_framework.compat import smart_text\n\nfrom amo.utils import to_language\n\n\nclass TranslationSerializerField(fields.WritableField):\n \"\"\"\n Django-rest-framework custom serializer field for our TranslatedFields.\n\n - When deserializing, in `from_native`, it accepts both a string or a\n dictionary. If a string is given, it'll be considered to be in the\n default language.\n\n - When serializing, its behavior depends on the parent's serializer context:\n\n If a request was included, and its method is 'GET', and a 'lang' parameter\n was passed, then only returns one translation (letting the TranslatedField\n figure out automatically which language to use).\n\n Else, just returns a dict with all translations for the given `field_name`\n on `obj`, with languages as the keys.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(TranslationSerializerField, self).__init__(*args, **kwargs)\n # Default to return all translations for each field.\n self.return_all_translations = True\n\n def initialize(self, parent, field_name):\n super(TranslationSerializerField, self).initialize(parent, field_name)\n request = self.context.get('request', None)\n if request and request.method == 'GET' and 'lang' in request.GET:\n # A specific language was requested, we only return one translation\n # per field.\n self.return_all_translations = False\n\n def field_to_native(self, obj, field_name):\n field = getattr(obj, field_name)\n if field is None:\n return None\n if not self.return_all_translations:\n return unicode(field)\n else:\n translations = field.__class__.objects.filter(id=field.id,\n localized_string__isnull=False)\n return dict((to_language(trans.locale), unicode(trans))\n for trans in translations)\n\n def from_native(self, data):\n if isinstance(data, basestring):\n return data.strip()\n elif isinstance(data, dict):\n for key, value in data.items():\n data[key] = value.strip()\n return data\n data = super(TranslationSerializerField, self).from_native(data)\n return unicode(data)\n\n\nclass SplitField(fields.Field):\n \"\"\"\n A field that accepts a primary key as input but serializes a\n nested representation of the object represented by that key as\n output.\n \"\"\"\n label = None\n def __init__(self, input, output, **kwargs):\n self.input = input\n self.output = output\n self.source = input.source\n\n def field_from_native(self, data, files, field_name, into):\n self.input.initialize(parent=self.parent, field_name=field_name)\n self.input.field_from_native(data, files, field_name, into)\n\n def field_to_native(self, obj, field_name):\n self.output.initialize(parent=self.parent, field_name=field_name)\n return self.output.field_to_native(obj, field_name)\n\n\nclass SlugOrPrimaryKeyRelatedField(serializers.RelatedField):\n \"\"\"\n Combines SlugRelatedField and PrimaryKeyRelatedField. Takes a\n `render_as` argument (either \"pk\" or \"slug\") to indicate how to\n serialize.\n \"\"\"\n default_error_messages = serializers.SlugRelatedField.default_error_messages\n read_only = False\n\n def __init__(self, *args, **kwargs):\n self.render_as = kwargs.pop('render_as', 'pk')\n if self.render_as not in ['pk', 'slug']:\n raise ValueError(\"'render_as' must be one of 'pk' or 'slug', \"\n \"not %r\" % (self.render_as,))\n self.slug_field = kwargs.pop('slug_field', 'slug')\n super(SlugOrPrimaryKeyRelatedField, self).__init__(\n *args, **kwargs)\n\n def to_native(self, obj):\n if self.render_as == 'slug':\n return getattr(obj, self.slug_field)\n else:\n return obj.pk\n\n def from_native(self, data):\n if self.queryset is None:\n raise Exception('Writable related fields must include a `queryset` argument')\n\n try:\n return self.queryset.get(pk=data)\n except:\n try:\n return self.queryset.get(**{self.slug_field: data})\n except ObjectDoesNotExist:\n msg = self.error_messages['does_not_exist'] % ('pk_or_slug', smart_text(data))\n raise ValidationError(msg)\n\n","sub_path":"mkt/api/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"482996454","text":"job_name = 'cfa_cos_tanh'\nchunk_size = 500\nbatch_size = 10\n\nfrom pylearn2.utils import serial\nimport SkyNet\n\n\nSkyNet.set_job_name(job_name)\ncomponents = SkyNet.get_dir_path('components')\n\nnum_examples = serial.load(components+'/num_examples.pkl')\nserial.save(components+'/chunk_size.pkl',chunk_size)\nserial.save(components+'/batch_size.pkl',batch_size)\n\ncommand = '--mem=2000 '+SkyNet.get_user_dir(tmp = False, force = SkyNet.cluster) + '/galatea/contractive_feature_analysis/cos_experiment_condor/stage_3_worker.py '+job_name+' \"{{'\n\nassert num_examples % chunk_size == 0\n\nfor b in xrange(0,num_examples,chunk_size):\n if b != 0:\n command+=','\n command += str(b)\ncommand += '}}\"'\n\nSkyNet.launch_job(command)\n","sub_path":"old/contractive_feature_analysis/cos_experiment_condor/stage_2_launcher.py","file_name":"stage_2_launcher.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"567199758","text":"import re\nimport os\nimport csv\n\n\n\ndef get_files_in_dir(basepath, ext=[], debug=False):\n basepath = os.path.abspath(basepath)\n\n ext = [str.lower(x) for x in ext]\n\n try:\n if os.path.exists(basepath) and os.path.isdir(basepath):\n result = [os.path.join(basepath, x) for x in os.listdir(basepath)]\n files = [[os.path.split(x)[0], *os.path.splitext(os.path.basename(x))] for x in result if os.path.isfile(x)]\n if len(ext) == 0:\n # print('无类型筛选,返回所有文件')\n if debug: print(files)\n return files\n\n if len(ext) > 0:\n # print('返回{}类型的文件'.format(ext))\n files = [[os.path.split(x)[0], *os.path.splitext(os.path.basename(x))] for x in result if\n str.lower(re.split(r'\\.', x)[-1]) in ext]\n if debug: print(files)\n return files\n else:\n return False\n except Exception as e:\n print('发生错误{}'.format(e))\n\n\ndef write_csv(filepath, line: list):\n with open(filepath, 'a', newline='', encoding='utf-8-sig') as csv_file:\n data = csv.writer(csv_file, delimiter=',')\n data.writerow(line)\n\n\ndef read_txt(filepath):\n with open(filepath, 'r', encoding='utf-8-') as f:\n return f.read()\n\n\ndef write_txt(filepath, txt):\n with open(filepath, 'a', encoding='utf-8') as f:\n f.write(txt)\n\n\ndef parse(filepath):\n txt=read_txt(filepath)\n # print(txt)\n mail=re.findall(r'''Amazon账号.*?:(.*?@.*?)\\n''',txt)\n if mail:\n write_csv('mails_info.csv',[filepath]+mail)\n write_txt('mails_info.txt',mail[0]+'\\n')\n\ndef check_dir(d):\n d = os.path.abspath(d)\n if not os.path.exists(d):\n os.makedirs(d)\n return d\n\n\nsourcedir = check_dir('./txt')\n# outputdir = check_dir('./output')\n\nfor basepath, filename, extname in get_files_in_dir(sourcedir, ['txt']):\n print(basepath, filename, extname)\n source_file_path = os.path.join(basepath, filename + extname)\n # output_file_path = os.path.join(outputdir, filename + '.json')\n parse(source_file_path)\n\n\n\n","sub_path":"job/平安理财保险-金丰-txt提取邮箱/提取邮箱.py","file_name":"提取邮箱.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"90151965","text":"from ..Mapper import Mapper\nfrom pandas import DataFrame\nfrom .Models import AbstractModel\nfrom .Models import ModelFactory\nfrom ..Exceptions.learnerException import LearnerException\n\n\nclass Learner:\n \"\"\"\n The class that handles the learning inside the pipeline.\n It's main task is to learn from a dataset and return a model.\n Based on a configuration file given as constructor parameter it is able to do a series of tasks:\n - fit the data on a dataset with a default predefined model (defined in config)\n - fit the data using a series of models and evolutionary algorithms for finding the best one #TO BE DONE\n\n Methods:\n - learn: creates a model and learns it based on a given dataset\n - get_model: returns the last trained model\n - get_mapper: gets the mapper with attributes\n \"\"\"\n\n def __init__(self, config: dict = None, model: 'AbstractModel' = None):\n \"\"\"\n Creates a learner instance based on the configuration file.\n :param config: dictionary with the configurations for the learning module\n - expected to get the TRAINING_CONFIG section of the config file\n \"\"\"\n\n if config is None:\n config = {}\n\n self._config = config\n self._mapper = Mapper('Learner')\n self._model_factory = ModelFactory(self._config)\n self._model = model\n\n def learn(self, X: DataFrame, Y: DataFrame, verbose: bool = True, callbacks: list = None, time: int = None) \\\n -> AbstractModel:\n \"\"\"\n Learns based on the configuration provided.\n :param callbacks: callbacks to be executed by the model when training it\n :param X: the data to learn from\n :param Y: the predictions to compare to\n\n :param verbose: decides whether the learn() method should produce any output\n :param time: time in seconds for the training session; if not specified the time in config is used\n :return: the trained model\n \"\"\"\n if callbacks is None:\n callbacks = []\n\n # input and output size\n input_size = X.shape[1]\n output_size = Y.shape[1]\n\n self._mapper.set(\"input_size\", input_size)\n self._mapper.set(\"output_size\", output_size)\n\n # creates a model\n model = self._model\n if model is None:\n model = self._model_factory.create_model(in_size=input_size, out_size=output_size)\n\n # trains the model\n if time is None:\n train_time = self._convert_train_time(self._config.get(\"TIME\", \"10m\"))\n else:\n train_time = time\n\n # here's where the magic happens\n model.train(X, Y, train_time, verbose=verbose, callbacks=callbacks)\n\n # returns it\n self._model = model\n return model\n\n @staticmethod\n def _convert_train_time(time: str) -> int:\n \"\"\"\n Converts the time from \"xd yh zm ts\" into seconds\n :param time: string containing the time in textual format -number of days , hours, minutes and seconds\n :return: the time in seconds\n \"\"\"\n mapping = {}\n crt_count = 0\n\n for c in time: # for each character\n if c.isnumeric():\n crt_count = crt_count * 10 + int(c)\n elif c in \"dhms\": # days hours minutes seconds\n mapping[c] = mapping.get(c, 0) + crt_count\n crt_count = 0\n else:\n crt_count = 0\n\n seconds = mapping.get(\"s\", 0) + mapping.get(\"m\", 0) * 60 + \\\n mapping.get(\"h\", 0) * (60 * 60) + mapping.get(\"d\", 0) * 24 * 60 * 60\n\n return seconds\n\n def get_model(self) -> AbstractModel:\n \"\"\"\n Returns the model after training.\n :return: the model that has been trained with the learn method\n :exception LearnerException if this method is called before learn is called\n \"\"\"\n if self._model is None:\n raise LearnerException(\"Could not retrieve model before 'learn' is called.\")\n\n return self._model\n\n def get_mapper(self) -> 'Mapper':\n \"\"\"\n Returns the mapper that contains data about training\n :return: the mapper\n \"\"\"\n model_map = None\n if not (self._model is None):\n model_map = self._model.to_dict()\n\n self._mapper.set(\"MODEL\", model_map)\n return self._mapper\n","sub_path":"Pipeline/Learner/learner.py","file_name":"learner.py","file_ext":"py","file_size_in_byte":4463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"403272911","text":"from gurobipy import tuplelist\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom pprint import pprint\r\n\r\ndef graph_parameter(node_file=\"Nodes_Revised.csv\", arc_file=\"Arcs.csv\", commodities_file=\"Commodities.csv\"):\r\n # data setup into pandas df's\r\n node_df = pd.read_csv(node_file)\r\n arc_df = pd.read_csv(arc_file)\r\n commodities_df = pd.read_csv(commodities_file)\r\n\r\n # comodities and quantity {commodity:quantity}\r\n commodity_quantity = {k: g['weight'].values[0] for k, g in commodities_df.groupby('name')}\r\n\r\n # nodes\r\n nodes = node_df['nodes'].tolist()\r\n # nodes = [tuple(pair[1:]) for pair in node_df.values]\r\n\r\n # arcs (tuplelist)\r\n arcs = tuplelist([tuple(pair) for pair in arc_df.values])\r\n\r\n # sources {commodity:source}\r\n commodity_source = {k: g['source'].values[0] for k, g in commodities_df.groupby('name')}\r\n\r\n # sinks {commodity:sink}\r\n commodity_sink = {k: g['sink'].values[0] for k, g in commodities_df.groupby('name')}\r\n\r\n # m_distance {(arc pair): euclidean distance}\r\n m_distance = {}\r\n for x,y in arcs:\r\n x1, y1 = node_df.loc[node_df['nodes'] == x].values[0][1:3]\r\n x2, y2 = node_df.loc[node_df['nodes'] == y].values[0][1:3]\r\n distance = np.sqrt((x2-x1)**2 + (y2-y1)**2)\r\n m_distance[(x, y)] = distance\r\n\r\n final_list = [commodity_quantity, nodes, arcs, commodity_source, commodity_sink, m_distance]\r\n return final_list\r\nif __name__ == \"__main__\":\r\n data = graph_parameter()\r\n pprint(data)","sub_path":"graph_parameter.py","file_name":"graph_parameter.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"268869189","text":"#!/usr/bin/env python\n# coding: utf-8\n\n'''\n@Author: Senkita\n'''\n\nimport pandas as pd\nimport numpy as np\nfrom openpyxl import Workbook\nimport re\n\npd.set_option('mode.chained_assignment', None)\n\nclass BackgroundProcessing:\n @classmethod\n def __init__(cls, file_path, match_file_path):\n cls.file = pd.read_excel(file_path)\n cls.match_file = pd.read_excel(match_file_path)\n \n @classmethod\n def match_barcode(cls):\n cls.file['数量'] = np.nan\n not_found_barcode = []\n \n for barcode in cls.match_file['商品条码']:\n file_index = cls.file[cls.file['商品编码']==barcode].index\n match_index = cls.match_file[cls.match_file['商品条码']==barcode].index\n if file_index.size == 0:\n not_found_barcode.append((barcode, int(cls.match_file['数量'][match_index])))\n else:\n cls.file['数量'][file_index] = cls.match_file['数量'][match_index]\n\n cls.file.to_excel('配饰条码匹配.xlsx', index=False)\n count = '共匹配{}个条码'.format(cls.file['数量'].sum())\n\n if len(not_found_barcode) != 0:\n wb = Workbook()\n ws = wb.active\n ws.cell(1, 1).value = '未匹配条码'\n ws.cell(1, 2).value = '数量'\n \n for i in range(len(not_found_barcode)):\n ws.cell(i + 2, 1).value = not_found_barcode[i][0]\n ws.cell(i + 2, 2).value = not_found_barcode[i][1]\n\n wb.save('未匹配条码.xlsx')\n\n return count\n","sub_path":"AccessoriesBarcodeMatchTool/background_processing.py","file_name":"background_processing.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"52462751","text":"#!/usr/bin/python3\n\nfrom ipaddress import ip_network\nfrom ipify import get_ip\nfrom troposphere import Base64, ec2, GetAtt, Join, Output, Parameter, Ref, Template\n\nApplicationPort = '3000'\nPublicCidrIp = str(ip_network(get_ip()))\nt = Template()\n\nt.add_description('Effective DevOps in AWS: Test application')\nt.add_parameter(Parameter(\n 'KeyPair',\n Description = 'Existing AWS Keypair',\n Type = 'AWS::EC2::Keypair::KeyName',\n ConstraintDescription='name of an existing EC2 KeyPair',\n))\nt.add_resource(ec2.SecurityGroup(\n 'SecurityGroup',\n GroupDescription='Allow SSH and TCP/{} access'.format(ApplicationPort),\n SecurityGroupIngress=[ec2.SecurityGroupRule(\n IpProtocol='tcp',\n FromPort='22',\n ToPort='22',\n CidrIp=PublicCidrIp,\n ),\n ec2.SecurityGroupRule(\n IpProtocol='tcp',\n FromPort=ApplicationPort,\n ToPort=ApplicationPort,\n CidrIp=PublicCidrIp,\n )]\n))\n\n\nud = Base64(Join('\\n', ['#!/bin/bash',\n 'sudo yum install --enablerepo=epel -y nodejs',\n 'wget http://bit.ly/2vESNuc -O /home/ec2-user/helloworld.js',\n 'wget http://bit.ly/2vVvT18 -O /etc/init/helloworld.conf',\n 'start helloworld',\n ]))\n\nt.add_resource(ec2.Instance(\n 'instance',\n ImageId='ami-a4c7edb2',\n InstanceType='t2.micro',\n SecurityGroups=[Ref('SecurityGroup')],\n KeyName=Ref('KeyPair'),\n UserData=ud,\n))\n\nt.add_output(Output(\n 'InstancePublicIp',\n Description='Public IP of your instance.',\n Value=GetAtt(instance, 'PublicIp'),\n))\n\nt.add_output(Output(\n 'WebUrl',\n Description='Application endpoint',\n Value=Join('', ['http://', GetAtt(instance, 'PublicDnsName.'), ':', ApplicationPort]),\n))\n\nprint(t.to_json)\n\n","sub_path":"python/troposphere-test.py","file_name":"troposphere-test.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"105437640","text":"import os, sys, time\nimport argparse\nimport json\nimport logging, coloredlogs\nimport itertools\nimport datetime\n\n# unpacker\nimport sqlite3\nimport dateutil.parser\nimport pytz\n\n# comparer\nimport re\nimport pandas as pd\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport csv\n\n\ndef ms(seconds):\n return math.floor(seconds * 1000)\n\n\nCST = pytz.timezone('US/Central')\n\n\ndef sample_frame(df, time):\n time = range(ms(time)+1)\n nf = pd.DataFrame(columns=['rating'], index=time)\n # Every once in a while we somehow get an entry that isn't sorted by time.\n # Not sure what's causing that.\n df = df.sort_values('time')\n for index, row in df.iterrows():\n timeindex = ms(row['time'])\n nf.iloc[timeindex,0] = row['rating']\n nf = nf.fillna(method='ffill')\n nf = nf.fillna(0.5)\n return nf\n\n\n\ndef load_original(f):\n # Load the original actor's ratings given a video filename\n m = re.search('(EA\\d+-[NP]\\d+)', f)\n name = m.group(0)\n this_dir = os.path.dirname(os.path.realpath(__file__))\n csv_name = os.path.join(this_dir, 'original-ratings', f'{name}.csv')\n original = pd.read_csv(csv_name, header=None)\n original.columns = ['rating', 'time']\n # normalize ratings from likert 1-9 to 0-1\n original['rating'] = (original['rating'] - 1) / 8\n return original, name\n\n\ndef fix_ratings(rating, last_original_time):\n rating.rename(columns={\"value\":\"rating\", \"browserTime\":\"time\"}, inplace=True)\n # print(f\"Last rating time is {rating['time'].iloc[-1]}\")\n # print(f\"Last player time is {rating['player_time'].iloc[-1]}\")\n # Browser time is more reliable than the player callback\n rating = rating.drop(columns=['playerTime'])\n # Browser time is in ms\n rating['time'] = rating['time'] / 1000\n\n # Add a beginning rating that starts at the midpoint\n # (oops, I should have had the task do this)\n rating.loc[-1] = [0.0, 0.5]\n rating.index = rating.index + 1 # shifting index forward\n\n # Sometimes not sorted, unclear why\n rating = rating.sort_values('time')\n\n # Add an end rating that just drags out what they started with\n # if they didn't move the mouse for a while\n last_rating_time = rating['time'].iloc[-1]\n last_time = last_rating_time\n\n if last_original_time > last_rating_time:\n last_time = last_original_time\n new_row = {'time':last_time, 'rating':rating['rating'].iloc[-1]}\n rating = rating.append(new_row, ignore_index=True)\n\n return rating, last_time\n\n\nclass Unpacker():\n def __init__(self, path, start_date):\n self.conn = sqlite3.connect(path)\n self.start_date = start_date\n\n def execute(self, sql):\n cur = self.conn.cursor()\n cur.execute(sql)\n self.conn.commit()\n\n def select(self, sql):\n cur = self.conn.cursor()\n cur.execute(sql)\n return cur.fetchall()\n\n def unpack(self):\n # Map of labjs session data by ppt id and then by session\n sessions = {}\n for row in self.select(\"select * from labjs where metadata like '%\\\"payload\\\":\\\"full\\\"%'\"):\n rowid = row[0]\n # This is the internal unique id for a given \"session\" of the task, not the \"session\" passed in via URL parameter\n labjs_session = row[1]\n\n # The data is a JSON-encoded array in the last column\n data = json.loads(row[5])\n for thing in data:\n if thing['sender'] == 'Instructions Start':\n if 'ppt' in thing:\n ppt = thing['ppt']\n logging.info(f\"PPT {ppt}: Reading row {rowid} for session {labjs_session}\")\n\n if thing['sender'] == 'Video':\n trial_count = 0\n if 'trial_count' in thing:\n trial_count = thing['trial_count']\n ppt = thing['ppt']\n if not ppt in sessions:\n sessions[ppt] = {}\n\n ppt_session = str(thing['session']) or \"1\"\n if not ppt_session in sessions[ppt]:\n sessions[ppt][ppt_session] = []\n\n timestamp = dateutil.parser.parse(thing['timestamp']).astimezone(CST)\n\n logging.debug(f\"Got video {trial_count} with {len(thing['response'])} mouse movements for {ppt} session {ppt_session} at {timestamp}\")\n\n to_save = {\n 'affect': thing['affect'],\n 'trial_count': trial_count,\n 'response': thing['response'],\n 'ppt': thing['ppt'],\n 'ppt_session': ppt_session,\n 'labjs_session': labjs_session,\n 'timestamp': timestamp,\n }\n if 'video_filename' in thing:\n to_save['video_filename'] = thing['video_filename']\n\n # Now we skip this if the timestamp is after the given start date\n # (but we add everything if the start date is not specified)\n if not self.start_date or timestamp.date() >= self.start_date:\n sessions[ppt][ppt_session].append(to_save)\n\n return sessions\n \n\nclass Aggregator():\n def __init__(self, data):\n # Here we just want to get aggregated \"mean\" ratings for the comparer to use later\n\n self.vids = {}\n self.ppts = {}\n self.short_name = {}\n self.original_videos = {}\n self.original_video_length = {}\n\n # Cache original file lengths\n def get_original_length(name):\n if name in self.original_video_length:\n return self.original_video_length[name]\n else:\n original, short_name = load_original(vid['video_filename'])\n\n time = original['time'].iloc[-1]\n self.original_video_length[name] = time\n original_sampled = sample_frame(original, time)\n self.original_videos[name] = original_sampled\n self.short_name[name] = short_name\n return time\n\n for ppt in data.keys():\n for session, vids in data[ppt].items():\n for vid in vids:\n filename = vid['video_filename']\n\n rating = pd.DataFrame(vid['response'])\n if len(rating.index) > 0:\n rating, last_time = fix_ratings(rating, get_original_length(filename))\n # Resample to second bins\n rating_sampled = sample_frame(rating, last_time)\n if not filename in self.vids:\n self.vids[filename] = []\n if not ppt in self.ppts:\n self.ppts[ppt] = {}\n if not session in self.ppts[ppt]:\n self.ppts[ppt][session] = []\n self.vids[filename].append(rating_sampled)\n self.ppts[ppt][session].append({\n 'filename': filename,\n 'rating': rating,\n 'rating_sampled': rating_sampled,\n 'trial_count': vid['trial_count'],\n 'affect': vid['affect'],\n 'labjs_session': vid['labjs_session'],\n 'timestamp': vid['timestamp'],\n })\n\n self.means = {}\n # OK, now we have a hash by video file and can average them together...\n for vid in self.vids.keys():\n ratings_for_video = self.vids[vid]\n all_ratings = pd.concat(ratings_for_video, axis=1)\n means = all_ratings.mean(axis=1)\n df_means = pd.DataFrame(means)\n df_means.columns = ['rating']\n self.means[vid] = df_means\n\n\nclass OriginalRaterPlots():\n def __init__(self, agg, output_dir):\n # Make some plots showing original raters plus aggregated mean participant ratings\n for name in agg.original_videos.keys():\n mean_ratings = agg.means[name]\n original_sampled = agg.original_videos[name]\n\n ax = plt.gca()\n original_sampled.plot(kind='line',use_index=True,y='rating',ax=ax,label='Original Actor')\n mean_ratings.plot(kind='line',use_index=True,y='rating',ax=ax,label='Mean Ratings')\n ax.get_figure().savefig(os.path.join(output_dir, f'video_mean_plot_{name}.png'))\n plt.clf()\n\nclass Comparer():\n def __init__(self, ppt, agg, tsvwriter, output_dir):\n for session, trials in agg.ppts[ppt].items():\n if len(trials) != 6:\n logging.warning(f\"Got {len(trials)} for {ppt} in {session}\")\n # Write summary stats and plots for each trial this participant did\n for trial in trials:\n trial_count = trial['trial_count']\n affect = trial['affect']\n timestamp = trial['timestamp']\n name = trial['filename']\n\n # Get original actor's ratings, previously loaded and resampled by aggregator\n original_sampled = agg.original_videos[name]\n short_name = agg.original_videos[name]\n\n # Get the mean ratings for this video\n mean_ratings = agg.means[name]\n\n # Compare with our resampled ratings for this trial\n rating_sampled = trial['rating_sampled']\n\n pearson_correlation_original = original_sampled.corrwith(rating_sampled, axis=0)\n pearson_correlation_mean_participant = mean_ratings.corrwith(rating_sampled, axis=0)\n tsvwriter.writerow([\n ppt, session, trial_count, affect, timestamp, name,\n float(pearson_correlation_original),\n float(pearson_correlation_mean_participant)])\n\n ax = plt.gca()\n\n original_sampled.plot(kind='line',use_index=True,y='rating',ax=ax,label='Original Actor')\n mean_ratings.plot(kind='line',use_index=True,y='rating',ax=ax,label='Mean Ratings')\n rating_sampled.plot(kind='line',use_index=True,y='rating',color='red',ax=ax,label=f'Participant {ppt}')\n\n ax.get_figure().savefig(os.path.join(output_dir, f'plot_{ppt}_{session}_figure{trial_count}.png'))\n plt.clf()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Extract usable data from lab.js sqlite database for Empathic Accuracy task')\n parser.add_argument('-v', '--verbose', action='count')\n parser.add_argument('-s', '--start-date', type=datetime.date.fromisoformat,\n help=\"Only include data after a given ISO-formatted date\")\n parser.add_argument('db')\n parser.add_argument('output')\n args = parser.parse_args()\n\n if args.verbose:\n if args.verbose > 1:\n coloredlogs.install(level='DEBUG')\n elif args.verbose > 0:\n coloredlogs.install(level='INFO')\n else:\n coloredlogs.install(level='WARN')\n\n if os.path.exists(args.db):\n u = Unpacker(args.db, args.start_date)\n data = u.unpack()\n\n tsv_path = os.path.join(args.output, f'eat_summary.tsv')\n with open(tsv_path, 'w') as tsvfile:\n tsvwriter = csv.writer(tsvfile, delimiter='\\t')\n tsvwriter.writerow(['ppt', 'session', 'trial', 'affect', 'timestamp', 'video_name', 'original_rater_pearson_coefficient', 'mean_participant_pearson_coefficient'])\n agg = Aggregator(data)\n OriginalRaterPlots(agg, args.output)\n for ppt in agg.ppts.keys():\n comp = Comparer(ppt, agg, tsvwriter, args.output)\n\n else:\n logging.error(\"DB path does not exist\")\n sys.exit(1)\n","sub_path":"unpack-labjs-from-sqlite.py","file_name":"unpack-labjs-from-sqlite.py","file_ext":"py","file_size_in_byte":11943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"77544796","text":"import Analysis.source_selector as ss\n\ndef select_analysis():\n trigger_one = ''\n print('--> 1 : Golden/Black Cross.')\n print('--> 2 : Relative Strength Index.')\n\n while trigger_one != 1 and trigger_one != 2:\n trigger_one = int(input('Select which analysis tool to run: '))\n\n if trigger_one == 1:\n analysis = 'GB_Cross'\n ss.select_data_type(analysis)\n\n if trigger_one == 2:\n print('--> 1 : Create Relative Strength Index.')\n print('--> 2 : Analyse Relative Strength Index.')\n trigger_two = ''\n while trigger_two != 1 and trigger_two != 2:\n trigger_two = int(input('Select which analysis tool to run: '))\n\n if trigger_two == 1:\n analysis = 'RSI_Create'\n type = '\\\\Compiled_Data'\n ss.select_data(type, analysis)\n elif trigger_two == 2:\n analysis = 'RSI_Analyse'\n type = '\\\\Compiled_Data'\n ss.select_data(type, analysis)\n","sub_path":"Analysis/analysis_selector.py","file_name":"analysis_selector.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"523134137","text":"import sys\nimport numpy as np\nimport os\nimport tensorflow as tf\nfrom skimage import io\nimport urllib.request\n#os.environ[\"CUDA_VISIBLE_DEVICES\"] = '0'\nsys.path.append(\"D:/graduation_project/workspace/models/research/slim\")\n\nfrom matplotlib import pyplot as plt\nfrom datasets import imagenet\nfrom nets import vgg\nfrom preprocessing import vgg_preprocessing\nimport time\ncheckpoints_dir = 'D:/graduation_project/checkpoints'\n\nslim = tf.contrib.slim\n\n# 网络模型的输入图像有默认的尺寸\n# 因此,我们需要先调整输入图片的尺寸\nimage_size = vgg.vgg_16.default_image_size\nsess2 = tf.Session()\nwith tf.Graph().as_default():\n # 读取图片\n # url = (\"https://upload.wikimedia.org/wikipedia/commons/d/d9/First_Student_IC_school_bus_202076.jpg\")\n url = ('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1512416144146&di=69f1c6faea06cd374b3d0808ab9acde8&imgtype=0&src=http%3A%2F%2Fphotos.pkone.cn%2Fwx%2FSHIRE_IMAGESIGN_MEDIUM%2F2009%2F04%2F18%2F216ab01a-a23a-4ea2-8677-1b889fa063b1%2F24d29263-8aaf-45a4-96d0-72bd9747bfd2.jpg')\n # Open specified url and load image as a string\n image_string = urllib.request.urlopen(url).read()\n\n # image_string = io.imread('D:/graduation_project/workspace/image_data/First_Student_IC_school_bus_202076.jpg').tostring()\n\n # 将图片解码成jpeg格式\n image = tf.image.decode_jpeg(image_string, channels=3)\n # print(type(image))\n # print(image)\n # 对图片做缩放操作,保持长宽比例不变,裁剪得到图片中央的区域\n # 裁剪后的图片大小等于网络模型的默认尺寸\n processed_image = vgg_preprocessing.preprocess_image(image,\n image_size,\n image_size,\n is_training=False)\n\n # 可以批量导入图像\n # 第一个维度指定每批图片的张数\n # 我们每次只导入一张图片\n # print(type(processed_image))\n # plt.figure()\n # plt.imshow(processed_image.astype(np.uint8))\n # plt.suptitle(\"ori image\", fontsize=14, fontweight='bold')\n # plt.axis('off')\n # plt.show()\n print(processed_image.shape)\n print(type(processed_image))\n processed_images = tf.expand_dims(processed_image, 0)\n print(processed_images.shape)\n print(type(processed_images))\n print(processed_images[0])\n # plt.figure()\n # plt.imshow(processed_image.astype(np.uint8))\n # plt.suptitle(\"processed image\", fontsize=14, fontweight='bold')\n # plt.axis('off')\n # plt.show()\n # 创建模型,使用默认的arg scope参数\n # arg_scope是slim library的一个常用参数\n # 可以设置它指定网络层的参数,比如stride, padding 等等。\n with slim.arg_scope(vgg.vgg_arg_scope()):\n logits, _ = vgg.vgg_16(processed_images,\n num_classes=1000,\n is_training=False)\n\n # 我们在输出层使用softmax函数,使输出项是概率值\n probabilities = tf.nn.softmax(logits)\n\n # 创建一个函数,从checkpoint读入网络权值\n init_fn = slim.assign_from_checkpoint_fn(\n os.path.join(checkpoints_dir, 'vgg_16.ckpt'),\n slim.get_model_variables('vgg_16'))\n print(slim.get_model_variables())\n time1 = time.time()\n # saver = tf.train.Saver()\n saver = tf.train.Saver(var_list=slim.get_variables('vgg_16/fc8'))\n with tf.Session() as sess:\n\n # 加载权值\n time2 = time.time()\n init_fn(sess)\n saver.save(sess, \"D:/graduation_project/dummy_checkpoints/save_test.ckpt\")\n print('Time1: ', time.time() - time1)\n print('Time2:', time.time() - time2)\n # # 图片经过缩放和裁剪,最终以numpy矩阵的格式传入网络模型\n # np_image, network_input, probabilities = sess.run([image,\n # processed_image,\n # probabilities])\n # print(probabilities.shape, type(probabilities))\n # probabilities = probabilities[0, 0:]\n # print(probabilities.shape, type(probabilities))\n # sorted_inds = [i[0] for i in sorted(enumerate(-probabilities),\n # key=lambda x:x[1])]\n # # 显示下载的图片\n # # plt.figure()\n # # plt.imshow(np_image)\n # # print(type(np_image.astype(np.uint8)))\n # # plt.suptitle(\"Downloaded image\", fontsize=14, fontweight='bold')\n # # plt.axis('off')\n # # plt.show()\n # #\n # # # 显示最终传入网络模型的图片\n # # # 图像的像素值做了[-1, 1]的归一化\n # # # to show the image.\n # # plt.imshow(network_input / (network_input.max() - network_input.min()))\n # # plt.suptitle(\"Resized, Cropped and Mean-Centered in put to network\",\n # # fontsize=14, fontweight='bold')\n # # plt.axis('off')\n # # plt.show()\n #\n # names = imagenet.create_readable_names_for_imagenet_labels()\n # for i in range(5):\n # index = sorted_inds[i]\n # # 打印top5的预测类别和相应的概率值。\n # print('Probability %0.2f => [%s]' % (probabilities[index], names[index+1]))\n #\n # res = slim.get_model_variables()\n\n\n","sub_path":"pre_Feb_work/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"239540026","text":"import requests\nimport logging\nimport src.models.representative as Representative\n\n\nclass RepresentativeCollector:\n\n \"\"\"\n This class will control the collection of data related to representatives\n of any kind.\n \"\"\"\n # Config is assumed to be JSON pulled from config.json in the base\n # directory\n\n def __init__(self, config):\n \"\"\"\n Initialize the necessary variables using values from config.\n \"\"\"\n logging.info(\"Initializing RepresentativeCollector\")\n self.config = config\n logging.debug(self.config)\n govtrack = config[\"govtrack\"]\n sunlight = config[\"sunlight_congress\"]\n govtrack_api = govtrack[\"apiBaseLink\"]\n sunlight_api = sunlight[\"apiBaseLink\"]\n self.sunlight_key = config[\"api_keys\"][\"Sunlight Foundation\"]\n self.govtrack_all = str(govtrack_api +\n govtrack[\"apiSubLinks\"]\n [\"All Representatives\"]\n [\"link\"] +\n \"?current=true&limit=%d\" %\n int(govtrack[\"limit\"]))\n logging.info(\"Govtrack All: %s\" % self.govtrack_all)\n self.govtrack_rep_link = str(govtrack_api + govtrack[\"apiSubLinks\"]\n [\"Representative\"]\n [\"link\"])\n logging.info(\"GovTrack Rep Link: %s\" % self.govtrack_rep_link)\n self.sunlight_rep_link = str(sunlight_api +\n sunlight[\"apiSubLinks\"]\n [\"Representative\"]\n [\"link\"] %\n \"?bioguide_id=%s&apikey=%s\")\n logging.info(\"Sunlight Foundation Rep Link: %s\" %\n self.sunlight_rep_link)\n self.collect()\n\n def collect(self):\n \"\"\"\n Collect each rep and write it to the database.\n \"\"\"\n representative_list_request = requests.get(self.govtrack_all)\n logging.info(\"Response: %s\" % representative_list_request)\n\n representative_list = representative_list_request.json()[\"objects\"]\n\n for representative in representative_list:\n bioguide_id = representative[\"person\"][\"bioguideid\"]\n govtrack_rep = self.make_govtrack_rep(representative)\n logging.debug(govtrack_rep)\n logging.info(\"Working on: %s %s, %s\" % (\n govtrack_rep[\"firstname\"],\n govtrack_rep[\"lastname\"],\n govtrack_rep[\"title\"]))\n try:\n sunlight_rep_request = requests.get(\n self.sunlight_rep_link % (\n bioguide_id, self.sunlight_key\n ))\n logging.info(\"Response: %s\" % sunlight_rep_request)\n sunlight_rep = sunlight_rep_request.json()[\"results\"][0]\n logging.debug(sunlight_rep)\n except IndexError:\n logging.info(\"No results for %s %s, %s\" % (\n govtrack_rep[\"firstname\"],\n govtrack_rep[\"lastname\"],\n govtrack_rep[\"title\"]))\n sunlight_rep = {}\n\n rep = Representative.Representative(\n govtrack_rep,\n sunlight_rep,\n self.config)\n rep.write_to_database()\n # break # uncomment during dev to perform single iteration\n\n def make_govtrack_rep(self, gt_rep):\n \"\"\"\n Use gt_rep to build a dictionary defining a single representative and\n return it.\n \"\"\"\n rep = {\n \"firstname\": gt_rep[\"person\"][\"firstname\"],\n \"middlename\": gt_rep[\"person\"][\"middlename\"],\n \"lastname\": gt_rep[\"person\"][\"lastname\"],\n \"name_suffix\": gt_rep[\"person\"][\"namemod\"],\n \"nickname\": gt_rep[\"person\"][\"nickname\"],\n \"gender\": gt_rep[\"person\"][\"gender\"][0],\n \"birthday\": gt_rep[\"person\"][\"birthday\"],\n \"chamber\": gt_rep[\"title\"][0:3],\n \"state\": gt_rep[\"state\"],\n \"rank\": gt_rep[\"senator_rank\"],\n \"party\": gt_rep[\"party\"][0],\n \"senate_class\": gt_rep[\"senator_class\"][-1] if\n gt_rep[\"senator_class\"] else \"\",\n \"title\": gt_rep[\"title\"][0:3],\n \"leadership_title\": gt_rep[\"leadership_title\"],\n \"term_start\": gt_rep[\"startdate\"],\n \"term_end\": gt_rep[\"enddate\"],\n \"phone_no\": gt_rep[\"phone\"],\n \"website\": gt_rep[\"website\"],\n \"twitter_id\": gt_rep[\"person\"][\"twitterid\"],\n \"youtube_id\": gt_rep[\"person\"][\"youtubeid\"],\n \"govtrack_id\": gt_rep[\"person\"][\"id\"],\n \"bioguide_id\": gt_rep[\"person\"][\"bioguideid\"],\n \"os_id\": gt_rep[\"person\"][\"osid\"],\n \"votesmart_id\": gt_rep[\"person\"][\"pvsid\"],\n \"cspan_id\": gt_rep[\"person\"][\"cspanid\"],\n \"govtrack_link\": gt_rep[\"person\"][\"link\"],\n }\n return rep\n","sub_path":"src/api/representativecollector.py","file_name":"representativecollector.py","file_ext":"py","file_size_in_byte":5222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"511157830","text":"import math\n\ndef qsort(alist):\n if alist: return qsort([x for x in alist if xalist[0]])\n return []\n\n\ndef merge(left, right):\n lst = []\n while left and right:\n if left[0] < right[0]:\n lst.append(left.pop(0))\n else:\n lst.append(right.pop(0))\n\n if left:\n lst.extend(left)\n\n if right:\n lst.extend(right)\n\n return lst\n\ndef msort(lst):\n length = len(lst)\n if length >= 2:\n mid = int(length / 2)\n lst = merge(msort(lst[:mid]), msort(lst[mid:]))\n\n return lst\n\ndef rsort(lst):\n maxLength = -1\n for number in lst:\n numLength = int(math.log10(int(number)))+1\n if numLength>maxLength:\n maxLength = numLength\n\n buckets=[[] for i in range(0,10)]\n for digit in range(0,maxLength):\n for number in lst:\n buckets[int(int(number)/10**digit%10)].append(number)\n\n del lst[:]\n for bucket in buckets:\n lst.extend(bucket)\n del bucket[:]\n\n return lst\n","sub_path":"1lab/sorts.py","file_name":"sorts.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"483402877","text":"from django.contrib import admin\nfrom .models import Project, Member, File, Directory\n# Register your models here.\n\nclass MemberInLine(admin.TabularInline):\n\tmodel = Member\n\textra = 3\n\nclass ProjectAdmin(admin.ModelAdmin):\n\tfieldsets = [\n\t\t# (None,\t{'fields' : ['admin']}),\n\t\t(None, {'fields' : ['project_name']}),\n\t\t(None, {'fields' : ['project_type']}),\n\t\t(None, {'fields' : ['description']}),\n\t]\n\n\tinlines = [MemberInLine]\n\nadmin.site.register(Project,ProjectAdmin)\nadmin.site.register(Member)\nadmin.site.register(File)\nadmin.site.register(Directory)\n","sub_path":"codeapp/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"503460471","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 17 18:36:21 2016\n\n@author: thomasaref\n\"\"\"\n\n\n\n\nfrom D0514_highfrq1sidelobe import a as d0514\nfrom D0316_S4A1_coupling_midpeak import a as d0316\nfrom D0629_fft_try import a as d0629\n#from D0629_wide_gate_fluxswp import a as d0629wg\nfrom D0506_lowfrq34sidelobe import a as d0506\nfrom D0509_lowfrq2sidelobe import a as d0509\nfrom D0503_lowfrq1sidelobe import a as d0503\nfrom D0518_highfrq3sidelobe import a as d0518\n\nfrom numpy import array, linspace, absolute, sqrt\nfrom taref.plotter.api import line, colormesh, scatter\n\nfrom taref.core.api import process_kwargs\n\nfrom TA88_fundamental import qdt, TA88_Lyzer, TA88_VNA_Lyzer, TA88_Read\nfrom TA53_fundamental import TA53_VNA_Pwr_Lyzer, TA53_Read\n\ncolormesh(qdt.MagAbs)\n\na=TA88_Lyzer( name=\"combo\",\n desc=\"combined data\",\n )\na.save_folder.main_dir=\"fig3_ls2\"\n\nlyzers=[d0514, d0316, d0629, d0518, d0506, d0509, d0503#, d0629wg,\n]\n\nb=TA53_VNA_Pwr_Lyzer(name=\"d1118\", on_res_ind=301,\n rd_hdf=TA53_Read(main_file=\"Data_1118/S3A4_trans_swp_n5n15dBm.hdf5\"),\n fit_indices=[ #range(7, 42), range(79, 120), range(171, 209), range(238, 296),\n range(316, 358),range(391, 518), range(558, 603),\n # range(629, 681), range(715, 771), range(790, 845),\n # range(872, 921), range(953, 960), range(963, 985)\n ],\n desc=\"transmission power sweep\",\n offset=-0.07,\n swp_type=\"yoko_first\",\n )\nb.filt.center=0 #71 #28*0 #141 #106 #58 #27 #139 #106 # #137\nb.filt.halfwidth=100 #8 #10\nb.fitter.gamma=0.3/10 #0.035\nb.flux_axis_type=\"fq\" #\"flux\"#\"fq\" #\nb.end_skip=10\n#a.flux_indices=[range(len(a.yoko)-1)]\nb.pwr_ind=1\n\ndef center_plot(self, **kwargs):\n process_kwargs(self, kwargs, pl=\"center_{0}_{1}_{2}\".format(self.filter_type, self.bgsub_type, self.name))\n\n pl=scatter(self.freq_axis[self.flat_indices], -(array([fp[1] for fp in self.fit_params])-self.freq_axis[self.flat_indices]), **kwargs)\n\n #pl=scatter(self.freq_axis[self.flat_indices], array([fp[1] for fp in self.fit_params]), **kwargs)\n\n # if self.show_quick_fit:\n\n # if self.flux_axis_type==\"fq\":\n # line(self.freq_axis[self.indices], self.ls_f[self.indices]/1e9, plotter=pl, color=\"red\", linewidth=1.0)\n # elif self.flux_axis_type==\"yoko\":\n # line(self.freq_axis[self.indices], self.qdt._get_Vfq0(f=self.frequency[self.indices]), plotter=pl, color=\"red\", linewidth=1.0)\n # else:\n # line(self.freq_axis, self.qdt._get_fluxfq0(f=self.frequency), plotter=pl, color=\"red\", linewidth=1.0)\n # if self.fitter.p_guess is not None:\n # line(self.freq_axis[self.indices], array([pg[1] for pg in self.fitter.p_guess]), pl=pl, color=\"green\", linewidth=1.0) #self.voltage_from_frequency(self.qdt._get_coupling(self.frequency)), plotter=pl, color=\"red\")\n return pl\n\ndef combo_plots():\n pl=\"fig3\"\n\n if 1:\n for d in lyzers:\n d.filter_type=\"FFT\"\n #d.bgsub_type=\"dB\"\n d.show_quick_fit=False\n d.flux_axis_type=\"fq\" #\"flux\"\n #d.fitter.gamma=d.fitter.gamma/10\n d.read_data()\n for d in lyzers:\n pl=center_plot(d, pl=pl, color=\"red\", nrows=2, ncols=2,\n auto_xlim=False, auto_ylim=False)\n\n #pl=d.center_plot(pl=pl, color=\"red\", nrows=2, ncols=2, auto_xlim=False, auto_ylim=False)\n frequency=linspace(3.5e9, 6.5e9, 1000)\n qdt.gate_type=\"constant\"\n\n line(frequency/1e9, qdt._get_Lamb_shift(f=frequency)/1.0/1e9, color=\"red\", pl=pl)\n #V=qdt._get_fq0(f=frequency)#[1]\n #line(frequency/1e9, V/1e9, pl=pl, ylabel=\"Qubit frequency (GHz)\", xlabel=\"Frequency (GHz)\")\n #line(frequency/1e9, frequency/1e9-qdt._get_Lamb_shift(f=frequency)/1.0/1e9, plotter=pl, color=\"purple\", xlabel=\"Frequency (GHz)\",\n # ylabel=\"HWFM (GHz)\")\n qdt.gate_type=\"constant\"\n #line(qdt._get_fluxfq0(f=frequency), frequency/1e9, plotter=pl, color=\"red\")\n\n #line(frequency/1e9, frequency/1e9-qdt._get_Lamb_shift(f=frequency)/1.0/1e9, plotter=pl, color=\"blue\")\n line(array([3.5, 6.5]), array([-1.5, 1.5])-0.3, pl=pl, color=\"green\", linestyle=\"dashed\")\n\n #pl.set_xlim(3.75, 6.1)\n pl.set_xlim(3.5, 6.5)\n\n pl.set_ylim(-1, 1.5)\n\n #pl.set_ylim(3.75, 6.1)\n #pl.add_label(\"a)\")\n pl.axes.set_xlabel(\"Frequency (GHz)\")\n pl.axes.set_ylabel(\"$\\Delta/2\\pi, \\, \\Gamma/2 \\pi$ (GHz)\")\n #pl.show()\n pl1=\"combined_heights\"\n for d in lyzers:\n pl1=d.heights_plot(pl=pl1)\n pl1.yscale=\"log\"\n pl1.xlabel=\"Frequency (GHz)\"\n pl1.ylabel=\"Lorentzian height (a.u.)\"\n pl1.set_xlim(3.8, 6.05)\n pl1.set_ylim(1e-8, 1e-3)\n pl1.add_label(\"b)\")\n\n pl1=\"combined_backgrounds\"\n for d in lyzers:\n pl1=d.background_plot(pl=pl1)\n\n pl1=\"comb_widths\"\n for d in lyzers:\n pl1=d.widths_plot(pl=pl, color=\"black\", facecolor=\"black\", edgecolor=\"black\",)\n #line(frequency/1e9, qdt._get_fFWHM(f=frequency)[2]/2.0/1e9, plotter=pl, color=\"blue\", xlabel=\"Frequency (GHz)\",\n # ylabel=\"HWFM (GHz)\")\n #qdt.gate_type=\"capacitive\"\n #co=qdt._get_coupling(f=frequency)/1.0/1e9\n #line(frequency/1e9, qdt._get_coupling(f=frequency)/1.0/1e9, plotter=pl1, color=\"purple\")\n qdt.gate_type=\"capacitive\"\n #co=qdt._get_coupling(f=frequency)/1.0/1e9\n #line(frequency/1e9, qdt._get_coupling(f=frequency)/1.0/1e9, plotter=pl, color=\"purple\")\n #qdt.gate_type=\"constant\"\n line(frequency/1e9, qdt._get_coupling(f=frequency)/1.0/1e9, plotter=pl,\n color=\"purple\")\n\n\n #co=(co+(idt.sinc(f=frequency)**2)*qdt._get_coupling(f=frequency)/1.0/1e9)/(1.0+(idt.sinc(f=frequency)**2))\n\n #line(frequency/1e9, co, plotter=pl, color=\"blue\", xlabel=\"Frequency (GHz)\",\n # ylabel=\"HWFM (GHz)\")\n\n dephasing=qdt.dephasing\n #deph_slope=qdt.dephasing_slope\n #qdt.dephasing=0.0\n #qdt.dephasing_slope=0.0\n #line(frequency/1e9, qdt._get_fFWHM(f=frequency)[2]/2.0/1e9, plotter=pl, color=\"green\")\n #pl1.set_xlim(3.8, 6.05)\n #pl1.set_ylim(-0.05, 1.15)\n #pl1.add_label(\"c)\")\n\n pl.nplot=2\n for d in lyzers:\n pl=d.widths_plot(pl=pl, color=\"black\", facecolor=\"black\", edgecolor=\"black\",)\n #qdt.dephasing=dephasing\n #line(frequency/1e9, qdt._get_fFWHM(f=frequency)[2]/2.0/1e9, plotter=pl, color=\"blue\")\n qdt.gate_type=\"capacitive\"\n #co=qdt._get_coupling(f=frequency)/1.0/1e9\n #line(frequency/1e9, qdt._get_coupling(f=frequency)/1.0/1e9, plotter=pl, color=\"purple\")\n #qdt.gate_type=\"constant\"\n line(frequency/1e9, qdt._get_coupling(f=frequency)/1.0/1e9, plotter=pl,\n color=\"purple\")\n\n #qdt.dephasing=0.0\n #line(frequency/1e9, qdt._get_fFWHM(f=frequency)[2]/2.0/1e9, plotter=pl, color=\"green\")\n pl.set_xlim(3.75, 6.1)\n pl.set_ylim(-0.01, 0.1)\n #pl.add_label(\"d)\")\n pl.axes.set_xlabel(\"Frequency (GHz)\")\n pl.axes.set_ylabel(\"$\\Gamma/2\\pi$ (GHz) \")\n\n\n pl.nplot=4\n if 1:\n pl2=\"FFT_magabs\"\n pl1=\"Fit_magabs\"\n f=d.frequency\n from numpy import pi\n f=linspace(3e9, 8e9, 501)\n fqq=linspace(2e9, 9e9, 2001)\n magcom=array([qdt._get_simple_S(f=f, YL=-1.0j/f*qdt.Ct*2*pi*fq**2) for fq in fqq])[:, 0, :]\n\n pl=colormesh(fqq/1e9, f/1e9, 1-absolute(magcom).transpose(), pl=pl)\n for d in lyzers:\n d.filter_type=\"Fit\"\n pl1, pf=d.magabs_colormesh(pl=pl1, pf_too=True)#, cmap=\"nipy_spectral\")\n d.bgsub_type=\"dB\"\n d.filter_type=\"FFT\"\n pl2=d.magdB_colormesh(pl=pl2, auto_zlim=False, vmin=-3.0, vmax=0.0)#, cmap=\"nipy_spectral\")\n new_fp=[[fp[0], fp[1], 1.0, 0.0] for fp in d.fit_params]\n new_magabs=sqrt(d.fitter.reconstruct_fit(d.flux_axis[d.flat_flux_indices], new_fp))\n\n #process_kwargs(self, kwargs, pl=\"magabs_{0}_{1}_{2}\".format(self.filter_type, self.bgsub_type, self.name))\n flux_axis=d.flux_axis[d.flat_flux_indices]\n #freq_axis=d.freq_axis[d.indices]\n start_ind=0\n for ind in d.fit_indices:\n pl=colormesh(flux_axis, d.freq_axis[ind], new_magabs[start_ind:start_ind+len(ind), :], pl=pl)\n start_ind+=len(ind)\n\n\n pl.set_xlim(3.8, 6.05)\n pl.set_ylim(3.8, 6.05)\n pl2.set_xlim(3.8, 6.05)\n pl2.set_ylim(3.8, 6.05)\n pl2.add_label(\"a)\")\n pl1.set_xlim(3.8, 6.05)\n pl1.set_ylim(3.8, 6.05)\n pl1.add_label(\"b)\")\n #pls.append(pl)\n #pls.append(pl1)\n\n def MagAbsFit(self):\n return sqrt(self.fitter.reconstruct_fit(self.flux_axis[self.flat_flux_indices], self.fit_params))\n\n def magabs_colormesh(self, **kwargs):\n flux_axis=self.flux_axis[self.flat_flux_indices]\n freq_axis=self.freq_axis[self.indices]\n start_ind=0\n for ind in self.fit_indices:\n pl=colormesh(flux_axis, self.freq_axis[ind], self.MagAbs[start_ind:start_ind+len(ind), :], **kwargs)\n start_ind+=len(ind)\n\n\n b.read_data()\n\n b.filter_type=\"None\"\n b.show_quick_fit=False\n #pl_raw=b.magabs_colormesh()\n #b.bgsub_type=\"dB\"\n #b.magabs_colormesh()\n #pl1=colormesh(absolute(a.MagcomData[:, :, 30]))\n\n #pl_ifft=b.ifft_plot()#.show()\n #a.pwr_ind=22\n\n b.filter_type=\"FFT\"\n #pl_fft=b.magabs_colormesh()#.show()\n b.bgsub_type=\"None\"\n #pl1=b.magdB_colormesh()\n #pl2=b.magabs_colormesh()\n b.filter_type=\"Fit\"\n #b.magabs_colormesh(pl=pl2)\n #b.magdB_colormesh(pl=pl1)\n #pl.nplot=3\n pl=center_plot(b, color=\"red\", auto_xlim=False, x_min=3.75, x_max=5.1,\n auto_ylim=False, y_min=3.75, y_max=5.1, pl=pl, nrows=2, ncols=2, nplot=3)\n b.qdt.gate_type=\"constant\"\n b.qdt.K2=0.032\n\n line(frequency/1e9, b.qdt._get_Lamb_shift(f=frequency)/1.0/1e9, color=\"red\", pl=pl)\n line(array([3.5, 6.5]), array([-1.5, 1.5])+0.5, pl=pl, color=\"green\", linestyle=\"dashed\")\n\n\n #pl=b.center_plot(color=\"red\", auto_xlim=False, x_min=3.75, x_max=5.1,\n # auto_ylim=False, y_min=3.75, y_max=5.1, pl=pl, nrows=2, ncols=2, nplot=3)\n\n #pl.nplot=4\n pl_widths=b.widths_plot(color=\"black\", facecolor=\"black\", edgecolor=\"black\", auto_xlim=False, x_min=3.5, x_max=5.5,\n auto_ylim=False, y_min=-0.5, y_max=0.5, pl=pl)#.show()\n\n pl.nplot=3\n\n b.pwr_ind=0\n b.fit_indices=[ range(7, 42), range(79, 120), range(171, 209), range(238, 291), #range(558, 603),\n range(629, 681),\n range(715, 764), range(803, 835),\n range(879, 915), range(953, 960), range(963, 985)]\n\n b.get_member(\"fit_params\").reset(b)\n b.get_member(\"MagcomFilt\").reset(b)\n b.fitter.fit_params=None\n pl_centers=center_plot(b, color=\"red\", auto_xlim=False, x_min=3.5, x_max=5.5,\n auto_ylim=False, y_min=-0.3, y_max=0.3, pl=pl)\n\n #pl_centers=b.center_plot(color=\"red\", auto_xlim=False, x_min=3.75, x_max=5.1,\n # auto_ylim=False, y_min=3.75, y_max=5.1, pl=pl)\n\n b.qdt.gate_type=\"constant\"\n frequency=linspace(3.5e9, 5.5e9, 1000)\n line(frequency/1e9, frequency/1e9-b.qdt._get_Lamb_shift(f=frequency)/1.0/1e9, plotter=pl, color=\"blue\")\n line(array([3.5, 5.5]), array([3.5, 5.5]), pl=pl_centers, color=\"green\")\n #pl.axes.set_xlabel(\"Frequency (GHz)\")\n #pl.axes.set_ylabel(\"Qubit Frequency (GHz)\")\n #pl.nplot=4\n pl_widths=b.widths_plot(color=\"black\", facecolor=\"black\", edgecolor=\"black\", auto_xlim=False, x_min=3.5, x_max=5.5,\n auto_ylim=False, y_min=-0.3, y_max=0.5, pl=pl)#.show()\n #qdt.gate_type=\"constant\"\n b.qdt.gate_type=\"capacitive\"\n #b.qdt.gate_type=\"constant\"\n #co=qdt._get_coupling(f=frequency)/1.0/1e9\n line(frequency/1e9, b.qdt._get_coupling(f=frequency)/1.0/1e9, plotter=pl, color=\"purple\")\n #b.qdt.gate_type=\"constant\"\n #line(frequency/1e9, b.qdt._get_coupling(f=frequency)/1.0/1e9, plotter=pl, color=\"green\")\n\n #line(frequency/1e9, b.qdt._get_coupling(f=frequency)/1.0/1e9, plotter=pl, color=\"green\")\n\n pl.axes.set_xlabel(\"Frequency (GHz)\")\n pl.axes.set_ylabel(\"$\\Delta/2\\pi, \\, \\Gamma/2 \\pi$ (GHz)\")\n pl.figure.text(0.0, 0.95, \"a)\")\n pl.figure.text(0.0, 0.45, \"b)\")\n pl.figure.text(0.5, 0.95, \"c)\")\n pl.figure.text(0.5, 0.45, \"d)\")\n\n# pl.nplot=4\n#\n# c=TA88_VNA_Lyzer(on_res_ind=215,# VNA_name=\"RS VNA\", filt_center=15, filt_halfwidth=15,\n# rd_hdf=TA88_Read(main_file=\"Data_0704/S4A4_gate_flux_swp.hdf5\"))\n#\n# c.filt.center=40#0 #107\n# c.filt.halfwidth=60\n# #a.fitter.fit_type=\"lorentzian\"\n# #a.fitter.gamma=0.01\n# c.flux_axis_type=\"flux\"#\"yoko\"#\n# c.end_skip=10\n# c.read_data()\n# #a.ifft_plot()\n#\n# c.bgsub_type=\"dB\"\n# #a.bgsub_type=\"Complex\"\n# c.filter_type=\"FFT\"\n# line(c.freq_axis[c.indices], c.MagAbs[:, 222], pl=pl,\n# auto_xlim=False, y_min=0.96, y_max=1.02,\n# auto_ylim=False, x_min=3.5, x_max=7.5)\n #c.magabs_colormesh(vmin=0.987, vmax=1.00, cmap=\"afmhot\",\n # auto_zlim=False, pl=pl,\n # auto_xlim=False, x_min=0.0, x_max=1.5,\n # auto_ylim=False, y_min=3.5, y_max=7.5)#.show()\n\n\n pl.figure.tight_layout()\n return pl\n\nif __name__==\"__main__\":\n pl=combo_plots()\n #a.save_plots([pl])\n\n pl.show()\n\n","sub_path":"Lamb_shift/fig3_lamb_shift2.py","file_name":"fig3_lamb_shift2.py","file_ext":"py","file_size_in_byte":13843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"459194533","text":"#-*- coding: utf8 -*-\n\nfrom __future__ import print_function, division\n\nclass Board(object):\n def __init__(self, grid):\n self.grid = grid\n\n def normalize(self):\n for r in range(0, 9):\n for c in range(0, 9):\n self.grid[r][c] = int(self.grid[r][c])\n\n def display(self):\n for r in range(0, 9):\n if r==3 or r==6:\n print('- '*11)\n for c in range(0, 9):\n if c==3 or c==6:\n print('|', end=' ')\n print(self.grid[r][c], end=' ')\n print('')\n print('')\n\n def solve(self):\n rowInfos = [Info(i, 0) for i in range(0, 9)]\n colInfos = [Info(i, 0) for i in range(0, 9)]\n blkInfos = [Info(i, 0) for i in range(0, 9)]\n for r in range(0, 9):\n for c in range(0, 9):\n b = int(r/3)*3 + int(c/3)\n v = self.grid[r][c]\n if v:\n rowInfos[r].incr()\n colInfos[c].incr()\n blkInfos[b].incr()\n else:\n rowInfos[r].set_point(r, c)\n colInfos[c].set_point(r, c)\n blkInfos[b].set_point(r, c)\n xr = self.find_max_occupied_but_not_full(rowInfos)\n if xr is None:\n return True\n xc = self.find_max_occupied_but_not_full(colInfos)\n xb = self.find_max_occupied_but_not_full(blkInfos)\n mini = self.find_max_occupied_but_not_full((xr, xc, xb))\n for i in range(1, 10):\n if self.check_num_at(i, mini.r, mini.c):\n self.grid[mini.r][mini.c] = i\n if self.solve():\n return True\n self.grid[mini.r][mini.c] = 0\n return False\n\n def check_num_at(self, n, r, c):\n for i in range(0, 9):\n if self.grid[r][i] == n:\n return False\n if self.grid[i][c] == n:\n return False\n br = int(r/3)*3\n bc = int(c/3)*3\n for r in range(br, br+3):\n for c in range(bc, bc+3):\n if self.grid[r][c] == n:\n return False\n return True\n\n def find_max_occupied_but_not_full(self, ls):\n maxi = ls[0]\n for i in ls[1:]:\n if maxi.num < i.num < 9 or maxi.num==9:\n maxi = i\n return maxi if maxi.num<9 else None\n\nclass Info(object):\n def __init__(self, idx, num):\n self.idx, self.num = idx, num\n self.r = self.c = -1\n\n def set_point(self, r, c):\n self.r, self.c = r, c\n\n def incr(self):\n self.num += 1\n return self.num\n\n def decr(self):\n self.num -= 1\n return self.num\n\n def __lt__(self, i):\n return self.num < i.num\n\n def __str__(self):\n return '(%d, %d, %d, %d)' % (self.idx, self.num, self.r, self.c)\n\n def __repr__(self):\n return self.__str__()\n\nif __name__ == '__main__':\n import sys\n with open('files/sudoku.txt' if len(sys.argv)==1 else sys.argv[1]) as file:\n sum = 0\n item = 0\n while True:\n if not file.readline():\n break\n item += 1\n gd = []\n n = 0\n while n<9:\n gd.append(list(file.readline().strip()))\n n += 1\n brd = Board(gd)\n brd.normalize()\n assert brd.solve()\n brd.display()\n sum += brd.grid[0][0]*100 + brd.grid[0][1]*10 + brd.grid[0][2]\n print(item, sum)\n print(sum)\n","sub_path":"Euler/p96-sudoku.py","file_name":"p96-sudoku.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"455560318","text":"H,W = map(int,input().rstrip().split(\" \"))\nN = int(input())\na = list(map(int,input().rstrip().split(\" \")))\nans = [[0 for _ in range(W)]for _ in range(H)]\nnowx = 0\nnowy = 0\niki = True\nfor i in range(N):\n for j in range(a[i]):\n ans[nowy][nowx] = i+1\n if iki:\n nowx += 1\n if nowx >= W:\n nowx = W - 1\n nowy += 1\n iki = False\n else:\n nowx -= 1\n if nowx < 0:\n nowx = 0\n nowy += 1\n iki = True\nfor i in range(H):\n print(\" \".join(map(str,ans[i])))","sub_path":"Python_codes/p03638/s404978740.py","file_name":"s404978740.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"4073362","text":"import discord\nfrom discord.ext import commands\nfrom utils import card as cards\nfrom utils.db import *\nimport json\nfrom discord_slash import SlashCommand\nfrom discord_slash.model import SlashCommandPermissionType\nfrom discord_slash.utils.manage_components import wait_for_component\nfrom discord_slash.utils.manage_components import create_button, create_actionrow\nfrom discord_slash.utils.manage_commands import create_option, create_permission\nfrom discord_slash.model import ButtonStyle\nfrom discord_slash import cog_ext\nclass economy(commands.Cog):\n def __init__(self, bot:commands.Bot):\n self.bot = bot\n @commands.guild_only()\n @cog_ext.cog_slash(name='rank', description='Ранк', guild_ids=[761991504793174117], options=[\n create_option(\n name='участник',\n description='Участник, чей ранк ты хочешь посмотреть.',\n required=False,\n option_type=6\n )], connector={'участник':'member'})\n async def rank(self, ctx, member=None):\n if not member:\n member=ctx.author\n \n try:\n ecc=geteco(ctx.guild.id, member.id)\n except Exception as e:\n print(e)\n seteco(ctx.guild.id, member.id, 0, 1, 100)\n ecc=geteco(ctx.guild.id, member.id)\n lvl=ecc['lvl']\n nextxp=ecc['nextxp']\n xp=ecc['xp']\n card=cards.RankCard()\n await card.setBackground(url='https://images.unsplash.com/photo-1600758208050-a22f17dc5bb9?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80')#(color='#98afc1')\n await card.setTextColor(color = \"#a4a4ac\")\n await card.setStatus(status = member.status)\n await card.setStatusBack(color = \"#4e6b7f\")\n await card.setAvatar(avatar = member.avatar_url)\n await card.setAvatarBack(color = \"#4e6b7f\")\n await card.setName(name = member.name)\n await card.setTag(tag = member.discriminator)\n await card.setLvl(lvl = lvl)\n await card.setXp(xp = xp)\n await card.setXpToNextLvl(xp = nextxp)\n await card.setBarColor(color = \"#273e55\")\n await card.setBarBack(color = \"#4e6b7f\")\n await card.setDisplayProcents(True)\n await card.setTextStyle(path='bot/font.ttf')\n file = await card.create()\n await ctx.send(file = discord.File(fp = file, filename = \"rank.png\"))\n \n @commands.Cog.listener()\n async def on_message(self, message:discord.Message):\n if message.channel.type != 'private':\n try:\n ecc=geteco(message.guild.id, message.author.id)\n except:\n seteco(message.guild.id, message.author.id, 0, 1, 100)\n ecc=geteco(message.guild.id, message.author.id)\n print(ecc['nextxp'])\n lenn=len((message.content))\n if lenn>=ecc['lvl']*10:\n lenn=ecc['lvl']\n if ecc['nextxp']<=lenn:\n seteco(message.guild.id, message.author.id, 0, ecc['lvl']+1, (ecc['lvl']+1)*100)\n else:\n seteco(message.guild.id, message.author.id, ecc['xp']+lenn, ecc['lvl'], ecc['nextxp']-lenn)\n \n \ndef setup(bot:commands.Bot):\n bot.add_cog(economy(bot))","sub_path":"bot/cogs/economy.py","file_name":"economy.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"583702742","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 5 12:03:55 2019\n\n@author: Ilker Meric\n\nDetermine and plot hit multiplicities (number of responding segments) with segmentation.\nCriterion:\n At least one hit in a given segment !\nNote:\n These multiplicities are not corrected for multiple interactions in a given segment.\n Multiple hits in a given segment are counted as a single hit.\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\ndef read_file(file):\n data = np.loadtxt(fname=file, delimiter=' ')\n return data\n\nif(len(sys.argv) != 5):\n raise RuntimeError (\"Please pass all the arguments!\" ) \nfilename = sys.argv[1]\nFractionIncidentPhotons = float(sys.argv[2])\nTotalPhotons = float(sys.argv[3])\nIncidentPhotonEnergy = float(sys.argv[4])\n\nIncidentPhotons = FractionIncidentPhotons * TotalPhotons\n\ndata = read_file(filename)\nimax = len(data)\nCurrentHistoryNo = data[0,0]\nCurrentHitSegment = data[0,-1]\n\nMultiplicities = np.zeros(11)\nStoreHitSegment = []\ncounts = 0\nHistoryflag = False\nSegmentflag = False\n\nfor i in range(len(data)):\n \n if(CurrentHistoryNo != data[i,0]): # New particle history, 1st hit \n Historyflag = True\n counts = 0\n if(Historyflag == True):\n StoreHitSegment = np.array(StoreHitSegment)\n u = np.unique(StoreHitSegment)\n \n counts = len(u)\n if(counts >= len(Multiplicities)):\n Multiplicities[-1] += 1\n else:\n Multiplicities[counts] += 1\n StoreHitSegment =[]\n \n CurrentHistoryNo = data[i,0]\n StoreHitSegment.append(data[i,-1])\n \n continue\n if(CurrentHistoryNo == data[i,0] and CurrentHistoryNo != 0): # Same particle history\n \n StoreHitSegment.append(data[i,-1])\n Historyflag = False\n continue\n \nMultiplicities = Multiplicities / IncidentPhotons\n\nprint(Multiplicities)\n\nypos = np.arange(1,11,1)\n\nplt.figure()\n\nplt.bar(ypos,Multiplicities[1:],0.35,align='center')\nplt.title( str(IncidentPhotonEnergy) + \" MeV photons with segmentation\")\nplt.xlabel(\"Segment multiplicities\")\nplt.ylabel(\"Normalized entries\")\nplt.yscale(\"log\")\nplt.xticks(ypos, ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10+'))\n\nplt.savefig('SegmentMultiplicities.png', dpi=250, bbox_inches='tight')\n\n#plt.show()\n","sub_path":"PointSources/Photons/PythonScripts/SegmentMultiplicities.py","file_name":"SegmentMultiplicities.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"2596770","text":"import json,os\nfrom unittest.mock import patch, ANY\nimport mafiaManageSlack\nfrom tests.unit.testHelpers import createMafia\nfrom models.gameState import Game, States\nfrom stateManagers.gameStateManager import Actions\nfrom data_access.dataRepos import GameStateRepo\n\nos.environ['DYNAMODB_TABLE'] = 'test_table'\nos.environ['TOKEN_SOURCE'] = 'test_table2'\n\ndef createSqsEvent(body):\n return {\n 'Records' : [\n {\n 'body':json.dumps(body)\n }\n ]\n }\ndef test_StartGame_CreatesChannelAndInvitesMafia():\n repo = GameStateRepo()\n game = Game()\n testpId = 'test'\n testMafiaChannelId = 'testChannel'\n game.players = [createMafia(id=testpId)]\n game.state = States.NIGHT\n game.meta = {'channel_id':'channel'}\n with patch('mafiaManageSlack.WebClient') as slackClientConstructor:\n with patch('mafiaManageSlack.get_state_change_message') as messageBuilder:\n with patch('data_access.dataRepos.boto3'):\n with patch('mafiaManageSlack.boto3'):\n slackClient = slackClientConstructor.return_value\n slackClient.conversations_create.return_value = {'channel':{'id':testMafiaChannelId}}\n mafiaManageSlack.lambda_handler(createSqsEvent({'state':repo._serializeGame(game), 'action':Actions.START_GAME, 'source': 'initiator', 'target':None}), None)\n slackClient.conversations_create.assert_called_with(name='mafia-secrets', is_private=True)\n slackClient.conversations_invite.assert_called_with(channel=testMafiaChannelId, users=testpId)\n slackClient.chat_postMessage.assert_called_with(channel=testMafiaChannelId, text='You are members of the local mafia. Rabble-rousers in the village have decided to make a stand against you. It is time you taught them a lesson...\\nKill one of them using the command: /mafia kill @who-to-kill\\nIf there is more than one member of the mafia you must all /mafia kill the same villager before they will be killed.')\n\ndef test_RecordReceived_GenerateMessageAndBroadcastToChannel():\n repo = GameStateRepo()\n game = Game()\n testExecutorId = 'source'\n testTargetId = 'target'\n testMainChannelId = 'testChannel'\n game.meta = {'channel_id' : testMainChannelId}\n with patch('mafiaManageSlack.WebClient') as slackClientConstructor:\n with patch('mafiaManageSlack.get_state_change_message') as messageBuilder:\n with patch('mafiaManageSlack.boto3'):\n slackClient = slackClientConstructor.return_value\n mafiaManageSlack.lambda_handler(createSqsEvent({'state':repo._serializeGame(game), 'action':'ACTION', 'source': testExecutorId, 'target':testTargetId}), None)\n slackClient.chat_postMessage.assert_called_with(channel=testMainChannelId, text=messageBuilder.return_value)\n messageBuilder.assert_called_with(ANY, True, 'ACTION', testExecutorId, testTargetId)","sub_path":"tests/unit/lambda/test_manageSlack.py","file_name":"test_manageSlack.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"274841592","text":"from django.apps import apps\n\n\nclass CustomRouter(object):\n\n def db_for_read(self, model, **hints):\n database = getattr(model, \"_DATABASE\", None)\n if database:\n return database\n else:\n return \"default\"\n\n def db_for_write(self, model, **hints):\n database = getattr(model, \"_DATABASE\", None)\n if database:\n return database\n else:\n return \"default\"\n\n def allow_relation(self, obj1, obj2, **hints):\n \"\"\"\n Relations between objects are allowed if both objects are\n in the master/slave pool.\n \"\"\"\n db_list = ('default')\n if obj1._state.db in db_list and obj2._state.db in db_list:\n return True\n return None\n\n def allow_migrate(self, target_db, app_label, model_name=None, **hints):\n model_name = model_name or hints.pop('model_name', None)\n belongs_to = None\n if model_name:\n try:\n model = apps.get_model(app_label, model_name)\n belongs_to = getattr(model, \"_DATABASE\", 'default')\n except LookupError:\n # Due to model deletion\n belongs_to = 'default'\n\n is_belong = (belongs_to == target_db)\n if not is_belong:\n is_belong = (target_db == app_label)\n return is_belong\n","sub_path":"mapserver/django/django_project/core/settings/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"374103996","text":"\"\"\"Config agent for loading and setting global configuration.\n\nIRConfig load configuration from file. It can be accessed anywhere. The config\nfile should be like:\n\n database_name:=mongodb_test\n # this is a comment line\n\nAny line which violates the format will be ignored.\nTo load the config file:\n\n config = IRConfig.get_instance()\n config.load('config.cfg')\n db_name = config.get('database_name')\n config.set('global_var', 12)\n var = config.get('global_var')\n\"\"\"\n\n\nclass IRConfig(object):\n \"\"\"Config Agent.\"\"\"\n\n __ir_config = None\n\n @classmethod\n def get_instance(cls):\n if cls.__ir_config is None:\n cls.__ir_config = IRConfig()\n return cls.__ir_config\n\n def __init__(self):\n self.__config = {}\n\n def load(self, config_file):\n \"\"\"Load config from config_file.\n\n Args:\n config_file: str, Filepath of config file.\n \"\"\"\n from ir_log import IRLog\n in_file = open(config_file)\n line_num = 0\n for line in in_file:\n line = line.strip()\n # '#' for comment\n if line[0] == '#':\n continue\n fields = line.split(':=')\n line_num += 1\n if fields.__len__() != 2:\n IRLog.get_instance().println('Load config file error: %s, in ' \\\n 'line %d: %s' % (config_file, line_num, line))\n continue\n else:\n self.__config[fields[0]] = fields[1]\n\n def set(self, name, value):\n \"\"\"Set global variable.\n\n Args:\n name: str, Name of variable.\n value: object, The value of variable.\n \"\"\"\n self.__config[name] = value\n\n def get(self, name, default_value = None):\n \"\"\"Get the variable with the given name.\n \n Args:\n name: str, Name of the variable.\n default_value: object, Backup value, see Returns\n\n Returns:\n object, if variable with the given name is found, return the \n variable. if the name is not found, return default_value if\n default_value != None. Otherwise, throw exception.\n \"\"\"\n if name in self.__config:\n return self.__config[name]\n else:\n if None != default_value:\n return default_value\n else:\n assert ( None != self.__config[name]) or (None != default_value)\n\n def get_int(self, name, default_value = None):\n \"\"\"Get the int value with the given name.\"\"\"\n try:\n res = self.get(name, default_value)\n return int(res)\n except ValueError:\n from ir_log import IRLog\n IRLog.get_instance().println('Could not convert %d to int.' \\\n % (self.get(name)))\n return default_value\n\n def get_float(self, name, default_value = None):\n \"\"\"Get the float value with the given name.\"\"\"\n try:\n res = self.get(name, default_value)\n return float(res)\n except ValueError:\n from ir_log import IRLog\n IRLog.get_instance().println('Could not convert %d to float.' \\\n % (self.get(name)))\n return default_value\n\n def get_bool(self, name, default_value = None):\n \"\"\"Get the boolean value with the given name.\"\"\"\n try:\n res = self.get(name, default_value)\n return bool(res)\n except ValueError:\n from ir_log import IRLog\n IRLog.get_instance().println('Could not convert %d to bool.' \\\n % (self.get(name)))\n return default_value\n","sub_path":"server/bin/ir_config.py","file_name":"ir_config.py","file_ext":"py","file_size_in_byte":3692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"44741128","text":"# calculate the distribution of the dataset\nimport os\nimport os.path as osp\nimport json\nfrom textblob import TextBlob\nfrom collections import Counter\n\ndef read_json(filename):\n with open(filename, \"r\") as jfile:\n content = json.load(jfile)\n return content\n\n\n\nif __name__ == '__main__':\n \n file_path = 'tasks/R2R/data/R2R_test.json'\n content = read_json(file_path)\n # print (len(content)) #4675 train \n ignore_list = ['right','left','walk','turn','wait','exit','stop']\n nouns = []\n for item in content:\n for command in item['instructions']:\n blob = TextBlob(command)\n for phrase in blob.tags:\n if phrase[1] in ['NN','NNS'] and phrase[0] not in ignore_list:\n nouns.append(phrase[0].lower())\n ans = Counter(nouns).most_common(10)\n\n \n\n\n","sub_path":"scripts/distribute.py","file_name":"distribute.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"180826008","text":"import ix\n\nfrom conductor.native.lib.sequence import Sequence\n\n\ndef handle_use_custom_frames(obj, attr):\n hide = not attr.get_bool()\n obj.get_attribute(\"custom_frames\").set_hidden(hide)\n update_frame_stats_message(obj)\n\n\ndef handle_use_scout_frames(obj, attr):\n obj.get_attribute(\"scout_frames\").set_hidden(not attr.get_bool())\n update_frame_stats_message(obj)\n\n\ndef handle_custom_frames(obj, _):\n update_frame_stats_message(obj)\n\n\ndef handle_scout_frames(obj, _):\n update_frame_stats_message(obj)\n\n\ndef handle_chunk_size(obj, _):\n update_frame_stats_message(obj)\n\n\ndef handle_images(obj, _):\n update_frame_stats_message(obj)\n\n\ndef handle_best_chunk_size(obj, _):\n main_seq = main_frame_sequence(obj)\n obj.get_attribute(\"chunk_size\").set_long(main_seq.best_chunk_size())\n update_frame_stats_message(obj)\n\n\ndef custom_frame_sequence(obj):\n \"\"\"Generate Sequence from the value in custom_frames attribute.\"\"\"\n try:\n\n spec = obj.get_attribute(\"custom_frames\").get_string()\n seq = Sequence.create(\n spec, chunk_size=obj.get_attribute(\"chunk_size\").get_long()\n )\n return seq\n except (ValueError, TypeError):\n return None\n\n\ndef image_range(image):\n return (\n image.get_attribute(\"first_frame\").get_long(),\n image.get_attribute(\"last_frame\").get_long(),\n image.get_attribute(\"frame_step\").get_long()\n )\n\n\ndef _union_sequence(images):\n if not images:\n return None\n rng = image_range(images[0])\n seq = Sequence.create(*rng)\n for image in images[1:]:\n rng = image_range(image)\n other = Sequence.create(*rng)\n seq = seq.union(other)\n return seq\n\n\ndef range_frame_sequence(obj):\n \"\"\"Generate Sequence from value in the standard range.\n\n As there may be multiple sources, we make sure all sources have the\n same frame range. If they don't, then we suggest splitting the\n images over multiple jobs. In future we may do this automatically.\n \"\"\"\n\n images = ix.api.OfObjectArray()\n obj.get_attribute(\"images\").get_values(images)\n\n seq = _union_sequence(list(images))\n if not seq:\n return None\n\n seq.chunk_size = obj.get_attribute(\"chunk_size\").get_long()\n return seq\n\n\ndef main_frame_sequence(obj):\n \"\"\"Generate Sequence containing current chosen frames.\"\"\"\n if obj.get_attribute(\"use_custom_frames\").get_bool():\n return custom_frame_sequence(obj)\n return range_frame_sequence(obj)\n\n\ndef scout_frame_sequence(obj):\n \"\"\"Generate Sequence from value in scout_frames attribute.\"\"\"\n try:\n spec = obj.get_attribute(\"scout_frames\").get_string()\n return Sequence.create(spec)\n except (ValueError, TypeError):\n return None\n\n\ndef resolved_scout_sequence(obj):\n \"\"\"The sub-sequence the user intends to render immediately.\n\n If do_scout is off then returning None indicates all frames will be\n rendered. However, if it is on and the set of scout frames\n intersects the main frames, then only start those frames. If scout\n frames does not intersect the main frames, then the user intended to\n scout but ended up with no frames. This produces None.\n \"\"\"\n\n main_seq = main_frame_sequence(obj)\n if main_seq and obj.get_attribute(\"use_scout_frames\").get_bool():\n scout_seq = scout_frame_sequence(obj)\n if scout_seq:\n return main_seq.intersection(scout_seq)\n return None\n\n\ndef update_frame_stats_message(obj):\n info_attr = obj.get_attribute(\"frames_info\")\n\n main_seq = main_frame_sequence(obj)\n\n if not main_seq:\n info_attr.set_string(\"--\")\n return\n\n num_frames = len(main_seq)\n scout_seq = resolved_scout_sequence(obj)\n if scout_seq:\n frame_info = \"%d/%d Frames\" % (len(scout_seq), num_frames)\n else:\n frame_info = \"%d Frames\" % num_frames\n\n chunks = (\"%d Chunks\" % main_seq.chunk_count())\n\n info_attr.set_string(\"{} -- {} -- {}\".format(frame_info, chunks, main_seq))\n","sub_path":"conductor/clarisse/scripted_class/frames_ui.py","file_name":"frames_ui.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"579297050","text":"\n# coding: utf-8\n\n'''\nAuthor@Yongshun Zhang\nDate: 07.18.2018\n\nFunction:\n First stage: load the positive samples (facial lbp features) and negative samples (not-facial lbp features) to train a sample neural network, which contains two fully connection layers and a active layer\n Second stage: test the trained classifier with test samples\n Third stage: load a new image, abstract the lbp features after detecting the skin regions and show the results of detection\n'''\n\n\nimport os\nimport sys\nimport torch\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nimport torchvision\nfrom torch.utils.data import DataLoader, Dataset\nimport cv2 as cv\nimport time\nimport random\nfrom skimage.feature import local_binary_pattern, multiblock_lbp\n\n\n\n#hyper-parameters\nbatch_size = 100\nnum_epoches = 5\nlearning_rate = 0.001\nmomen = 0.9\ninput_size = 490\nhidden_size = 224\nnum_classes = 2\n\n#set 'csv' file\nfile_path = os.path.dirname(os.path.abspath('__file__'))\nface_lbp_data_path = file_path + '/face_lbp.csv'\nface_lbp_test_path = file_path + '/face_lbp_test.csv'\n\n\ndef calc_lbp(img):\n \"\"\"\n Function: calculate the lbp features of images input.\n When image is input, resize it to 21*21 firstly, then divide the image resized to 7*7 regions, which is called MBLBP\n\n Args:\n img: (np.array) image input to calculate the lbp feature\n Return:\n lbp_hist: (array), shape: (490, )\n the results of uniform lbp feaures for 7*7 regions\n \"\"\"\n length = 21\n block_length = 3\n img_c = cv.resize(img, (length, length))\n img_c = cv.cvtColor(img_c, cv.COLOR_BGR2GRAY)\n lbp = np.array(local_binary_pattern(img_c, 8, 2, method='uniform'))\n\n lbp_hist = []\n for h in range(7):\n for w in range(7):\n sub_lbp = np.zeros((3, 3))\n sub_lbp[0] = lbp[h*3][w*3:(w+1)*3]\n sub_lbp[1] = lbp[h*3+1][w*3:(w+1)*3]\n sub_lbp[2] = lbp[h*3+2][w*3:(w+1)*3]\n hist = np.zeros((1, 10))\n count = pd.value_counts(sub_lbp.flatten())\n for idx in count.index:\n hist[0][int(idx)] = int(count[idx])\n lbp_hist.extend(hist[0].tolist())\n return lbp_hist\n\ndef ycrcb(img):\n '''get skin image, with the methods changing the RGB space to ycrcb spaces\n\n Args:\n img: (array) image input to get the skin regions\n Return:\n imgSkin: (array), the same shape and class of image input, which change the no-skin pixels to [0,0,0]\n '''\n\n rows,cols,channels = img.shape\n # convert color space from rgb to ycbcr\n imgYcc = cv.cvtColor(img, cv.COLOR_BGR2YCR_CB)\n # convert color space from bgr to rgb\n #img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n # prepare an empty image space\n imgSkin = np.zeros(img.shape, np.uint8)\n # copy original image\n imgSkin = img.copy()\n for r in range(rows):\n for c in range(cols):\n # get values from rgb color space\n R = img.item(r,c,0)\n G = img.item(r,c,1)\n B = img.item(r,c,2)\n # get values from ycbcr color space\n Y = imgYcc.item(r,c,0)\n Cr = imgYcc.item(r,c,1)\n Cb = imgYcc.item(r,c,2)\n #skin when skin = 1\n skin = 1 if Cr >= 133 and Cr <= 173 and Cb >= 77 and Cb <= 127 else 0\n if 0 == skin:\n imgSkin.itemset((r,c,0),0)\n imgSkin.itemset((r,c,1),0)\n imgSkin.itemset((r,c,2),0)\n return imgSkin\n\n\ndef is_skin_region(imgSkin, height_top, height_bottom, width_left, width_right):\n '''\n Function: check the region input is skin region or not\n\n Args:\n imgSkin: (array) image only with skin regions\n height_top: (int)\n height_bottom: (int)\n width_left: (int)\n width_right: (int) (height_top, width_left) is the top-left point of checking region, and (height_bottom, width_right) is the bottom-right\n point of checking region.\n\n Returns:\n boolean:\n True represents skin region and False represents not-skin region\n '''\n area_width = width_right - width_left\n area_height = height_bottom - height_top\n area = area_height * area_width\n no_skin_numbers = 0\n\n\n for h in range(height_top, height_bottom):\n for w in range(width_left, width_right):\n #print(imgSkin[h, w])\n if (imgSkin[h, w] <= [10, 10, 10]).all():\n no_skin_numbers += 1\n if no_skin_numbers*1. / area > 0.5:\n return False\n return True\n\ndef select_skin_region(imgSkin, img, zoom):\n '''search the image which contains skin\n\n Args:\n imgSkin: (array) image only with skin regions\n img: (array) original image\n face_regions: (list) face_regions contains the points of each face region\n zoom: (int) the scale to scale the original image to new scaled image, which is used for multiscale detection\n\n '''\n\n lbp_result = []\n scale = 21\n img_height = int(imgSkin.shape[0] >> zoom) #change the img_height and img_width with the coefficient of zooming\n img_width = int(imgSkin.shape[1] >> zoom)\n imgSkin_zoom = cv.resize(imgSkin, (img_width, img_height))\n img_zoom = cv.resize(img, (img_width, img_height))\n h = 0\n print(zoom)\n while h + scale < img_height:\n w = 0\n\n while w + scale < img_width:\n is_skin = is_skin_region(imgSkin_zoom, h, h+scale, w, w+scale)\n if is_skin:\n lbp_item = [int(h<> 1)\n h += (scale >> 1)\n return lbp_result\n\n\n\nclass FaceLBPDataset(Dataset):\n \"\"\"load the positive samples (facial lbp features) and negative samples (not-facial lbp features) to train a sample neural network\n\n Args:\n csv_file_path: (string) the path of 'csv' file which contains the facial lbp features and not-facial lbp features\n \"\"\"\n\n def __init__(self, csv_file_path):\n '''\n Args:\n csv_file_path(string): the path of file which contains facial features\n '''\n self.data = pd.read_csv(csv_file_path)\n\n def __len__(self):\n\n return len(self.data)\n\n def __getitem__(self, idx):\n\n label = self.data.iloc[idx, -1]\n feature = self.data.iloc[idx, :-1].as_matrix()\n sample = {\n 'label': label,\n 'feature': feature\n }\n return sample\n\nclass FaceDetection(Dataset):\n \"\"\"test image\n\n Args:\n list_lbp: (list) list contains locations of checking regions [:3], and features of regions [3:]\n \"\"\"\n def __init__(self, list_lbp):\n self.data = list_lbp\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n\n feature = np.array(self.data[idx][3:])\n location = np.array(self.data[idx][0:3])\n sample = {\n 'location': location,\n 'feature': feature\n }\n\n return sample\n\n\nclass NerualNet(nn.Module):\n \"\"\"simple nerual network, with two fully connected layers and one active layer\n\n Args:\n input_size: (int) length of lbp feature\n hidden_size: (int) length of input size of hidden fc\n num_classes: (int) number of classes to classifier\n \"\"\"\n\n def __init__(self, input_size, hidden_size, num_classes):\n '''\n initialize the nerual network\n '''\n super(NerualNet, self).__init__()\n self.fc1 = nn.Linear(input_size, hidden_size)\n #nn.init.kaiming_normal_(self.fc1.weight)\n self.relu = nn.ReLU()\n self.fc2 = nn.Linear(hidden_size, num_classes)\n #nn.init.kaiming_normal_(self.fc2.weight)\n\n def forward(self, x):\n out = self.fc1(x)\n out = self.relu(out)\n out = self.fc2(out)\n return out\n\n\n\n\n#load the samples\nface_data = FaceLBPDataset(face_lbp_data_path)\nface_test_data = FaceLBPDataset(face_lbp_test_path)\n\ntrain_data = DataLoader(face_data, batch_size=batch_size, shuffle=True)\ntest_data = DataLoader(face_test_data, batch_size=batch_size, shuffle=False)\n\n\n\n#train model\nmodel = NerualNet(input_size, hidden_size, num_classes)\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=1e-5)\n\ntotal_step = len(train_data)\nfor epoch in range(num_epoches):\n for i, sample in enumerate(train_data):\n output = model(sample['feature'].float())\n loss = criterion(output, sample['label'].long())\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (i+1) % 10 == 0:\n print('Epoch: [{}/{}], Step: [{}/{}], Loss: {:.4f}'.format(\n epoch+1, num_epoches, i+1, total_step, loss.item()\n ))\n\n\n\n#test the model\n\nwith torch.no_grad():\n correct = 0\n total = 0\n for sample in test_data:\n label = sample['label'].long()\n feature = sample['feature'].float()\n outputs = model(feature)\n\n _, predicted = torch.max(outputs.data, 1)\n total += label.size(0)\n correct += (predicted == label).sum().item()\n print('accuracy = {:4f}%'.format(100 * correct / total))\n\n#save the model\ntorch.save(model, 'simple_neural_network_of_lbp.pth')\n\ndef test():\n \"\"\"\n The third stage: load a test image, abstract lbp features and use model to produce results of detection, then show the results\n \"\"\"\n test_image = cv.imread(file_path+'/t1.jpg')\n cv.namedWindow('t')\n\n imgSkin = ycrcb(test_image)\n cv.imshow('t', imgSkin)\n cv.imwrite('skin.jpg', imgSkin)\n cv.waitKey(0)\n result = []\n result.extend(select_skin_region(imgSkin, test_image, 0))\n result.extend(select_skin_region(imgSkin, test_image, 2))\n result.extend(select_skin_region(imgSkin, test_image, 3))\n result.extend(select_skin_region(imgSkin, test_image, 1))\n test_data = FaceDetection(result)\n print(len(result))\n test_loader = DataLoader(test_data, batch_size = batch_size)\n\n with torch.no_grad():\n for sample in test_loader:\n feature = sample['feature']\n location = sample['location']\n outputs = model(feature.float())\n _, predicted = torch.max(outputs.data, 1)\n location = location.tolist()\n #print(location)\n predicted = predicted.tolist()\n print(predicted)\n for i in range(len(predicted)):\n if(1 == predicted[i]):\n cv.rectangle(test_image, (location[i][1], location[i][0]),\n (location[i][2]+location[i][1], location[i][2]+location[i][0]), (255,0,0), 1)\n cv.imshow('t', test_image)\n cv.imwrite('result.jpg', test_image)\n cv.waitKey(0)\n cv.destroyAllWindows()\n\nif __name__ == '__main__':\n test()\n\n\n","sub_path":"nerual_network_face_lbp.py","file_name":"nerual_network_face_lbp.py","file_ext":"py","file_size_in_byte":11004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"295493874","text":"## Licenza Libera progetto originario di Claudio Pizzillo\r\n## Modifiche e riadattamenti da Salvatore Crapanzano\r\n## V. 2.2.1 del 25-02-2020 - Intermediari e Diretto e Studio Associato\r\n\r\nimport requests\r\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\r\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\r\nimport re\r\nimport time\r\nfrom datetime import datetime\r\nimport sys\r\nimport pytz\r\nimport json\r\nimport os\r\n \r\ndef unixTime():\r\n dt = datetime.now(tz=pytz.utc)\r\n return str(int(dt.timestamp() * 1000))\r\n\r\nprofilo = 1 # Impostare il profilo Delega diretta codice 1, Me stesso 2, Studio Associato Default\r\nCF = sys.argv[1]\r\nPIN = sys.argv[2]\r\nPassword = sys.argv[3]\r\ncfstudio = sys.argv[4]\r\nDal = sys.argv[5]\r\nAl = sys.argv[6]\r\ncfcliente = sys.argv[7]\r\npivadiretta = sys.argv[8]\r\ntipo = int(sys.argv[9]) # 1 per data di ricezione 2 (QUALSIASI VALORE DIVERSA DA 1) per data di emissione\r\nprint('Sintassi:')\r\nprint('py fec_ricevute.py UTENZA_ENTRATEL pin_entratel password_entratel cfstudio Data_inizio Data_fine cf_cliente piva_cliente [1 SCARICAMENTO PER data ricezione 2 SCARICAMENTO PER data emissione] ')\r\ntime.sleep(5)\r\n\r\ns = requests.Session()\r\ns.headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'})\r\ns.headers.update({'Connection': 'keep-alive'})\r\n\r\ncookie_obj1 = requests.cookies.create_cookie(domain='ivaservizi.agenziaentrate.gov.it',name='LFR_SESSION_STATE_20159',value='expired')\r\ns.cookies.set_cookie(cookie_obj1)\r\ncookie_obj2 = requests.cookies.create_cookie(domain='ivaservizi.agenziaentrate.gov.it',name='LFR_SESSION_STATE_10811916',value=unixTime())\r\ns.cookies.set_cookie(cookie_obj2)\r\nr = s.get('https://ivaservizi.agenziaentrate.gov.it/portale/web/guest', verify=False)\r\n\r\nprint('Collegamento alla homepage')\r\ncookieJar = s.cookies\r\n\r\nprint('Effettuo il login')\r\n\r\n\r\npayload = {'_58_saveLastPath': 'false', '_58_redirect' : '', '_58_doActionAfterLogin': 'false', '_58_login': CF , '_58_pin': PIN, '_58_password': Password} \r\nr = s.post('https://ivaservizi.agenziaentrate.gov.it/portale/home?p_p_id=58&p_p_lifecycle=1&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_pos=3&p_p_col_count=4&_58_struts_action=%2Flogin%2Flogin', data=payload)\r\n\r\ncookieJar = s.cookies\r\n\r\nliferay = re.findall(r\"Liferay.authToken = '.*';\", r.text)[0]\r\np_auth = liferay.replace(\"Liferay.authToken = '\",\"\")\r\np_auth = p_auth.replace(\"';\", \"\")\r\n\r\nr = s.get('https://ivaservizi.agenziaentrate.gov.it/dp/api?v=' + unixTime())\r\ncookieJar = s.cookies\r\n\r\nprint('Seleziono il tipo di incarico')\r\nif profilo == 1:\r\n# Delega Diretta\r\n payload = {'cf_inserito': cfcliente};\r\n r = s.post('https://ivaservizi.agenziaentrate.gov.it/portale/scelta-utenza-lavoro?p_auth='+ p_auth + '&p_p_id=SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet&p_p_lifecycle=1&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet_javax.portlet.action=delegaDirettaAction', data=payload);\r\n payload = {'cf_inserito': cfcliente, 'sceltapiva' : pivadiretta}; \r\n r = s.post('https://ivaservizi.agenziaentrate.gov.it/portale/scelta-utenza-lavoro?p_auth='+ p_auth + '&p_p_id=SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet&p_p_lifecycle=1&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet_javax.portlet.action=delegaDirettaAction', data=payload);\r\n# Me stesso\r\nelif profilo == 2:\r\n payload = {'sceltaincarico': cfstudio + '-000', 'tipoincaricante' : 'incDiretto'};\r\n r = s.post('https://ivaservizi.agenziaentrate.gov.it/portale/scelta-utenza-lavoro?p_auth='+ p_auth + '&p_p_id=SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet&p_p_lifecycle=1&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet_javax.portlet.action=meStessoAction', data=payload)\r\n payload = {'sceltaincarico': cfstudio + '-000', 'tipoincaricante' : 'incDiretto', 'sceltapiva' : pivadiretta}; \r\n r = s.post('https://ivaservizi.agenziaentrate.gov.it/portale/scelta-utenza-lavoro?p_auth='+ p_auth + '&p_p_id=SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet&p_p_lifecycle=1&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet_javax.portlet.action=meStessoAction', data=payload);\r\n# Login per STUDIO ASSOCIATO\r\nelse:\r\n payload = {'sceltaincarico': cfstudio + '-000', 'tipoincaricante' : 'incDelega', 'cf_inserito': cfcliente};\r\n r = s.post('https://ivaservizi.agenziaentrate.gov.it/portale/scelta-utenza-lavoro?p_auth='+ p_auth + '&p_p_id=SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet&p_p_lifecycle=1&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet_javax.portlet.action=incarichiAction', data=payload);\r\n payload = {'sceltaincarico': cfstudio + '-000', 'tipoincaricante' : 'incDelega', 'cf_inserito': cfcliente, 'sceltapiva' : pivadiretta};\r\n r = s.post('https://ivaservizi.agenziaentrate.gov.it/portale/scelta-utenza-lavoro?p_auth='+ p_auth + '&p_p_id=SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet&p_p_lifecycle=1&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_SceltaUtenzaLavoro_WAR_SceltaUtenzaLavoroportlet_javax.portlet.action=incarichiAction', data=payload);\r\n\r\nprint('Aderisco al servizio')\r\nr = s.get('https://ivaservizi.agenziaentrate.gov.it/ser/api/fatture/v1/ul/me/adesione/stato/')\r\ncookieJar = s.cookies \r\n\r\nheaders_token = {'x-xss-protection': '1; mode=block',\r\n 'strict-transport-security': 'max-age=16070400; includeSubDomains',\r\n 'x-content-type-options': 'nosniff',\r\n 'x-frame-options': 'deny'}\r\nr = s.get('https://ivaservizi.agenziaentrate.gov.it/cons/cons-services/sc/tokenB2BCookie/get?v='+unixTime() , headers = headers_token )\r\ncookieJar = s.cookies\r\ntokens = r.headers\r\n\r\nxb2bcookie = r.headers.get('x-b2bcookie')\r\nxtoken = r.headers.get('x-token')\r\n\r\ns.headers.update({'Host': 'ivaservizi.agenziaentrate.gov.it'})\r\ns.headers.update({'Referer': 'https://ivaservizi.agenziaentrate.gov.it/cons/cons-web/?v=' + unixTime()})\r\ns.headers.update({'Accept': 'application/json, text/plain, */*'})\r\ns.headers.update({'Accept-Encoding': 'gzip, deflate, br'})\r\ns.headers.update({'Accept-Language': 'it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7,fr;q=0.6'})\r\ns.headers.update({'DNT': '1'})\r\ns.headers.update({'X-XSS-Protection': '1; mode=block'})\r\ns.headers.update({'Strict-Transport-Security': 'max-age=16070400; includeSubDomains'})\r\ns.headers.update({'X-Content-Type-Options': 'nosniff'})\r\ns.headers.update({'X-Frame-Options': 'deny'})\r\ns.headers.update({'x-b2bcookie': xb2bcookie})\r\ns.headers.update({'x-token': xtoken})\r\n\r\nheaders = {'Host': 'ivaservizi.agenziaentrate.gov.it',\r\n 'referer': 'https://ivaservizi.agenziaentrate.gov.it/cons/cons-web/?v=' + unixTime(),\r\n 'accept': 'application/json, text/plain, */*',\r\n 'accept-encoding': 'gzip, deflate, br',\r\n 'accept-language': 'it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7,fr;q=0.6',\r\n 'DNT': '1',\r\n 'x-xss-protection': '1; mode=block',\r\n 'strict-transport-security': 'max-age=16070400; includeSubDomains',\r\n 'x-content-type-options': 'nosniff',\r\n 'x-frame-options': 'deny',\r\n 'x-b2bcookie': xb2bcookie,\r\n 'x-token': xtoken,\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'}\r\nprint('Accetto le condizioni')\r\nr = s.get('https://ivaservizi.agenziaentrate.gov.it/cons/cons-services/rs/disclaimer/accetta?v='+unixTime() , headers = headers_token )\r\ncookieJar = s.cookies\r\nif tipo == 1:\r\n# r = s.get('https://ivaservizi.agenziaentrate.gov.it/ser/api/monitoraggio/v1/monitoraggio/fatture/?v='+unixTime()+'&idFiscCedente=&idFiscDestinatario=&idFiscEmittente=&idFiscTrasmittente=&idSdi=&perPage=10&start=1&statoFile=&tipoFattura=EMESSA')\r\n print('Scarico il json delle fatture ricevute per data di ricezione la partita IVA ' + cfcliente)\r\n r = s.get('https://ivaservizi.agenziaentrate.gov.it/cons/cons-services/rs/fe/ricevute/dal/'+Dal+'/al/'+Al+'/ricerca/ricezione?v=' + unixTime(), headers = headers)\r\nelse: \r\n print('Scarico il json delle fatture ricevute per data di emissione per la partita IVA ' + cfcliente)\r\n r = s.get('https://ivaservizi.agenziaentrate.gov.it/cons/cons-services/rs/fe/ricevute/dal/'+Dal+'/al/'+Al+'/ricerca/emissione?v=' + unixTime(), headers = headers)\r\n\r\nwith open('fe_ricevute.json', 'wb') as f:\r\n f.write(r.content)\r\n \r\nprint('Inizio a scaricare le fatture ricevute')\r\npath = r'FattureRicevute_' + cfcliente\r\nif not os.path.exists(path):\r\n os.makedirs(path)\r\nwith open('fe_ricevute.json') as data_file: \r\n data = json.load(data_file)\r\n numero_fatture = 0\r\n numero_notifiche = 0\r\n for fattura in data['fatture']:\r\n fatturaFile = fattura['tipoInvio']+fattura['idFattura']\r\n r = s.get('https://ivaservizi.agenziaentrate.gov.it/cons/cons-services/rs/fatture/file/'+fatturaFile+'?tipoFile=FILE_FATTURA&download=1&v='+unixTime() , headers = headers_token )\r\n if r.status_code == 200:\r\n numero_fatture = numero_fatture + 1\r\n d = r.headers['content-disposition']\r\n fname = re.findall(\"filename=(.+)\", d)\r\n print('Downloading ' + fname[0])\r\n print('Totale fatture scaricate: ', numero_fatture)\r\n with open(path + '/' + fname[0], 'wb') as f:\r\n f.write(r.content)\r\n fmetadato = re.findall(\"filename=(.+)\", d)\r\n r = s.get('https://ivaservizi.agenziaentrate.gov.it/cons/cons-services/rs/fatture/file/'+fatturaFile+'?tipoFile=FILE_METADATI&download=1&v='+unixTime() , headers = headers_token )\r\n if r.status_code == 200:\r\n numero_notifiche = numero_notifiche + 1\r\n d = r.headers['content-disposition']\r\n fname = re.findall(\"filename=(.+)\", d)\r\n print('Downloading metadati = ' + fname[0])\r\n print('Downloading metadati rinominato = ' + fmetadato[0] + '_metadato.xml')\r\n print('Totale notifiche scaricate: ', numero_notifiche)\r\n with open(path + '/' + fmetadato[0] + '_metadato.xml', 'wb') as f:\r\n f.write(r.content) \r\nos.system('cls')\r\nprint('Totale fatture scaricate: ', numero_fatture)\r\nprint('Totale notifiche scaricate: ', numero_notifiche)\r\nsys.exit()","sub_path":"scripts/fec_ricevute.py","file_name":"fec_ricevute.py","file_ext":"py","file_size_in_byte":10696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"27968514","text":"__author__ = 'tsunami'\nfrom labelpropagation import *\n\niter_count = 100\nsources = [(0, 0), (10, 10), (-10, 10), (-10, -10), (10, -10)] # centers\ncalc_wei = False\nn = [500]\nratio = [0.8]\nradius = [7.0]\nfor _radius in radius:\n for _n in n:\n for _ratio in ratio:\n filename = \"\".join([str(_n), \"_\", str(len(sources)), \"_\", str(_radius)])\n lpa = LPA(n=_n, c=len(sources), datafile=filename, ratio=_ratio)\n lpa.read_data()\n if calc_wei:\n lpa.calc_weight()\n lpa.write_weight()\n else:\n lpa.pollute()\n lpa.read_weight()\n lpa.find_labeled_data()\n lpa.plot() # plot the data distribution before classification\n for i in range(iter_count):\n lpa.start_propagation()\n\n lpa.plot()\n lpa.prf()\n plt.show()","sub_path":"lpa_examine.py","file_name":"lpa_examine.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"605320509","text":"#DSA-Assgn-13\nclass Stack:\n def __init__(self, max_size):\n self.__max_size = max_size\n self.__elements = [None] * self.__max_size\n self.__top = -1\n\n def get_max_size(self):\n return self.__max_size\n\n def is_full(self):\n if (self.__top + 1) >= self.get_max_size():\n return True\n else:\n return False\n\n def push(self, data):\n if self.is_full():\n print(\"Stack is full\")\n else:\n self.__top += 1\n self.__elements[self.__top] = data\n \n def is_empty(self):\n if self.__top == -1:\n return True\n else:\n return False\n \n def pop(self, print_popped_element = False):\n if self.is_empty():\n print(\"Stack is empty\")\n else:\n data = self.__elements[self.__top]\n self.__top -= 1\n if print_popped_element:\n print(data, \"has been popped\")\n return data\n \n def display(self):\n index = self.__top\n while index > -1:\n print(self.__elements[index], end = \" \")\n index -= 1\n print()\n \n #You can use the below __str__() to print the elements of the DS object while debugging\n def __str__(self):\n msg = []\n index = self.__top\n while index >= 0:\n msg.append(str(self.__elements[index]))\n index -= 1\n msg = \" \".join(msg)\n msg = \"Stack data(Top to Bottom): \" + msg\n return msg\n\ndef change_smallest_value(number_stack):\n temp_stack = Stack(number_stack.get_max_size())\n small = None\n count = 0\n \n while not number_stack.is_empty():\n data = number_stack.pop()\n \n if small is None:\n small = data\n count = 1\n elif small > data:\n small = data\n count = 1\n elif small == data:\n count += 1\n\n temp_stack.push(data)\n \n print(small, \"is the smallest and occurs\", count, \"times\")\n \n while count > 0:\n number_stack.push(small)\n count -= 1\n \n while not temp_stack.is_empty():\n data = temp_stack.pop()\n if data == small:\n pass\n else:\n number_stack.push(data)\n \n return number_stack \n\n#Add different values to the stack and test your program\nnumber_stack = Stack(8)\nnumber_stack.push(7)\nnumber_stack.push(8)\nnumber_stack.push(5)\nnumber_stack.push(66)\nnumber_stack.push(5)\nprint(\"Initial Stack:\")\nnumber_stack.display()\nchange_smallest_value(number_stack)\nprint(\"After the change:\")\nnumber_stack.display()\n \n","sub_path":"Data-Structures-and-Algorithms/Day-3/Assignments/Assignment-13.py","file_name":"Assignment-13.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"397804531","text":"from django.shortcuts import render\n# Create your views here.\nfrom django.http import HttpResponse\nfrom .models import Voter\nimport datetime\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom twilio.rest import Client\nimport datetime\n\ndef index(request):\n return render(request, 'index.html')\n\n\ndef details(request):\n return render(request, 'details.html')\n\n\ndef result(request):\n count, count1, count2, count3 = 0, 0, 0, 0\n party1, party2, party3 = \"BJP\", \"CONGRESS\", \"AAP\"\n V1 = Voter.objects.filter(vote_for=party1)\n count1 = V1.count()\n V2 = Voter.objects.filter(vote_for=party2)\n count2 = V2.count()\n V3 = Voter.objects.filter(vote_for=party3)\n count3 = V3.count()\n if count1 > count2 and count1 > count3:\n statement0 = \"

RESULTS: \" + str(party1) + \" won the election.

\"\n elif count2 > count1 and count2 > count3:\n statement0 = \"

RESULTS: \" + str(party2) + \" won the election.

\"\n elif count3 > count1 and count3 > count2:\n statement0 = \"

RESULTS: \" + str(party3) + \" won the election.

\"\n else:\n statement0 = \"No single party got the majority.\"\n statement1 = \"

\" + str(party1) + \" got \" + str(count1) + \" votes.\\n

\"\n statement2 = \"

\" + str(party2) + \" got \" + str(count2) + \" votes.\\n

\"\n statement3 = \"

\" + str(party3) + \" got \" + str(count3) + \" votes.\\n

\"\n statement4 = \"
\"\n\n statement = statement0 + statement1 + statement2 + statement3 + statement4\n\n return HttpResponse(statement)\n\n\ndef voterinfo(request):\n number = request.POST.get(\"voter_number\")\n V = Voter.objects.filter(voter_number=number)\n if V.count() == 1:\n a = []\n a = V.values_list()\n name = a[0][1]\n address = a[0][3]\n father_name = a[0][4]\n sex = a[0][5]\n date_of_birth = a[0][6]\n contact = a[0][7]\n str1 = \"

Details of voter-number: \" + number + \"\\n

\"\n str2 = \"

Voter-name: \" + name + \"\\n

\"\n str3 = \"

Address: \" + address + \"\\n

\"\n str4 = \"

Father-name: \" + father_name + \"\\n

\"\n str5 = \"

Sex: \" + sex + \"\\n

\"\n str6 = \"

Date of birth: \" + str(date_of_birth) + \"\\n

\"\n str7 = \"

Contact Number: \" + contact + \"\\n

\"\n detail = str1 + str2 + str3 + str4 + str5 + str6 + str7\n return HttpResponse(detail)\n else:\n return HttpResponse(\"The voter number you have entered is incorrect\")\n\n\ndef sign(request):\n return render(request, 'signup.html')\n\n\ndef vote(request):\n number = request.POST.get('voterid')\n v = Voter.objects.filter(voter_number=number)\n a = v.values_list()\n contact = \"+91\"+a[0][7]\n party = request.POST.get(\"party\")\n v.update(vote_value=True, vote_for=party)\n data1 = request.COOKIES['uid']\n data2 = request.COOKIES['name']\n logintime = request.COOKIES['logintime']\n\n\n # email\n subject = \"Election log\"\n message = \"Thank you for casting your vote: \" + str(data2) + \", Voting time \" + str(logintime) + \". You voted for \" + party + \".\"\n from_email = settings.EMAIL_HOST_USER\n to_list = [settings.EMAIL_TO_LIST, settings.EMAIL_HOST_USER]\n send_mail(subject, message, from_email, to_list, fail_silently=False)\n\n # SMS\n account_sid = settings.SMS_ACCOUNT_SID\n auth_token = settings.SMS_AUTH_TOKEN\n\n client = Client(account_sid, auth_token)\n\n client.messages.create(\n to=contact,\n from_=settings.SMS_FROM,\n body=\"Thank you for casting your vote: \" + str(data2) + \", Voting time \" + str(logintime) + \". You voted for \" + party + \".\\n\\n ~ Election Commission\"\n )\n return HttpResponse(\"Thank you for casting your vote: \" + str(data2) + \", Voting time \" + str(logintime) + \". You voted for \" + party+\".\")\n\n\ndef signup(request):\n if request.method == \"POST\":\n V = Voter()\n name = request.POST.get(\"voter_name\")\n number = request.POST.get(\"voter_number\")\n address = request.POST.get(\"address\")\n fname = request.POST.get(\"father_name\")\n sex = request.POST.get(\"sex\")\n dob = request.POST.get(\"date_of_birth\")\n contact = request.POST.get(\"contact_number\")\n V.voter_name = name\n V.voter_number = number\n V.address = address\n V.father_name = fname\n V.sex = sex\n V.date_of_birth = dob\n V.contact_number = contact\n V.vote_value = False\n V.vote_for = \"None\"\n V.save()\n return HttpResponse('Signup Completed')\n else:\n return HttpResponse('You have clicked on button through get method')\n\n\ndef login(request):\n if request.method == 'POST':\n name = request.POST.get(\"voter_name\")\n number = request.POST.get(\"voter_number\")\n sc = Voter.objects.filter(voter_number=number, voter_name=name, vote_value=False)\n if sc.count() == 1:\n reponse = render(request, 'vote.html',\n {'number': str(number)}) # response is a variable which stores an object\n reponse.set_cookie('uid', str(number),\n 180) # uid is key which works like global variable , and name is data\n reponse.set_cookie('name', name, 180)\n reponse.set_cookie('logintime', '{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))\n return reponse\n else:\n return HttpResponse('Username-password combination entered wrong OR Voter has already casted his vote')\n else:\n return HttpResponse('You have clicked on button through get method')\n","sub_path":"polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"60017230","text":"#The prime factors of 13195 are 5, 7, 13 and 29.\n\n#What is the largest prime factor of the number 600851475143 ?\n\nsayı = 600851475143\ni = 3\nliste = []\nwhile sayı != 1 :\n for i in range(3,int(sayı+1)):\n if sayı % i == 0:\n sayı = sayı / i \n print(i)\n print(sayı)\n break\n i += 2\n","sub_path":"ProjectsEuler/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"519778427","text":"# This file is part of the Python aiocoap library project.\n#\n# Copyright (c) 2012-2014 Maciej Wasilak ,\n# 2013-2014 Christian Amsüss \n#\n# aiocoap is free software, this file is published under the MIT license as\n# described in the accompanying LICENSE file.\n\n\"\"\"This tests advanced cases of blockwise transfer; simple sequential transfers\nare covered in test_server.TestServer.test_replacing_resource.\"\"\"\n\nimport asyncio\n\nimport unittest\nimport aiocoap\nimport aiocoap.defaults\n\nfrom .test_server import WithTestServer, WithClient, no_warnings\n\nif 'simple6' in aiocoap.defaults.get_default_clienttransports():\n # simple6 has the (comparatively) odd property that whenever it resolves an\n # address it creates a new client port. Two blockwise requests thus can\n # proceed without error even when they are simultaneous.\n expectedFailure_unless_simple6 = lambda x:x\nelse:\n expectedFailure_unless_simple6 = unittest.expectedFailure\n\nclass TestBlockwise(WithTestServer, WithClient):\n @expectedFailure_unless_simple6\n @no_warnings\n def test_sequential(self):\n \"\"\"Test whether the client serializes simultaneous block requests\"\"\"\n self.loop.run_until_complete(self._test_sequential())\n\n @asyncio.coroutine\n def _test_sequential(self):\n pattern1 = b\"01234 first pattern\" + b\"01\" * 1024\n pattern2 = b\"01234 second pattern\" + b\"02\" * 1024\n\n request1 = aiocoap.Message(\n uri='coap://' + self.servernetloc + '/replacing/one',\n code=aiocoap.POST,\n payload=pattern1,\n )\n request2 = aiocoap.Message(\n uri='coap://' + self.servernetloc + '/replacing/one',\n code=aiocoap.POST,\n payload=pattern2,\n )\n\n responses = []\n for response in asyncio.as_completed([self.client.request(r).response for r in [request1, request2]]):\n response = yield from response\n self.assertTrue(response.code.is_successful(), \"Simultaneous blockwise requests caused error.\")\n responses.append(response.payload)\n\n self.assertSetEqual(set(responses), set(x.replace(b'0', b'O') for x in (pattern1, pattern2)))\n","sub_path":"venv/Lib/site-packages/tests/test_blockwise.py","file_name":"test_blockwise.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"581336270","text":"from time import time\n\nimport numpy as np\n\nfrom experiments.lnpdfs.create_target_lnpfs import build_target_likelihood_planar_n_link\nfrom sampler.elliptical_slice.bovy_mcmc.elliptical_slice import elliptical_slice as ess_update\n\nnum_dimensions = 10\nconf_likelihood_var = 4e-2 * np.ones(num_dimensions)\nconf_likelihood_var[0] = 1\ncart_likelihood_var = np.array([1e-4, 1e-4])\n\n[target_lnpdf, prior, prior_chol] = build_target_likelihood_planar_n_link(num_dimensions, conf_likelihood_var,\n cart_likelihood_var)\n\ndef sample(n_samps, path=None):\n iters = []\n nfevals = []\n target_lnpdf.counter = 0\n start = time()\n timestamps = []\n cur_theta = prior.rvs(1)\n cur_lnpdf = target_lnpdf(cur_theta, without_prior=True)\n all_samples = []\n samples = []\n for i in range(1, n_samps+1):\n [cur_theta, cur_lnpdf] = ess_update(cur_theta, prior_chol, target_lnpdf, pdf_params=(True,),\n cur_lnpdf=cur_lnpdf)\n samples.append(cur_theta)\n if i> 1 and i % 1000 == 0:\n all_samples.append(np.array(samples))\n samples = []\n iters.append(i)\n nfevals.append(target_lnpdf.counter)\n timestamps.append(time() - start)\n if path is not None:\n np.savez(path+\"processed_data\", iter=iters, samples=np.array(all_samples), fevals=np.array(nfevals), timestamps=np.array(timestamps))\n print(\"done\")\n\n\nif __name__ == '__main__':\n sample(1000)\n\n","sub_path":"python/experiments/ESS/planar_robot_10.py","file_name":"planar_robot_10.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"437213612","text":"\"\"\"\nThis file contains channel and figure information specific to each SPM technique. The dictionary is structured as follows:\n\ndata_info{\n \"SPM_technique\":{\n \"properties (i.e. channels)\": [\"List\", \"of\", \"Channels\"],\n \"sample_size (i.e. scan dimensions)\": {\n \"sample_key_word\": int,\n \"sample_key_word\": int,\n \"sample_key_word\": int,\n },\n },\n ...\n}\n\"\"\"\n\ndata_info = {\n \"QNM\": {\"properties\": [\"Adhesion\", \"Deformation\", \"Dissipation\", \"LogDMT\", \"Height\", \"Stiffness\"],\n \"sample_size\": {\"Backgrounded\": 2, \"2ComponentFilms\": 0.5, \"Nanowires\": 5}},\n \n \"AMFM\": {\"properties\": [\"Height\", \"Deformation\", \"Youngs Modulus\", \"Phase\"],\n \"sample_size\": {\"Nanowires\": 2}},\n \n \"cAFM\": {\"properties\": [\"Current\", \"Height\"],\n \"sample_size\": {\"Nanowires\": 2}},\n \n \"Full_QNM\": {\"properties\": [\"Zscale\", \"Height\", \"PFE\", \"Stiffness\", \"LogDMT\", \"Adhesion\", \"Deformation\", \"Dissipation\"],\n \"sample_size\": {\"P3HT:PCBM_OPV\": 0.5, \"P3HT_OFET\":0.5}},\n \n \"OPV_QNM\": {\"properties\": [\"Zscale\", \"PFE\", \"Stiffness\", \"LogDMT\", \"Adhesion\", \"Deformation\", \"Dissipation\", \"Height\"],\n \"sample_size\": {\"P3HT:PCBM_OPV\": 0.5, \"P3HT_OFET\":0.5}},\n \n \"Raman\": {\"properties\": ['R', 'G', 'B'],\n \"sample_size\": {\"Microplastics\": 20}}\n}\n","sub_path":"m2py/utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"378415728","text":"from Main_1 import root\r\nimport os.path\r\nfrom datetime import datetime\r\nimport pydicom as dicom\r\nimport csv\r\nimport pandas as pd\r\nimport shutil\r\n\r\nstart_time = datetime.now()\r\ni=1\r\nfor path, subdirs, files in os.walk(root):\r\n for name in files:\r\n if not name.endswith ('.dcm'):\r\n os.rename(os.path.join(path, name), os.path.join(path,'MR000'+ str(i)+'.dcm'))\r\n i=i+1\r\n print('initial path --->> \\n',str(os.path.join(path, name)))\r\n print('New Path --->> \\n', str(os.path.join(path,'MR000'+ str(i)+'.dcm')))\r\n\r\ndcm_files = []\r\nfor path, dirs, files in os.walk(root):\r\n for names in files:\r\n if names.endswith(\".dcm\"):\r\n dcm_files.append(os.path.join(path, names))\r\n \r\n#print (dcm_files)\r\n \r\nwith open('junk/Ignore_Junk.csv', 'w', newline='') as csvfile:\r\n spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\r\n spamwriter.writerow([\"Folder Name\",\"Institution Name\",\"Manufacturer\",\"Patient's Name\",\"Patient's ID\",\"Patient's Sex\",\"Patient Birth Date\",\r\n \"Study Description\",\"Physician Name\",\"Modality\",\"Study UID\",\"Series UID\",\"SliceThickness\",\r\n \"Study ID\",\"Rows\",\"Columns\",\"Pixel Spacing\"])\r\n \r\n\r\n for dcm_file in dcm_files:\r\n ds = dicom.read_file(dcm_file)\r\n fileName = dcm_file.split(\"\\\\\")\r\n spamwriter.writerow([fileName[1], ds.get(\"InstitutionName\", \"None\"),ds.get(\"Manufacturer\", \"None\"), ds.get(\"PatientName\", \"None\"), ds.get(\"PatientID\", \"None\"),\r\n ds.get(\"PatientSex\", \"None\"), ds.get(\"PatientBirthDate\", \"None\") ,ds.get(\"StudyDescription\", \"None\"),ds.get(\"ReferringPhysicianName\", \"None\"),\r\n ds.get(\"Modality\", \"None\"),ds.get(\"StudyInstanceUID\", \"None\"), ds.get(\"SeriesInstanceUID\", \"None\"), ds.get(\"SliceThickness\", \"None\"),\r\n ds.get(\"StudyID\", \"None\"),ds.get(\"Rows\", \"None\"), ds.get(\"Columns\", \"None\"),ds.get(\"PixelSpacing\", \"None\") ])\r\n \r\n pixel = pd.to_numeric(ds.get(\"PixelSpacing\", \"None\"),errors='coerce')\r\n pixel=pixel[:1]\r\n \r\n if (pixel>[1]):\r\n shutil.move(dcm_file, 'Repo')\r\n print (pixel)\r\n \r\n \r\nend_time = datetime.now()\r\nprint('Duration: {}'.format(end_time - start_time))\r\n\r\n#os.remove('junk/Ignore_Junk.csv',dir_fd=None)","sub_path":"Main_2.py","file_name":"Main_2.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"60528461","text":"\n# coding: utf-8\n\n# In[33]:\n\n\nimport pandas as pd \nimport numpy as np # For mathematical calculations \nimport seaborn as sns # For data visualization \nimport matplotlib.pyplot as plt # For plotting graphs \nget_ipython().run_line_magic('matplotlib', 'inline')\nimport warnings # To ignore any warnings warnings.filterwarnings(\"ignore\")||}]\\}|\n\n\n# In[34]:\n\n\n#importing datasets\ntrain=pd.read_csv(\"train.csv\") \ntest=pd.read_csv(\"test.csv\")\n\n\n# In[35]:\n\n\n#making a copy so that we would not lose the original datasets.\ntrain_original=train.copy() \ntest_original=test.copy()\n\n\n# In[36]:\n\n\ntrain.columns\n\n\n# In[37]:\n\n\ntest.columns\n\n\n# In[38]:\n\n\n#target_variable = Loan_status and 12 independent variables\ntrain.shape, test.shape\n\n\n# In[40]:\n\n\ntrain.dtypes\n\n\n# In[41]:\n\n\n#univariate_analysis\ntrain['Loan_Status'].value_counts()\n\n\n# In[42]:\n\n\ntrain['Loan_Status'].value_counts(normalize=True)\n\n\n# In[43]:\n\n\ntrain['Loan_Status'].value_counts().plot.bar()\n\n\n# In[47]:\n\n\nplt.figure(1) \nplt.subplot(221) \ntrain['Gender'].value_counts(normalize=True).plot.bar(figsize=(20,10), title= 'Gender') \nplt.subplot(222) \ntrain['Married'].value_counts(normalize=True).plot.bar(title= 'Married') \nplt.subplot(223) \ntrain['Self_Employed'].value_counts(normalize=True).plot.bar(title= 'Self_Employed') \nplt.subplot(224) \ntrain['Credit_History'].value_counts(normalize=True).plot.bar(title= 'Credit_History') \nplt.show()\n\n\n# It can be inferred from the above bar plots that:\n# \n# 80% applicants in the dataset are male.\n# Around 65% of the applicants in the dataset are married.\n# Around 15% applicants in the dataset are self employed.\n# Around 85% applicants have repaid their debts.\n\n# In[48]:\n\n\nplt.figure(1) \nplt.subplot(131) \ntrain['Dependents'].value_counts(normalize=True).plot.bar(figsize=(24,6), title= 'Dependents') \nplt.subplot(132) \ntrain['Education'].value_counts(normalize=True).plot.bar(title= 'Education') \nplt.subplot(133) \ntrain['Property_Area'].value_counts(normalize=True).plot.bar(title= 'Property_Area') \nplt.show()\n\n\n# Following inferences can be made from the above bar plots:\n# \n# Most of the applicants don’t have any dependents.\n# Around 80% of the applicants are Graduate.\n# Most of the applicants are from Semiurban area.\n\n# In[49]:\n\n\nplt.figure(1) \nplt.subplot(121) \nsns.distplot(train['ApplicantIncome']); \nplt.subplot(122) \ntrain['ApplicantIncome'].plot.box(figsize=(16,5)) \nplt.show()\n\n\n# It can be inferred that most of the data in the distribution of applicant income is towards left which means it is not normally distributed. We will try to make it normal in later sections as algorithms works better if the data is normally distributed.The boxplot confirms the presence of a lot of outliers/extreme values\n\n# In[52]:\n\n\ntrain.boxplot(column='ApplicantIncome', by = 'Education') \nplt.suptitle(\"\")\n\n\n# In[53]:\n\n\nplt.figure(1) \nplt.subplot(121) \nsns.distplot(train['CoapplicantIncome']); \nplt.subplot(122) \ntrain['CoapplicantIncome'].plot.box(figsize=(16,5)) \nplt.show()\n\n\n# In[56]:\n\n\nplt.figure(1) \nplt.subplot(121) \ndf=train.dropna() \nsns.distplot(df['LoanAmount']); \nplt.subplot(122) \ntrain['LoanAmount'].plot.box(figsize=(16,5)) \nplt.show()\n\n\n# Now,we will find the relation between target variable and categorical independent variables.\n\n# In[58]:\n\n\nGender=pd.crosstab(train['Gender'],train['Loan_Status']) \nGender.div(Gender.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True, figsize=(4,4))\n\n\n# It is same for both Male and female.\n\n# In[61]:\n\n\nMarried=pd.crosstab(train['Married'],train['Loan_Status']) \nDependents=pd.crosstab(train['Dependents'],train['Loan_Status']) \nEducation=pd.crosstab(train['Education'],train['Loan_Status']) \nSelf_Employed=pd.crosstab(train['Self_Employed'],train['Loan_Status']) \nMarried.div(Married.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True, figsize=(4,4)) \nplt.show() \nDependents.div(Dependents.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True) \nplt.show() \nEducation.div(Education.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True, figsize=(4,4)) \nplt.show() \nSelf_Employed.div(Self_Employed.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True, figsize=(4,4)) \nplt.show()\n\n\n# In[62]:\n\n\n#continuing finding relationships btw categorical independent variables and Loan_Status.\nCredit_History=pd.crosstab(train['Credit_History'],train['Loan_Status']) \nProperty_Area=pd.crosstab(train['Property_Area'],train['Loan_Status']) \nCredit_History.div(Credit_History.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True, figsize=(4,4)) \nplt.show() \nProperty_Area.div(Property_Area.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True) \nplt.show()\n\n\n# In[63]:\n\n\n#Numerical Independent Variable vs Target Variable\ntrain.groupby('Loan_Status')['ApplicantIncome'].mean().plot.bar()\n\n\n# In[71]:\n\n\nbins=[0,2500,4000,6000,81000] \ngroup=['Low','Average','High','Very_high'] \ntrain['Income_bin']=pd.cut(train['ApplicantIncome'],bins,labels=group)\nIncome_bin=pd.crosstab(train['Income_bin'],train['Loan_Status']) \nIncome_bin.div(Income_bin.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True) \nplt.xlabel('ApplicantIncome') \nP = plt.ylabel('Percentage')\n\n\n# It can be inferred that Applicant income does not affect the chances of loan approval which contradicts our hypothesis in which we assumed that if the applicant income is high the chances of loan approval will also be high.\n\n# In[75]:\n\n\nbins=[0,1000,3000,42000] \ngroup=['Low','Average','High'] \ntrain['Coapplicant_Income_bin']=pd.cut(df['CoapplicantIncome'],bins,labels=group)\nCoapplicant_Income_bin=pd.crosstab(train['Coapplicant_Income_bin'],train['Loan_Status']) \nCoapplicant_Income_bin.div(Coapplicant_Income_bin.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True) \nplt.xlabel('CoapplicantIncome') \nP = plt.ylabel('Percentage')\n\n\n# It shows that if coapplicant’s income is less the chances of loan approval are high. But this does not look right. The possible reason behind this may be that most of the applicants don’t have any coapplicant so the coapplicant income for such applicants is 0 and hence the loan approval is not dependent on it. So we can make a new variable in which we will combine the applicant’s and coapplicant’s income to visualize the combined effect of income on loan approv\n\n# In[76]:\n\n\ntrain['Total_Income']=train['ApplicantIncome']+train['CoapplicantIncome']\nbins=[0,2500,4000,6000,81000] \ngroup=['Low','Average','High', 'Very high'] \ntrain['Total_Income_bin']=pd.cut(train['Total_Income'],bins,labels=group)\nTotal_Income_bin=pd.crosstab(train['Total_Income_bin'],train['Loan_Status']) \nTotal_Income_bin.div(Total_Income_bin.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True) \nplt.xlabel('Total_Income') \nP = plt.ylabel('Percentage')\n\n\n# In[80]:\n\n\nbins=[0,100,200,500] \ngroup=['Low','Average','High'] \ntrain['LoanAmount_bin']=pd.cut(df['LoanAmount'],bins,labels=group)\nLoanAmount_bin=pd.crosstab(train['LoanAmount_bin'],train['Loan_Status']) \nLoanAmount_bin.div(LoanAmount_bin.sum(1).astype(float), axis=0).plot(kind=\"bar\", stacked=True) \nplt.xlabel('LoanAmount') \nP = plt.ylabel('Percentage')\n\n\n# In[81]:\n\n\ntrain=train.drop(['Income_bin', 'Coapplicant_Income_bin', 'LoanAmount_bin', 'Total_Income_bin', 'Total_Income'], axis=1)\ntrain['Dependents'].replace('3+', 3,inplace=True) \ntest['Dependents'].replace('3+', 3,inplace=True) \ntrain['Loan_Status'].replace('N', 0,inplace=True) \ntrain['Loan_Status'].replace('Y', 1,inplace=True)\n\n\n# In[83]:\n\n\nmatrix = train.corr() \nf, ax = plt.subplots(figsize=(9, 6)) \nsns.heatmap(matrix, vmax=.8, square=True, cmap=\"BuPu\");\n\n\n# We see that the most correlated variables are (ApplicantIncome - LoanAmount) and (Credit_History - Loan_Status). LoanAmount is also correlated with CoapplicantIncome.\n\n# In[84]:\n\n\n#Missing values\ntrain.isnull().sum()\n\n\n# In[85]:\n\n\ntrain['Gender'].fillna(train['Gender'].mode()[0], inplace=True) \ntrain['Married'].fillna(train['Married'].mode()[0], inplace=True) \ntrain['Dependents'].fillna(train['Dependents'].mode()[0], inplace=True) \ntrain['Self_Employed'].fillna(train['Self_Employed'].mode()[0], inplace=True) \ntrain['Credit_History'].fillna(train['Credit_History'].mode()[0], inplace=True)\n\n\n# In[86]:\n\n\ntrain['Loan_Amount_Term'].fillna(train['Loan_Amount_Term'].mode()[0], inplace=True)\ntrain['LoanAmount'].fillna(train['LoanAmount'].median(), inplace=True)\n\n\n# In[87]:\n\n\ntrain.isnull().sum()\n\n\n# In[88]:\n\n\n#missing values in test dataset\ntest['Gender'].fillna(train['Gender'].mode()[0], inplace=True) \ntest['Dependents'].fillna(train['Dependents'].mode()[0], inplace=True) \ntest['Self_Employed'].fillna(train['Self_Employed'].mode()[0], inplace=True) \ntest['Credit_History'].fillna(train['Credit_History'].mode()[0], inplace=True) \ntest['Loan_Amount_Term'].fillna(train['Loan_Amount_Term'].mode()[0], inplace=True) \ntest['LoanAmount'].fillna(train['LoanAmount'].median(), inplace=True)\n\n\n# In[89]:\n\n\ntrain['LoanAmount_log'] = np.log(train['LoanAmount']) \ntrain['LoanAmount_log'].hist(bins=20) \ntest['LoanAmount_log'] = np.log(test['LoanAmount'])\n\n\n# In[93]:\n\n\ntrain=train.drop('Loan_ID',axis=1) \ntest=test.drop('Loan_ID',axis=1)\n\n\n# In[94]:\n\n\nX = train.drop('Loan_Status',1) \ny = train.Loan_Status\n\n\n# In[95]:\n\n\nX=pd.get_dummies(X) \ntrain=pd.get_dummies(train) \ntest=pd.get_dummies(test)\n\n\n# In[96]:\n\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_cv, y_train, y_cv = train_test_split(X,y, test_size =0.3)\n\n\n# In[97]:\n\n\nfrom sklearn.linear_model import LogisticRegression \nfrom sklearn.metrics import accuracy_score\nmodel = LogisticRegression() \nmodel.fit(x_train, y_train)\nLogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1, penalty='l2', random_state=1, solver='liblinear', tol=0.0001, verbose=0, warm_start=False)\n\n\n# In[98]:\n\n\npred_cv = model.predict(x_cv)\naccuracy_score(y_cv,pred_cv)\n\n\n# In[99]:\n\n\npred_test = model.predict(test)\nsubmission=pd.read_csv(\"submission.csv\")\n\n\n# In[100]:\n\n\nsubmission['Loan_Status']=pred_test \nsubmission['Loan_ID']=test_original['Loan_ID']\nsubmission['Loan_Status'].replace(0, 'N',inplace=True) \nsubmission['Loan_Status'].replace(1, 'Y',inplace=True)\n\n\n# In[101]:\n\n\npd.DataFrame(submission, columns=['Loan_ID','Loan_Status']).to_csv('logistic.csv')\n\n\n# In[102]:\n\n\nfrom sklearn.model_selection import StratifiedKFold\ni=1 \nkf = StratifiedKFold(n_splits=5,random_state=1,shuffle=True) \nfor train_index,test_index in kf.split(X,y): \n print('\\n{} of kfold {}'.format(i,kf.n_splits)) \n xtr,xvl = X.loc[train_index],X.loc[test_index] \n ytr,yvl = y[train_index],y[test_index] \n model = LogisticRegression(random_state=1) \n model.fit(xtr, ytr) \n pred_test = model.predict(xvl) \n score = accuracy_score(yvl,pred_test) \n print('accuracy_score',score) \n i+=1 \n pred_test = model.predict(test) \n pred=model.predict_proba(xvl)[:,1]\n\n\n# In[105]:\n\n\nfrom sklearn import metrics \nfpr, tpr, _ = metrics.roc_curve(yvl, pred) \nauc = metrics.roc_auc_score(yvl, pred) \nplt.figure(figsize=(12,8)) \nplt.plot(fpr,tpr,label=\"validation, auc=\"+str(auc)) \nplt.xlabel('False Positive Rate') \nplt.ylabel('True Positive Rate') \nplt.legend(loc=4) \nplt.show()\n\n\n# In[106]:\n\n\nsubmission['Loan_Status']=pred_test \nsubmission['Loan_ID']=test_original['Loan_ID']\nsubmission['Loan_Status'].replace(0, 'N',inplace=True) \nsubmission['Loan_Status'].replace(1, 'Y',inplace=True)\n\n\n# In[107]:\n\n\npd.DataFrame(submission, columns=['Loan_ID','Loan_Status']).to_csv('Logistic.csv')\n\n\n# In[108]:\n\n\ntrain['Total_Income']=train['ApplicantIncome']+train['CoapplicantIncome'] \ntest['Total_Income']=test['ApplicantIncome']+test['CoapplicantIncome']\n\n\n# In[109]:\n\n\nsns.distplot(train['Total_Income']);\n\n\n# In[110]:\n\n\ntrain['Total_Income_log'] = np.log(train['Total_Income']) \nsns.distplot(train['Total_Income_log']); \ntest['Total_Income_log'] = np.log(test['Total_Income'])\n\n\n# In[112]:\n\n\ntrain['EMI']=train['LoanAmount']/train['Loan_Amount_Term'] \ntest['EMI']=test['LoanAmount']/test['Loan_Amount_Term']\n\n\n# In[113]:\n\n\nsns.distplot(train['EMI']);\n\n\n# In[121]:\n\n\ntrain['Balance Income']=train['Total_Income']-(train['EMI']*1000) # Multiply with 1000 to make the units equal \ntest['Balance Income']=test['Total_Income']-(test['EMI']*1000)\nsns.distplot(train['Balance Income']);\n\n\n# In[122]:\n\n\ntrain=train.drop(['ApplicantIncome', 'CoapplicantIncome', 'LoanAmount', 'Loan_Amount_Term'], axis=1) \ntest=test.drop(['ApplicantIncome', 'CoapplicantIncome', 'LoanAmount', 'Loan_Amount_Term'], axis=1)\n\n\n# In[123]:\n\n\nX = train.drop('Loan_Status',1) \ny = train.Loan_Status # Save target variable in separate dataset\n\n\n# In[124]:\n\n\n#Logistic Regression\nfrom sklearn import tree\n#Let’s fit the decision tree model with 5 folds of cross validation.\n\ni=1 \nkf = StratifiedKFold(n_splits=5,random_state=1,shuffle=True) \nfor train_index,test_index in kf.split(X,y): \n print('\\n{} of kfold {}'.format(i,kf.n_splits)) \n xtr,xvl = X.loc[train_index],X.loc[test_index] \n ytr,yvl = y[train_index],y[test_index] \n model = tree.DecisionTreeClassifier(random_state=1) \n model.fit(xtr, ytr) \n pred_test = model.predict(xvl) \n score = accuracy_score(yvl,pred_test) \n print('accuracy_score',score) \n i=i + 1 \n pred_test = model.predict(test)\n\n\n# In[125]:\n\n\nsubmission['Loan_Status']=pred_test # filling Loan_Status with predictions submission['Loan_ID']=test_original['Loan_ID'] # filling Loan_ID with test Loan_ID\n# replacing 0 and 1 with N and Y \nsubmission['Loan_Status'].replace(0, 'N',inplace=True) \nsubmission['Loan_Status'].replace(1, 'Y',inplace=True)\n# Converting submission file to .csv format \npd.DataFrame(submission, columns=['Loan_ID','Loan_Status']).to_csv('sample_submission.csv')\n\n","sub_path":"Loan_Prediction_AV/Loan_Prediction.py","file_name":"Loan_Prediction.py","file_ext":"py","file_size_in_byte":13887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"425893693","text":"#!/usr/bin/env python2\nimport unittest\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom collections import namedtuple\nfrom data_loader import SeizureDataset\nimport pdb\n\n\nclass DataLoaderTest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n FLAGS = namedtuple('FLAGS',\n 'input_subsample_rate train_set test_set batch_size')\n flags = FLAGS(160,\n 'train_1_dummy',\n 'test_1_dummy',\n 1)\n cls.ds = SeizureDataset(flags)\n\n def test_label(self):\n\n all_data = ['1_843_0.mat', '1_58_1.mat', '1_919_0.mat']\n\n self.assertEqual(self.ds.get_class_from_name(all_data[0]), 0)\n self.assertEqual(self.ds.get_class_from_name(all_data[1]), 1)\n self.assertEqual(self.ds.get_class_from_name(all_data[2]), 0)\n\n def test_class_occurrence_counter(self):\n print('Test occurrence counter')\n all_data = ['1_843_0.mat', '1_58_1.mat', '1_919_0.mat']\n\n file_with_class = np.array(\n [(mat_file, self.ds.get_class_from_name(mat_file))\n for mat_file in all_data],\n dtype=[('file', '|S16'),\n ('class', 'float32')])\n\n inter, preic = self.ds.count_class_occurrences(file_with_class)\n self.assertEqual(inter, 2, 'Wrong number of interictal case')\n self.assertEqual(preic, 1, 'Wrong number of preictal case')\n\n def test_rand_observation_loader(self):\n all_data = [\n '1_843_0.mat',\n '1_58_1.mat',\n '1_919_0.mat',\n '1_580_0.mat',\n '1_631_0.mat',\n '1_93_1.mat',\n '1_967_0.mat',\n '1_788_0.mat',\n '1_140_0.mat',\n '1_619_0.mat',\n ]\n\n file_with_class = np.array(\n [(mat_file, self.ds.get_class_from_name(mat_file))\n for mat_file in all_data],\n dtype=[('file', '|S16'),\n ('class', 'float32')])\n\n inter, preic = self.ds.count_class_occurrences(file_with_class)\n self.assertEqual(inter, 8, 'Wrong number of interictal case')\n self.assertEqual(preic, 2, 'Wrong number of preictal case')\n rand_interictal = np.random.choice(\n file_with_class\n [file_with_class['class'] == self.ds.INTERICTAL_CLASS],\n size=inter)\n\n rand_preictal = np.random.choice(\n file_with_class[file_with_class['class'] == self.ds.PREICTAL_CLASS],\n size=preic)\n self.assertEquals(\n len(rand_interictal),\n inter,\n 'Size of loaded interictal does not match')\n self.assertEquals(\n len(rand_preictal),\n preic,\n 'Size of loaded preictal does not match')\n\n def test_check_ids_match(self):\n\n all_data = [\n '1_843_0.mat',\n '1_58_1.mat',\n ]\n\n file_with_class = np.array(\n [(mat_file, self.ds.get_class_from_name(mat_file))\n for mat_file in all_data],\n dtype=[('file', '|S16'),\n ('class', 'float32')])\n\n ids = file_with_class['file']\n self.assertEqual(ids[0], '1_843_0.mat')\n self.assertEqual(ids[1], '1_58_1.mat')\n\n def test_data_loader(self):\n train_set_name = 'train_1_dummy'\n data_interictal, data_preictal = self.ds.pick_random_observation(\n train_set_name)\n shuffled_dataset = self.ds.merge_and_shuffle_selection(data_interictal,\n data_preictal)\n\n print(\"test data loader\")\n # print(shuffled_dataset)\n #eeg_label = shuffled_dataset['class']\n #print(\"Labels\", eeg_label)\n\n base_dir_train = self.ds.path_to_all_datasets + '/' + train_set_name\n #print(\"Data set directory==>\", base_dir_train)\n eeg_data, _ = self.ds.get_X_from_files(\n base_dir_train, shuffled_dataset['file'],\n self.ds.input_subsample_rate)\n\n data_indx = 0\n chan = 1\n plt.plot(eeg_data[data_indx][chan, :])\n # plt.show()\n\n def test_next_batch(self):\n all_data = [\n '1_843_0.mat',\n '1_58_1.mat',\n '1_919_0.mat',\n '1_580_0.mat',\n '1_631_0.mat',\n '1_93_1.mat',\n '1_967_0.mat',\n '1_788_0.mat',\n '1_140_0.mat',\n '1_619_0.mat',\n ]\n\n file_with_class = np.array(\n [(mat_file, self.ds.get_class_from_name(mat_file))\n for mat_file in all_data],\n dtype=[('file', '|S16'),\n ('class', 'float32')])\n\n X_train = file_with_class['file']\n y_labels = file_with_class['class']\n\n batch_size = 2\n self.ds.set_batch_size(batch_size)\n\n total_batch = int(len(X_train)/batch_size)\n\n self.assertEqual(total_batch, 5, 'Wrong total batch size')\n batch_xs, batch_ys = self.ds.next_training_batch(X_train,\n y_labels)\n\n self.assertEqual(len(batch_xs), batch_size, 'Wrong x_train batch size')\n\n self.assertEqual(batch_xs[0], '1_843_0.mat', 'Grabbed the wrong file')\n self.assertEqual(batch_xs[1], '1_58_1.mat', 'Grabbed the wrong file')\n self.assertEqual(batch_ys[0], 0, 'Label did not match the batch file')\n self.assertEqual(batch_ys[1], 1, 'Label did not match the batch file')\n\n batch_xs, batch_ys = self.ds.next_training_batch(X_train,\n y_labels)\n\n self.assertEqual(len(batch_xs), batch_size, 'Wrong x_train batch size')\n\n self.assertEqual(batch_xs[0], '1_919_0.mat', 'Grabbed the wrong file')\n self.assertEqual(batch_xs[1], '1_580_0.mat', 'Grabbed the wrong file')\n self.assertEqual(batch_ys[0], 0, 'Label did not match the batch file')\n self.assertEqual(batch_ys[1], 0, 'Label did not match the batch file')\n\n batch_xs, batch_ys = self.ds.next_training_batch(X_train,\n y_labels)\n\n self.assertEqual(len(batch_xs), batch_size, 'Wrong x_train batch size')\n\n self.assertEqual(batch_xs[0], '1_631_0.mat', 'Grabbed the wrong file')\n self.assertEqual(batch_xs[1], '1_93_1.mat', 'Grabbed the wrong file')\n self.assertEqual(batch_ys[0], 0, 'Label did not match the batch file')\n self.assertEqual(batch_ys[1], 1, 'Label did not match the batch file')\n\n batch_xs, batch_ys = self.ds.next_training_batch(X_train,\n y_labels)\n\n batch_xs, batch_ys = self.ds.next_training_batch(X_train,\n y_labels)\n\n # Final batch\n self.assertEqual(batch_xs[0], '1_140_0.mat', 'Grabbed the wrong file')\n self.assertEqual(batch_xs[1], '1_619_0.mat', 'Grabbed the wrong file')\n self.assertEqual(batch_ys[0], 0, 'Label did not match the batch file')\n self.assertEqual(batch_ys[1], 0, 'Label did not match the batch file')\n\n # One batch iteration is done, make sure the indices are reset\n self.assertEqual(\n self.ds.index_0,\n 0,\n 'Initial batch index not reset correctly')\n self.assertEqual(\n self.ds.batch_index, batch_size,\n 'Initial batch index not reset correctly')\n\n batch_xs, batch_ys = self.ds.next_training_batch(X_train,\n y_labels)\n\n self.assertEqual(batch_xs[0], '1_843_0.mat', 'Grabbed the wrong file')\n self.assertEqual(batch_xs[1], '1_58_1.mat', 'Grabbed the wrong file')\n self.assertEqual(batch_ys[0], 0, 'Label did not match the batch file')\n self.assertEqual(batch_ys[1], 1, 'Label did not match the batch file')\n\n def test_next_batch_completion(self):\n all_data = [\n '1_843_0.mat',\n '1_58_1.mat',\n '1_919_0.mat',\n '1_580_0.mat'\n ]\n\n file_with_class = np.array(\n [(mat_file, self.ds.get_class_from_name(mat_file))\n for mat_file in all_data],\n dtype=[('file', '|S16'),\n ('class', 'float32')])\n\n X_train = file_with_class['file']\n y_labels = file_with_class['class']\n\n batch_size = 2\n self.ds.set_batch_size(batch_size)\n\n total_batch = int(len(X_train)/batch_size)\n\n self.assertEqual(total_batch, 2, 'Wrong total batch size')\n batch_xs, batch_ys = self.ds.next_training_batch(X_train,\n y_labels)\n batch_xs, batch_ys = self.ds.next_training_batch(X_train,\n y_labels)\n\n # After two iterations it should be set back to initial\n self.assertEqual(self.ds.index_0, 0, 'Wrong index update')\n self.assertEqual(\n self.ds.batch_index,\n batch_size,\n 'Wrong batch index update')\n\n batch_xs, batch_ys = self.ds.next_training_batch(X_train,\n y_labels)\n self.assertEqual(\n self.ds.index_0,\n batch_size,\n 'Next batch generation failed')\n self.assertEqual(\n self.ds.batch_index,\n batch_size*2,\n 'Next batch generation failed')\n self.assertIsNotNone(batch_xs)\n self.assertIsNotNone(batch_ys)\n\n def test_evaluation_loader(self):\n #self.ds.input_subsample_rate = 240000/160\n eval_size = 2\n X_train, y_train = self.ds.load_train_data('train_1_dummy')\n X_train_eval_sampl, y_train_eval_sampl = self.ds.get_evaluation_set(\n X_train,\n y_train,\n eval_size)\n\n self.assertEqual(len(X_train_eval_sampl), eval_size, 'Wrong eval size')\n self.assertEqual(len(y_train_eval_sampl), eval_size, 'Wrong eval size')\n self.assertIsInstance(y_train_eval_sampl[0], np.float32)\n # If this fails, double check the subsample rate\n # pdb.set_trace()\n self.assertEqual(\n X_train_eval_sampl[0].shape,\n (16,\n (240000/self.ds.input_subsample_rate)),\n 'Size of the subsampled data does not match the original data')\n\n def test_data_sampler(self):\n\n dummy_matrix = np.array(\n [[-0.13130315, -3.13130307, -9.13130283, 24.86869621,\n 23.86869621, 28.86869621],\n [2.33613181, 5.33613157, 18.33613205, 30.33613205,\n 36.33613205, 28.33613205],\n [-26.15572548, -35.15572357, -39.15572357, 3.84427452,\n 4.84427452, 4.84427452]])\n dummy_matrix_downsampl = np.array(\n [[-0.13130315, -9.13130283, 23.86869621],\n [2.33613181, 18.33613205, 36.33613205],\n [-26.15572548, -39.15572357, 4.84427452]])\n\n downsample_rate = 2\n subsampled_mat = self.ds.subsample_data(dummy_matrix, downsample_rate)\n self.assertEqual(\n subsampled_mat.shape, (3, 3),\n 'Mismatch in downsampled size')\n self.assertTrue(np.array_equal(subsampled_mat, dummy_matrix_downsampl),\n 'Downsampled matrices do not match')\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"dl_tf/tf_rnn/unit_tests.py","file_name":"unit_tests.py","file_ext":"py","file_size_in_byte":11616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"143005683","text":"# coding=utf-8\n\nimport markdown\nfrom markdown.extensions import tables, fenced_code, footnotes\n\n\nclass MarkdownParser(object):\n def __init__(self):\n self.md = markdown.Markdown(extensions=[\n tables.TableExtension(),\n fenced_code.FencedCodeExtension(),\n footnotes.FootnoteExtension(),\n ])\n\n def parse(self, md_text):\n html = self.md.convert(md_text)\n self.md.reset()\n return html\n\n\ndef test():\n md_text = \"\"\"# Markdown 示例\n \n## Markdown简介\n\n> Markdown 是一种轻量级标记语言 —— [维基百科](https://zh.wikipedia.org/wiki/Markdown)\n\n**粗体**或者*斜体*,[链接](http://www.example.com)或脚注[^demo]。按`Ctrl + /`帮助。 \n\n### 代码块\n\n``` python\ndef somefunc(param1='', param2=0):\n '''A docstring'''\n return (param2 - param1 + 1) or None\n```\n### LaTeX 公式\n\n行内公式如 $\\Gamma(n) = (n-1)!\\quad\\forall n\\in\\mathbb N$。块级公式:\n\n$$\tx = \\dfrac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} $$\n\n### 表格\n\n| Item | Value | Qty |\n| :-------- | --------:| :--: |\n| Computer | 1600 USD | 5 |\n| Phone | 12 USD | 12 |\n\n\"\"\"\n parser = MarkdownParser()\n md_html = parser.parse(md_text)\n print(md_html)\n\n\nif __name__ == '__main__':\n test()\n","sub_path":"markdown_parser.py","file_name":"markdown_parser.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"257809260","text":"#!/usr/bin/env python\n# Copyright (c) 2016 Calvin Ference\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n# of the Software, and to permit persons to whom the Software is furnished to do\n# so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport csv, praw, re, string\n\nsub_fr = ['france','toulouse','aixmarseille','Lyon']\nwordcount_fr = {}\nsub_qc = ['quebec','troisrivieres','quebeccity','longueuil']\nwordcount_qc = {}\n\n'''\nfile=open(\"D:\\\\zzzz\\\\names2.txt\",\"r+\")\nwordcount={}\nfor word in file.read().split():\n if word not in wordcount:\n wordcount[word] = 1\n else:\n wordcount[word] += 1\nfor k,v in wordcount.items():\n print k, v\n'''\n\ndef addToWordCount(wordcount, text):\n # A bit of filtering\n replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))\n text = re.sub(r'^https?:\\/\\/.*[\\r\\n]*', '', text, flags=re.MULTILINE)\n #text = text.translate(replace_punctuation)\n for word in text.split():\n if word not in wordcount:\n wordcount[word] = 1\n else:\n wordcount[word] += 1\n return wordcount\n\n\ndef analyzeSubReddit(wordcount,subreddit):\n submissions = r.get_subreddit(subreddit).get_top(limit=100)\n for submission in submissions:\n submission.replace_more_comments(limit=None, threshold=0)\n wordcount = addToWordCount(wordcount,submission.title)\n flat_comments = praw.helpers.flatten_tree(submission.comments)\n for comment in flat_comments:\n wordcount = addToWordCount(wordcount, comment.body)\n return wordcount\n\nif __name__ == \"__main__\":\n r = praw.Reddit(user_agent='FrenchAnalyzer Script by /u/vezril')\n r.login('veztest', 'pythoniscool')\n dictionary = set(open('/usr/share/dict/words','r').read().lower().split())\n\n # Gather France text\n for subreddit in sub_fr:\n wordcount_fr = analyzeSubReddit(wordcount_fr,subreddit)\n for subreddit in sub_qc:\n wordcount_qc = analyzeSubReddit(wordcount_qc,subreddit)\n\n try:\n f_fr = open('france.csv','wb',encoding='utf8')\n f_qc = open('qc.csv','wb',encoding='utf8')\n except:\n raise\n\n writer = csv.writer(f_fr)\n for key, value in wordcount_fr.items():\n if key in dictionary:\n writer.writerow([key, value])\n writer = csv.writer(f_qc)\n for key, value in wordcount_qc.items():\n if key in dictionary:\n writer.writerow([key, value])\n writer.writerow([key, value])\n\n f_fr.close()\n f_qc.close()\n","sub_path":"froganalyzer/froganalyzer.py","file_name":"froganalyzer.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"360960300","text":"# 小易有n块砖块,每一块砖块有一个高度。小易希望利用这些砖块堆砌两座相同高度的塔。为了让问题简单,砖块堆砌就是简单的高度相加,\n# 某一块砖只能使用在一座塔中一次。小易现在让能够堆砌出来的两座塔的高度尽量高,小易能否完成呢。 \n# 输入描述:\n# 输入包括两行:\n# 第一行为整数n(1 ≤ n ≤ 50),即一共有n块砖块\n# 第二行为n个整数,表示每一块砖块的高度height[i] (1 ≤ height[i] ≤ 500000)\n\n\n# 输出描述:\n# 如果小易能堆砌出两座高度相同的塔,输出最高能拼凑的高度,如果不能则输出-1.\n# 保证答案不大于500000。\n\n# 输入例子1:\n# 3\n# 2 3 5\n\n# 输出例子1:\n# 5\n\n# 假设砖块分为A,B两堆,dp[i][j]中的j表示B-A的长度。\n# 因为B-A有可能是负的,所以j整体偏移sum个长度,即2*sum+1。\n# 而dp[i][j]的值则表示当A-B的值为j时,B的最大长度是多少。\n# dp[i][j] = dp[i-1][j]表示我不用第i块砖\n# dp[i][j] = max(dp[i-1][j-h], dp[i-1][j])表示我把砖放在A堆。\n# dp[i][j] = max(dp[i-1][j+h]+h, dp[i-1][j])表示我把砖放在B堆。\n# 然后会爆内存,所以用了滚动数组。\n\nfrom random import randint\n\ndef dp(bricks):\n\ttable = [[-1 for _ in range(500001)] for _ in range(2)]\n\ttable[0][0] = 0\n\tlength = len(bricks)\n\tsummary = sum(bricks)\n\tp = 1\n\tfor i in range(length):\n\t\tfor j in range(summary):\n\t\t\t# 不放\n\t\t\ttable[p][j] = table[1 - p][j]\n\t\t\t# 放在矮的那一堆,放上去比原来高的矮\n\t\t\tif j + bricks[i] <= summary and table[1 - p][j + bricks[i]] >= 0:\n\t\t\t\ttable[p][j] = max(table[p][j], table[1 - p][j + bricks[i]] + bricks[i])\n\t\t\t# 放在矮的那一堆,放上去比原来高的高\n\t\t\tif bricks[i] - j >= 0 and table[1 - p][bricks[i] - j] >= 0:\n\t\t\t\ttable[p][j] = max(table[p][j], table[1 - p][bricks[i] - j] + bricks[i] - j)\n\t\t\t# 放在高的那一堆\n\t\t\tif j - bricks[i] >= 0 and table[1 - p][j - bricks[i]] >= 0:\n\t\t\t\ttable[p][j] = max(table[p][j], table[1 - p][j - bricks[i]])\n\t\tp = 1 - p\n\tif table[1 - p][0] == 0:\n\t\treturn -1\n\telse:\n\t\treturn table[1 - p][0]\n\nif __name__ == '__main__':\n\tprint(dp([3, 2, 3, 5]))\n\tfor i in range(10):\n\t\tbricks = [randint(1, 20000) for _ in range(10)]\n\t\tprint(bricks, sum(bricks))\n\t\tprint(dp(bricks))\n\n\n\n\n","sub_path":"网易/2017春季实习/DP堆砖块.py","file_name":"DP堆砖块.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"53076193","text":"from collections import OrderedDict\n\nfrom django.http import Http404\nfrom django.shortcuts import render\nfrom django.views.decorators.cache import cache_page\nfrom django.core.urlresolvers import reverse\nfrom django.utils.text import slugify\nfrom django.utils.translation import ugettext as _\n\nfrom .analysis import analysis_manager\nimport contracts.analysis\n\n\ndef analysis_selector(request, analysis_id, slug=None):\n try:\n analysis_id = int(analysis_id)\n except:\n raise Http404\n if int(analysis_id) not in contracts.analysis.PRIMARY_KEY or \\\n contracts.analysis.PRIMARY_KEY[analysis_id] not in AVAILABLE_VIEWS:\n raise Http404\n\n name = contracts.analysis.PRIMARY_KEY[analysis_id]\n\n return AVAILABLE_VIEWS[name](request)\n\n\n@cache_page(60 * 60 * 24)\ndef entities_category_ranking(request):\n entities = analysis_manager.get_analysis('municipalities_categories_ranking')\n\n count = 1\n for entity in entities:\n entity.rank = count\n count += 1\n\n context = {'navigation_tab': 'analysis',\n 'entities': entities,\n 'REQUIRE_D3JS': True}\n\n return render(request, 'contracts/analysis/entity_rank/main.html', context)\n\n\ndef contracts_price_histogram(request):\n\n data = analysis_manager.get_analysis(\"contracts_macro_statistics\")\n\n context = {'navigation_tab': 'analysis',\n 'count': data['total_count'],\n 'price': data['total_sum'],\n 'REQUIRE_D3JS': True}\n\n return render(request,\n 'contracts/analysis/contracts_price_histogram/main.html', context)\n\n\ndef entities_values_histogram(request):\n\n context = {'navigation_tab': 'analysis',\n 'REQUIRE_D3JS': True}\n\n return render(request,\n 'contracts/analysis/entities_values_histogram/main.html', context)\n\n\ndef procedure_types_time_series(request):\n context = {'navigation_tab': 'analysis',\n 'REQUIRE_D3JS': True}\n return render(request,\n 'contracts/analysis/procedure_type_time_series/main.html', context)\n\n\n@cache_page(60 * 60 * 24)\ndef municipalities_delta_time(request):\n\n entities = analysis_manager.get_analysis('municipalities_delta_time')\n count = 1\n for entity in entities:\n entity.rank = count\n count += 1\n\n context = {'navigation_tab': 'analysis',\n 'entities': entities,\n 'REQUIRE_D3JS': True}\n\n return render(request,\n 'contracts/analysis/municipalities_delta_time/main.html', context)\n\n\ndef municipalities_contracts_time_series(request):\n context = {'navigation_tab': 'analysis', 'REQUIRE_D3JS': True}\n return render(request,\n 'contracts/analysis/municipalities_contracts_time_series/main.html', context)\n\n\ndef municipalities_procedure_types_time_series(request):\n context = {'navigation_tab': 'analysis', 'REQUIRE_D3JS': True}\n return render(request,\n 'contracts/analysis/municipalities_procedure_type_time_series/main.html', context)\n\n\ndef ministries_contracts_time_series(request):\n context = {'navigation_tab': 'analysis', 'REQUIRE_D3JS': True}\n return render(request,\n 'contracts/analysis/ministries_contracts_time_series/main.html', context)\n\n\ndef contracts_time_series(request):\n context = {'navigation_tab': 'analysis', 'REQUIRE_D3JS': True}\n return render(request, 'contracts/analysis/contracts_time_series/main.html', context)\n\n\ndef legislation_application_time_series(request):\n context = {'navigation_tab': 'analysis', 'REQUIRE_D3JS': True}\n return render(request,\n 'contracts/analysis/legislation_application_time_series/main.html', context)\n\n\ndef contracted_lorenz_curve(request):\n\n _, gini_index = analysis_manager.get_analysis('contracted_lorenz_curve')\n\n context = {'navigation_tab': 'analysis', 'gini_index': gini_index,\n 'REQUIRE_D3JS': True}\n return render(request, 'contracts/analysis/contracted_lorenz_curve/main.html', context)\n\n\nAVAILABLE_VIEWS = {\n 'municipalities_delta_time': municipalities_delta_time,\n 'municipalities_contracts_time_series': municipalities_contracts_time_series,\n 'municipalities_procedure_types_time_series': municipalities_procedure_types_time_series,\n 'municipalities_categories_ranking': entities_category_ranking,\n\n 'ministries_contracts_time_series': ministries_contracts_time_series,\n #'ministries_delta_time': ministries_delta_time,\n\n 'contracts_price_distribution': contracts_price_histogram,\n 'entities_values_distribution': entities_values_histogram,\n 'procedure_type_time_series': procedure_types_time_series,\n 'contracts_time_series': contracts_time_series,\n 'legislation_application_time_series': legislation_application_time_series,\n 'contracted_lorenz_curve': contracted_lorenz_curve,\n}\n\n\ntitles = OrderedDict([\n ('contracts_time_series', _('When do Portugal contract most?')),\n ('contracts_price_distribution', _('Distribution of prices of contracts')),\n ('entities_values_distribution', _('Distribution of earnings of entities')),\n ('procedure_type_time_series', _('Percentage of contracts by direct procurement or public tender')),\n ('legislation_application_time_series', _('How many contracts are published too late?')),\n\n ('municipalities_contracts_time_series', _('When do portuguese municipalities contract most?')),\n ('municipalities_procedure_types_time_series', _('How do portuguese municipalities contract most?')),\n ('municipalities_delta_time', _('Time of publication of municipalities')),\n ('municipalities_categories_ranking', _('Ranking of specificity of municipalities')),\n\n ('ministries_contracts_time_series', _('When do portuguese ministries contract most?')),\n\n ('contracted_lorenz_curve', _('Income Inequality in Public Contracts')),\n])\n\n\ndef analysis_list():\n\n analysis_list = []\n for analysis in titles:\n analysis_list.append({\n 'id': contracts.analysis.ANALYSIS[analysis],\n 'url': reverse('contracts_analysis_selector',\n args=(contracts.analysis.ANALYSIS[analysis],\n slugify(titles[analysis]))),\n 'title': titles[analysis]\n })\n\n return list(reversed(analysis_list))\n\n\ndef analysis(request):\n return render(request, 'contracts/analysis.html', {\n 'analysis': analysis_list(),\n 'navigation_tab': 'analysis'})\n","sub_path":"contracts/views_analysis.py","file_name":"views_analysis.py","file_ext":"py","file_size_in_byte":6529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"103899663","text":"#/usr/bin/python\n#coding=utf-8\nimport os, sys, time\nimport zipfile\n\ndef zip_de(filedir, fname, fpath):\n\n filename = fname #要解压的文件\n filedir = filedir + fpath #解压后放入的目录\n r = zipfile.is_zipfile(filename)\n if r:\n starttime = time.time()\n fz = zipfile.ZipFile(filename,'r')\n for file in fz.namelist():\n print(file) #打印zip归档中目录\n fz.extract(file, filedir)\n endtime = time.time()\n times = endtime - starttime\n else:\n print('This file is not zip file')\n print('times' + str(times))\nif __name__ == '__main__':\n filedir = \"D:\\\\py_buffer\\\\docx_Pro\\\\\"\n os.rename(\"test1.docx\", \"test1.zip\")\n os.rename(\"test2.docx\", \"test2.zip\")\n os.rename(\"test3.docx\", \"test3.zip\")\n zip_de(filedir, 'test1.zip', 'test1\\\\')\n zip_de(filedir, 'test2.zip', 'test2\\\\')\n zip_de(filedir, 'test3.zip', 'test3\\\\')","sub_path":"zip_De.py","file_name":"zip_De.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"514653487","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\nfrom pymongo import MongoClient\nfrom scrapy.conf import settings\nfrom scrapy.exceptions import DropItem\nimport mysql.connector\nimport logging \nimport json\n\nclass MongoDBPipeline(object):\n \n def __init__(self):\n conn = MongoClient(\n settings['MONGODB_SERVER'],\n settings['MONGODB_PORT']\n )\n db = conn[settings['MONGODB_DB']]\n self.collection = db[settings['MONGODB_COLLECTION']]\n\n def process_item(self, item, spider):\n valid = True\n for data in item:\n if not data:\n valid = False\n raise DropItem(\"Missing {0}!\".format(data))\n if valid :\n self.collection.update({'choiceId':item['choiceId']},{'$set':dict(item)},upsert=True,multi=True)\n logging.info(item['url'], exc_info=True)\n return item\n \nclass MysqlPipeline(object):\n\n def __init__(self):\n try:\n self.conn = mysql.connector.connect(\n user='root',\n password='hoboom',\n host = settings['MYSQL_SERVER'],\n database=settings['MYSQL_DB'],\n charset='utf8'\n )\n self.cur = self.conn.cursor(buffered=True)\n except Exception as e: \n logging.error(e, exc_info=True)\n raise\n\n\n def __del__(self):\n self.cur.close()\n self.conn.close()\n\n def process_item(self, item, spider):\n try:\n #if spider.name == 'choiceBondSpider' or spider.name=='choiceBondGetSpider' :\n if self.is_new(item): \n self.insert_data(item)\n except Exception as e:\n logging.error(e, exc_info=True)\n logging.error(\"error from question: \")\n raise\n return item\n\n def insert_data(self, item): \n insertSql = \"\"\"insert into \"\"\"+settings['MYSQL_TABLE']+\"\"\" (%s) values ( %s )\"\"\" \n item['secuList'] = json.dumps(item['secuList'])\n keys = item.fields.keys() \n fields = u','.join(keys) \n qm = u','.join([u'%s'] * len(keys)) \n sql = insertSql % (fields, qm) \n data = [item[k] for k in keys]\n try:\n self.cur.execute(sql, data)\n self.conn.commit()\n except Exception as e:\n logging.error(e, exc_info=True)\n self.conn.rollback()\n raise\n\n def is_new(self, item):\n is_new = False\n sql = 'select * from '+settings['MYSQL_TABLE']+' where choiceId=\"'+item['choiceId']+'\"'\n try:\n self.cur.execute(sql)\n result = self.cur.fetchall()\n if len(result) == 0:\n is_new = True\n except Exception as e:\n logging.error(e, exc_info=True)\n return is_new\n\n","sub_path":"choice/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"459940516","text":"import re\nimport subprocess\nimport pandas as pd\nimport numpy as np\ntry:\n from StringIO import StringIO as BytesIO\nexcept ImportError:\n from io import BytesIO\n\n\nTABLE_RE = re.compile(\"CREATE TABLE \\[([^\\]]+)\\]\\s+\\((.*?\\));\",\n re.MULTILINE | re.DOTALL)\n\n\nclass MdbTable:\n \"\"\" A MdbTable is basically a list of MdbColumns with some added\n functionality.\n :param name: Name of the table\n \"\"\"\n def __init__(self, name):\n self._name = name\n # array instead of dict to preserve the order\n self._columns = []\n\n def update_dtypes(self, newDtypes):\n \"\"\" sets the dtype manually to the given types\n :param newDtypes: a dictionary {columnName: newDtype}\n \"\"\"\n for c in self._columns:\n if c.get_name() in newDtypes:\n c.set_dtype(newDtypes[c.get_name()])\n\n def get_dtypes(self, promote=None):\n \"\"\" return a dictionary of {columnName: dataType}\n :param promote: see MdbColumn.get_dtype\n \"\"\"\n return {c.get_name(): c.get_dtype(promote) for c in self._columns}\n\n def date_field_indices(self):\n \"\"\" returns the column indices of all datetime fields \"\"\"\n result = []\n for idx, col in enumerate(self._columns):\n if col.is_datetime():\n result.append(idx)\n return result\n\n def parse_columns(self, defs_str, implicit_string=True):\n \"\"\"\n Initialize the columns of the table from a schema definition string\n created by mdb-schema. The defs_str needs to look like:\n [FieldA] Text (100) NOT NULL,\n [FieldB] DateTime NOT NULL\n ...\n Even though the table name can be included in the defs_str, the table\n name will NOT be altered by this function.\n \"\"\"\n defs = []\n lines = defs_str.splitlines()\n for line in lines:\n col = MdbColumn.try_parse_schema_line(line)\n if col is None:\n continue\n if col.get_dtype() is None and implicit_string:\n col.set_dtype(np.str_)\n defs.append(col)\n self._columns = defs\n\n def get_columns(self):\n return self._columns\n\n def get_name(self):\n return self._name\n\n\nclass MdbColumn:\n __type_conversions = {\n 'single': np.float32,\n 'double': np.float64,\n 'long integer': np.int64,\n 'integer': np.int_,\n 'text': np.str_,\n 'long text': np.str_,\n 'boolean': np.bool_,\n 'datetime': np.str_, # additional special handling\n }\n __schema_line_regex = re.compile(\n \"^\\s*\\[(\\w+)\\]\\s*(.*?)(?:\\s+(NOT NULL))?,?\\s*$\", re.IGNORECASE)\n\n @staticmethod\n def try_parse_schema_line(line):\n \"\"\" Create a new MdbColumn object from the given line if possible.\n If the format doesn't fit, return None. \"\"\"\n m = MdbColumn.__schema_line_regex.match(line)\n if m:\n return MdbColumn(m.group(1), m.group(2), m.group(3) == 'NOT NULL')\n return None\n\n def __init__(self, name, mdb_type_name, not_null):\n self._name = name\n self._data_type_name = mdb_type_name\n self._dtype = self.__get_numpy_type(mdb_type_name)\n self._not_null = not_null\n\n def is_datetime(self):\n return self._data_type_name.lower().startswith('datetime')\n\n def __get_numpy_type(self, mdb_type_name):\n mdb_name_lc = mdb_type_name.lower()\n for mdbstart, nptype in MdbColumn.__type_conversions.items():\n if mdb_name_lc.startswith(mdbstart):\n return nptype\n # print(\"Unknown type:\", mdb_type_name)\n return None\n\n def get_name(self):\n return self._name\n\n def get_dtype(self, promote=None):\n \"\"\"\n Returns the data type of a column, possibly promoted to a different\n type - promotions are useful for NAN values where no NAN is supported\n in pandas.\n :param promote: Valid values: 'int_to_float', 'nullable_int_to_float'\n \"\"\"\n if self._dtype in [np.int_, np.int64]:\n if (promote == 'nullable_int_to_float' and self.maybe_null()) or \\\n (promote == 'int_to_float'):\n return np.float_\n return self._dtype\n\n def set_dtype(self, newtype):\n self._dtype = newtype\n\n def is_not_null(self):\n return self._not_null\n\n def maybe_null(self):\n return not self.is_not_null()\n\n\ndef list_tables(rdb_file, encoding=\"utf-8\"):\n \"\"\"\n :param rdb_file: The MS Access database file.\n :param encoding: The content encoding of the output. MDBTools\n print the output in UTF-8.\n :return: A list of the tables in a given database.\n \"\"\"\n # We use -1 (one table name per line) to support stange table names\n tables = subprocess.check_output(['mdb-tables', '-1', rdb_file])\n return tables.decode(encoding).splitlines()\n\n\ndef read_schema(rdb_file, encoding='utf8', implicit_string=True):\n \"\"\"\n :param rdb_file: The MS Access database file.\n :param encoding: The schema encoding. I'm almost positive that MDBTools\n spits out UTF-8, exclusively.\n :return: a dictionary of tablename -> MdbTable object\n \"\"\"\n output = subprocess.check_output(['mdb-schema', rdb_file])\n lines = output.decode(encoding).splitlines()\n schema_ddl = \"\\n\".join(l for l in lines if l and not l.startswith('-'))\n\n schema = {}\n for tablename, defs in TABLE_RE.findall(schema_ddl):\n table = MdbTable(tablename)\n table.parse_columns(defs, implicit_string)\n schema[tablename] = table\n\n return schema\n\n\ndef read_table(rdb_file, table_name, *args, **kwargs):\n \"\"\"\n Read a MS Access database as a Pandas DataFrame.\n\n Unless you set `converters_from_schema=False`, this function assumes you\n want to infer the schema from the Access database's schema. This sets the\n `dtype` argument of `read_csv`, which makes things much faster, in most\n cases. If you set the `dtype` keyword argument also, it overrides\n inferences. The `schema_encoding and implicit_string keyword arguments are\n passed through to `read_schema`.\n\n In case you have integer columns with NaNs (not supported by pandas), you\n can either manually set the corresponding columns to float by passing the\n `dtype` argument. By passing `promote='int_to_float'`, all ints are\n automatically converted to float64. For NOT NULL int columns, it is safe\n to keep them as int. To promote only int columns that aren't marked NOT\n NULL, pass `promote='nullable_int_to_float'`to `read_table`.\n\n I recommend setting `chunksize=k`, where k is some reasonable number of\n rows. This is a simple interface, that doesn't do basic things like\n counting the number of rows ahead of time. You may inadvertently start\n reading a 100TB file into memory. (Although, being a MS product, I assume\n the Access format breaks after 2^32 bytes -- har, har.)\n\n :param rdb_file: The MS Access database file.\n :param table_name: The name of the table to process.\n :param args: positional arguments passed to `pd.read_csv`\n :param kwargs: keyword arguments passed to `pd.read_csv`\n :return: a pandas `DataFrame` (or, `TextFileReader` if you set\n `chunksize=k`)\n \"\"\"\n if kwargs.pop('converters_from_schema', True):\n specified_dtypes = kwargs.pop('dtype', {})\n schema_encoding = kwargs.pop('schema_encoding', 'utf8')\n promote = kwargs.pop('promote', None)\n schemas = read_schema(rdb_file, schema_encoding,\n kwargs.pop('implicit_string', True))\n table = schemas[table_name]\n table.update_dtypes(specified_dtypes)\n kwargs['dtype'] = table.get_dtypes(promote)\n kwargs['parse_dates'] = table.date_field_indices()\n\n cmd = ['mdb-export', '-D', '%Y-%m-%d %H:%M:%S', rdb_file, table_name]\n proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)\n try:\n return pd.read_csv(proc.stdout, *args, **kwargs)\n except ValueError as ve:\n if 'Integer column has NA values' in str(ve):\n msg = str(ve).splitlines()[-1]\n raise ValueError(\"\\n\".join((\n msg,\n \"Consider passing promote='nullable_int_to_float' or\",\n \"passing promote='int_to_float' to read_table\")))\n else:\n raise ve\n","sub_path":"pandas_access/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"193220843","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Apr 21 16:25:58 2019\r\n\r\n@author: Dai\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import classification_report\r\n#from sklearn.pipeline import Pipeline\r\nfrom sklearn.metrics import confusion_matrix, roc_curve, auc\r\n#import scipy as sp\r\n#from sklearn.utils.multiclass import unique_labels\r\n\r\nfrom sklearn import svm\r\n#from sklearn.datasets import make_moons, make_blobs\r\nfrom sklearn.covariance import EllipticEnvelope\r\nfrom sklearn.ensemble import IsolationForest\r\nfrom sklearn.neighbors import LocalOutlierFactor\r\n\r\ndef balance(data):\r\n sincere = data[data['Class'] == 0]\r\n fraud = data[data['Class'] == 1]\r\n sincere = sincere.sample(frac=1)\r\n fraudOverSample = fraud\r\n while len(sincere) - len(fraudOverSample) > 0:\r\n fraudOverSample = fraudOverSample.append(fraud, ignore_index=True)\r\n# \r\n# sincere = sincere[: len(fraud)]\r\n balanced_data = sincere.append(fraudOverSample, ignore_index=True)\r\n balanced_data = balanced_data.sample(frac=1)\r\n return balanced_data\r\n\r\n#def scorer(pipeline, X, y):\r\n# y_score = - pipeline.decision_function(X)\r\n# score = roc_auc_score(y, y_score) * 100.\r\n# return score\r\n\r\ndef plot_confusion_matrix(y_true, y_pred, classes,\r\n normalize=False,\r\n title=None,\r\n cmap=plt.cm.Blues):\r\n if not title:\r\n if normalize:\r\n title = 'Normalized confusion matrix'\r\n else:\r\n title = 'Confusion matrix, without normalization'\r\n\r\n # Compute confusion matrix\r\n cm = confusion_matrix(y_true, y_pred)\r\n\r\n if normalize:\r\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\r\n print(\"Normalized confusion matrix\")\r\n else:\r\n print('Confusion matrix, without normalization')\r\n\r\n print(cm)\r\n\r\n fig, ax = plt.subplots()\r\n im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\r\n ax.figure.colorbar(im, ax=ax)\r\n # We want to show all ticks...\r\n ax.set(xticks=np.arange(cm.shape[1]),\r\n yticks=np.arange(cm.shape[0]),\r\n # ... and label them with the respective list entries\r\n xticklabels=classes, yticklabels=classes,\r\n title=title,\r\n ylabel='True label',\r\n xlabel='Predicted label')\r\n\r\n # Rotate the tick labels and set their alignment.\r\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\r\n rotation_mode=\"anchor\")\r\n\r\n # Loop over data dimensions and create text annotations.\r\n fmt = '.2f' if normalize else 'd'\r\n thresh = cm.max() / 2.\r\n for i in range(cm.shape[0]):\r\n for j in range(cm.shape[1]):\r\n ax.text(j, i, format(cm[i, j], fmt),\r\n ha=\"center\", va=\"center\",\r\n color=\"white\" if cm[i, j] > thresh else \"black\")\r\n fig.tight_layout()\r\n return ax\r\n\r\n\r\ndef plot_ROC(y_true, y_score):\r\n fpr, tpr, threshold = roc_curve(y_true, y_score)\r\n roc_auc = auc(fpr, tpr)\r\n \r\n plt.title('Receiver Operating Characteristic')\r\n plt.plot(fpr, tpr, 'b', label = 'AUC = %0.4f' % roc_auc)\r\n plt.legend(loc = 'lower right')\r\n plt.plot([0, 1], [0, 1],'r--')\r\n plt.xlim([0, 1])\r\n plt.ylim([0, 1])\r\n plt.ylabel('True Positive Rate')\r\n plt.xlabel('False Positive Rate')\r\n plt.show()\r\n \r\n return roc_auc\r\n\r\ndata = pd.read_csv(\"creditcard.csv\")\r\n\r\nbalanced_data = balance(data)\r\n\r\nX = data.drop([\"Time\", \"Amount\"], axis=1)\r\n\r\n#X = balanced_data.drop([\"Time\", \"Amount\"], axis=1)\r\n\r\nX = X.as_matrix()\r\ny = X[:, -1]\r\n\r\n#split data into train and test\r\nX_train, X_test, y_train, y_test = train_test_split(X[:, :-1], y, test_size=0.2)\r\n\r\n#Elliptic Envelipe model\r\npipeline2 = EllipticEnvelope(support_fraction = 1)\r\nprint(\"=======================Elliptic Envelope Parameter====================\")\r\nprint(pipeline2.get_params())\r\n\r\npipeline2.fit(X_train)\r\n\r\npred2 = -(pipeline2.predict(X_test) - 1)/2\r\npred2 = pred2.astype(int)\r\n#score2 = scorer(pipeline2, X_test, y_test)\r\nyscore2 = - pipeline2.decision_function(X_test)\r\nprint(\"========================Elliptic Envelope Performance====================\")\r\nprint(classification_report(y_test, pred2, target_names=['Sincere', 'Fraud']))\r\nprint(\"Confusin Matix:\")\r\nplot_confusion_matrix(y_test, pred2, classes=['Sincere', 'Fraud'],title='Confusion matrix of Elliptic Envelope' )\r\nprint(\"ROC curve:\")\r\nscore2 = plot_ROC(y_test, yscore2)\r\nprint(\"The AUC is:\" + str(score2))\r\nprint(\"\\n\")\r\n\r\n\r\n\r\n#Isolation forest model\r\nprint(\"========================Isolation Forest Parameters====================\")\r\nprint(IsolationForest().get_params())\r\n\r\npipeline = IsolationForest(behaviour = 'new')\r\n\r\npipeline.fit(X_train)\r\n\r\npred = -(pipeline.predict(X_test) - 1)/2\r\npred = pred.astype(int)\r\n#score = scorer(pipeline, X_test, y_test)\r\nyscore = - pipeline.decision_function(X_test)\r\nprint(\"========================Isolation Forest Performance====================\")\r\nprint(classification_report(y_test, pred, target_names=['Sincere', 'Fraud']))\r\nprint(\"Confusin Matix:\")\r\nplot_confusion_matrix(y_test, pred, classes=['Sincere', 'Fraud'],title='Confusion matrix of Isolation Forest' )\r\nprint(\"ROC curve:\")\r\nscore = plot_ROC(y_test, yscore)\r\nprint(\"The AUC is:\" + str(score))\r\nprint(\"\\n\")\r\n\r\n\r\n#One class SVM model\r\npipeline3 = svm.OneClassSVM(gamma = 'auto', nu = 0.002)\r\nprint(\"=======================One-Class SVM Parameter====================\")\r\nprint(pipeline3.get_params())\r\n\r\npipeline3.fit(X_train)\r\npred3 = -(pipeline3.predict(X_test) - 1)/2\r\npred3 = pred3.astype(int)\r\n#score3 = scorer(pipeline3, X_test, y_test)\r\nyscore3 = - pipeline3.decision_function(X_test)\r\nprint(\"========================One-Class SVM Performance====================\")\r\nprint(classification_report(y_test, pred3, target_names=['Sincere', 'Fraud']))\r\nprint(\"Confusin Matix:\")\r\nplot_confusion_matrix(y_test, pred3, classes=['Sincere', 'Fraud'],title='Confusion matrix of One-Class SVM' )\r\nprint(\"ROC curve:\")\r\nscore3 = plot_ROC(y_test, yscore3)\r\nprint(\"The AUC is:\" + str(score3))\r\nprint(\"\\n\")\r\n\r\n\r\n\r\n\r\n#LOF model\r\npipeline4 = LocalOutlierFactor(novelty = True)\r\nprint(\"=======================LocalOutlierFactor Parameter====================\")\r\nprint(pipeline4.get_params())\r\n\r\npipeline4.fit(X_train)\r\npred4 = -(pipeline4.predict(X_test) - 1)/2\r\npred4 = pred4.astype(int)\r\n#score4 = scorer(pipeline4, X_test, y_test)\r\nyscore4 = - pipeline4.decision_function(X_test)\r\nprint(\"========================LocalOutlierFactor Performance====================\")\r\nprint(classification_report(y_test, pred4, target_names=['Sincere', 'Fraud']))\r\nprint(\"Confusin Matix:\")\r\nplot_confusion_matrix(y_test, pred4, classes=['Sincere', 'Fraud'],title='LocalOutlierFactor' )\r\nprint(\"ROC curve:\")\r\nscore4 = plot_ROC(y_test, yscore4)\r\nprint(\"The AUC is:\" + str(score4))\r\nprint(\"\\n\")","sub_path":"OutlierDetection.py","file_name":"OutlierDetection.py","file_ext":"py","file_size_in_byte":6924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"576318198","text":"import os\nimport csv\nimport re\nimport requests\nimport json\nfrom lxml import html\nfrom datetime import datetime\n\n# data_folder = os.path.join(os.getcwd(), '')\ndata_folder = os.path.join(os.pardir, 'data')\ndataset1_path = os.path.join(data_folder, 'ks-projects-201612.csv')\ndataset2_path = os.path.join(data_folder, 'ks-projects-201801.csv')\n\nCATEGORIES = set(['games',\n 'design',\n 'technology',\n 'film & video',\n 'music',\n 'fashion',\n 'publishing',\n 'food',\n 'art',\n 'comics',\n 'theater',\n 'photography',\n 'crafts',\n 'dance',\n 'journalism'])\n\n\ndef scrape_from_csv(dataset_path):\n # 64 per second\n # open data\n X = []\n Y = []\n with open(dataset_path, 'r') as csvfile:\n # TODO validate title - remove quotes and parenthesis\n dataset1 = csv.reader(csvfile)\n # iterate through projects\n for counter, row in enumerate(dataset1):\n # give everything default values\n try:\n outcome = row[9] # possible values: success, failed, canceled (sic)\n except:\n outcome = '0'\n\n try:\n category = row[3].lower()\n except:\n category = 'food'\n\n try:\n goal = row[6]\n except:\n goal = '1000'\n\n deadline = row[5]\n launched = row[7]\n name = row[1]\n\n # print('cat before checking: ', category)\n #if counter == 0 or outcome == 'canceled' or outcome == 'suspended': # ignore csv categories and canceled projects\n if counter == 0 or (outcome != 'successful' and outcome != 'failed'):\n continue\n elif category not in CATEGORIES:\n continue\n elif '(' in name or ')' in name:\n continue\n elif counter >= 100000:\n break\n\n try:\n duration = get_duration(launched, deadline)\n except:\n duration = '0'\n\n # print('scraping: {}, number: {}'.format(name, counter))\n scrape_results = scrape_for_training( category, goal, duration)\n X.append(scrape_results)\n num_label = label_to_number(outcome)\n #num_label = outcome\n Y.append((num_label,))\n return X, Y\n\n\ndef scrape_for_training(category, goal, duration):\n # TODO update this to better match error checking done in funct above\n # init dictionary\n data = {'category': '',\n 'blurb': '',\n 'title': '',\n 'duration': '',\n 'goal': '',\n 'raised': '',\n 'description': '',\n 'risks': '',\n 'name': ''}\n data['category'] = category\n data['goal'] = goal\n data['duration'] = duration\n # clean\n for key in data:\n data[key] = data[key].replace('\\n', ' ').strip()\n\n return data\n\n\ndef scrape_from_url(project_url):\n # TODO update this to better match error checking done in funct above\n # init dictionary\n data = {'category': '',\n 'blurb': '',\n 'title': '',\n 'duration': '',\n 'goal': '',\n 'raised': '',\n 'description': '',\n 'risks': '',\n 'name': ''}\n # get html tree\n page = requests.get('https://www.kickstarter.com/projects/search.json?search=&tearm={}'.format(project_url.split('/')[-1]))\n response = page.json()\n project = response['projects'][0] \n\n data['category'] = project['category']['slug'].split('/')[0]\n data['goal'] = project['goal']\n data['duration'] = project['deadline'] - project['launched_at'] \n\n # return\n return data\n\n\ndef label_to_number(outcome): # text_label is success=0, failed=1, canceled=2 (sic)\n if outcome == 'successful':\n num_label = 0\n elif outcome == 'failed':\n num_label = 1\n else:\n num_label = 0\n return num_label\n\n\ndef get_duration(launched, deadline):\n # convert string to datetime\n t1 = datetime.strptime(launched[0:18], '%Y-%m-%d %H:%M:%S')\n t2 = datetime.strptime(deadline[0:18], '%Y-%m-%d %H:%M:%S')\n # get delta\n t3 = t2 - t1\n # return\n return(str(t3.total_seconds()))\n\ndef get_duration_url(launched, deadline):\n # convert string to datetime\n t1 = datetime.strptime(launched[0:18], '%Y-%m-%dT%H:%M:%S')\n t2 = datetime.strptime(deadline[0:18], '%Y-%m-%dT%H:%M:%S')\n # get delta\n t3 = t2 - t1\n # return\n return(str(t3.total_seconds()))\n\n\nif __name__=='__main__':\n print('yup')\n #\n # FOR TESTING\n # TRAIN_DATA_PATH = r'C:\\Users\\lewys\\PycharmProjects\\kick-help\\kick_help_api\\kick_help_model\\data\\ks-projects-train.csv'\n # raw_train_data, raw_train_labels = scrape_from_csv(TRAIN_DATA_PATH)\n # print(len(raw_train_data), len(raw_train_labels))\n # print()\n #","sub_path":"kick_help_api/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"582723719","text":"__author__ = 'walid'\n\nfilename = 'A-small-attempt0'\n# dirname = '/Users/walid/Downloads/'\ndirname = 'D:\\\\Downloads\\\\'\ninFile = open(dirname+filename+'.in', 'r')\noutFile = open(dirname+filename+'.out', 'w')\n\nT = (int)(inFile.readline())\n\ndef process(ms, t):\n ds = [y-x for (x, y) in zip(ms, ms[1:])]\n d1s = [min(d, 0) for d in ds]\n r1 = -sum(d1s)\n rate = -min(d1s)\n r2 = sum(min(m, rate) for m in ms[0:-1])\n\n\n outFile.write('Case #{}: {} {}\\n'.format(t, r1, r2))\n\n\nfor t in range(1, T+1):\n N = int(inFile.readline())\n ms = [int(x) for x in inFile.readline().strip().split(' ')]\n process(ms, t)\n","sub_path":"solutions_6404600001200128_0/Python/walid/MushroomMonster.py","file_name":"MushroomMonster.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"11402574","text":"# Licensed under the Prefect Community License, available at\n# https://www.prefect.io/legal/prefect-community-license\n\n\nimport asyncio\nimport os\nimport subprocess\nimport time\nfrom pathlib import Path\n\nimport click\n\nimport prefect_server\nfrom prefect_server import config\n\nroot_dir = Path(prefect_server.__file__).parents[2]\nservices_dir = root_dir / \"src\" / \"prefect_server\" / \"services\"\n\n\n@click.group()\ndef services():\n \"\"\"\n Commands for running services\n \"\"\"\n\n\ndef run_proc_forever(proc):\n try:\n while True:\n time.sleep(0.5)\n except:\n click.secho(\"Exception caught; killing process.\", fg=\"white\", bg=\"red\")\n proc.kill()\n raise\n\n\n@services.command()\ndef graphql():\n \"\"\"\n Start the Python GraphQL server\n \"\"\"\n run_proc_forever(\n subprocess.Popen(\n [\"python\", services_dir / \"graphql\" / \"server.py\"],\n env=dict(os.environ, SERVER_VERSION=\"development\"),\n )\n )\n\n\n@services.command()\ndef ui():\n \"\"\"\n Start the UI\n \"\"\"\n ui_path = (\n os.environ.get(\"PREFECT_SERVER_WEB_UI_PATH\")\n or root_dir.parent / \"server-web-ui\"\n )\n\n ui_path = Path(ui_path)\n\n if not ui_path.exists():\n raise RuntimeError(\n \"Cannot find server-web-ui repository path. Please set PREFECT_SERVER_WEB_UI_PATH environment variable.\"\n )\n\n run_proc_forever(\n subprocess.Popen(\n [\"npm\", \"run\", \"serve\"],\n cwd=ui_path,\n env=dict(\n os.environ,\n SERVER_VERSION=\"development\",\n VUE_APP_GRAPHQL_HTTP=f\"http://localhost:{config.services.apollo.port}\",\n ),\n )\n )\n\n\n@services.command()\ndef scheduler():\n \"\"\"\n Start the scheduler service\n \"\"\"\n run_proc_forever(\n subprocess.Popen([\"python\", services_dir / \"scheduler\" / \"scheduler.py\"])\n )\n\n\n@services.command()\ndef apollo():\n \"\"\"\n Start the Apollo GraphQL server\n \"\"\"\n run_proc_forever(\n subprocess.Popen(\n [\"npm\", \"run\", \"start\"],\n cwd=root_dir / \"services\" / \"apollo\",\n env=dict(\n os.environ,\n SERVER_VERSION=\"development\",\n HASURA_API_URL=config.hasura.graphql_url,\n PREFECT_API_URL=f\"http://{config.services.graphql.host}:{config.services.graphql.port}{config.services.graphql.path}\",\n ),\n )\n )\n","sub_path":"server/src/prefect_server/cli/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"244540691","text":"# Copyright 2018-2021 Xanadu Quantum Technologies Inc.\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\"\"\"Multiple dispatch functions\"\"\"\r\n# pylint: disable=import-outside-toplevel,too-many-return-statements\r\nimport warnings\r\n\r\nfrom autograd.numpy.numpy_boxes import ArrayBox\r\nfrom autoray import numpy as np\r\nfrom numpy import ndarray\r\n\r\nfrom . import single_dispatch # pylint:disable=unused-import\r\nfrom .utils import cast, get_interface, requires_grad\r\n\r\n\r\ndef _multi_dispatch(values):\r\n \"\"\"Determines the correct framework to dispatch to given a\r\n sequence of tensor-like objects.\r\n\r\n Args:\r\n values (Sequence[tensor_like]): a sequence of tensor like objects\r\n\r\n Returns:\r\n str: the name of the interface\r\n\r\n To determine the framework to dispatch to, the following rules\r\n are applied:\r\n\r\n * Tensors that are incompatible (such as Torch and TensorFlow tensors)\r\n cannot both be present.\r\n\r\n * Autograd tensors *may* be present alongside Torch and TensorFlow tensors,\r\n but Torch and TensorFlow take precendence; the autograd arrays will\r\n be treated as non-differentiable NumPy arrays. A warning will be raised\r\n suggesting that vanilla NumPy be used instead.\r\n\r\n * Vanilla NumPy arrays can be used alongside other tensor objects; they will\r\n always be treated as non-differentiable constants.\r\n \"\"\"\r\n if \"resource_variable\" in getattr(values, \"__module__\", tuple()):\r\n values = np.asarray(values)\r\n\r\n interfaces = {get_interface(v) for v in values}\r\n\r\n if len(set(interfaces) - {\"numpy\", \"autograd\"}) > 1:\r\n # contains multiple non-autograd interfaces\r\n raise ValueError(\"Tensors contain mixed types; cannot determine dispatch library\")\r\n\r\n non_numpy_interfaces = set(interfaces) - {\"numpy\"}\r\n\r\n if len(non_numpy_interfaces) > 1:\r\n # contains autograd and another interface\r\n warnings.warn(\r\n f\"Contains tensors of types {non_numpy_interfaces}; dispatch will prioritize \"\r\n \"TensorFlow and PyTorch over autograd. Consider replacing Autograd with vanilla NumPy.\",\r\n UserWarning,\r\n )\r\n\r\n if \"tensorflow\" in interfaces:\r\n return \"tensorflow\"\r\n\r\n if \"torch\" in interfaces:\r\n return \"torch\"\r\n\r\n if \"autograd\" in interfaces:\r\n return \"autograd\"\r\n\r\n if \"jax\" in interfaces:\r\n return \"jax\"\r\n\r\n return \"numpy\"\r\n\r\n\r\ndef block_diag(values):\r\n \"\"\"Combine a sequence of 2D tensors to form a block diagonal tensor.\r\n\r\n Args:\r\n values (Sequence[tensor_like]): Sequence of 2D arrays/tensors to form\r\n the block diagonal tensor.\r\n\r\n Returns:\r\n tensor_like: the block diagonal tensor\r\n\r\n **Example**\r\n\r\n >>> t = [\r\n ... np.array([[1, 2], [3, 4]]),\r\n ... torch.tensor([[1, 2, 3], [-1, -6, -3]]),\r\n ... torch.tensor(5)\r\n ... ]\r\n >>> qml.math.block_diag(t)\r\n tensor([[ 1, 2, 0, 0, 0, 0],\r\n [ 3, 4, 0, 0, 0, 0],\r\n [ 0, 0, 1, 2, 3, 0],\r\n [ 0, 0, -1, -6, -3, 0],\r\n [ 0, 0, 0, 0, 0, 5]])\r\n \"\"\"\r\n interface = _multi_dispatch(values)\r\n values = np.coerce(values, like=interface)\r\n return np.block_diag(values, like=interface)\r\n\r\n\r\ndef concatenate(values, axis=0):\r\n \"\"\"Concatenate a sequence of tensors along the specified axis.\r\n\r\n .. warning::\r\n\r\n Tensors that are incompatible (such as Torch and TensorFlow tensors)\r\n cannot both be present.\r\n\r\n Args:\r\n values (Sequence[tensor_like]): Sequence of tensor-like objects to\r\n concatenate. The objects must have the same shape, except in the dimension corresponding\r\n to axis (the first, by default).\r\n axis (int): The axis along which the input tensors are concatenated. If axis is None,\r\n tensors are flattened before use. Default is 0.\r\n\r\n Returns:\r\n tensor_like: The concatenated tensor.\r\n\r\n **Example**\r\n\r\n >>> x = tf.constant([0.6, 0.1, 0.6])\r\n >>> y = tf.Variable([0.1, 0.2, 0.3])\r\n >>> z = np.array([5., 8., 101.])\r\n >>> concatenate([x, y, z])\r\n \r\n \"\"\"\r\n interface = _multi_dispatch(values)\r\n\r\n if interface == \"torch\":\r\n import torch\r\n\r\n if axis is None:\r\n # flatten and then concatenate zero'th dimension\r\n # to reproduce numpy's behaviour\r\n values = [np.flatten(torch.as_tensor(t)) for t in values]\r\n axis = 0\r\n else:\r\n values = [torch.as_tensor(t) for t in values]\r\n\r\n if interface == \"tensorflow\" and axis is None:\r\n # flatten and then concatenate zero'th dimension\r\n # to reproduce numpy's behaviour\r\n values = [np.flatten(np.array(t)) for t in values]\r\n axis = 0\r\n\r\n return np.concatenate(values, axis=axis, like=interface)\r\n\r\n\r\ndef diag(values, k=0):\r\n \"\"\"Construct a diagonal tensor from a list of scalars.\r\n\r\n Args:\r\n values (tensor_like or Sequence[scalar]): sequence of numeric values that\r\n make up the diagonal\r\n k (int): The diagonal in question. ``k=0`` corresponds to the main diagonal.\r\n Use ``k>0`` for diagonals above the main diagonal, and ``k<0`` for\r\n diagonals below the main diagonal.\r\n\r\n Returns:\r\n tensor_like: the 2D diagonal tensor\r\n\r\n **Example**\r\n\r\n >>> x = [1., 2., tf.Variable(3.)]\r\n >>> qml.math.diag(x)\r\n \r\n >>> y = tf.Variable([0.65, 0.2, 0.1])\r\n >>> qml.math.diag(y, k=-1)\r\n \r\n >>> z = torch.tensor([0.1, 0.2])\r\n >>> qml.math.diag(z, k=1)\r\n tensor([[0.0000, 0.1000, 0.0000],\r\n [0.0000, 0.0000, 0.2000],\r\n [0.0000, 0.0000, 0.0000]])\r\n \"\"\"\r\n interface = _multi_dispatch(values)\r\n\r\n if isinstance(values, (list, tuple)):\r\n values = np.stack(np.coerce(values, like=interface), like=interface)\r\n\r\n return np.diag(values, k=k, like=interface)\r\n\r\n\r\ndef dot(tensor1, tensor2):\r\n \"\"\"Returns the matrix or dot product of two tensors.\r\n\r\n * If both tensors are 0-dimensional, elementwise multiplication\r\n is performed and a 0-dimensional scalar returned.\r\n\r\n * If both tensors are 1-dimensional, the dot product is returned.\r\n\r\n * If the first array is 2-dimensional and the second array 1-dimensional,\r\n the matrix-vector product is returned.\r\n\r\n * If both tensors are 2-dimensional, the matrix product is returned.\r\n\r\n * Finally, if the the first array is N-dimensional and the second array\r\n M-dimensional, a sum product over the last dimension of the first array,\r\n and the second-to-last dimension of the second array is returned.\r\n\r\n Args:\r\n tensor1 (tensor_like): input tensor\r\n tensor2 (tensor_like): input tensor\r\n\r\n Returns:\r\n tensor_like: the matrix or dot product of two tensors\r\n \"\"\"\r\n interface = _multi_dispatch([tensor1, tensor2])\r\n x, y = np.coerce([tensor1, tensor2], like=interface)\r\n\r\n if interface == \"torch\":\r\n if x.ndim == 0 and y.ndim == 0:\r\n return x * y\r\n\r\n if x.ndim <= 2 and y.ndim <= 2:\r\n return x @ y\r\n\r\n return np.tensordot(x, y, dims=[[-1], [-2]], like=interface)\r\n\r\n if interface == \"tensorflow\":\r\n if x.ndim == 0 and y.ndim == 0:\r\n return x * y\r\n\r\n if y.ndim == 1:\r\n return np.tensordot(x, y, axes=[[-1], [0]], like=interface)\r\n\r\n if x.ndim == 2 and y.ndim == 2:\r\n return x @ y\r\n\r\n return np.tensordot(x, y, axes=[[-1], [-2]], like=interface)\r\n\r\n return np.dot(x, y, like=interface)\r\n\r\n\r\ndef get_trainable_indices(values):\r\n \"\"\"Returns a set containing the trainable indices of a sequence of\r\n values.\r\n\r\n Args:\r\n values (Iterable[tensor_like]): Sequence of tensor-like objects to inspect\r\n\r\n Returns:\r\n set[int]: Set containing the indices of the trainable tensor-like objects\r\n within the input sequence.\r\n\r\n **Example**\r\n\r\n >>> def cost_fn(params):\r\n ... print(\"Trainable:\", qml.math.get_trainable_indices(params))\r\n ... return np.sum(np.sin(params[0] * params[1]))\r\n >>> values = [np.array([0.1, 0.2], requires_grad=True),\r\n ... np.array([0.5, 0.2], requires_grad=False)]\r\n >>> cost_fn(values)\r\n Trainable: {0}\r\n tensor(0.0899685, requires_grad=True)\r\n \"\"\"\r\n interface = _multi_dispatch(values)\r\n trainable_params = set()\r\n\r\n for idx, p in enumerate(values):\r\n if requires_grad(p, interface=interface):\r\n trainable_params.add(idx)\r\n\r\n return trainable_params\r\n\r\n\r\ndef ones_like(tensor, dtype=None):\r\n \"\"\"Returns a tensor of all ones with the same shape and dtype\r\n as the input tensor.\r\n\r\n Args:\r\n tensor (tensor_like): input tensor\r\n dtype (str, np.dtype, None): The desired output datatype of the array. If not provided, the dtype of\r\n ``tensor`` is used. This argument can be any supported NumPy dtype representation, including\r\n a string (``\"float64\"``), a ``np.dtype`` object (``np.dtype(\"float64\")``), or\r\n a dtype class (``np.float64``). If ``tensor`` is not a NumPy array, the\r\n **equivalent** dtype in the dispatched framework is used.\r\n\r\n Returns:\r\n tensor_like: an all-ones tensor with the same shape and\r\n size as ``tensor``\r\n\r\n **Example**\r\n\r\n >>> x = torch.tensor([1., 2.])\r\n >>> ones_like(x)\r\n tensor([1, 1])\r\n >>> y = tf.Variable([[0], [5]])\r\n >>> ones_like(y, dtype=np.complex128)\r\n \r\n \"\"\"\r\n if dtype is not None:\r\n return cast(np.ones_like(tensor), dtype)\r\n\r\n return np.ones_like(tensor)\r\n\r\n\r\ndef stack(values, axis=0):\r\n \"\"\"Stack a sequence of tensors along the specified axis.\r\n\r\n .. warning::\r\n\r\n Tensors that are incompatible (such as Torch and TensorFlow tensors)\r\n cannot both be present.\r\n\r\n Args:\r\n values (Sequence[tensor_like]): Sequence of tensor-like objects to\r\n stack. Each object in the sequence must have the same size in the given axis.\r\n axis (int): The axis along which the input tensors are stacked. ``axis=0`` corresponds\r\n to vertical stacking.\r\n\r\n Returns:\r\n tensor_like: The stacked array. The stacked array will have one additional dimension\r\n compared to the unstacked tensors.\r\n\r\n **Example**\r\n\r\n >>> x = tf.constant([0.6, 0.1, 0.6])\r\n >>> y = tf.Variable([0.1, 0.2, 0.3])\r\n >>> z = np.array([5., 8., 101.])\r\n >>> stack([x, y, z])\r\n \r\n \"\"\"\r\n interface = _multi_dispatch(values)\r\n values = np.coerce(values, like=interface)\r\n return np.stack(values, axis=axis, like=interface)\r\n\r\n\r\ndef where(condition, x, y):\r\n \"\"\"Returns elements chosen from x or y depending on a boolean tensor condition.\r\n\r\n The input tensors ``condition``, ``x``, and ``y`` must all be broadcastable to the same shape.\r\n\r\n Args:\r\n condition (tensor_like[bool]): A boolean tensor. Where True, elements from\r\n ``x`` will be chosen, otherwise ``y``.\r\n x (tensor_like): values from which to choose if the condition evaluates to ``True``\r\n y (tensor_like): values from which to choose if the condition evaluates to ``False``\r\n\r\n Returns:\r\n tensor_like: A tensor with elements from ``x`` where the condition is ``True``, and\r\n ``y`` otherwise. The output tensor has the same shape as the input tensors.\r\n\r\n **Example**\r\n\r\n >>> a = torch.tensor([0.6, 0.23, 0.7, 1.5, 1.7], requires_grad=True)\r\n >>> b = torch.tensor([-1., -2., -3., -4., -5.], requires_grad=True)\r\n >>> math.where(a < 1, a, b)\r\n tensor([ 0.6000, 0.2300, 0.7000, -4.0000, -5.0000], grad_fn=)\r\n \"\"\"\r\n return np.where(condition, x, y, like=_multi_dispatch([condition, x, y]))\r\n\r\n\r\ndef frobenius_inner_product(A, B, normalize=False):\r\n r\"\"\"Frobenius inner product between two matrices.\r\n\r\n .. math::\r\n\r\n \\langle A, B \\rangle_F = \\sum_{i,j=1}^n A_{ij} B_{ij} = \\operatorname{tr} (A^T B)\r\n\r\n The Frobenius inner product is equivalent to the Hilbert-Schmidt inner product for\r\n matrices with real-valued entries.\r\n\r\n Args:\r\n A (tensor_like[float]): First matrix, assumed to be a square array.\r\n B (tensor_like[float]): Second matrix, assumed to be a square array.\r\n normalize (bool): If True, divide the inner product by the Frobenius norms of A and B.\r\n\r\n Returns:\r\n float: Frobenius inner product of A and B\r\n\r\n **Example**\r\n\r\n >>> A = np.random.random((3,3))\r\n >>> B = np.random.random((3,3))\r\n >>> qml.math.frobenius_inner_product(A, B)\r\n 3.091948202943376\r\n \"\"\"\r\n interface = _multi_dispatch([A, B])\r\n A, B = np.coerce([A, B], like=interface)\r\n\r\n inner_product = np.sum(A * B)\r\n\r\n if normalize:\r\n norm = np.sqrt(np.sum(A * A) * np.sum(B * B))\r\n inner_product = inner_product / norm\r\n\r\n return inner_product\r\n\r\n\r\ndef unwrap(values, max_depth=None):\r\n \"\"\"Unwrap a sequence of objects to NumPy arrays.\r\n\r\n Note that tensors on GPUs will automatically be copied\r\n to the CPU.\r\n\r\n Args:\r\n values (Sequence[tensor_like]): sequence of tensor-like objects to unwrap\r\n max_depth (int): Positive integer indicating the depth of unwrapping to perform\r\n for nested tensor-objects. This argument only applies when unwrapping\r\n Autograd ``ArrayBox`` objects.\r\n\r\n **Example**\r\n\r\n >>> values = [np.array([0.1, 0.2]), torch.tensor(0.1, dtype=torch.float64), torch.tensor([0.5, 0.2])]\r\n >>> math.unwrap(values)\r\n [array([0.1, 0.2]), 0.1, array([0.5, 0.2], dtype=float32)]\r\n\r\n This function will continue to work during backpropagation:\r\n\r\n >>> def cost_fn(params):\r\n ... unwrapped_params = math.unwrap(params)\r\n ... print(\"Unwrapped:\", [(i, type(i)) for i in unwrapped_params])\r\n ... return np.sum(np.sin(params))\r\n >>> params = np.array([0.1, 0.2, 0.3])\r\n >>> grad = autograd.grad(cost_fn)(params)\r\n Unwrapped: [(0.1, ), (0.2, ), (0.3, )]\r\n >>> print(grad)\r\n [0.99500417 0.98006658 0.95533649]\r\n \"\"\"\r\n res = []\r\n\r\n for t in values:\r\n if isinstance(t, ArrayBox):\r\n a = np.to_numpy(t, max_depth=max_depth)\r\n else:\r\n a = np.to_numpy(t)\r\n\r\n if isinstance(a, ndarray) and not a.shape:\r\n # if NumPy array is scalar, convert to a Python float\r\n res.append(a.tolist())\r\n else:\r\n res.append(a)\r\n\r\n return res\r\n","sub_path":"pennylane/math/multi_dispatch.py","file_name":"multi_dispatch.py","file_ext":"py","file_size_in_byte":15836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"453531248","text":"# import socket module\nfrom socket import *\nimport threading\nimport os.path\n\n\ndef handle_client(connectionSocket):\n try:\n message = connectionSocket.recv(2048) # Fill in start #Fill in end\n print(\"Get message: \", message.decode())\n filename = message.split()[1]\n # print(\"Try to find file: \", filename.decode())\n output_data = open(filename[1:]).read()\n # Send one HTTP header line into socket\n header = \"HTTP/1.1 200 OK\\r\\nContent-Type: text/html\\r\\n\"\n # Fill in start #Fill in end\n # Send the content of the requested file to the client\n\n connectionSocket.send(header.encode('utf-8'))\n connectionSocket.send(\"\\r\\n\".encode())\n for i in range(0, len(output_data)):\n connectionSocket.send(output_data[i].encode('utf-8'))\n connectionSocket.send(\"\\r\\n\".encode())\n connectionSocket.close()\n except IOError:\n print(\"File does not exists!\")\n connectionSocket.send(\"HTTP/1.1 404 Not Found\\r\\ncontent-type:text/html\\r\\n\".encode())\n connectionSocket.send(\"\\r\\n\".encode())\n connectionSocket.send('''\n \n \n 404 Not Found\n

404 Not Found!

\n \n \n '''.encode())\n connectionSocket.close()\n\n\nserverSocket = socket(AF_INET, SOCK_STREAM)\n# Prepare a sever socket\n# Fill in start\nserverSocket.bind(('localhost', 12345))\nserverSocket.listen(1)\n# Fill in end\nwhile True:\n # Establish the connection\n print('Ready to serve...')\n connectionSocket, addr = serverSocket.accept()\n client_handler = threading.Thread(target=handle_client, args=(connectionSocket,))\n client_handler.start()\n # print(connectionSocket, addr)\n\n # Send response message for file not found\n # Close client socket\n# Fill in start\nserverSocket.close()\n# Fill in end\n","sub_path":"web-server/web-server-threading.py","file_name":"web-server-threading.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"439686916","text":"INPUT_PATH = 'input_5'\n\n\ndef read_input():\n with open(INPUT_PATH,'r') as f:\n return f.read().strip('\\n')\n\n\ndef transform(inp):\n result = []\n for idx, char in enumerate(inp):\n if not result:\n result.append(char)\n elif all([char != result[-1], char.capitalize() == result[-1].capitalize()]):\n result.pop()\n else:\n result.append(char)\n return len(result), ''.join(result)\n\n\ndef find_shortest(inp):\n results = {}\n letters = set(inp.lower())\n for i in letters:\n inp_replaced = inp\n inp_replaced = inp_replaced.replace(i, '')\n inp_replaced = inp_replaced.replace(i.upper(), '')\n cnt, _ = transform(inp_replaced)\n results[i] = cnt\n\n return min(results, key=results.get), min(results.values())\n\n\nif __name__ == '__main__':\n inp = read_input()\n result_len, result_s = transform(inp)\n shortest = find_shortest(inp)\n print(result_len, shortest)\n","sub_path":"2018_5.py","file_name":"2018_5.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"505079711","text":"__author__ = 'TheJoker'\n\nfrom win32com.client import Dispatch\n\nwordapp = Dispatch(\"Word.Application\") # Create new Word Object\nwordapp.Visible = 1 # Word Application should`t be visible\nworddoc = wordapp.Documents.Add(Template=\n 'C:\\\\Users\\\\18171\\\\OneDrive\\\\LJZ\\\\FieldSensorTest\\\\Data\\\\Original.dot')\ndocRange = worddoc.Range(0, 0)\ntablenum = worddoc.Tables.Count\ntable = worddoc.Tables.Item(1)\nworddoc.Tables.Add(worddoc.Paragraphs(21).Range, 1, 1) # first test result table\nworddoc.Tables[1].Rows[1].Cells[0].Range.Text ='123123'\nworddoc.Content.Text = \"Hello, I am a text!\"\nworddoc.Range(0, 0).Style = '标题 2'\nworddoc.Tables.Add(worddoc.Range(0, 0), 2, 2)\nworddoc.Tables(1).Style = '网格型'\na = input()\nworddoc.Close() # Close the Word Document (a save-Dialog pops up)\nwordapp.Quit() # Close the Word App\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"381139289","text":"from jinja2 import (\n Template,\n Environment,\n PackageLoader,\n select_autoescape\n)\n\nfrom core.settings.settings import TEMPLATE_PACKAGE\n\n\nenv_templates = Environment(\n loader=PackageLoader(package_name=TEMPLATE_PACKAGE, package_path=\"templates\"),\n autoescape=select_autoescape([\"html\", \"xml\"])\n)\n\n\nclass BaseTemplateRender:\n\n template: str = None\n\n def get_template(self) -> Template:\n\n if self.template is None:\n raise NotImplementedError(\n \"You must implement template\"\n )\n\n return env_templates.get_template(self.template)\n\n def __call__(self, **kwargs) -> Template:\n return self.get_template().render(**kwargs)\n","sub_path":"app/core/utils/templates.py","file_name":"templates.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"458323265","text":"from apps import app\nfrom flask import render_template,jsonify\nfrom apps.Model import *\n\n@app.route('/')\n@app.route('/index')\ndef index():\n return render_template('index.html') \n\n@app.route('/top10')\ndef get_table():\n st=db.session.query(bolg.createtime,user.name,body.str,bolg.sended).\\\n filter(body.strid==bolg.strid,user.wbid==bolg.wbid).\\\n order_by(bolg.createtime.desc()).\\\n limit(10).\\\n all()\n return jsonify(st)\n\n\n\n\n\n","sub_path":"apps/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"531748319","text":"\n\nimport sys\nimport json\nimport os\nfrom os.path import join, realpath, split, splitext\nimport zipfile\nimport base64\nimport re\nfrom PIL import Image\nfrom gamecommon.utils import convertJsonFBSToBin, formatString, scanJSONStringForAssetUUIDs\nfrom subprocess import Popen, PIPE\nfrom struct import unpack_from, calcsize\n\n# .anim format\n# # Comments!!\n# # Like .obj format, prefix a line with the type of data \n# # AnimationName filepath \n# A Idle idle_.csv\n# # Curve type, Linear or Catmull-Rom spline\n# C Linear\n# # list of frames x , y , end time as % of total anim ;\n# # In the maths this can be a 3D curve where z is position along the 2D curve?\n# P 0, 0, 0;\n# P 16, 0, 100;\n# # Walk cycle\n# A WalkLeft walk_.csv\n# # \n# C Linear\n# #\n# P 0, 0, 0;\n# P -16, 0, 100;\n\n# .csv format\n# \"Name\",\"Transparent Color\",\"Transparent Color(Hex)\",\"Delay(1/60)\",\"File Name\",\"Width\",\"Height\"\n# \"Frame1\",\"16777215\",\"00FFFFFF\",\"6\",\"walk_0000.png\",\"32\",\"48\"\n# ...and repeat\n#\n\nlog = None\n\n# TODO: add palette class with __hash__, __eq__ & __ne__ methods (NB: use built in hash function?)\n# \n\ndef formatString(s, parameters):\n for k, p in parameters.iteritems():\n s = s.replace(\"%%(%s)\"%(k), p)\n return s\n\ndef getImageBBox(image):\n l = image.width+1\n r = -1\n t = image.height+1\n b = -1\n for y in range(image.height):\n for x in range(image.width):\n if image.getpixel((x,y))[3] > 0:\n l = min(l, x)\n r = max(r, x)\n t = min(t, y)\n b = max(b, y)\n return (l, (image.height-t), r+1, (image.height-b)-1)\n\ndef readSpriteFile(filebuf, palettes, full_pal):\n filebytes = bytearray(filebuf.read())\n filesize = os.fstat(filebuf.fileno()).st_size\n data_ofs = 0\n palette_idx = 0\n sprite = {\n 'palettes':[],\n 'frames':[]\n }\n header = unpack_from('=cccHHH', filebytes, data_ofs)\n data_ofs += calcsize('=cccHHH')\n if header[0] != 'S' or header[1] != 'P' or header[2] != 'R':\n raise ValueError('Unexpected file format. Expected .SPR')\n sprite['frameCount'] = header[3]\n sprite['width'] = header[4]\n sprite['height'] = header[5]\n frame_size = header[4]*header[5]\n try:\n t,r,a,n,s,p,P = unpack_from('=ccccccB', filebytes, filesize-7)\n sprite['transparent'] = P\n except:\n sprite['transparent'] = -1\n sprite['layers'] = []\n current_layer = {\n 'order': 0,\n 'type': 'Unknown',\n 'frames': []\n }\n for f in range(sprite['frameCount']):\n frame = {}\n frame['delay'] = int(round(unpack_from('=H', filebytes, data_ofs)[0] / 10))\n data_ofs += calcsize('=H')\n pal = []\n for p in range(256):\n rgb = unpack_from('=BBB', filebytes, data_ofs)\n data_ofs += calcsize('=BBB')\n pal += [{'r':rgb[0], 'g':rgb[1], 'b':rgb[2]}]\n pal_str = str(pal)\n if not pal_str in palettes:\n palette_idx = len(palettes)\n palettes[pal_str] = palette_idx\n full_pal += [{'transparent':sprite['transparent'], 'pal':pal}]\n frame['palette'] = palettes[pal_str]\n frame['data'] = []\n for b in range(frame_size):\n frame['data'] += [unpack_from('=B', filebytes, data_ofs)[0]]\n data_ofs += calcsize('=B')\n current_layer['frames'] += [frame]\n sprite['layers'] += [current_layer]\n\n return sprite\n\ndef readSplitLayerSpriteFile(filepath, palettes, full_pal):\n # Read a collection fo files with the file name format [filepath w/o ext]-[layername]-[layerorder]\n # and merge these into a single sprite image to process\n file_path_root, file_name = split(filepath)\n file_path_base, file_path_ext = splitext(file_name)\n\n log.write(\"Reading multi-layer sprite file. Searching for '\")\n log.write(\"%s\\-(Char|Gun)\\-\\d+\\.spr'\\n\"%(file_path_base))\n\n sprite_files = []\n for root, dirs, files in os.walk(file_path_root):\n sprite_files += [os.path.realpath(os.path.join(root, x)) for x in files if re.search(\"%s\\-(Char|Gun)\\-(\\d+)\\.spr\"%(file_path_base), x)]\n\n log.write(\"Found Layer sprite files %s\\n\"%(str(sprite_files)))\n\n all_inputs = []\n final_sprite = None\n for sprite in sprite_files:\n with open(sprite, 'rb') as f:\n log.write(\"Opened %s\\n\"%(sprite))\n all_inputs += [sprite]\n match = re.search(\"-(Char|Gun)-(\\d+)\\.spr\", split(sprite)[1])\n sprite_layer = readSpriteFile(f, palettes, full_pal)\n sprite_layer['layers'][0]['order'] = int(match.group(2))\n sprite_layer['layers'][0]['type'] = match.group(1)\n if final_sprite == None:\n final_sprite = sprite_layer\n log.write(\"initial layer set\\n%s\\n\"%(str(final_sprite['layers'])))\n else:\n final_sprite['layers'] += sprite_layer['layers']\n log.write(\"layer add\\n%s\\n\"%(str(final_sprite['layers'])))\n\n log.write(\"layer sprite read finished\\n\")\n return final_sprite, all_inputs\n\n\ndef spriteFrameBBox(sprite, frame):\n transparent_px = sprite['transparent']\n frame_px = frame['data']\n sw = sprite['width']\n sh = sprite['height'] \n l = sprite['width']+1\n r = -1\n t = sprite['height']+1\n b = -1\n for y in range(sh):\n for x in range(sw):\n if frame_px[y*sw+x] != transparent_px:\n l = min(l, x)\n r = max(r, x)\n t = min(t, y)\n b = max(b, y)\n return (l, (sh-t), r+1, (sh-b)-1)\n\nif __name__ == '__main__':\n with open(sys.argv[1]) as fin:\n asset = json.load(fin)\n TEXTUREC = join(asset['buildparams']['working_directory'], 'texturecRelease')\n FLATC = join(asset['buildparams']['working_directory'], \"flatc\")\n tmp_dir = asset['tmp_directory']\n frame_tmp_dir = join(asset['tmp_directory'], 'frames')\n fbs_def_path = join(asset['asset_directory'],'game/fbs/sprite.fbs')\n final_fbs_path = join(asset['tmp_directory'], 'sprite.json')\n final_atlas_path = join(asset['tmp_directory'], 'fullatlas_')\n output_ktx = join(asset['tmp_directory'], 'tmp.ktx')\n sprite_path = asset['processoptions']['input']\n sprite_folder = split(sprite_path)[0]\n found_inputs = []\n\n log = open(join(asset['tmp_directory'], 'log.txt'), 'wb')\n\n total_control_points = 0\n total_events = 0\n total_anims = 0\n total_frames = 0\n total_pages = 0\n asset_json = {\n 'pages':[],\n 'anims':[],\n 'palettes':[]\n }\n anim_json = None\n frame_id = {}\n frame_bbox = {}\n palettes = {}\n\n log.write(\"opening .sprite file %s\\n\"%(sprite_path))\n found_inputs += [sprite_path]\n with open(sprite_path, \"rb\") as f:\n for line in f.readlines():\n line = line.strip()\n if line[0] == '#':\n continue\n if line[0] == 'A':\n if not anim_json == None:\n asset_json['anims'] += [anim_json]\n csv_path = join(sprite_folder, line.split()[2])\n flipx = False\n cp_anim_precent = 0;\n anim_json = {\n 'animType':line.split()[1],\n 'flipx':False,\n 'curveType':'Linear',\n 'layers':[],\n 'controlPoints':[],\n 'events':[]\n }\n\n if 'canInterrupt' in line.split():\n anim_json['canInterrupt'] = True\n if 'alwaysInterrupts' in line.split():\n anim_json['alwaysInterrupts'] = True\n\n if 'flipx' in line.split():\n anim_json['flipx'] = True\n anim_json['flipSource']=line.split()[2]\n elif splitext(csv_path)[1] == '.csv':\n log.write(\"opening .csv file %s\\n\"%(csv_path))\n found_inputs += [csv_path]\n with open(csv_path, 'rb') as csv_f:\n layer = {\n 'order': 0,\n 'type': 'Unknown',\n 'frames': []\n }\n for cline in csv_f.readlines()[1:]:\n # \"Name\",\"Transparent Color\",\"Transparent Color(Hex)\",\"Delay(1/60)\",\"File Name\",\"Width\",\"Height\"\n # \"Frame1\",\"16777215\",\"00FFFFFF\",\"6\",\"walk_0000.png\",\"32\",\"48\"\n log.write(str(cline.split())+'\\n')\n params = cline.strip().split(',')\n tex_path = join(sprite_folder, params[4].strip('\"'))\n frame_js = {}\n frame_js['length'] = int(params[3].strip('\"'))\n frame_js['page'] = total_pages\n frame_id[tex_path] = total_pages\n with Image.open(tex_path) as image:\n bbox = getImageBBox(image)#image.getbbox()\n frame_bbox[tex_path] = bbox\n frame_js['left'] = bbox[0]\n frame_js['top'] = bbox[1]\n frame_js['right'] = bbox[2]\n frame_js['bottom'] = bbox[3]\n total_pages += 1\n frame_js['width'] = int(params[5].strip('\"'))\n frame_js['height'] = int(params[6].strip('\"'))\n layer['frames'] += [frame_js]\n total_frames += 1\n found_inputs += [tex_path]\n\n cmdline = TEXTUREC\n cmdline += ' -f ' + tex_path\n cmdline += ' -o ' + output_ktx\n cmdline += ' -t ' + 'RGBA8'\n log.write(str(cmdline)+'\\n')\n \n p = Popen(cmdline, stdout=PIPE, stderr=PIPE)\n stdout, stderr = p.communicate()\n \n log.write(stdout+'\\n')\n log.write(stderr+'\\n') \n \n s_bytes = []\n with open(output_ktx, 'rb') as f:\n while 1:\n byte_s = f.read(1)\n if not byte_s:\n break\n s_bytes += [ord(byte_s[0])]\n \n js_bytes = []\n for b in s_bytes:\n js_bytes += [b]\n asset_json['pages'] += [{\n 'type':'FullColour',\n 'data':js_bytes\n }]\n anim_json['layers'] = layer\n elif splitext(csv_path)[1] == '.spr':\n log.write(\"opening .spr file %s\\n\"%(csv_path))\n if not os.path.exists(csv_path):\n sprite_data, all_inputs = readSplitLayerSpriteFile(csv_path, palettes, asset_json['palettes'])\n found_inputs += all_inputs\n else:\n found_inputs += [csv_path]\n sprite_data = readSpriteFile(open(csv_path, 'rb'), palettes, asset_json['palettes'])\n frame_len = 0\n for sprite_layer in sprite_data['layers']:\n log.write(str(sprite_layer))\n layer = {\n 'order': sprite_layer['order'],\n 'type': sprite_layer['type'],\n 'frames': []\n }\n assert frame_len == 0 or len(sprite_layer['frames']) == frame_len, \"Frame count across all layers MUST be the same\"\n frame_len = len(sprite_layer['frames'])\n for f in sprite_layer['frames']:\n frame_js = {}\n frame_js['length'] = f['delay']\n frame_js['width'] = sprite_data['width']\n frame_js['height'] = sprite_data['height']\n # TODO: tight bounds\n bbox = spriteFrameBBox(sprite_data, f)\n frame_js['left'] = bbox[0]\n frame_js['top'] = bbox[1]\n frame_js['right'] = bbox[2]\n frame_js['bottom'] = bbox[3]\n # frame_js['left'] = 0\n # frame_js['top'] = sprite_data['height']\n # frame_js['right'] = sprite_data['width']\n # frame_js['bottom'] = 0 \n frame_js['page'] = total_pages\n asset_json['pages'] += [{\n 'type':'Palette',\n 'width': sprite_data['width'],\n 'height': sprite_data['height'],\n 'palette': f['palette'],\n 'data':f['data']\n }]\n total_pages += 1\n total_frames += 1\n layer['frames'] += [frame_js]\n anim_json['layers'] += [layer]\n else:\n raise ValueError(\"Unknown file type %s\"%(csv_path))\n elif line[0] == 'C':\n line_type = line.split()[1]\n anim_json['curveType'] = line_type\n elif line[0] == 'P':\n params = line.split()\n anim_json['controlPoints'] += [{\n 'x': float(params[1]), \n 'y': float(params[2]),\n 'z': float(params[3])/100\n }]\n cp_anim_precent += (float(params[3])-cp_anim_precent)\n total_control_points += 1\n elif line[0] == 'E':\n params = line.split()\n anim_json['events'] += [{\n 'type':params[1],\n 'time':float(params[2])/100\n }]\n total_events += 1\n\n if not anim_json == None:\n asset_json['anims'] += [anim_json]\n\n asset_json['totalControlPoints'] = total_control_points\n asset_json['totalFrames'] = total_frames\n asset_json['totalEvents'] = total_events\n\n# with open(final_fbs_path, 'wb') as f:\n# f.write(json.dumps(asset_json, indent=2, sort_keys=True))\n#\n# cmdline = [FLATC, '-o', asset['tmp_directory'], '-b', fbs_def_path, final_fbs_path]\n# log.write(str(cmdline)+'\\n')\n# p = Popen(cmdline, stdout=PIPE, stderr=PIPE)\n# stdout, stderr = p.communicate()\n# log.write(stdout+'\\n')\n# log.write(stderr+'\\n')\n#\n# with open(splitext(final_fbs_path)[0]+'.bin', 'rb') as bin_file:\n# encoded_data_string = base64.b64encode(bin_file.read())\n final_tmp_path = join(asset['tmp_directory'], 'final_template.json')\n ii, s_bytes, r_bytes = convertJsonFBSToBin(FLATC, asset_json, fbs_def_path, final_tmp_path, asset['tmp_directory'], log)\n\n log.write('read outputted fbs binary')\n asset['buildoutput'] = {\n \"data\": base64.b64encode(r_bytes),\n }\n asset['assetmetadata']['inputs'] = found_inputs+ii\n\n with open(asset['output_file'], 'wb') as f:\n f.write(json.dumps(asset, indent=2, sort_keys=True))\n\n","sub_path":"process_sprite.py","file_name":"process_sprite.py","file_ext":"py","file_size_in_byte":15671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"224450201","text":"import pygame\r\nimport common\r\nimport time\r\ntime_textpos = (common.screen_size[0] * 0.76,common.screen_size[1] * 0.04)\r\npauseimgpos = (common.screen_size[0] * 0.72,common.screen_size[1] * 0.04)\r\npauseimg = pygame.image.load(\"./bilder/Pause.png\")\r\nunpauseimg = pygame.image.load(\"./bilder/Un-Pause.png\")\r\n\r\nclass time():\r\n def __init__(self):\r\n self.cooldown1 = 4800\r\n self.cooldown2 = 4800\r\n self.running = True\r\n\r\n def draw(self):\r\n pygame.font.init()\r\n font_path = (\"./font/FreePixel.ttf\")\r\n font_size = 32\r\n fontObj = pygame.font.Font(font_path, font_size)\r\n timetext = fontObj.render(\"Time : \"+str(mytime.cooldown2),100,common.black)\r\n common.screen.blit(timetext,time_textpos)\r\n\r\n def reduce_time(self):\r\n if self.running == True:\r\n self.cooldown2 -= 1\r\n if self.cooldown2 <= 1:\r\n self.cooldown2 = self.cooldown1\r\n\r\nclass timebutton(pygame.sprite.Sprite):\r\n def __init__(self):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image = pauseimg\r\n self.imagepos = pauseimgpos\r\n self.rect = self.image.get_rect()\r\n self.rect.left, self.rect.top = self.imagepos\r\n self.cooldown1 = 10\r\n self.cooldown2 = 10\r\n\r\n def draw_time_button(self):\r\n common.screen.blit(self.image,self.imagepos)\r\n self.cooldown1 -= 1\r\n if self.cooldown1 <= 1:\r\n self.cooldown1 = 1\r\n\r\n def pause(self):\r\n if mytime.running == True:\r\n pos = pygame.mouse.get_pos()\r\n (pressed1, pressed2, pressed3) = pygame.mouse.get_pressed()\r\n if pressed1 == 1 and self.rect.collidepoint(pos) and self.cooldown1 == 1:\r\n mytime.running = False\r\n self.cooldown1 = self.cooldown2\r\n\r\n def unpause(self):\r\n if mytime.running == False:\r\n pos = pygame.mouse.get_pos()\r\n (pressed1, pressed2, pressed3) = pygame.mouse.get_pressed()\r\n if pressed1 == 1 and self.rect.collidepoint(pos) and self.cooldown1 == 1:\r\n mytime.running = True\r\n self.cooldown1 = self.cooldown2\r\n\r\n def changeimg(self):\r\n if mytime.running == True:\r\n self.image = pauseimg\r\n if mytime.running == False:\r\n self.image = unpauseimg\r\n\r\nmytime = time()\r\nmytimebutton = timebutton()\r\n\r\ndef draw_all_time():\r\n mytime.draw()\r\n mytime.reduce_time()\r\n mytimebutton.draw_time_button()\r\n mytimebutton.pause()\r\n mytimebutton.unpause()\r\n mytimebutton.changeimg()","sub_path":"gamelib/time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"408768357","text":"import socket\n\nhost = '127.0.0.1'\nport = 5000\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.bind((host, port))\n\nprint(\"Server Started\")\nwhile True:\n\tdata, addr = s.recvfrom(1024)\n\tdata = data.decode('utf-8')\n\tprint (\"message from\" + str(addr))\n\tprint(\"from connected user:\" + str(data))\n\tdata = str(data).upper()\n\tprint(\"sending\" + str(data))\n\ts.sendto(data, addr)\ns.close()\t","sub_path":"Sockets/udpserver.py","file_name":"udpserver.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"634302957","text":"import os\nimport shutil\n\nfrom mcsdk.codebase import generator\nfrom mcsdk.integration.os.process import Command\n\n\nclass CodeGenerator(generator.AbstractGenerator):\n \"\"\" Handles the Swagger codegen process but also custom generation processes \"\"\"\n\n def _delete_standard_tests(self):\n \"\"\" The testing framework is also automated so we must delete the existing generated tests \"\"\"\n api_tests_dir = os.path.join(self._repo_dir, 'test', 'Api')\n if os.path.isdir(api_tests_dir):\n shutil.rmtree(api_tests_dir)\n\n model_tests_dir = os.path.join(self._repo_dir, 'test', 'Model')\n if os.path.isdir(model_tests_dir):\n shutil.rmtree(model_tests_dir)\n\n def generate_sdk(self):\n \"\"\" Generates the SDK code using the swagger codegen library \"\"\"\n cmd = \" \".join([\n 'java',\n '-jar',\n '{swagger_exec}'.format(swagger_exec=self._config['repos']['core']['swagger_cli']),\n 'generate',\n '-l',\n 'php',\n '-i',\n '{spec_file}'.format(spec_file=self._config['repos']['core']['swagger_spec']),\n '-t',\n '{templates_dir}'.format(templates_dir=os.path.join(self._templates_dir, 'mustache')),\n '-c',\n '{config_file}'.format(config_file=os.sep.join([self._config_dir, 'swagger-codegen-config.json'])),\n '-o',\n '{sdk_folder}'.format(sdk_folder=self._repo_dir)\n ])\n\n command = Command(cmd)\n command.run()\n\n return not command.returned_errors()\n\n def generate_client(self):\n \"\"\" Generates the SDK code custom PHP code generator \"\"\"\n cmd = \" \".join([\n 'php',\n '-f',\n os.sep.join([self._root_dir, 'src', 'generator', self._config['generators']['php']]),\n os.path.join(self._templates_dir, 'phtml'),\n os.sep.join([self._config_dir, 'swagger-codegen-config.json']),\n self._repo_dir\n ])\n\n print(\"Generate PHP client command: \" + cmd)\n\n command = Command(cmd)\n command.run()\n\n return not command.returned_errors()\n\n def generate(self):\n \"\"\" Generates the SDK code \"\"\"\n self._delete_standard_tests()\n\n if self.generate_sdk() and self.generate_client():\n return 0\n\n return 255\n","sub_path":"src/integrator/codebase/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"553402647","text":"from copy import deepcopy\n\ndef write(program, position, value):\n\tif position >= len(program):\n\t\tprogram += [0] * (position - len(program) + 1)\n\tprogram[position] = value\n\ndef read(program, position):\n\tif position >= len(program):\n\t\tprogram += [0] * (position - len(program) + 1)\n\treturn program[position]\n\ndef getParameter(program, pointer, parameter, relativeBase):\n\tif read(program, pointer)//10**(parameter+1)%10 == 1:\n\t\treturn pointer + parameter\n\telif read(program, pointer)//10**(parameter+1)%10 == 2:\n\t\treturn read(program, pointer + parameter) + relativeBase\n\telse:\n\t\treturn read(program, pointer + parameter)\n\ndef runProgram(program, processInput, processOutput, condition = lambda: True):\n\tpointer = relativeBase = 0\n\tprogram = deepcopy(program)\n\t\n\twhile condition() and read(program, pointer) != 99:\n\t\tinstruction = read(program, pointer)%100\n\t\tparam1 = getParameter(program, pointer, 1, relativeBase)\n\t\tparam2 = getParameter(program, pointer, 2, relativeBase)\n\t\tparam3 = getParameter(program, pointer, 3, relativeBase)\n\n\t\tif instruction == 1:\n\t\t\twrite(program, param3, read(program, param1) + read(program, param2))\n\t\t\tpointer += 4\n\t\telif instruction == 2:\n\t\t\twrite(program, param3, read(program, param1) * read(program, param2))\n\t\t\tpointer += 4\n\t\telif instruction == 3:\n\t\t\twrite(program, param1, processInput())\n\t\t\tpointer += 2\n\t\telif instruction == 4:\n\t\t\tprocessOutput(read(program, param1))\n\t\t\tpointer += 2\n\t\telif instruction == 5:\n\t\t\tif read(program, param1):\n\t\t\t\tpointer = read(program, param2)\n\t\t\telse:\n\t\t\t\tpointer += 3\n\t\telif instruction == 6:\n\t\t\tif not read(program, param1):\n\t\t\t\tpointer = read(program, param2)\n\t\t\telse:\n\t\t\t\tpointer += 3\n\t\telif instruction == 7:\n\t\t\twrite(program, param3, 1 if read(program, param1) < read(program, param2) else 0)\n\t\t\tpointer += 4\n\t\telif instruction == 8:\n\t\t\twrite(program, param3, 1 if read(program, param1) == read(program, param2) else 0)\n\t\t\tpointer += 4\n\t\telif instruction == 9:\n\t\t\trelativeBase += read(program, param1)\n\t\t\tpointer += 2\n\t\telse:\n\t\t\tprint(\"Error\")","sub_path":"2019/intcode.py","file_name":"intcode.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"223841722","text":"'''\nCreated on Aug 31, 2018\nProcessing Instagram dataset\n\n@author: Shatha Jaradat (shatha@kth.se)\nKTH - Royal Institute of Technology\n'''\n\nimport scipy.sparse as sp\nimport numpy as np\nfrom outfit import outfitInstance\n\nclass InstagramDataset(object):\n def __init__(self, path):\n '''\n Constructor\n '''\n self.trainData = self.loadData_SingleValues(path)\n self.testData = self.loadData_SingleValues(path)\n #self.testNegatives = self.load_negative_file(path + \".test.negative\")\n #assert len(self.testData) == len(self.testNegatives)\n\n #self.num_users, self.num_items = self.trainData.shape\n\n def loadData_SingleValues(self, filename):\n '''\n Read file and Return outfit class instance.\n '''\n # Get number of users and items\n userId, subcategories, patterns, materials, styles =0,0,0,0,0\n with open(filename, \"r\") as f:\n line = f.readline()\n lstOutfits_withStyles = []\n while line != None and line != \"\":\n arr = line.split(\" \")\n print('length of array')\n print(len(arr))\n print(arr)\n subcategories = int(arr[0])\n patterns = int(arr[1])\n materials = int(arr[2])\n styles = int(arr[3])\n print('subcategory')\n print(subcategories)\n print('pattern')\n print(patterns)\n print('material')\n print(materials)\n print('style')\n print(styles)\n obj_outfit = outfitInstance(userId,subcategories,patterns,materials, styles)\n lstOutfits_withStyles.append(obj_outfit)\n line = f.readline()\n return lstOutfits_withStyles\n\n#obj = InstagramDataset('/var/root/PycharmProjects/neural_collaborative_filtering/InstagramData/outfits_training')\n#obj.loadData_SingleValues('/var/root/PycharmProjects/neural_collaborative_filtering/InstagramData/outfits_training')","sub_path":"InstagramDataset.py","file_name":"InstagramDataset.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"315751515","text":"# coding:utf-8\n\nfrom django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponseRedirect\nfrom django.contrib import messages\nfrom django.core.urlresolvers import reverse\n\nfrom .models import Factory\nfrom .models import Workshop\nfrom .models import Equipment\n\nfrom .forms import FactoryEditForm\nfrom .forms import FactoryAddForm\n\n\nfrom warden.models import ReadOnyGroup\n\nfrom django.http import JsonResponse\n\n################################################################################\n# list 页面\n\n\n\n@login_required # 必须登录才能访问\ndef my_factories(request):\n\t# 当前用户\n\tuser = request.user\n\n\t# 当前用户的工厂\n\tmy_factories = Factory.objects.filter(owner=user) # 只能访问自己的工厂\n\n\t# 当前用户所在的 ReadOnyGroup 组\n\tmy_read_only_groups = ReadOnyGroup.objects.filter(read_only_users=user) # 我所在的只读组\n\tgroups_owners = [g.owner for g in my_read_only_groups] # 所有只读组的组长\n\t# 对应的只读信息的 工厂\n\tread_only_factories = Factory.objects.filter(owner__in=groups_owners) # 工厂所有人必须是在只读组的组长之内\n\n\treturn render(request,'humidifier/factory.html',{\n\t\t'my_factories':my_factories, \t\t\t\t\t\t\t# 对于 user 有读写权限的工厂(多个,是一个list)\n\t\t'read_only_factories':read_only_factories, \t\t\t\t\t\t\t# 对于 user 只有读权限的工厂(多个,是一个list)\n\t})\n\n\n@login_required\ndef my_workshops(request):\n\t# 当前用户\n\tuser = request.user\n\n\t# 当前用户的车间\n\tmy_workshops = Workshop.objects.filter(owner=user)\n\n\t# 当前用户所在的 ReadOnyGroup 组\n\tmy_read_only_groups = ReadOnyGroup.objects.filter(read_only_users=user)\n\tgroups_owners = [g.owner for g in my_read_only_groups]\n\t# 对应的只读信息的 工厂\n\tread_only_workshops = Workshop.objects.filter(owner__in=groups_owners)\n\n\treturn render(request,'humidifier/my_workshop.html',{\n\t\t'my_workshops':my_workshops, # 对于 user 有读写权限的车间(多个,是一个list)\n\t\t'read_only_workshops':read_only_workshops, # 对于 user 只有读权限的车间(多个,是一个list)\n\t})\n\n\n@login_required\ndef my_equitments(request):\n\t# 当前用户\n\tuser = request.user\n\n\t# 当前用户的车间\n\tmy_equitments = Equipment.objects.filter(owner=user)\n\n\t# 当前用户所在的 ReadOnyGroup 组\n\tmy_read_only_groups = ReadOnyGroup.objects.filter(read_only_users=user)\n\tgroups_owners = [g.owner for g in my_read_only_groups]\n\t# 对应的只读信息的 工厂\n\tread_only_equitments = Equipment.objects.filter(owner__in=groups_owners)\n\n\treturn render(request,'humidifier/my_workshop.html',{\n\t\t'my_equitments':my_equitments, # 对于 user 有读写权限的设备(多个,是一个list)\n\t\t'read_only_equitments':read_only_equitments, # 对于 user 只有读权限的设备(多个,是一个list)\n\t})\n\n\n################################################################################\n# 下面是 detail 页面\n\n@login_required\ndef factory_detail(request,id):\n\tuser = request.user\n\n\tfactory = Factory.objects.get(id=id)\n\n\tif factory.owner == user:\n\t\tis_read_and_write_permission = True\n\telse:\n\t\tis_read_and_write_permission = False\n\n\t# 我所在组的 owner\n\tmy_read_only_groups = ReadOnyGroup.objects.filter(read_only_users=user)\n\tgroups_owners = [g.owner for g in my_read_only_groups]\n\n\tif factory.owner in groups_owners:\n\t\tis_read_only_permisson = True\n\telse:\n\t\tis_read_only_permisson = False\n\n\t# 如果既没有读写权限,也没有 只读权限,就 404 或者 403 提示\n\tif not is_read_and_write_permission and not is_read_only_permisson:\n\t\treturn HttpResponseRedirect(request.META.get(\"HTTP_REFERER\",\"/\"))\n\n\treturn render(request,'humidifier/factory_detail.html',{\n\t\t'factory':factory,\n\t\t'is_read_only_permisson':is_read_only_permisson,\n\t\t'is_read_and_write_permission':is_read_and_write_permission,\n\t})\n\n\n\n@login_required\ndef workshop_detail(request,id):\n\tuser = request.user\n\t\n\tworkshop = Workshop.objects.get(id=id)\n\t\n\tif workshop.owner == user:\n\t\tis_read_and_write_permission = True\n\telse:\n\t\tis_read_and_write_permission = False\n\n\t# 我所在组的 owner\n\tmy_read_only_groups = ReadOnyGroup.objects.filter(read_only_users=user)\n\tgroups_owners = [g.owner for g in my_read_only_groups]\n\t\n\tif workshop.owner in groups_owners:\n\t\tis_read_only_permisson = True\n\telse:\n\t\tis_read_only_permisson = False\n\n\t# 如果既没有读写权限,也没有 只读权限,就 404 或者 403 提示\n\tif not is_read_and_write_permission and not is_read_only_permisson:\n\t\treturn HttpResponseRedirect(request.META.get(\"HTTP_REFERER\",\"/\"))\n\t\n\treturn render(request,'humidifier/workshop_detail.html',{\n\t\t'workshop':workshop,\n\t\t'is_read_only_permisson':is_read_only_permisson,\n\t\t'is_read_and_write_permission':is_read_and_write_permission,\n\t})\n\n@login_required\ndef equipment(request):\n\treturn render(request, 'humidifier/equipment.html')\n\n@login_required\ndef equitment_detail(request,id):\n\tuser = request.user\n\t\n\tequitment = Equipment.objects.get(id=id)\n\t\n\tif equitment.owner == user:\n\t\tis_read_and_write_permission = True\n\telse:\n\t\tis_read_and_write_permission = False\n\n\t# 我所在组的 owner\n\tmy_read_only_groups = ReadOnyGroup.objects.filter(read_only_users=user)\n\tgroups_owners = [g.owner for g in my_read_only_groups]\n\t\n\tif equitment.owner in groups_owners:\n\t\tis_read_only_permisson = True\n\telse:\n\t\tis_read_only_permisson = False\n\n\t# 如果既没有读写权限,也没有 只读权限,就 404 或者 403 提示\n\tif not is_read_and_write_permission and not is_read_only_permisson:\n\t\treturn HttpResponseRedirect(request.META.get(\"HTTP_REFERER\",\"/\"))\n\t\n\treturn render(request,'humidifier/workshop_detail.html',{\n\t\t'equitment':equitment,\n\t\t'is_read_only_permisson':is_read_only_permisson,\n\t\t'is_read_and_write_permission':is_read_and_write_permission,\n\t})\n\n\n################################################################################\n# 下面是编辑功能\n\n@login_required\ndef factory_edit(request,id):\n\tuser = request.user\n\n\tfactory = Factory.objects.get(id=id)\n\n\tif factory.owner != user:\n\t\tmessages.info(request,\"你不是该工厂的所有人,你不能编辑该工厂的信息\")\n\t\treturn HttpResponseRedirect(request.META.get(\"HTTP_REFERER\",'/'))\n\n\tif request.method == \"POST\":\n\t\tform = FactoryEditForm(request.POST,instance=factory)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tmessages.info(request,'工厂信息修改成功')\n\t\t\treturn HttpResponseRedirect(reverse('factory_detail',args=[factory.id]))\n\t\telse:\n\t\t\tmessages.info(request,form.errors)\n\t\t\treturn HttpResponseRedirect(request.META.get(\"HTTP_REFERER\",'/'))\n\n\tform = FactoryEditForm(instance=factory)\n\treturn render(request,'humidifier/factory_edit.html',{\n\t\t'form':form,\n\t})\n\n\n################################################################################\n# 下面是新增功能\n@login_required\ndef factory_add(request):\n\tuser = request.user\n\n\tfactory_instance = Factory(owner=user)\n\n\tif request.method == \"POST\":\n\t\tform = FactoryAddForm(request.POST,instance=factory_instance)\n\t\tif form.is_valid():\n\t\t\tnew_factory = form.save()\n\t\t\tmessages.info(request,'工厂创建成功')\n\t\t\treturn HttpResponseRedirect(reverse('factory_detail',args=[new_factory.id]))\n\t\telse:\n\t\t\tmessages.info(request,form.errors)\n\t\t\treturn HttpResponseRedirect(request.META.get(\"HTTP_REFERER\",'/'))\n\n\tform = FactoryAddForm(instance=factory_instance)\n\treturn render(request,'humidifier/factory_add.html',{\n\t\t'form':form,\n\t})\n\n\n#加湿器\n@login_required\ndef humidifier( request ):\n\thumidifier_list = Humidifier.objects.all()\n\tresponse = JsonResponse( [{ 'first': '89757', 'two': 100, 'last': 'Barker', 'age': 89 , 'tool': '89757'}] , safe=False)\n\treturn response\n#打包器\n@login_required\ndef packetizer( request ):\n\tpass\n\n#运输机\n@login_required\ndef conveyor(request):\n\tpass\n\n#电子秤\n@login_required\ndef electronic_scale(request):\n\tpass\n\n#风机\n@login_required\ndef blower(request):\n\tpass\n#压缩机\n@login_required\ndef compreessor(request):\n\tpass\n","sub_path":"humidifier/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"563883308","text":"import os, sys\n\n##method that removes steps from prerequisites and returns updated list\n##plus list of newly available steps\ndef remove_step_from_prerequisites(step, requirements):\n empties = []\n for requirement in requirements:\n ##if the step we just did is a prerequisite, remove it since it\n ##has been fulfilled\n if step in requirements[requirement]:\n requirements[requirement].remove(step)\n ##if that was the last prerequisite, add the step to the \"empty\"\n ##list since it no longer has any prerequisites and is \"available\"\n if len(requirements[requirement]) == 0:\n empties.append(requirement)\n \n ##remove the newly available steps from the requirements\n for empty in empties:\n requirements.pop(empty)\n return requirements, empties\n\n\n\ndirname, filename = os.path.split(os.path.abspath(sys.argv[0]))\n\n##collect all input, or \"requirements\"\nwith open(os.path.join(dirname, \"input.txt\")) as requirement_list:\n requirements = [requirements.split() for requirements in requirement_list]\n\nprerequisite_set = set()\nstep_set = set()\nrequirement_pairs = {}\n\n##store all prerequisite/step pairs and store each in sets to find our starting points\nfor requirement in requirements:\n prerequisite = requirement[1]\n prerequisite_set.add(prerequisite)\n \n step = requirement[7]\n step_set.add(step)\n\n if step in requirement_pairs:\n prerequisite_list = list(requirement_pairs[step])\n prerequisite_list.append(prerequisite)\n requirement_pairs[step] = prerequisite_list\n else:\n requirement_pairs[step] = [prerequisite]\n\n##sort alphabetically so the one we choose is at index = 0\navailable_steps = sorted(prerequisite_set.difference(step_set))\ndone_steps = []\n\n##loop through all steps and update available steps to find the best next step\nwhile len(available_steps) > 0:\n current_step = available_steps[0]\n\n prerequisite_list, fresh_steps = remove_step_from_prerequisites(current_step, requirement_pairs)\n\n ##remove the current step from available_steps since we just \"did\" it\n available_steps.remove(current_step)\n\n ##add the newly available steps\n available_steps += fresh_steps\n\n ##sort again so that the best step is at index = 0\n available_steps = sorted(available_steps)\n\n ##keep track of steps done\n done_steps.append(current_step)\n\nprint(\"\".join(done_steps))","sub_path":"7/7-1.py","file_name":"7-1.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"8748364","text":"import torch\nimport torch.nn as nn\nfrom pytorch_lightning import LightningModule\nfrom pytorch_lightning.metrics import Accuracy\n\n\ndef lin_relu(in_features, out_features):\n return nn.Sequential(\n nn.Linear(in_features, out_features),\n nn.ReLU(inplace=True),\n )\n\n\nclass MLP(nn.Module):\n def __init__(self, input_dim=25*(8+1+1),\n hidden_dim=256, num_layers=6,\n num_classes=101):\n super().__init__()\n self.layers = nn.ModuleList([lin_relu(input_dim, hidden_dim)])\n for _ in range(num_layers-2):\n self.layers.append(lin_relu(hidden_dim, hidden_dim))\n self.layers.append(nn.Linear(hidden_dim, num_classes))\n\n def forward(self, x):\n for i in range(len(self.layers)):\n x = self.layers[i](x)\n return x\n\n\nclass MLPModule(LightningModule):\n def __init__(self, input_dim=25*(8+1+1),\n hidden_dim=256,\n num_layers=6,\n num_classes=101):\n super().__init__()\n self.save_hyperparameters()\n self.model = MLP(input_dim, hidden_dim, num_layers, num_classes)\n self.loss = nn.CrossEntropyLoss()\n self.val_accuracy = Accuracy()\n\n def forward(self, x):\n return self.model(x)\n\n def training_step(self, batch, batch_idx):\n x, y = batch\n out = self(x)\n loss = self.loss(out, y)\n self.log('train_loss', loss, on_step=False, on_epoch=True)\n return loss\n\n def validation_step(self, batch, batch_idx):\n x, y = batch\n out = self(x)\n\n loss = self.loss(out, y)\n acc = self.val_accuracy(out, y)\n self.log('val_loss', loss, prog_bar=True)\n self.log('acc', acc, prog_bar=True)\n\n def configure_optimizers(self):\n optimizer = torch.optim.AdamW(self.model.parameters(), lr=1e-3)\n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer,\n step_size=50,\n gamma=0.5)\n return {\n 'optimizer': optimizer,\n 'lr_scheduler': lr_scheduler,\n }\n","sub_path":"graph_machine_learning/what_can_neural_networks_reason_about/src/model_mlp.py","file_name":"model_mlp.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"291994594","text":"from model.contact import Contact\nimport re\nfrom selenium.webdriver.support.ui import Select\nfrom operator import index\n\n\nclass ContactHelper:\n\n def __init__(self, app):\n self.app = app\n\n def create(self, contact):\n wd = self.app.wd\n self.open_home_page()\n wd.find_element_by_link_text(\"add new\").click()\n self.fill_form_contact(contact)\n # Submit contact creation\n wd.find_element_by_xpath(\"(//input[@name='submit'])[2]\").click()\n self.open_home_page()\n self.contact_cache = None\n\n def open_home_page(self):\n wd = self.app.wd\n if not (wd.current_url.endswith(\"/\") and len(wd.find_elements_by_css_selector('img[alt=\"Edit\"]')) > 0):\n wd.find_element_by_link_text(\"home\").click()\n\n def edit_contact_by_index(self, new_contact_data, index):\n wd = self.app.wd\n self.open_home_page()\n element = self.selected_contact_by_index(index)\n element.find_element_by_xpath(\"td[8]\").click()\n self.fill_form_contact(new_contact_data)\n # Submit contact creation\n wd.find_element_by_name(\"update\").click()\n self.open_home_page()\n self.contact_cache = None\n\n def selected_contact_by_index(self, index):\n wd = self.app.wd\n contact_list = list(wd.find_elements_by_xpath(\"//tr[@name='entry']\"))\n return contact_list[index]\n\n def edit_contact_by_id(self, new_contact_data, id_contact):\n wd = self.app.wd\n self.open_home_page()\n index = self.get_contact_index(id_contact)\n contact = self.selected_contact_by_index(index)\n contact.find_element_by_xpath(\"td[8]\").click()\n self.fill_form_contact(new_contact_data)\n # Submit contact creation\n wd.find_element_by_name(\"update\").click()\n self.open_home_page()\n self.contact_cache = None\n\n def get_contact_index(self, id_contact):\n wd = self.app.wd\n contact_list = wd.find_elements_by_xpath(\"//tr[@name='entry']\")\n for contact in contact_list:\n id = contact.find_element_by_name(\"selected[]\").get_attribute(\"value\")\n if id == id_contact:\n return contact_list.index(contact)\n\n\n def selected_contact_by_id(self, id):\n wd = self.app.wd\n return wd.find_element_by_xpath(\"//input[@id='%s']\" % id)\n\n def delete_contact_by_index(self, index):\n wd = self.app.wd\n self.open_home_page()\n element = self.selected_contact_by_index(index)\n element.find_element_by_xpath(\"td[1]\").click()\n wd.find_element_by_xpath(\"//input[@value='Delete']\").click()\n wd.switch_to_alert().accept()\n self.open_home_page()\n self.contact_cache = None\n\n def delete_contact_by_id(self, id):\n wd = self.app.wd\n self.open_home_page()\n element = self.selected_contact_by_id(id)\n element.click()\n wd.find_element_by_xpath(\"//input[@value='Delete']\").click()\n wd.switch_to_alert().accept()\n self.open_home_page()\n self.contact_cache = None\n\n def delete_first_contact(self):\n self.delete_contact_by_index(0)\n\n def fill_form_contact(self, contact):\n # Name\n self.change_field_contact(\"firstname\", contact.firstname)\n self.change_field_contact(\"middlename\", contact.middlename)\n self.change_field_contact(\"lastname\", contact.lastname)\n self.change_field_contact(\"nickname\", contact.nickname)\n # Different information\n self.change_field_contact(\"photo\", contact.photo)\n self.change_field_contact(\"title\", contact.title)\n self.change_field_contact(\"company\", contact.company)\n self.change_field_contact(\"address\", contact.address)\n # Telephones and emails\n self.change_field_contact(\"home\", contact.thome)\n self.change_field_contact(\"mobile\", contact.tmobile)\n self.change_field_contact(\"work\", contact.twork)\n self.change_field_contact(\"fax\", contact.tfax)\n self.change_field_contact(\"email\", contact.email)\n self.change_field_contact(\"email2\", contact.email2)\n self.change_field_contact(\"email3\", contact.email3)\n self.change_field_contact(\"homepage\", contact.homepage)\n # Birthday and anniversary\n self.change_field_contact(\"bday\", contact.bday)\n self.change_field_contact(\"bmonth\", contact.bmonth)\n self.change_field_contact(\"byear\", contact.byear)\n self.change_field_contact(\"aday\", contact.aday)\n self.change_field_contact(\"amonth\", contact.amonth)\n self.change_field_contact(\"ayear\", contact.ayear)\n # wd.find_element_by_name(\"new_group\").click()\n # wd.find_element_by_xpath(\"//option[@value='[none]']\").click()\n # Secondary\n self.change_field_contact(\"address2\", contact.secaddress)\n self.change_field_contact(\"phone2\", contact.sechome)\n self.change_field_contact(\"notes\", contact.secnote)\n\n def change_field_contact(self, field, text):\n wd = self.app.wd\n if text is not None:\n if field == \"bday\" or field == \"bmonth\" or field == \"aday\" or field == \"amonth\":\n wd.find_element_by_name(field).click()\n wd.find_element_by_name(field).send_keys(text)\n elif field == \"photo\":\n wd.find_element_by_name(field).send_keys(text)\n else:\n wd.find_element_by_name(field).click()\n wd.find_element_by_name(field).clear()\n wd.find_element_by_name(field).send_keys(text)\n\n def count(self):\n wd = self.app.wd\n return len(wd.find_elements_by_name(\"selected[]\"))\n\n contact_cache = None\n\n def get_contact_list(self):\n if self.contact_cache is None:\n wd = self.app.wd\n self.open_home_page()\n self.contact_cache = []\n for element in wd.find_elements_by_xpath(\"//tr[@name='entry']\"):\n lastname = element.find_element_by_xpath(\"td[2]\").text\n firstname = element.find_element_by_xpath(\"td[3]\").text\n address = element.find_element_by_xpath(\"td[4]\").text\n id = element.find_element_by_name(\"selected[]\").get_attribute(\"id\")\n all_emails = element.find_element_by_xpath(\"td[5]\").text\n all_phones = element.find_element_by_xpath(\"td[6]\").text\n self.contact_cache.append(Contact\n (lastname=lastname, firstname=firstname, address=address, id=id,\n all_emails_from_home_page=all_emails, all_phones_from_home_page=all_phones))\n return list(self.contact_cache)\n\n def open_contact_to_edit_by_index(self, index):\n wd = self.app.wd\n self.open_home_page()\n row = wd.find_elements_by_name('entry')[index]\n cell = row.find_elements_by_tag_name(\"td\")[7]\n cell.find_element_by_tag_name(\"a\").click()\n\n def open_contact_view_by_index(self, index):\n wd = self.app.wd\n self.open_home_page()\n row = wd.find_elements_by_name('entry')[index]\n cell = row.find_elements_by_tag_name(\"td\")[6]\n cell.find_element_by_tag_name(\"a\").click()\n\n def get_contact_info_from_edit_page(self, index):\n wd = self.app.wd\n self.open_contact_to_edit_by_index(index)\n lastname = wd.find_element_by_name(\"lastname\").get_attribute(\"value\")\n firstname = wd.find_element_by_name(\"firstname\").get_attribute(\"value\")\n id = wd.find_element_by_name(\"home\").get_attribute(\"value\")\n email = wd.find_element_by_name(\"email\").get_attribute(\"value\")\n email2 = wd.find_element_by_name(\"email2\").get_attribute(\"value\")\n email3 = wd.find_element_by_name(\"email3\").get_attribute(\"value\")\n thome = wd.find_element_by_name(\"home\").get_attribute(\"value\")\n twork = wd.find_element_by_name(\"work\").get_attribute(\"value\")\n tmobile = wd.find_element_by_name(\"mobile\").get_attribute(\"value\")\n sechome = wd.find_element_by_name(\"phone2\").get_attribute(\"value\")\n address = wd.find_element_by_name(\"address\").get_attribute(\"value\")\n return Contact(lastname=lastname, firstname=firstname, id=id,\n email=email, email2=email2, email3=email3,\n thome=thome, twork=twork, tmobile=tmobile, sechome=sechome, address=address)\n\n def get_contact_info_from_edit_page_by_id(self, id_contact):\n wd = self.app.wd\n self.open_contact_to_edit_by_id(id_contact)\n lastname = wd.find_element_by_name(\"lastname\").get_attribute(\"value\")\n firstname = wd.find_element_by_name(\"firstname\").get_attribute(\"value\")\n id = id_contact #wd.find_element_by_name(\"home\").get_attribute(\"value\")\n email = wd.find_element_by_name(\"email\").get_attribute(\"value\")\n email2 = wd.find_element_by_name(\"email2\").get_attribute(\"value\")\n email3 = wd.find_element_by_name(\"email3\").get_attribute(\"value\")\n thome = wd.find_element_by_name(\"home\").get_attribute(\"value\")\n twork = wd.find_element_by_name(\"work\").get_attribute(\"value\")\n tmobile = wd.find_element_by_name(\"mobile\").get_attribute(\"value\")\n sechome = wd.find_element_by_name(\"phone2\").get_attribute(\"value\")\n address = wd.find_element_by_name(\"address\").get_attribute(\"value\")\n return Contact(lastname=lastname, firstname=firstname, id=id,\n email=email, email2=email2, email3=email3,\n thome=thome, twork=twork, tmobile=tmobile, sechome=sechome, address=address)\n\n def open_contact_to_edit_by_id(self, id):\n wd = self.app.wd\n self.open_home_page()\n contact_by_id = self.find_contact_by_id(id)\n edit_button = contact_by_id.find_elements_by_tag_name(\"td\")[7]\n edit_button.find_element_by_tag_name(\"a\").click()\n # row = wd.find_elements_by_xpath(\"//input[@id='%s']\" % id)\n # cell = row.find_elements_by_tag_name(\"td\")[7]\n # cell.find_element_by_tag_name(\"a\").click()\n\n def find_contact_by_id(self, id):\n wd = self.app.wd\n contacts_list = wd.find_elements_by_xpath(\"//tr[@name='entry']\")\n for contact in contacts_list:\n id_contact = contact.find_element_by_name(\"selected[]\").get_attribute(\"id\")\n if id_contact == id:\n return contact\n\n def get_contact_from_view_page(self, index):\n wd = self.app.wd\n self.open_contact_view_by_index(index)\n text = wd.find_element_by_id(\"content\").text\n thome = re.search(\"H: (.*)\", text).group(1)\n twork = re.search(\"W: (.*)\", text).group(1)\n tmobile = re.search(\"M: (.*)\", text).group(1)\n sechome = re.search(\"P: (.*)\", text).group(1)\n return Contact(thome=thome, twork=twork, tmobile=tmobile, sechome=sechome)\n\n def add_contact_in_group_by_id(self, id_contact, id_group):\n wd = self.app.wd\n self.open_home_page()\n self.selected_contact_by_id(id_contact).click()\n self.select_group_for_add_contact(id_group)\n wd.find_element_by_xpath(\"//input[@value='Add to']\").click()\n self.open_home_page()\n # self.contact_cache = None\n\n def select_group_for_add_contact(self, id_group):\n wd = self.app.wd\n wd.find_element_by_name(\"to_group\").click()\n Select(wd.find_element_by_name(\"to_group\")).select_by_value(id_group)\n wd.find_element_by_name(\"to_group\").click()\n\n def del_contact_in_group_by_id(self, id_contact, id_group):\n wd = self.app.wd\n self.open_home_page()\n self.show_contacts_in_group(id_group)\n self.selected_contact_by_id(id_contact).click()\n wd.find_element_by_name(\"remove\").click()\n self.open_home_page()\n\n def show_contacts_in_group(self, id_group):\n wd = self.app.wd\n wd.find_element_by_name(\"group\").click()\n Select(wd.find_element_by_name(\"group\")).select_by_value(id_group)\n wd.find_element_by_name(\"to_group\").click()\n","sub_path":"fixture/contact.py","file_name":"contact.py","file_ext":"py","file_size_in_byte":12060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"293349823","text":"#because we parse json\nimport json\n\nglobal N\nN = 8\n#forget this and it will throw NameError: global name 'board' is not defined\nboard = [[0 for x in range(8)] for x in range(8)]\n\ndef isPlaced(board,row,col):\n\t# traverse on row, or it will add all the queens to board[row++][0]\n\tfor i in range(row):\n\t\tif(board[i][col] ==1):\n\t\t\treturn True\n\t#returns true if queen is preset at board[i,col]\t\n\ti = row - 1\n\tj = col - 1\n\t# decrements are used to traverse upper left diagonal of the board\n\twhile((i>=0) and (j>=0)):\n\t\tif(board[i][j] == 1):\n\t\t\treturn True\n\t\ti = i - 1\n\t\tj = j - 1\n\ti = row - 1\n\tj = col + 1\n\t#decrement and increment are used to traverse lower left diagonal if the board\n\twhile((i>=0) and (j<8)):\n\t\tif(board[i][j] == 1):\n\t\t\treturn True\n\t\ti = i - 1\n\t\tj = j + 1\n\t# if safe position if found\n\treturn False\n\t\n\n\n\ndef NQueenSolver(board,row):\n\t#solves N Queen Poblem, Backtracking\t\n\ti = 0\n\twhile(i 7):\n\t\tprint(\"Invalid Json Input!\")\n\t\texit()\n\t#positioning first queen at start th coloumn\n\tboard[0][data[\"start\"]] = 1\n\t#calling Solver \n\tif(NQueenSolver(board,1)):\n\t\tprint(\"Solution:\")\n\t\tPrintBoard(board)\n\telse:\n\t\tprint(\"No Solution Found!\")\n\n#calls main method\nmain()\n","sub_path":"EightQueens.py","file_name":"EightQueens.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"65274347","text":"from itertools import islice\nfrom typing import List, Tuple\n\nInterval = Tuple[int, int]\nIntervals = List[Interval]\n\n\ndef merge_two_interval(a: Interval, b: Interval) -> Intervals:\n \"\"\"\n a[0] <= b[0] 일때 a와 b를 합친 intervals\n \"\"\"\n if a[1] < b[0]:\n return [a, b]\n\n return [(a[0], max(a[1], b[1]))]\n\n\ndef merge(intervals: Intervals) -> Intervals:\n intervals.sort()\n result: Intervals = []\n before = intervals[0]\n\n for interval in islice(intervals, 1, None):\n *a, before = merge_two_interval(before, interval)\n result.extend(a)\n result.append(before)\n\n return result\n","sub_path":"p77/python/my_solution.py","file_name":"my_solution.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"284631236","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#import urllib2\nimport re\nimport requests\nimport urllib2\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nfrom anti_crawl import USER_AGENTS\nimport random\nfrom lxml import etree\n\n\nclass Video:\n name = ''\n item_url = ''\n openurl = ''\n author = ''\n\nclass Search:\n def __init__(self,keyword):\n self.keyword = keyword\n self.search_video()\n\n def Link_exists(self):\n request = urllib2.Request(self.url)\n request.get_method = lambda: 'HEAD'\n try:\n response = urllib2.urlopen(request)\n return True\n except:\n return False\n\n def search_video(self):\n self.res_list = []\n _searchurl = 'http://www.opclass.com/index.php/search/' + self.keyword\n user_agent = random.choice(USER_AGENTS)\n headers = { 'User-Agent' : user_agent }\n\n the_res = []\n #获取html\n # 用正则匹配结果的信息\n pattern = re.compile(\n '

.*?

', re.S)\n r = requests.get(_searchurl, timeout=20)\n items = re.findall(pattern, r.content)\n for info in items:\n video = Video()\n url = info.split('\"')[1]\n r = requests.get(url)\n tree = etree.HTML(r.content)\n video.openurl = url\n try:\n video.item_url= tree.xpath(\"//a[@rel='nofollow']/@href\")[2]\n except:\n video.item_url = 'No DownLink'\n video.name = tree.xpath(\"//div[@class='container']/h2\")[0].text.replace('-', '')\n video.author = tree.xpath(\"//a[@itemprop='name']\")[0].text\n the_res.append(video)\n self.res_list=the_res # 把获得的结果赋予到类的属性上,更方便之后调用\n return the_res\n\n if the_res == []:\n flash(u'未找到包含关键字\\\"' + self.keyword + u'\\\"的公开课')\n return the_res","sub_path":"app/core/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"365133540","text":"from PyQt4 import QtGui, QtCore, uic\nimport main\n\n\n\nclass Window(QtGui.QWidget):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n uic.loadUi('window/1.ui', self)\n\n self.size = self.geometry().height(), self.geometry().width()\n\n scene = QtGui.QGraphicsScene()\n scene.addPixmap(QtGui.QPixmap('test3.png'))\n self.graphicsView.setScene(scene)\n\n self.textEditFunction.textChanged.connect(self.update_image)\n\n self.spaceV.valueChanged.connect(self.update_image)\n self.spaceH.valueChanged.connect(self.update_image)\n self.widthBlock.valueChanged.connect(self.update_image)\n self.heightBlock.valueChanged.connect(self.update_image)\n\n self.rand.clicked.connect(self.random_func)\n\n self.funcZero.clicked.connect(lambda: self.insert('0'))\n self.funcOne.clicked.connect(lambda: self.insert('1'))\n self.funcInv.clicked.connect(lambda: self.insert('-'))\n self.funcPlus.clicked.connect(lambda: self.insert('+'))\n self.funcStar.clicked.connect(lambda: self.insert('*'))\n self.funcTild.clicked.connect(lambda: self.insert('~'))\n self.funcM2.clicked.connect(lambda: self.insert('o'))\n self.funcThen.clicked.connect(lambda: self.insert('>'))\n self.funcNotThen.clicked.connect(lambda: self.insert('/>'))\n self.funcShef.clicked.connect(lambda: self.insert('|'))\n self.funcPirs.clicked.connect(lambda: self.insert('v'))\n\n def insert(self, func):\n self.textEditFunction.insertPlainText(func)\n self.textEditFunction.setFocus()\n\n def random_func(self):\n self.textEditFunction.setText(main.rand())\n\n def update_image(self):\n fun = self.textEditFunction.toPlainText().lower()\n\n print('>' * 80 + fun)\n\n l = fun.count('(')\n r = fun.count(')')\n if l > r:\n self.info.setText('\"(\" больше \")\" на {}'.format(l - r))\n elif r > l:\n self.info.setText('\")\" больше \"(\" на {}'.format(r - l))\n else:\n print('MAIN: ', main.accumulator_of_height, main.alphabet)\n main.accumulator_of_height = []\n main.height_of_all = []\n print('MAIN: ', main.accumulator_of_height, main.alphabet)\n\n main.vertical_space = self.spaceV.value()\n main.horizontal_space = self.spaceH.value()\n\n main.height_block = self.heightBlock.value()\n main.width_block = self.widthBlock.value()\n\n t = main.Tree(fun, 0, 0, root=True)\n t.calc_position_of_blocks()\n t.reset_size_img()\n t.draw_tree(None)\n t.draw_connection()\n del t\n\n scene = QtGui.QGraphicsScene()\n scene.addPixmap(QtGui.QPixmap('test3.png'))\n self.graphicsView.setScene(scene)\n\n\nif __name__ == \"__main__\":\n import sys\n\n app = QtGui.QApplication(sys.argv)\n window = Window()\n window.show()\n app.exec()","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"210320262","text":"import os\nimport numpy as np\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport operator as o\nimport matplotlib.cm as cm\nfrom fibte.misc.colorPlotConfig import ColorPlotConfig\n\n\nclass AvgCompletionTimes(object):\n def __init__(self, test_folder='', to_plot='all', plot_name=''):\n # What to plot: mices/elephants, all?\n self.to_plot = to_plot\n\n # Extra folder where algo folders reside under\n if test_folder.split('/')[-1] != 'delay':\n self.test_folder = os.path.join(test_folder, 'delay')\n else:\n self.test_folder = os.path.join(test_folder)\n\n # Load them\n self.measurements = self.load_measurements()\n self.plot_name = plot_name\n\n # Get object for color config\n self.colorConfig = ColorPlotConfig()\n\n def load_measurements(self):\n \"\"\"\n \"\"\"\n # Get pattern folders\n pattern_to_dir = {d: os.path.join(self.test_folder, d) for d in os.listdir(self.test_folder)\n if os.path.isdir(os.path.join(self.test_folder, d))}\n measurements = {}\n for pattern, dir in pattern_to_dir.iteritems():\n algos_to_dir = {d: os.path.join(dir, d) for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))}\n measurements[pattern] = {}\n for algo, adir in algos_to_dir.iteritems():\n delays = self.read_delays(adir)\n\n # mice average\n mice = [delay['measured'] for delay in delays.itervalues() if delay['type'] == 'mice']\n if mice:\n mice_avg = np.asarray(mice).mean()\n else:\n mice_avg = 0\n\n nonbmice = [delay['expected'] for delay in delays.itervalues() if delay['type'] == 'mice']\n if nonbmice:\n nonbmice_avg = np.asarray(nonbmice).mean()\n else:\n nonbmice_avg = 0\n\n # elephant average\n elep = [delay['measured'] for delay in delays.itervalues() if delay['type'] != 'mice']\n if elep:\n eleph_avgs = np.asarray(elep).mean()\n else:\n eleph_avgs = 0\n\n # non blocking average\n nonbelep = [delay['expected'] for delay in delays.itervalues() if delay['type'] != 'mice']\n if nonbelep:\n nonbelep_avg = np.asarray(nonbelep).mean()\n else:\n nonbelep_avg = 0\n\n # add it into measuerements\n measurements[pattern][algo] = {'mice': mice_avg, 'elephant': eleph_avgs,\n 'non-blocking-elephant': nonbelep_avg,\n 'non-blocking-mice': nonbmice_avg}\n\n return measurements\n\n def read_delays(self, folder):\n \"\"\"Returns a dictionary keyed by measuring time, containing\n the link loads readouts for the aggregation core links at\n specified times.\n \"\"\"\n flows_to_delay = {}\n for flowfile in os.listdir(folder):\n fields = flowfile.split('_')\n if len(fields) == 5:\n (ftype, src, sport, dst, dport) = fields\n round = 0\n elif len(fields) == 6:\n (ftype, src, sport, dst, dport, round) = fields\n else:\n raise ValueError\n\n flow = (src, sport, dst, dport, round)\n with open(os.path.join(folder, flowfile), 'r') as f:\n expected = float(f.readline().strip('\\n').split(' ')[1])\n starttime_ms = float(f.readline().strip('\\n'))\n try:\n endtime_ms = float(f.readline().strip('\\n'))\n except:\n print(\"Found flow that couldn't be completely sent!\")\n continue\n else:\n flows_to_delay[flow] = {'type': ftype, 'expected': expected, 'measured': (endtime_ms - starttime_ms)/1000.0}\n\n return flows_to_delay\n\n\n def getMaxNonBlockingDelays(self, pattern):\n # Add ideal case for that pattern\n maxnbmice = max([adata['non-blocking-mice'] for algo, adata in self.measurements[pattern].iteritems()])\n maxnbelep = max([adata['non-blocking-elephant'] for algo, adata in self.measurements[pattern].iteritems()])\n return (maxnbelep, maxnbmice)\n\n def createMatrix(self, algo_list, pattern_list):\n # Create matrix from experiment data dictionary: (algo, pattern, value)\n matrix = []\n for pattern, pdata in self.measurements.iteritems():\n if pattern_list:\n if pattern in pattern_list:\n # Add ideal\n ideal_elep, ideal_mice = self.getMaxNonBlockingDelays(pattern)\n if self.to_plot == 'mice':\n matrix.append(['Ideal', pattern, ideal_mice])\n elif self.to_plot == 'elephant':\n matrix.append(['Ideal', pattern, ideal_elep])\n\n for algo, palgo in pdata.iteritems():\n if algo_list:\n if algo in algo_list:\n if self.to_plot in ['mice', 'elephant']:\n matrix.append([algo, pattern, palgo[self.to_plot]])\n\n elif self.to_plot == 'together':\n value = palgo.get('mice', 0) + palgo.get('elephant', 0)\n matrix.append([algo, pattern, value])\n else:\n if self.to_plot in ['mice', 'elephant']:\n matrix.append((algo, pattern, palgo[self.to_plot]))\n elif self.to_plot == 'together':\n value = palgo.get('mice', 0) + palgo.get('elephant', 0)\n matrix.append([algo, pattern, value])\n else:\n # Add ideal\n ideal_elep, ideal_mice = self.getMaxNonBlockingDelays(pattern)\n if self.to_plot == 'mice':\n matrix.append(['Ideal', pattern, ideal_mice])\n elif self.to_plot == 'elephant':\n matrix.append(['Ideal', pattern, ideal_elep])\n\n for algo, palgo in pdata.iteritems():\n if algo_list:\n if algo in algo_list:\n if self.to_plot in ['mice', 'elephant']:\n matrix.append([algo, pattern, palgo[self.to_plot]])\n\n elif self.to_plot == 'together':\n value = palgo.get('mice', 0) + palgo.get('elephant', 0)\n matrix.append([algo, pattern, value])\n else:\n if self.to_plot in ['mice', 'elephant']:\n matrix.append((algo, pattern, palgo[self.to_plot]))\n elif self.to_plot == 'together':\n value = palgo.get('mice', 0) + palgo.get('elephant', 0)\n matrix.append([algo, pattern, value])\n\n # Convert into np array\n matrix = np.asarray(matrix)\n return matrix\n\n def plotData(self, algo_list=[], pattern_list=[],):\n \"\"\"\"\"\"\n matrix = self.createMatrix(algo_list, pattern_list)\n\n # Start figure\n fig = plt.figure(figsize=(17.5, 7))\n\n # Set title\n # fig.suptitle(\"TCP total completion times\", fontsize=20, weight='bold')\n ax = plt.subplot(111)\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n ax.spines[\"bottom\"].set_linewidth(2.5)\n ax.spines[\"left\"].set_linewidth(2.5)\n\n ax.get_xaxis().tick_bottom()\n ax.get_yaxis().tick_left()\n # ax.set_xlabel(\"Traffic pattern\", size='x-large', weight='bold')\n ax.set_ylabel(\"Average delay [s]\", size='x-large', weight='bold')\n plt.tick_params(axis=\"both\", which=\"both\", bottom=\"on\", top=\"off\", labelbottom=\"on\", left=\"off\", right=\"off\",\n labelleft=\"on\")\n plt.xticks(fontsize=18, weight=\"bold\")\n plt.yticks(fontsize=18, weight=\"bold\")\n\n # Generate bar plot\n self._barplot(ax, matrix, log=False)\n\n # Set fontsize and weight of axis ticks\n plt.xticks(fontsize=16, weight=\"bold\")\n plt.yticks(fontsize=16, weight=\"bold\")\n\n add_bottom_legend = True\n if add_bottom_legend:\n # Add a legend\n handles, labels = ax.get_legend_handles_labels()\n\n # Put a legend below current axis\n ax.legend(handles[:], labels[:], loc='upper left', shadow=True, fontsize='x-large', ncol=len(matrix))\n\n plt.grid(True)\n ax.grid(zorder=4)\n plt.tight_layout()\n fig.subplots_adjust(left=0.08, right=0.97)\n if self.plot_name:\n filename = '{0}.pdf'.format(self.plot_name)\n else:\n filename = 'avgCompletionTimes.pdf'\n filename = os.path.join(self.test_folder, filename)\n plt.savefig(filename)\n print (\"*** Plot saved --> {0}\".format(filename))\n\n def _barplot(self, ax, matrix, log=False):\n '''\n Create a barchart for data across different patterns with\n multiple algos for each category.\n\n @param ax: The plotting axes from matplotlib.\n @param matrix: The data set as an (n, 3) numpy array\n '''\n # Aggregate the conditions and the categories according to their\n # mean values\n\n # Aggregate the algos and the patterns according to their mean values\n algos = [(c, np.mean(matrix[matrix[:, 0] == c][:, 2].astype(float))) for c in np.unique(matrix[:, 0])]\n patterns = [(c, np.mean(matrix[matrix[:, 1] == c][:, 2].astype(float))) for c in np.unique(matrix[:, 1])]\n\n # Sort the algos, patterns and data so that the bars in\n # the plot will be ordered by category and condition\n algos = [c[0] for c in sorted(algos, key=o.itemgetter(1))]\n patterns = [c[0] for c in sorted(patterns, key=o.itemgetter(1))]\n\n # Extract the completion time values\n matrix = np.array(sorted(matrix, key=lambda x: patterns.index(x[1])))\n\n # Set the space between each set of bars\n space = 0.2\n n = len(algos)\n width = (1 - space) / (len(algos))\n\n # Create a set of bars at each position\n for i, algo in enumerate(algos):\n indeces = range(1, len(patterns) + 1)\n vals = matrix[matrix[:, 0] == algo][:, 2].astype(np.float)\n pos = [j - (1 - space) / 2. + i * width for j in indeces]\n color = self.colorConfig.getColor(algo)\n\n if not log:\n ax.bar(pos, vals, width=width, label=algo, color=color, alpha=1, zorder=40, edgecolor=\"none\", linewidth=0)\n else:\n ax.bar(pos, vals, width=width, label=algo, color=color, alpha=1, zorder=40, log=1,\n edgecolor=\"none\", linewidth=0)\n\n # Set the x-axis tick labels to be equal to the patterns\n ax.set_xticks(indeces)\n ax.set_xticklabels(patterns)\n\n plt.setp(plt.xticks()[1], rotation=0)\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n\n # Declare expected arguments\n\n parser.add_argument('--algo_list', nargs='+', help='List of measurement files to compare', type=str, default=[])\n parser.add_argument('--pattern_list', nargs='+', help='List of measurement files to compare', type=str, default=[])\n parser.add_argument('--test_folder', help='Folder in which the experiment folders reside in', type=str, default='./results/delay/')\n parser.add_argument('--to_plot', choices=['elephant', 'mice', 'together'], help='What to plot', type=str, default='mice')\n parser.add_argument('--plot_name', help=\"Name of the final plot\", type=str, default='')\n\n # Parse arguments\n args = parser.parse_args()\n\n # Start object and load measurement files\n ac = AvgCompletionTimes(test_folder=args.test_folder, to_plot=args.to_plot, plot_name=args.plot_name)\n ac.plotData(args.algo_list, args.pattern_list)","sub_path":"fibte/monitoring/makeAvgDelays.py","file_name":"makeAvgDelays.py","file_ext":"py","file_size_in_byte":12334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"283650896","text":"import importlib\nfrom flask import Flask, request, Response\n\nfrom common import message, StoreItem\nimport stores\nfrom generic import generic_parser\n\napp = Flask(__name__)\nstore_list = {m: importlib.import_module('stores.'+m, 'stores') for m in stores.__all__}\nstore_list = {k: v for k, v in store_list.items() if all(hasattr(v, i) for i in ['pat', 'parse'])}\n\n\n@app.route('/')\ndef hello_world():\n url = request.args.get('url', '')\n\n if not url:\n # Respuesta predeterminada\n return message('Hello, rata!')\n\n # Iterar por los módulos específicos de tiendas\n for mod_name, store in store_list.items():\n if not store.pat.match(url):\n continue\n\n item = store.parse(url)\n if not isinstance(item, dict):\n return item\n\n return {\n 'item': item,\n 'store_module': mod_name,\n 'store_name': getattr(store, 'name', mod_name.title())\n }\n\n generic_result = generic_parser(url)\n if generic_result is None:\n return message(code='unsupported_url')\n else:\n if isinstance(generic_result, Response):\n return generic_result\n if isinstance(generic_result, StoreItem):\n generic_result = generic_result.asdict()\n\n return {\n 'item': generic_result,\n 'store_module': 'generic',\n 'store_name': 'Generic'\n }\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"52079726","text":"from django.urls import reverse\nfrom django.contrib.auth.models import User\n\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase, APIClient\n\nfrom users.models import Doctor, Patient, StarredQuestion\nfrom qa.models import Question, Answer, AnswerComment\n\n# Number of questions for test\n# Should be larger than PAGE_SIZE\nTEST_QUESTION_NUM = 20\n\n# Number of answers for test\nTEST_ANSWER_NUM = 5\n\n# Number of comments for test\nTEST_COMMENT_NUM = 10\n\n\nclass QuestionTests(APITestCase):\n \"\"\"Test suite for the question model.\"\"\"\n\n def setUp(self):\n \"\"\"Initialize several questions to play with.\"\"\"\n self.doctor_user = User.objects.create_user(username='doctor', password='test')\n self.doctor = Doctor.objects.create(user=self.doctor_user,\n name='test',\n department='GYN',\n hospital='test',\n start='2000-01-01',\n title='C',\n active=True)\n self.patient_user = User.objects.create_user(username='patient', password='test')\n self.patient = Patient.objects.create(user=self.patient_user)\n\n for _ in range(TEST_QUESTION_NUM):\n Question.objects.create(\n title='test',\n department='NEO',\n owner=self.patient,\n body='text'\n )\n\n self.client = APIClient()\n self.client.force_authenticate(user=self.patient_user)\n self.test_question = Question.objects.first()\n\n def test_get_question_list(self):\n \"\"\"Ensure we can get a list of questions.\"\"\"\n url = reverse('qa:question-list')\n response = self.client.get(url)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data['count'], TEST_QUESTION_NUM)\n\n # Test if pagination works\n self.assertNotEqual(response.data['next'], None)\n\n def test_get_question_by_id(self):\n \"\"\"Ensure we can get one single question by id.\"\"\"\n url = reverse('qa:question-detail', args=[self.test_question.id])\n response = self.client.get(url)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data['id'], self.test_question.id)\n\n def test_create_new_question(self):\n \"\"\"Ensure we can create a new question.\"\"\"\n url = reverse('qa:new-question')\n data = {\n 'title': 'new question',\n 'department': 'PNE',\n 'body': 'new',\n 'owner': self.patient.id,\n }\n response = self.client.post(url, data, format='json')\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertNotEqual(Question.objects.count(), TEST_QUESTION_NUM)\n\n def test_add_and_get_images(self):\n \"\"\"Ensure we can add images to a question and retrieve them.\"\"\"\n url = reverse('qa:question-add-image', args=[self.test_question.id])\n with open('test_img.jpg', 'rb') as fp:\n data = {'question': self.test_question.id, 'image': fp}\n response = self.client.post(url, data)\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertNotEqual(Question.objects.get(id=self.test_question.id).images.count(), 0)\n\n url = reverse('qa:question-image-list', args=[self.test_question.id])\n response = self.client.get(url)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertNotEqual(response.data, None)\n\n def test_update_question(self):\n \"\"\"Ensure we can edit an existed question.\"\"\"\n url = reverse('qa:question-detail', args=[self.test_question.id])\n new_data = {\n 'title': 'new question',\n 'department': 'NEO',\n 'owner': self.patient.id,\n 'body': 'new question body',\n }\n response = self.client.put(url, new_data, format='json')\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(Question.objects.get(id=self.test_question.id).title, new_data['title'])\n\n def test_delete_question(self):\n \"\"\"Ensure we can delete a question.\"\"\"\n url = reverse('qa:question-detail', args=[self.test_question.id])\n response = self.client.delete(url)\n\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n self.assertNotEqual(Question.objects.count(), TEST_QUESTION_NUM)\n\n def test_star_and_unstar_question(self):\n \"\"\"Ensure we can star a question.\"\"\"\n url = reverse('qa:question-star', args=[self.test_question.id])\n response = self.client.get(url)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertNotEqual(Question.objects.get(id=self.test_question.id).stars, 0)\n self.assertNotEqual(self.patient.starred_questions.count(), 0)\n\n # then we unstar the question\n url = reverse('qa:question-unstar', args=[self.test_question.id])\n response = self.client.get(url)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(Question.objects.get(id=self.test_question.id).stars, 0)\n self.assertEqual(self.patient.starred_questions.count(), 0)\n\n def test_pick_an_answer_for_a_question(self):\n \"\"\"Ensure we can pick a best answer to get the question solved.\"\"\"\n answer = Answer.objects.create(owner=self.doctor, question=self.test_question)\n url = reverse('qa:pick-answer', args=[self.test_question.id])\n data = {'pick': answer.id}\n response = self.client.post(url, data)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(Answer.objects.first().picked, True)\n self.assertEqual(Question.objects.get(id=self.test_question.id).solved, True)\n\n def test_get_all_starred_questions(self):\n \"\"\"Ensure we can get all of our starred questions.\"\"\"\n for question in Question.objects.all():\n StarredQuestion.objects.create(patient=self.patient, question=question)\n\n url = reverse('users:patient-starred-questions')\n response = self.client.get(url)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(len(response.data), TEST_QUESTION_NUM)\n\n\nclass AnswerTests(APITestCase):\n \"\"\"Test suite for the answer model.\"\"\"\n\n def setUp(self):\n self.doctor_user = User.objects.create_user(username='doctor', password='test')\n self.doctor = Doctor.objects.create(user=self.doctor_user,\n name='test',\n department='GYN',\n hospital='test',\n start='2000-01-01',\n title='C',\n active=True)\n self.patient_user = User.objects.create_user(username='patient', password='test')\n self.patient = Patient.objects.create(user=self.patient_user)\n self.question = Question.objects.create(owner=self.patient, title='test', department='GYN', body='test')\n\n for _ in range(TEST_ANSWER_NUM):\n Answer.objects.create(question=self.question, owner=self.doctor)\n\n self.client = APIClient()\n self.client.force_authenticate(user=self.doctor_user)\n self.test_answer = Answer.objects.first()\n\n def test_get_answer_list(self):\n \"\"\"Ensure we can get all answers of one question.\"\"\"\n url = reverse('qa:answer-list', args=[self.question.id])\n response = self.client.get(url)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data['count'], TEST_ANSWER_NUM)\n\n def test_get_answer_by_id(self):\n \"\"\"Ensure we can get an answer by id.\"\"\"\n url = reverse('qa:answer-detail', args=[self.test_answer.id])\n response = self.client.get(url)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n def test_update_answer(self):\n \"\"\"Ensure we can update an answer by id.\"\"\"\n url = reverse('qa:answer-detail', args=[self.test_answer.id])\n new_data = {\n 'question': self.question.id,\n 'owner': self.doctor.id,\n 'diagnosis': 'new_data',\n }\n response = self.client.put(url, new_data)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data['diagnosis'], new_data['diagnosis'])\n\n def test_create_new_answer(self):\n \"\"\"Ensure we can create a new answer.\"\"\"\n url = reverse('qa:new-answer', args=[self.question.id])\n data = {'question': self.question.id, 'owner': self.doctor.id}\n response = self.client.post(url, data, format='json')\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertNotEqual(Answer.objects.count(), TEST_ANSWER_NUM)\n self.assertNotEqual(Doctor.objects.first().patient_num, 0)\n\n def test_upvote_answer(self):\n \"\"\"Ensure we can upvote an answer.\"\"\"\n url = reverse('qa:answer-upvote', args=[self.test_answer.id])\n response = self.client.get(url)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertNotEqual(Answer.objects.get(id=self.test_answer.id).upvotes, 0)\n\n\nclass AnswerCommentTests(APITestCase):\n \"\"\"Test suite for the AnswerComment model.\"\"\"\n\n def setUp(self):\n self.doctor_user = User.objects.create_user(username='test_doctor', password='test')\n self.doctor = Doctor.objects.create(\n user=self.doctor_user,\n name='test_doctor',\n department='GYN',\n hospital='test',\n start='2000-01-01',\n title='A',\n active=True\n )\n\n self.patient_user = User.objects.create_user(username='test_patient', password='test')\n self.patient = Patient.objects.create(user=self.patient_user, name='test_patient')\n\n self.client = APIClient()\n\n self.question = Question.objects.create(\n title='test',\n department='NEO',\n owner=self.patient,\n body='test'\n )\n self.answer = Answer.objects.create(\n question=self.question,\n owner=self.doctor\n )\n\n for _ in range(TEST_COMMENT_NUM):\n AnswerComment.objects.create(answer=self.answer, replier=self.patient)\n\n def test_get_comment_list(self):\n \"\"\"Ensure we can get a list of comments of one answer.\"\"\"\n url = reverse('qa:answer-comments', args=[self.answer.id])\n self.client.force_authenticate(user=self.patient_user)\n response = self.client.get(url)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data['count'], TEST_COMMENT_NUM)\n\n def test_patient_can_add_new_comment(self):\n \"\"\"Ensure a patient can create a new comment to an answer.\"\"\"\n url = reverse('qa:answer-new-comment', args=[self.answer.id])\n data = {\n 'answer': self.answer.id,\n 'body': 'test',\n }\n self.client.force_authenticate(user=self.patient_user)\n response = self.client.post(url, data)\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertNotEqual(AnswerComment.objects.count(), TEST_COMMENT_NUM)\n\n def test_doctor_can_add_new_comment(self):\n \"\"\"Ensure a doctor can create a new comment to an answer.\"\"\"\n url = reverse('qa:answer-new-comment', args=[self.answer.id])\n data = {\n 'answer': self.answer.id,\n 'body': 'test',\n }\n self.client.force_authenticate(user=self.doctor_user)\n response = self.client.post(url, data)\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertNotEqual(AnswerComment.objects.count(), TEST_COMMENT_NUM)\n","sub_path":"qa/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":12149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"28944984","text":"\n\"\"\"\nauthor : Mohammad Arman\ndate : 15/3/19\n\"\"\"\n# importing the libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.svm import SVR\n# for feature scaling\nfrom sklearn.preprocessing import StandardScaler\n# importing the dataset\ndataset = pd.read_csv('Position_Salaries.csv')\nX = dataset.iloc[:, 1:2].values\nY = dataset.iloc[:, 2].values\n\n# feature scaling\nsc_X = StandardScaler()\nsc_Y = StandardScaler()\nX = sc_X.fit_transform(X)\nY = sc_Y.fit_transform(Y.reshape(-1,1))\n\n\n# fitting svr to the dataset\nregressor = SVR(kernel='rbf')\nregressor.fit(X, Y)\n\n# predicting new result\nY_pred = sc_Y.inverse_transform(regressor.predict(sc_X.transform(np.array([[6.5]]))))\nprint(Y_pred)\n\n# visualising SVR result\nplt.scatter(X,Y, color='red',marker='x')\nplt.plot(X, regressor.predict(X), color='blue')\nplt.title('SVR')\nplt.xlabel(\"position level\")\nplt.ylabel(\"salary\")\nplt.show()\n\n\n# higer resolution curve\nX_grid = np.arange(min(X), max(X), 0.01)\nX_grid = X_grid.reshape((len(X_grid),1))\nplt.scatter(X,Y, color='red')\nplt.plot(X_grid, regressor.predict(X_grid), color='blue')\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#","sub_path":"2.linear_regression/svr.py","file_name":"svr.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"467724690","text":"#!/usr/bin/env python3\n\n# --------------------------------------------\n# Author: flyer \n# Date: 2015/03/11 20:41:37\n# --------------------------------------------\n\n\"\"\"Wrap the connetion operation to redis.\n\"\"\"\n\nimport redis\n\n\nclass Wrapper(object):\n \"\"\"\"\"\"\n instances = {}\n\n @staticmethod\n def client(host='localhost', port=6379, db=0, **kwargs):\n kwargs.update({'host': host, 'port': port, 'db': db})\n key = tuple(sorted(kwargs.items()))\n if not Wrapper.instances.get(key):\n pool_max_connections = kwargs.get('pool_max_connections', 3)\n redis_operation_timeout_sec = kwargs.get('redis_operation_timeout_sec', 10)\n error_pool_full_wait_sec = kwargs.get('error_pool_full_wait_sec', 0.1)\n error_hard_retry_limit = kwargs.get('error_hard_retry_limit', 100)\n error_server_full_wait_sec = kwargs.get('error_server_full_wait_sec', 2)\n error_host_unknown_wait_sec = kwargs.get('error_host_unknown_wait_sec', 20)\n error_server_port_dead_wait_sec = kwargs.get('error_port_dead_wait_sec', 5)\n\n conn_pool_args = (host, port, db)\n redis_conn_pool = redis.ConnectionPool(host=host,\n port=port,\n db=db,\n retry_on_timeout=True,\n socket_timeout=redis_operation_timeout_sec,\n max_connections=pool_max_connections)\n Wrapper.instances[key] = redis.StrictRedis(connection_pool=redis_conn_pool)\n \n return Wrapper.instances[key]\n \n\nif __name__ == '__main__':\n import sys\n \n rdb_0 = Wrapper.client()\n rdb_1 = Wrapper.client(db=0)\n rdb_2 = Wrapper.client(db=1)\n print('rdb0: {0}, rdb1: {1}, rdb2: {2}'.format(id(rdb_0), id(rdb_1), id(rdb_2)))\n\n print('before set key \"name\", value: '.format(rdb_0.get('name')))\n print('set key \"name\" to \"flyer\"')\n rdb_0.set('name', 'flyer')\n print('after set, the value of key \"name\" is ',format(rdb_0.get('name').decode('utf-8')))\n rdb_0.delete('name')\n","sub_path":"rediswrapper.py","file_name":"rediswrapper.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"251516908","text":"#coding=utf-8\r\n\r\nfrom PIL import Image,ImageDraw,ImageFont,ImageFilter\r\nimport random\r\nimport math\r\nimport StringIO\r\n\r\nfrom users.models import *\r\n\r\n#--------session 处理--------\r\ndef setSession(request,user):\r\n Sessionkey = \"user_session_key\"\r\n user.set_login()\r\n if Sessionkey in request.session:\r\n if request.session[Sessionkey] != user.id:\r\n request.session.flush()\r\n request.session[Sessionkey] = user.id\r\n\r\ndef getSession(request):\r\n Sessionkey = \"user_session_key\"\r\n if Sessionkey not in request.session:\r\n return Anonymouse()\r\n else:\r\n username = request.session[Sessionkey]\r\n return User.objects.get(id=username)\r\n\r\ndef delSession(request):\r\n Sessionkey = \"user_session_key\"\r\n user = getSession(request)\r\n user.set_logout()\r\n del request.session[Sessionkey]\r\n\r\nclass captcha(object):\r\n def __init__(self,size=(160,60),font_size=40):\r\n '''\r\n @todo: 生成验证码图片\r\n @param size: 图片的大小,格式(宽,高),默认为(120, 30)\r\n @param chars: 允许的字符集合,格式字符串\r\n @param img_type: 图片保存的格式,默认为GIF,可选的为GIF,JPEG,TIFF,PNG\r\n @param mode: 图片模式,默认为RGB\r\n @param bg_color: 背景颜色,默认为白色\r\n @param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF\r\n @param font_size: 验证码字体大小\r\n @param font_type: 验证码字体,默认为 ae_AlArabiya.ttf\r\n @param mix: 重合像素大小\r\n @param length: 验证码字符个数\r\n @param draw_lines: 是否划干扰线\r\n @param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有\r\n 效\r\n @param draw_points: 是否画干扰点\r\n @param point_chance: 干扰点出现的概率,大小范围[0, 100]\r\n @return: [0]: PIL Image实例\r\n @return: [1]: 验证码图片中的字符串\r\n '''\r\n self.size = size\r\n self.width = size[0]\r\n self.height = size[1]\r\n self.img_type = \"GIF\"\r\n self.mode = \"RGBA\"\r\n self.bg_color = (255,255,255)\r\n self.fg_color = (71,101,160)\r\n self.font_type = \"monaco.ttf\"\r\n self.font_size = font_size\r\n self.mix = 15\r\n self.length = 4\r\n self.draw_lines = True\r\n self.n_line = (2,4)\r\n self.draw_points = True\r\n self.point_chance = 20\r\n self.font = ImageFont.truetype(self.font_type, self.font_size)\r\n _letter_cases = \"abcdefghjkmnpqrstuvwxy\" # 小写字母,去除可能干扰的i,l,o,z\r\n _upper_cases = _letter_cases.upper() # 大写字母\r\n _numbers = ''.join(map(str, range(1, 10))) # 数字\r\n self.chars = ''.join(( _upper_cases, _numbers))\r\n\r\n def __rndColor(self):\r\n '''\r\n 生成随机背景颜色\r\n '''\r\n return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))\r\n\r\n def __rndColor2(self):\r\n '''\r\n 生成随机前景颜色\r\n '''\r\n return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))\r\n\r\n def rotate(self):\r\n rot = self.img.rotate(random.randint(-5,5),expand=0)\r\n default_bg = Image.new(\"RGBA\",self.size,self.bg_color)\r\n self.img = Image.composite(rot,default_bg,rot)\r\n #重建画布后,需要重建画笔\r\n self.draw = ImageDraw.Draw(self.img)\r\n\r\n def create_oval(self, h=0, k=0):\r\n '''\r\n 画椭圆,生成曲线(提供中心点坐标,默认原点)\r\n '''\r\n a = random.randint(40,self.width/2)\r\n b = random.randint(10,self.height/2)\r\n color = self.__rndColor2()\r\n for t in range(-180,180):\r\n rad = math.pi*t/180\r\n x = h + a * math.cos(rad)\r\n y = k + a * math.sin(rad)\r\n self.draw.point((x,y), fill=color)\r\n\r\n def create_lines(self):\r\n '''\r\n 绘制干扰线\r\n '''\r\n line_num = random.randint(self.n_line[0],self.n_line[1]) # 干扰线条数\r\n for i in range(line_num):\r\n\r\n #起始点(横向/纵向)\r\n begin1 = (random.randint(0, self.width / 5), random.randint(0, self.height))\r\n begin2 = (random.randint(0, self.width), random.randint(0, self.height/5))\r\n\r\n #结束点(横向/纵向)\r\n end1 = (random.randint(self.width*4/5, self.width), random.randint(0, self.height))\r\n end2 = (random.randint(0, self.width), random.randint(self.height*4/5, self.height))\r\n\r\n self.draw.line([begin1, end1], fill=self.__rndColor2(), width=1)\r\n self.draw.line([begin2, end2], fill=self.__rndColor2(), width=1)\r\n self.create_oval(random.randint(-self.width,self.width),random.randint(-self.height,self.height))\r\n\r\n def create_points(self):\r\n '''\r\n 绘制干扰点\r\n '''\r\n chance = min(100, max(0, int(self.point_chance))) # 大小限制在[0, 100]\r\n\r\n for w in xrange(self.width):\r\n for h in xrange(self.height):\r\n tmp = random.randint(0, 100)\r\n if tmp > 100 - chance:\r\n self.draw.point((w, h), fill=self.__rndColor())\r\n\r\n def create_strs(self):\r\n '''\r\n 绘制验证码字符\r\n 生成给定长度的字符串,返回列表格式\r\n '''\r\n c_chars = random.sample(self.chars, self.length)\r\n\r\n per_length = self.width/self.length\r\n count = 0\r\n for x in c_chars:\r\n w_tmp = count*per_length\r\n if count == 0:\r\n w = random.randint(w_tmp,w_tmp + self.mix)\r\n elif count == self.length:\r\n w = random.randint(w_tmp - self.mix, w_tmp)\r\n else:\r\n w = random.randint(w_tmp - self.mix, w_tmp + self.mix)\r\n h = (self.height - self.font_size)/4\r\n\r\n self.draw.text((w,h), x, font=self.font, fill=self.__rndColor2())\r\n self.rotate()\r\n\r\n count += 1\r\n \r\n self.strs = ''.join(c_chars)\r\n\r\n def gen_img(self):\r\n self.img = Image.new(self.mode, self.size, self.bg_color) #创建图形\r\n self.draw = ImageDraw.Draw(self.img) #创建画笔\r\n self.create_strs() \r\n if self.draw_points:\r\n self.create_points()\r\n if self.draw_lines:\r\n self.create_lines()\r\n \r\n # 图形扭曲参数\r\n params = [1 - float(random.randint(1, 2)) / 100,\r\n 0,\r\n 0,\r\n 0,\r\n 1 - float(random.randint(1, 10)) / 100,\r\n float(random.randint(1, 2)) / 500,\r\n 0.001,\r\n float(random.randint(1, 2)) / 500\r\n ]\r\n\r\n self.img = self.img.filter(ImageFilter.DETAIL) # 滤镜,边界加强(阈值更大)\r\n","sub_path":"website/users/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":6928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"521138302","text":"\"\"\" \nCanada has three national holidays which fall on the same dates each year.\nWrite a program that reads a month and day from the user. If the month and day match one of the holidays listed previously then your program should display the holiday’s name. Otherwise your program should indicate that the entered month and day do not correspond to a fixed-date holiday.\nCanada has two additional national holidays, Good Friday and Labour Day, whose dates vary from year to year. There are also numerous provincial and territorial holidays, some of which have fixed dates, and some of which have variable dates. We will not consider any of these additional holidays in this exercise.\n\"\"\"\n\nday = int(input('Insert day: '))\nmonth = input('Insert month: ')\n\nif day==1 and month =='January':\n holiday = 'New Year’s Day'\nelif day== 1 and month=='July':\n holiday= 'Canada Day'\nelif day== 25 and month=='December':\n holiday = 'Christmas Day' \nelse:\n holiday=''\nif holiday:\n print('The day ' + str(day) + ' ' + month + ' is ' + holiday)\nelse:\n print ('The day ' + str(day) + ' ' + month +' do not correspond to a fixed-date holiday')\n\n","sub_path":"The-Python-Workbook/2-Decision-Making/exercise45.py","file_name":"exercise45.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"167487867","text":"# -*- coding:utf-8 -*-\n'''\n@Author:\n\n@Date: \n\n@Description:\n \n'''\n\nimport pandas as pd\nimport numpy as np\nimport lightgbm as lgb\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import f1_score\n\n\ndef lgb_f1_score(y_hat, data):\n y_true = data.get_label()\n y_hat = np.round(y_hat) # scikits f1 doesn't like probabilities\n return 'f1', f1_score(y_true, y_hat), True\n\n\ndef lgb_f1_score_sk(y_hat, y_true):\n y_true = np.round(y_true)\n y_hat = np.round(y_hat) # scikits f1 doesn't like probabilities\n return 'f1', f1_score(y_true, y_hat), True\n\n\n'''\nInitial Configuration\n'''\npd.set_option('display.expand_frame_repr', False)\n\n'''\nData reading.\n'''\ntrain_data = pd.read_table('../data/oppo_round1_train_20180929.txt',\n names=['prefix', 'query_prediction', 'title', 'tag', 'label'],\n header=None, encoding='utf-8').astype(str)\nval_data = pd.read_table('../data/oppo_round1_vali_20180929.txt',\n names=['prefix', 'query_prediction', 'title', 'tag', 'label'],\n header=None, encoding='utf-8').astype(str)\ntest_data = pd.read_table('../data/oppo_round1_test_A_20180929.txt',\n names=['prefix', 'query_prediction', 'title', 'tag'],\n header=None, encoding='utf-8').astype(str)\n\n'''\nData preprocessing (clearing)\n'''\n\ntrain_data = train_data[train_data['label'] != '音乐']\n# train_data = pd.concat([train_data,val_data.copy()])\ntrain_data['label'] = train_data['label'].apply(lambda x: int(x))\nval_data['label'] = val_data['label'].apply(lambda x: int(x))\n# test_data['label'] = test_data['label'].apply(lambda x: int(x))\n\n\n'''\nFeature Enginnering\n'''\n\n# statistic features\nitems = ['prefix', 'title', 'tag']\ntemp = train_data.groupby(items, as_index=False)['label'].agg(\n {'_'.join(items) + '_click': 'sum', '_'.join(items) + '_count': 'count'})\ntemp['_'.join(items) + '_ctr'] = temp['_'.join(items) + '_click'] / (temp['_'.join(items) + '_count'])\ntrain_data = pd.merge(train_data, temp, on=items, how='left')\nval_data = pd.merge(val_data, temp, on=items, how='left')\ntest_data = pd.merge(test_data, temp, on=items, how='left')\n\nfor item in items:\n temp = train_data.groupby(item, as_index=False)['label'].agg({item + '_click': 'sum', item + '_count': 'count'})\n temp[item + '_ctr'] = temp[item + '_click'] / (temp[item + '_count'])\n train_data = pd.merge(train_data, temp, on=item, how='left')\n val_data = pd.merge(val_data, temp, on=item, how='left')\n test_data = pd.merge(test_data, temp, on=item, how='left')\n\nfor i in range(len(items)):\n for j in range(i + 1, len(items)):\n item_g = [items[i], items[j]]\n temp = train_data.groupby(item_g, as_index=False)['label'].agg(\n {'_'.join(item_g) + '_click': 'sum', '_'.join(item_g) + '_count': 'count'})\n temp['_'.join(item_g) + '_ctr'] = temp['_'.join(item_g) + '_click'] / (temp['_'.join(item_g) + '_count'])\n train_data = pd.merge(train_data, temp, on=item_g, how='left')\n val_data = pd.merge(val_data, temp, on=item_g, how='left')\n test_data = pd.merge(test_data, temp, on=item_g, how='left')\n\n# dict similarity features 31 + 4\nnew_test_data = pd.read_csv('../data/test_31_3.csv')\nnew_train_data = pd.read_csv('../data/train_31_3.csv')\nnew_val_data = pd.read_csv('../data/val_31_3.csv')\ntrain_data = pd.concat([train_data, new_train_data], axis=1)\ntest_data = pd.concat([test_data, new_test_data], axis=1)\nval_data = pd.concat([val_data, new_val_data], axis=1)\n\ntrain_data_ = train_data.drop(['prefix', 'query_prediction', 'title', 'tag'], axis=1)\nval_data_ = val_data.drop(['prefix', 'query_prediction', 'title', 'tag'], axis=1)\ntest_data_ = test_data.drop(['prefix', 'query_prediction', 'title', 'tag'], axis=1)\n\n'''\nTraining\n'''\n\n# Label Split\nX_train_data_ = np.array(train_data_.drop(['label'], axis=1))\ny_train_data_ = np.array(train_data_['label'])\nX_val_data_ = np.array(val_data_.drop(['label'], axis=1))\ny_val_data_ = np.array(val_data_['label'])\nX_test_data = test_data_\n\n# Data inspecting\nprint('train beginning')\nprint('================================')\n\nprint('-Training- : ')\nprint(X_train_data_.shape)\nprint(y_train_data_.shape)\n\nprint('-Training- : ')\nprint(X_val_data_.shape)\nprint(y_val_data_.shape)\n\nprint('-Testing- : ')\nprint(X_test_data.shape)\nprint('================================')\n\n# Algorithm: LightGBM\nN = 5\nskf = StratifiedKFold(n_splits=N, random_state=42, shuffle=True)\nxx_logloss = []\nxx_submit = []\nvalid_f1 = []\nLGBM_classify = lgb.LGBMClassifier(boosting_type='gbdt', objective='huber', num_leaves=32,\n learning_rate=0.05, subsample_freq=5, n_estimators=5000, silent=True)\n\nfor k, (train_loc, test_loc) in enumerate(skf.split(X_val_data_, y_val_data_)):\n print('train _K_ flod', k)\n X_train_combine = np.vstack([X_train_data_, X_val_data_[train_loc]])\n Y_train_combine = np.hstack([y_train_data_, y_val_data_[train_loc]])\n\n LGBM_classify.fit(X_train_combine, Y_train_combine,\n eval_set=(X_val_data_[test_loc], y_val_data_[test_loc]),\n early_stopping_rounds=60, eval_sample_weight=None, eval_metric=lgb_f1_score_sk)\n xx_logloss.append(LGBM_classify._best_score['valid_0']['f1'])\n xx_submit.append(LGBM_classify.predict_proba(X_test_data, num_iteration=LGBM_classify.best_iteration_))\n valid_f1.append(f1_score(y_val_data_, LGBM_classify.predict(X_val_data_)))\nprint('\\n\\nEventually score (f1):', np.mean(xx_logloss))\nprint('Validation Score (f1):', valid_f1, '. Mean: ', np.mean(valid_f1))\n\n'''\nSave result\n'''\ns = 0\nfor i in xx_submit:\n s = s + i\ntest_data_['pred_label'] = list(s[:, 1] / N) # 二元分类中,概率分布对应了- 0,1 -\ntest_data_['pred_label'] = test_data_['pred_label'].apply(lambda x: round(x))\ntest_data_['pred_label'].to_csv('../data/Result_LLC_1016_pre '+str(np.mean(valid_f1))+'.csv', index=False)\n","sub_path":"Model_1016_Yang.py","file_name":"Model_1016_Yang.py","file_ext":"py","file_size_in_byte":5976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"629031556","text":"import logging\nimport time\n\nclass FilteringClearer(object):\n\n \"\"\"Clear ALMemory keys relative to the test\"\"\"\n\n def __init__(self, mem, key_list):\n self.mem = mem\n self.key_list = key_list\n\n def _wait_to_clearall(self):\n \"\"\"\n If global test state is pass or fail, we wait until operator push\n FINISH or CLEAR_ERROR button\n \"\"\"\n if self.mem.getData(\"FilteringTest/Data/GlobalTestState\") == \"pass\":\n logging.info(\"Waiting for operator to push Finish button\")\n while self.mem.getData(\"FilteringTest/Button/Finish\") != 1:\n time.sleep(0.5)\n elif self.mem.getData(\"FilteringTest/Data/GlobalTestState\") == \"fail\":\n logging.info(\"Waiting for operator to push Clear Error button\")\n while self.mem.getData(\"FilteringTest/Button/ClearError\") != 1:\n time.sleep(0.5)\n\n def clear_all(self):\n \"\"\"Clear ALMemory keys created for the test\"\"\"\n self._wait_to_clearall()\n time.sleep(2.0)\n\n logging.info(\"Removing ALMemory keys concerning Filtering Test\")\n\n for key in self.key_list:\n try:\n logging.debug(\"Removing key : %s\", key)\n self.mem.removeData(key)\n except BaseException:\n logging.warning(\"Could not clear %s\", key)\n","sub_path":"src/utils/clear.py","file_name":"clear.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"539209583","text":"#!/usr/bin/env python\n# __author__ = \"Ronie Martinez\"\n# __copyright__ = \"Copyright 2018, Ronie Martinez\"\n# __credits__ = [\"Ronie Martinez\"]\n# __maintainer__ = \"Ronie Martinez\"\n# __email__ = \"ronmarti18@gmail.com\"\n# __status__ = \"Production\"\ntry:\n from collections.abc import Iterator\nexcept ImportError:\n from collections import Iterator\nfrom datetime import datetime, timedelta\n\nimport doccron\nfrom doccron.job import Job\n\n\ndef test_iter_cron_table():\n cron = iter(doccron.cron_quartz('* * * * * *'))\n assert isinstance(cron, Iterator)\n\n\ndef test_iter_job():\n job = iter(Job(['*'] * 6, quartz=True))\n assert isinstance(job, Iterator)\n\n\ndef test_not_repeated():\n cron = doccron.cron_quartz('* * * * * *\\n* * * * * *')\n first = next(cron)\n second = next(cron)\n assert first < second\n\n\ndef test_schedule_per_second():\n cron = doccron.cron_quartz('* * * * * *')\n assert isinstance(cron, Iterator)\n\n next_schedule = next(cron)\n assert next_schedule > datetime.now().replace(microsecond=0)\n assert isinstance(next_schedule, datetime)\n for i in range(10):\n n = next(cron)\n assert isinstance(n, datetime)\n assert next_schedule + timedelta(seconds=1) == n\n next_schedule = n\n\n\ndef test_schedule_per_second_list():\n cron = doccron.cron_quartz('0,10,20,30,40,50 * * * * * *')\n assert isinstance(cron, Iterator)\n\n next_schedule = next(cron)\n assert next_schedule > datetime.now().replace(microsecond=0)\n assert isinstance(next_schedule, datetime)\n for i in range(0, 60, 10):\n n = next(cron)\n assert isinstance(n, datetime)\n assert next_schedule + timedelta(seconds=10) == n\n next_schedule = n\n\n\ndef test_schedule_per_second_range_step():\n cron = doccron.cron_quartz('0-59/10 * * * * * *')\n assert isinstance(cron, Iterator)\n\n next_schedule = next(cron)\n assert next_schedule > datetime.now().replace(microsecond=0)\n assert isinstance(next_schedule, datetime)\n for i in range(0, 60, 10):\n n = next(cron)\n assert isinstance(n, datetime)\n assert next_schedule + timedelta(seconds=10) == n\n next_schedule = n\n\n\ndef foo():\n \"\"\"\n /etc/crontab::\n\n * * * * * * 2021\n * * * * * * 2020\n \"\"\"\n print(\"foo\")\n\n\ndef test_find_functions_with_docstrings():\n run_count = 0\n jobs_found = False\n for next_schedule, function_object in doccron.run_jobs(quartz=True, simulate=True):\n assert isinstance(next_schedule, datetime)\n assert function_object.__name__ == 'foo'\n jobs_found = True\n run_count += 1\n if run_count == 5:\n break\n assert jobs_found\n","sub_path":"tests/test_quartz.py","file_name":"test_quartz.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"94719385","text":"import scrapy\nimport json\nfrom urllib.parse import urljoin\nfrom reuter.items import ReuterItem\n\ndef save_extract(d, key):\n try:\n extract = d[key]\n except KeyError:\n extract = None\n return extract\n\ndef load_json(file):\n with open('headers.json') as f:\n headers = json.load(f)\n return headers\n\n\nclass ProductsSpider(scrapy.Spider):\n name = \"reuter\"\n start_urls = [\n 'https://www.reuter.de/bad.html',\n 'https://www.reuter.de/kueche.html',\n 'https://www.reuter.de/heizung.html'\n ]\n allowed_domains = ['reuter.de']\n\n def parse(self, response):\n products = response.xpath(\n \"//*[contains(@class, 'c-product-tile')]/a/@href\").extract()\n for p in products:\n url = urljoin(response.url, p)\n yield scrapy.Request(url, callback=self.parse_product)\n\n for next_page in response.css('.c-ajax-pagination__control > a'):\n yield response.follow(next_page, self.parse)\n\n def parse_product(self, response):\n supplier = response.xpath(\n \"//*[contains(@class, 'medium-5 columns')]/a/img/@title\")\n supplier = supplier.extract_first()\n header = response.xpath(\n \"//*[contains(@class, 'o-product-detail-title')]/span/text()\")\n header = header.extract_first()\n price = response.xpath(\n \"//*[contains(@class, 'c-price-block__price-price')]/text()\")\n price = price.extract_first()\n val = response.xpath(\n \"//*[contains(@class, 'c-definition-list__value')]/text()\")\n val = val.extract()\n attr = response.xpath(\n \"//*[contains(@class, 'c-definition-list__attribute')]/text()\")\n attr = attr.extract()\n\n attribute = dict(zip(attr, val))\n\n product = ReuterItem()\n product['supplier'] = supplier\n product['header'] = header\n product['price'] = price\n product['attribute'] = attribute\n\n yield dict(product)\n\n ids = response.xpath(\n \"//*[contains(@qa-data, 'product-model--list')]/li/@data-value\")\n ids = ids.extract()\n\n for id in ids:\n headers = load_json('headers.json')\n referer = response.url\n headers['referer'] = referer\n\n url_link = urljoin(\"https://www.reuter.de/api/v1/product/\", id)\n\n yield scrapy.Request(url_link, method=\"GET\", headers=headers,\n callback=self.parse_json)\n\n\n def parse_json(self, response):\n js = json.loads(response.text)\n\n productConfig = js['databind']['productConfiguration']\n\n price = save_extract(productConfig, 'productPrice')\n supplier = save_extract(productConfig, 'manufacturerName')\n header = save_extract(productConfig, 'productName')\n\n attribute = {\"Artikelnummer:\": save_extract(productConfig,\n 'productModel'),\n \"Serie:\": save_extract(productConfig, 'series')}\n\n detailsTop = save_extract(productConfig, 'detailsTop')\n\n if detailsTop:\n for i, k in enumerate(detailsTop):\n attribute['key_{}'.format(i)] = detailsTop[k]['value']\n\n product = ReuterItem()\n product['supplier'] = supplier\n product['header'] = header\n product['price'] = price\n product['attribute'] = attribute\n\n yield dict(product)\n","sub_path":"reuter/reuter/spiders/parse_reuter.py","file_name":"parse_reuter.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"58708729","text":"# -*- coding: utf-8 -*-\r\nfrom core import scr\r\nfrom db import db_handler\r\nimport logging.config\r\nfrom conf import setting\r\n\r\n\r\ndef is_login(fn):\r\n def inner(*args, **kwargs):\r\n if scr.now_user['name']:\r\n res = fn(*args, **kwargs)\r\n else:\r\n print('您未登录,请登录')\r\n res = scr.login()\r\n return res\r\n \r\n return inner\r\n\r\n\r\ndef locked_user(name):\r\n user_dic = db_handler.select(name)\r\n if user_dic:\r\n user_dic['Locked'] = True\r\n db_handler.save(user_dic)\r\n # return True, '用户已被冻结'\r\n\r\n\r\ndef get_logger(name):\r\n logging.config.dictConfig(setting.LOGGING_DIC)\r\n logger = logging.getLogger(name)\r\n return logger\r\n","sub_path":"ATM+购物车/lib/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"654326502","text":"from office365.sharepoint.navigation.navigation_node import NavigationNode\nfrom office365.sharepoint.navigation.navigation_node_collection import NavigationNodeCollection\nfrom office365.sharepoint.navigation.navigation_node_creation_information import NavigationNodeCreationInformation\nfrom office365.sharepoint.navigation.navigation_service import NavigationService\nfrom tests.sharepoint.sharepoint_case import SPTestCase\n\n\nclass TestNavigation(SPTestCase):\n target_node = None # type: NavigationNode\n\n @classmethod\n def setUpClass(cls):\n super(TestNavigation, cls).setUpClass()\n cls.nav_svc = NavigationService(cls.client)\n\n def test_2_is_global_nav_enabled(self):\n # self.nav_svc.set_global_nav_enabled(True).execute_query()\n result = self.nav_svc.global_nav_enabled()\n self.nav_svc.execute_query()\n self.assertIsNotNone(result.value)\n\n def test_3_get_web_navigation(self):\n web_nav = self.client.web.navigation.expand([\"TopNavigationBar\"]).get().execute_query()\n self.assertIsNotNone(web_nav.resource_path)\n self.assertIsInstance(web_nav.top_navigation_bar, NavigationNodeCollection)\n\n def test_4_create_navigation_node(self):\n node_create_info = NavigationNodeCreationInformation(\"Technical documentation\",\n \"https://docs.microsoft.com/en-us/documentation/\", True)\n new_node = self.client.web.navigation.quick_launch.add(node_create_info).execute_query()\n self.assertIsNotNone(new_node.resource_path)\n self.__class__.target_node = new_node\n\n def test_5_get_navigation_node_by_id(self):\n node_id = self.__class__.target_node.properties.get('Id')\n existing_node = self.client.web.navigation.quick_launch.get_by_id(node_id).get().execute_query()\n self.assertIsNotNone(existing_node.resource_path)\n\n def test_6_get_navigation_node_by_index(self):\n existing_node = self.client.web.navigation.quick_launch.get_by_index(0).get().execute_query()\n self.assertIsNotNone(existing_node.resource_path)\n\n def test_7_delete_navigation_node(self):\n node_to_del = self.__class__.target_node\n node_to_del.delete_object().execute_query()\n\n\n # def test1_ensure_home_site(self):\n # result = self.client.site.is_valid_home_site()\n # self.client.execute_query()\n # self.assertIsInstance(result.value, bool)\n # if result.value is False:\n # result = self.client.site.set_as_home_site()\n # self.client.execute_query()\n # self.assertIsNotNone(result.value)\n\n # def test2_get_publishing_navigation_provider_type(self):\n # result = self.nav_svc.get_publishing_navigation_provider_type()\n # self.client.execute_query()\n # self.assertIsInstance(result.value, int)\n\n # def test3_global_nav(self):\n # result = self.nav_svc.global_nav()\n # self.client.execute_query()\n # self.assertIsNotNone(result)\n","sub_path":"tests/sharepoint/test_navigation.py","file_name":"test_navigation.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"5433369","text":"# -*- coding:utf-8 -*-\r\n\r\nimport os,time\r\nfrom multiprocessing import Process\r\n\r\n# 方式二:自定义Process的子类,重写run方法\r\nclass MyProcess(Process):\r\n def __init__(self):\r\n Process.__init__(self)\r\n\r\n def run(self):\r\n print(\"子进程开始>>> pid={0}\".format(self.pid))\r\n time.sleep(2)\r\n print(\"子进程终止\")\r\n\r\ndef main():\r\n print(\"主进程开始> pid={}\".format(os.getpid()))\r\n myp=MyProcess()\r\n myp.start()\r\n myp.join()\r\n print(\"主进程终止\")\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"08_应用主题/并发编程/进程/multiprocessing模块实现多进程(二).py","file_name":"multiprocessing模块实现多进程(二).py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"140900850","text":"#!/usr/bin/env python\nfrom __future__ import print_function, absolute_import, division\n\nfrom modules.multimodal import MultiModal\nfrom modules.ppo import PPO\n\nimport tensorflow as tf\nimport numpy as np\nimport yaml\nimport os\nimport datetime\nimport functools\nimport msgpack\nimport msgpack_numpy as m\nm.patch()\nfrom std_msgs.msg import String\nfrom candy.srv import Step, Value, UpdateWeights\nfrom tqdm import tqdm\nimport rospy\n\nimport sys\nif not (sys.version_info[0] < 3):\n print = functools.partial(print, flush=True)\n\nclass Machine(object):\n def __init__(self):\n\n args = self.get_args()\n self.args = args\n\n #Building Graph\n self.is_training = tf.placeholder(tf.bool, shape=(None), name='is_training')\n self.multimodal_train = MultiModal(False, args, 'multimodal', is_training=self.is_training, reuse=False)\n self.multimodal_test = MultiModal(True, args, 'multimodal', is_training=self.is_training, reuse=True)\n\n self.speed = tf.placeholder(tf.float32, shape=(args['batch_size'], 1), name='speed')\n self.test_speed = tf.placeholder(tf.float32, shape=(1, 1), name='test_speed')\n\n z = self.multimodal_train.mean\n test_z = self.multimodal_test.mean\n\n z = tf.concat([z[:,:15], self.speed], 1)\n test_z = tf.concat([test_z[:,:15], self.test_speed], 1)\n\n z = tf.clip_by_value(z, -5, 5)\n test_z = tf.clip_by_value(test_z, -5, 5)\n\n self.ppo = PPO(args, 'ppo', z=z, test_z=test_z, ent_coef=0.00000001, vf_coef=1, max_grad_norm=0.5)\n\n # self.test_vae_loss.inference()\n # z = self.c3d_encoder.inference()\n\n self.variable_restore_parts = [self.multimodal_train, self.multimodal_test, self.ppo]\n self.variable_save_optimize_parts = [self.multimodal_train, self.ppo]\n\n total_loss = self.multimodal_train.loss + 10 * self.ppo.loss\n\n tf.summary.scalar('total_loss', tf.reduce_mean(total_loss))\n\n # for var in tf.trainable_variables():\n # tf.summary.histogram(var.op.name, var)\n \n self.final_ops = []\n for part in self.variable_save_optimize_parts:\n self.final_ops.append(part.optimize(total_loss))\n self.final_ops = tf.group(self.final_ops)\n\n config = tf.ConfigProto(allow_soft_placement = True)\n config.gpu_options.allow_growth = True\n\n\n self.merged = tf.summary.merge_all()\n self.sess = tf.Session(config = config)\n self.writer = tf.summary.FileWriter('/tmp/logs/' + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'), self.sess.graph)\n\n with tf.Graph().as_default() as g:\n tf.Graph.finalize(g)\n self.sess.run(tf.global_variables_initializer())\n\n print('Restoring!')\n\n for part in self.variable_restore_parts:\n part.variable_restore(self.sess)\n\n print('Get_Params!')\n self.params = []\n for va in tf.trainable_variables():\n self.params.append(va)\n print(len(self.params), 'params in all!')\n\n print('Model Started!')\n\n def get_args(self):\n with open(os.path.join(sys.path[0], \"args.yaml\"), 'r') as f:\n try:\n t = yaml.load(f)\n return t\n except yaml.YAMLError as exc:\n print(exc)\n\n def step(self, obs, state):\n # mask = np.zeros(1)\n td_map = {self.ppo.act_model.S:state}\n\n td_map[self.multimodal_test.camera_left] = np.array([obs[0][0]])\n td_map[self.multimodal_test.camera_right] = np.array([obs[0][1]])\n td_map[self.multimodal_test.eye_left] = np.array([obs[0][2]])\n td_map[self.multimodal_test.eye_right] = np.array([obs[0][3]])\n td_map[self.multimodal_test.actions] = np.array([obs[2]])\n\n # td_map[self.test_raw_image] = np.array([obs[0][1]])\n # td_map[self.test_raw_image] = np.array([obs[0][2]])\n\n td_map[self.is_training] = False\n td_map[self.test_speed] = np.array([[obs[1]]]) # speed\n # td_map[self.test_steer] = np.array([[obs[2]]])\n\n return self.sess.run([self.ppo.act_model.a0, self.ppo.act_model.v0, self.ppo.act_model.snew, self.ppo.act_model.neglogp0, self.multimodal_test.loss], td_map)\n\n\n def value(self, obs, state, action):\n raise NotImplementedError\n # mask = np.zeros(1)\n # if len(np.array(action).shape) == 1:\n # action = [action]\n # td_map = {self.ppo.act_model.S:state, self.ppo.act_model.a_z: action}\n # td_map[self.test_raw_image] = np.array([obs[0]])\n # td_map[self.is_training] = False\n # td_map[self.test_speed] = np.array([[obs[1]]])\n # # td_map[self.test_steer] = np.array([[obs[2]]])\n\n # return self.sess.run([self.ppo.act_model.a_z, self.ppo.act_model.v0, self.ppo.act_model.snew, self.ppo.act_model.neglogpz, self.test_vae_loss.recon], td_map)\n \n def update_weights(self, mat):\n\n # for ind, _ in tqdm(enumerate(self.params)):\n # self.params[ind].load(mat[ind], self.sess)\n for part in self.variable_restore_parts:\n part.variable_restore(self.sess)\n\n print('Weights Updated!')\n\n\n def train(self, inputs, global_step):\n obs, actions, values, neglogpacs, rewards, vaerecons, states, std_actions, manual, future_obs = inputs\n\n values = np.squeeze(values, 1)\n neglogpacs = np.squeeze(neglogpacs, 1)\n actions = np.squeeze(actions, 1)\n\n # print(raw_image.shape)\n # print(speed.shape)\n\n advs = rewards - values\n advs = (advs - advs.mean()) / (advs.std() + 1e-5)\n\n td_map = {self.ppo.A:actions, self.ppo.ADV:advs, self.ppo.R:rewards, self.ppo.OLDNEGLOGPAC:neglogpacs, self.ppo.OLDVPRED:values}\n td_map[self.is_training] = True\n\n # mask = np.zeros(self.args['batch_size'])\n td_map[self.ppo.train_model.S] = np.squeeze(states, 1)\n # td_map[self.ppo.train_model.M] = mask\n\n td_map[self.ppo.std_action] = std_actions\n td_map[self.ppo.std_mask] = manual\n\n td_map[self.multimodal_train.camera_left] = np.array([ob[0][0] for ob in obs])\n td_map[self.multimodal_train.camera_right] = np.array([ob[0][1] for ob in obs])\n td_map[self.multimodal_train.eye_left] = np.array([ob[0][2] for ob in obs])\n td_map[self.multimodal_train.eye_right] = np.array([ob[0][3] for ob in obs])\n td_map[self.multimodal_train.actions] = np.array([ob[2] for ob in obs])\n\n td_map[self.multimodal_train.camera_left_future] = np.array([ob[0][0] for ob in future_obs])\n td_map[self.multimodal_train.camera_right_future] = np.array([ob[0][1] for ob in future_obs])\n td_map[self.multimodal_train.eye_left_future] = np.array([ob[0][2] for ob in future_obs])\n td_map[self.multimodal_train.eye_right_future] = np.array([ob[0][3] for ob in future_obs])\n td_map[self.multimodal_train.actions_future] = np.array([ob[2] for ob in future_obs])\n\n td_map[self.speed] = np.array([[ob[1]] for ob in obs])\n\n td_map[self.multimodal_test.camera_left] = np.array([obs[0][0][0]])\n td_map[self.multimodal_test.camera_right] = np.array([obs[0][0][1]])\n td_map[self.multimodal_test.eye_left] = np.array([obs[0][0][2]])\n td_map[self.multimodal_test.eye_right] = np.array([obs[0][0][3]])\n td_map[self.multimodal_test.actions] = np.array([obs[0][2]])\n td_map[self.test_speed] = np.array([[obs[0][1]]]) # speed\n\n # td_map[self.test_raw_image] = np.array([obs[0][1]])\n # td_map[self.test_raw_image] = np.array([obs[0][2]])\n\n\n summary, _ = self.sess.run([self.merged, self.final_ops], feed_dict=td_map)\n if global_step % 10 == 0:\n self.writer.add_summary(summary, global_step)\n\n\n def save(self):\n print('Start Saving')\n for part in self.variable_save_optimize_parts:\n part.save(self.sess)\n print('Saving Done.')","sub_path":"src/candy/src/machine.py","file_name":"machine.py","file_ext":"py","file_size_in_byte":7890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"154316852","text":"#!/usr/bin/env python3\n#\n# ABOUT\n# This script runs the full substra CI pipeline.\n# \"Gotta test them all!\" ™\n#\n# This script performs the following operations:\n# - Create a new GKE cluster\n# - Clone the repos:\n# - hlf-k8s\n# - substa-backend\n# - substra-tests\n# - substra-chaincode\n# - Build the docker images using Google Cloud Builds\n# - Deploy these images using skaffold\n# - Wait for the substra application stack to be up and ready (i.e. wait\n# for the substra-backend servers readiness probe)\n# - Run the full 'substra-tests' test suite\n# - Destroy the cluster\n#\n# AUTOMATIC CLUSTER DESTRUCTION\n# We ensure the GKE cluster always gets destroyed at the end of the execution\n# of this script.\n#\n# We use 2 mechanisms:\n# - When the script exits, we destroy the cluster as the final step. That's\n# the case even if the script exits with an error or with an interruption\n# (Ctrl+C). See `trap` command.\n# - In any other \"abrupt shutdown\" case (system shutdown, Travis build\n# canceled, etc), we use a daily scheduled task to destroy stale clusters\n# after 24h. See https://console.cloud.google.com/functions/details/us-central1/clean-substra-tests-ci-deployment\n#\n# USEFUL LINKS\n# - Travis build history: https://travis-ci.org/github/SubstraFoundation/substra-tests/builds\n# - Stale cluster deletion script:\n# https://console.cloud.google.com/functions/details/us-central1/clean-substra-tests-ci-deployment\nimport os\nimport time\nimport json\nimport shutil\nimport string\nimport random\nimport argparse\nimport subprocess\nimport sys\nimport yaml\nimport logging\n\nCLUSTER_NAME_ALLOWED_PREFIX = 'substra-tests'\nCLUSTER_NAME = ''\nPVC_VOLUME_NAME_PREFIX = ''\nCLUSTER_MACHINE_TYPE = 'n1-standard-8'\n\nCLUSTER_PROJECT = 'substra-208412'\n\n# Zone must be specific (e.g. \"europe-west1-b\" and not \"europe-west1\")\n# or else several kubernetes nodes will be created instead of just one,\n# which can lead to pod/volume affinity issues at runtime.\nCLUSTER_ZONE = 'europe-west4-a'\n\nSERVICE_ACCOUNT = 'substra-tests@substra-208412.iam.gserviceaccount.com'\nKEY_SERVICE_ACCOUNT = 'substra-208412-3be0df12d87a.json'\n\nSUBSTRA_TESTS_BRANCH = 'master'\nSUBSTRA_BRANCH = 'master'\nSUBSTRA_BACKEND_BRANCH = 'master'\nSUBSTRA_CHAINCODE_BRANCH = 'master'\nHLF_K8S_BRANCH = 'master'\n\nCHAINCODE_COMMIT = ''\n\nDIR = os.path.dirname(os.path.realpath(__file__))\nCHARTS_DIR = os.path.realpath(os.path.join(DIR, '../charts/'))\nKEYS_DIR = os.path.realpath(os.path.join(os.getenv('HOME'), '.local/'))\n\nKUBE_CONTEXT = ''\nRUN_TAG = ''.join(random.choice(string.ascii_letters + '0123456789') for _ in range(10))\nSOURCE_DIR = os.path.realpath(os.path.join(DIR, 'src', RUN_TAG))\n\nKANIKO_CACHE_TTL = '168h' # 1 week\n\nBACKEND_CELERY_CONCURRENCY = 4\n\nTESTS_CONCURRENCY = 5\nTESTS_FUTURE_TIMEOUT = 400\n\n\ndef call(cmd):\n print(f'+ {cmd}')\n return subprocess.check_call([cmd], shell=True)\n\n\ndef call_output(cmd, print_cmd=True):\n if print_cmd:\n print(f'+ {cmd}')\n return subprocess.check_output([cmd], shell=True, stderr=subprocess.STDOUT).decode().strip()\n\n\ndef cluster_name(value):\n \"\"\"\n Validate the --cluster-name argument\n The cluster name must start with 'substra-tests'.\n This is to ensure the cluster gets picked up by the stale cluster deletion script.\n \"\"\"\n\n if not value.startswith(CLUSTER_NAME_ALLOWED_PREFIX):\n raise argparse.ArgumentTypeError(\n f'Invalid cluster name \"{value}\". '\n f'The cluster name must start with \"{CLUSTER_NAME_ALLOWED_PREFIX}\".')\n\n if len(value) > 35:\n raise argparse.ArgumentTypeError(\n f'Invalid cluster name \"{value}\". '\n f'The cluster name must not be longer than 35 characters.')\n\n return value\n\n\ndef arg_parse():\n\n global KEYS_DIR\n global CLUSTER_MACHINE_TYPE\n global CLUSTER_NAME\n global PVC_VOLUME_NAME_PREFIX\n global SUBSTRA_TESTS_BRANCH\n global SUBSTRA_BRANCH\n global SUBSTRA_BACKEND_BRANCH\n global SUBSTRA_CHAINCODE_BRANCH\n global HLF_K8S_BRANCH\n global SUBSTRA_CHAINCODE_BRANCH\n global KANIKO_CACHE_TTL\n global BACKEND_CELERY_CONCURRENCY\n global TESTS_CONCURRENCY\n global TESTS_FUTURE_TIMEOUT\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--machine-type', type=str, default=CLUSTER_MACHINE_TYPE,\n help='The GKE machine type to use')\n parser.add_argument('-N', '--cluster-name', type=cluster_name, default=CLUSTER_NAME_ALLOWED_PREFIX,\n help='The prefix name if the GKE kubernetes cluster to create')\n parser.add_argument('-K', '--keys-directory', type=str, default=KEYS_DIR,\n help='The path to a folder containing the GKE service account credentials')\n parser.add_argument('--substra-tests', type=str, default=SUBSTRA_TESTS_BRANCH,\n help='substra-tests branch or tag', metavar='GIT_BRANCH')\n parser.add_argument('--substra', type=str, default=SUBSTRA_BRANCH,\n help='substra branch or tag', metavar='GIT_REF')\n parser.add_argument('--substra-backend', type=str, default=SUBSTRA_BACKEND_BRANCH,\n help='substra-backend branch or tag', metavar='GIT_BRANCH')\n parser.add_argument('--substra-chaincode', type=str, default=SUBSTRA_CHAINCODE_BRANCH,\n help='substra-chaincode branch or tag', metavar='GIT_BRANCH')\n parser.add_argument('--hlf-k8s', type=str, default=HLF_K8S_BRANCH,\n help='hlf-k8s branch or tag', metavar='GIT_BRANCH')\n parser.add_argument('--no-cache', action='store_true',\n help='Use this option to disable kaniko caching')\n parser.add_argument('--backend-celery-concurrency', type=int, default=BACKEND_CELERY_CONCURRENCY,\n help='The substra-backend worker task concurrency')\n parser.add_argument('--tests-concurrency', type=int, default=TESTS_CONCURRENCY,\n help='The number of parallel test runners')\n parser.add_argument('--tests-future-timeout', type=int, default=TESTS_FUTURE_TIMEOUT,\n help='In substra-tests, the number of seconds to wait for a training task to complete')\n\n args = vars(parser.parse_args())\n\n CLUSTER_NAME = args['cluster_name']\n # Add RUN_TAG to cluster name to make it non-deterministic in case of retry\n CLUSTER_NAME += f'-{RUN_TAG[:40-len(CLUSTER_NAME)-1]}'\n CLUSTER_NAME = CLUSTER_NAME.lower() # Make it lower for gcloud compatibility\n PVC_VOLUME_NAME_PREFIX = CLUSTER_NAME[:18] # Only the 18 first characters are taken into account\n\n CLUSTER_MACHINE_TYPE = args['machine_type']\n KEYS_DIR = args['keys_directory']\n SUBSTRA_TESTS_BRANCH = args['substra_tests']\n SUBSTRA_BRANCH = args['substra']\n SUBSTRA_BACKEND_BRANCH = args['substra_backend']\n SUBSTRA_CHAINCODE_BRANCH = args['substra_chaincode']\n HLF_K8S_BRANCH = args['hlf_k8s']\n BACKEND_CELERY_CONCURRENCY = args['backend_celery_concurrency']\n TESTS_CONCURRENCY = args['tests_concurrency']\n TESTS_FUTURE_TIMEOUT = args['tests_future_timeout']\n if args['no_cache']:\n KANIKO_CACHE_TTL = '-1h'\n\n print('💃💃💃\\n')\n print_args()\n\n\ndef print_args():\n print(\n f'CLUSTER_MACHINE_TYPE\\t\\t= {CLUSTER_MACHINE_TYPE}\\n'\n f'CLUSTER_NAME\\t\\t\\t= {CLUSTER_NAME}\\n'\n f'KEYS_DIR\\t\\t\\t= {KEYS_DIR}\\n'\n f'SUBSTRA_TESTS_BRANCH\\t\\t= {SUBSTRA_TESTS_BRANCH}\\n'\n f'SUBSTRA_BRANCH\\t\\t\\t= {SUBSTRA_BRANCH}\\n'\n f'SUBSTRA_BACKEND_BRANCH\\t\\t= {SUBSTRA_BACKEND_BRANCH}\\n'\n f'SUBSTRA_CHAINCODE_BRANCH\\t= {SUBSTRA_CHAINCODE_BRANCH}\\n'\n f'HLF_K8S_BRANCH\\t\\t\\t= {HLF_K8S_BRANCH}\\n'\n f'KANIKO_CACHE_TTL\\t\\t= {KANIKO_CACHE_TTL}\\n'\n f'BACKEND_CELERY_CONCURRENCY\\t= {BACKEND_CELERY_CONCURRENCY}\\n'\n f'TESTS_CONCURRENCY\\t\\t= {TESTS_CONCURRENCY}\\n'\n f'TESTS_FUTURE_TIMEOUT\\t\\t= {TESTS_FUTURE_TIMEOUT}\\n'\n )\n\n\ndef gcloud_login():\n print('# Log into Google Cloud')\n call(f'gcloud auth activate-service-account {SERVICE_ACCOUNT} --key-file={KEYS_DIR}/{KEY_SERVICE_ACCOUNT}')\n\n\ndef get_kube_context():\n global KUBE_CONTEXT\n\n old_ctx = None\n print('\\n# Fetch kubernetes context')\n\n try:\n if call_output('kubectl config get-contexts --no-headers'):\n old_ctx = call_output('kubectl config current-context')\n except Exception:\n pass\n\n call(f'gcloud container clusters get-credentials {CLUSTER_NAME} --zone {CLUSTER_ZONE} --project {CLUSTER_PROJECT}')\n\n if old_ctx is not None:\n call(f'kubectl config use-context {old_ctx}') # Restore old context\n\n KUBE_CONTEXT = f'gke_{CLUSTER_PROJECT}_{CLUSTER_ZONE}_{CLUSTER_NAME}'\n\n\ndef create_cluster_async():\n print('\\n# Create GKE cluster')\n cmd = f'gcloud container clusters create {CLUSTER_NAME} '\\\n f'--machine-type {CLUSTER_MACHINE_TYPE} '\\\n f'--service-account {SERVICE_ACCOUNT} '\\\n f'--num-nodes=1 '\\\n f'--zone={CLUSTER_ZONE} '\\\n f'--project={CLUSTER_PROJECT} '\\\n f'--enable-ip-alias '\\\n f'--no-enable-autoupgrade '\\\n f'--enable-network-policy '\\\n f'--async'\n call(cmd)\n\n\ndef delete_cluster():\n wait_for_cluster()\n print('# Delete cluster')\n cmd = f'yes | gcloud container clusters delete {CLUSTER_NAME} --zone ' \\\n f'{CLUSTER_ZONE} --project {CLUSTER_PROJECT} --quiet'\n call(cmd)\n\n\ndef delete_disks():\n try:\n filter = f'name~^gke-{PVC_VOLUME_NAME_PREFIX}-pvc-.* users~.* zone~{CLUSTER_ZONE}' # the filter AND is implicit\n cmd = f'gcloud compute disks list --project {CLUSTER_PROJECT} --format=\"table(name)\" --filter=\"{filter}\" '\\\n '| sed 1d'\n disks = call_output(cmd)\n disks = disks.replace(\"\\n\", \" \")\n if disks:\n call(f'gcloud compute disks delete --zone {CLUSTER_ZONE} --project {CLUSTER_PROJECT} --quiet {disks}')\n except Exception as ex:\n print('ERROR: Deletion of the GCP disks failed', ex)\n\n\ndef wait_for_cluster():\n print('# Waiting for GKE cluster to be ready ...', end='')\n\n while True:\n output = call_output(\n f'gcloud container clusters list --filter=\"name={CLUSTER_NAME}\" --project {CLUSTER_PROJECT}',\n print_cmd=False\n )\n\n try:\n status = output.split('\\n')[1].split(' ')[-1]\n if status not in ['RUNNING', 'PROVISIONING']:\n raise Exception(f'Unknown status {status}')\n except Exception as e:\n print('\\nFATAL: Error retrieving cluster status. Output was:')\n print(output)\n raise(e)\n\n if status == 'RUNNING':\n print('done.')\n break\n\n print('.', end='', flush=True)\n time.sleep(5)\n\n\ndef setup_helm():\n print('\\n# Setup Helm')\n call('helm repo add stable https://charts.helm.sh/stable')\n call('helm repo add owkin https://owkin.github.io/charts')\n call('helm repo add bitnami https://charts.bitnami.com/bitnami')\n\n\ndef clone_repos():\n\n global CHAINCODE_COMMIT\n\n if os.path.exists(SOURCE_DIR):\n shutil.rmtree(SOURCE_DIR)\n\n os.makedirs(SOURCE_DIR)\n\n print(f'\\n# Clone repos in {SOURCE_DIR}')\n commit_backend = clone_substra_backend()\n CHAINCODE_COMMIT = clone_substra_chaincode()\n commit_hlf = clone_hlf_k8s()\n commit_substra_tests = clone_substra_tests()\n commit_substra = get_remote_commit('https://github.com/SubstraFoundation/substra.git', SUBSTRA_BRANCH)\n\n print(\n f'\\nCommit hashes:\\n'\n f'- substra-backend: \\t{commit_backend}\\n'\n f'- substra-chaincode: \\t{CHAINCODE_COMMIT}\\n'\n f'- hlf-k8s: \\t\\t{commit_hlf}\\n'\n f'- substra-tests: \\t{commit_substra_tests}\\n'\n f'- substra: \\t\\t{commit_substra}\\n'\n )\n return [\n {'name': 'hlf-k8s',\n 'images': ['fabric-tools', 'fabric-ca-tools', 'fabric-peer'],\n 'commit': commit_hlf,\n 'branch': HLF_K8S_BRANCH},\n {'name': 'substra-backend',\n 'images': ['substra-backend'],\n 'commit': commit_backend,\n 'branch': SUBSTRA_BACKEND_BRANCH},\n {'name': 'substra-chaincode',\n 'images': ['substra-chaincode'],\n 'commit': CHAINCODE_COMMIT,\n 'branch': SUBSTRA_CHAINCODE_BRANCH},\n {'name': 'substra-tests',\n 'images': ['substra-tests'],\n 'commit': commit_substra_tests,\n 'branch': SUBSTRA_TESTS_BRANCH,\n 'substra_commit': commit_substra}\n ]\n\n\ndef get_remote_commit(url, branch):\n commit = call_output(f'git ls-remote --refs {url} {branch}')\n commits = commit.split('\\t')\n if len(commits) != 2:\n print(f'FATAL: On the repository {url}, the branch does not match one and only one commit: {commits}')\n raise Exception('Unable to get the right commit for the repository.')\n return commits[0]\n\n\ndef clone_repository(dirname, url, branch, commit=None):\n call(f'git clone -q --depth 1 {url} --branch \"{branch}\" {dirname}')\n\n if commit is None:\n try:\n commit = call_output(f'git --git-dir={dirname}/.git rev-parse origin/{branch}')\n except Exception:\n # It didn't work with a branch name. Try with a tag name.\n commit = call_output(f'git --git-dir={dirname}/.git rev-list {branch}')\n\n return commit\n\n\ndef clone_substra_backend():\n url = 'https://github.com/SubstraFoundation/substra-backend.git'\n return clone_repository(\n dirname=os.path.join(SOURCE_DIR, 'substra-backend'),\n url=url,\n branch=SUBSTRA_BACKEND_BRANCH\n )\n\n\ndef clone_substra_chaincode():\n url = 'https://github.com/SubstraFoundation/substra-chaincode.git'\n return clone_repository(\n dirname=os.path.join(SOURCE_DIR, 'substra-chaincode'),\n url=url,\n branch=SUBSTRA_CHAINCODE_BRANCH\n )\n\n\ndef clone_hlf_k8s():\n url = 'https://github.com/SubstraFoundation/hlf-k8s.git'\n return clone_repository(\n dirname=os.path.join(SOURCE_DIR, 'hlf-k8s'),\n url=url,\n branch=HLF_K8S_BRANCH\n )\n\n\ndef clone_substra_tests():\n url = 'https://github.com/SubstraFoundation/substra-tests.git'\n return clone_repository(\n dirname=os.path.join(SOURCE_DIR, 'substra-tests'),\n url=url,\n branch=SUBSTRA_TESTS_BRANCH\n )\n\n\ndef build_images(configs):\n tag = f'substra-tests-{RUN_TAG}'\n images = {}\n\n print('# Queue docker image builds')\n for config in configs:\n for image in config['images']:\n build_id = build_image(\n tag=tag,\n image=image,\n config=config\n )\n images[build_id] = image\n\n wait_for_builds(tag, images)\n\n\ndef build_image(tag, image, config):\n branch = config[\"branch\"]\n commit = config[\"commit\"]\n name = config[\"name\"]\n config_file = os.path.join(DIR, f'cloudbuild/{name}.yaml')\n\n extra_substitutions = ''\n if name == 'substra-tests':\n extra_substitutions = f',_SUBSTRA_GIT_COMMIT={config[\"substra_commit\"]}'\n\n cmd = f'gcloud builds submit '\\\n f'--config={config_file} '\\\n f'--no-source '\\\n f'--async '\\\n f'--project={CLUSTER_PROJECT} '\\\n f'--substitutions=_BUILD_TAG={tag},_IMAGE={image},_BRANCH={branch},_COMMIT={commit},'\\\n f'_KANIKO_CACHE_TTL={KANIKO_CACHE_TTL}{extra_substitutions}'\n\n output = call_output(cmd)\n print(output)\n\n build_id = output.split('\\n')[-1].split(' ')[0]\n\n return build_id\n\n\ndef wait_for_builds(tag, images):\n print('\\n# Waiting for builds to complete ...', end='')\n do_wait = True\n while do_wait:\n build_list = call_output(\n f'gcloud builds list --filter=\"tags={tag}\" --project={CLUSTER_PROJECT}',\n print_cmd=False\n )\n\n builds = build_list.split('\\n')[1:]\n\n num_builds = len(builds)\n num_success = build_list.count('SUCCESS')\n num_failed = build_list.count('TIMEOUT') + build_list.count('CANCELLED') + build_list.count('FAIL')\n\n do_wait = (num_builds != (num_success + num_failed))\n\n time.sleep(5)\n print('.', end='', flush=True)\n\n print('done.')\n\n if num_failed:\n print('FATAL: One or more builds failed. See logs for more details')\n for build in builds:\n if 'TIMEOUT' in build or 'CANCELLED' in build or 'FAIL' in build:\n build_id = build.split(' ')[0]\n image = images[build_id]\n print(f\"- [{image}]: \"\n f\"https://console.cloud.google.com/cloud-build/builds/{build_id}?project={CLUSTER_PROJECT}\")\n raise Exception('docker image build(s) failed.')\n\n\ndef deploy_all(configs):\n print('\\n# Deploy helm charts')\n\n for config in configs:\n # Chaincode does not need to be deployed\n if config['name'] == 'substra-chaincode':\n continue\n\n wait = config['name'] != 'hlf-k8s' # don't wait for hlf-k8s deployment to complete\n deploy(config, wait)\n\n\ndef deploy(config, wait=True):\n artifacts_file = create_build_artifacts(config)\n skaffold_file = patch_skaffold_file(config)\n\n path = os.path.dirname(skaffold_file)\n\n if config['name'] == 'hlf-k8s':\n call(f'KUBE_CONTEXT={KUBE_CONTEXT} {path}/examples/dev-secrets.sh create')\n\n call(f'cd {path} && skaffold deploy --kube-context={KUBE_CONTEXT} '\n f'-f=skaffold.yaml -a={artifacts_file} --status-check={\"true\" if wait else \"false\"}')\n\n\ndef create_build_artifacts(config):\n # Gcloud Build artifacts\n artifacts_file = os.path.join(SOURCE_DIR, config['name'], 'tags.json')\n\n with open(artifacts_file, 'w') as file:\n tags = {'builds': []}\n\n for image in config['images']:\n\n tag = f'eu.gcr.io/{CLUSTER_PROJECT}/{image}:ci-{config[\"commit\"]}'\n\n if image == 'substra-tests':\n tag += f'-{config[\"substra_commit\"]}'\n\n tags['builds'].append({\n 'imageName': f'substrafoundation/{image}',\n 'tag': tag\n })\n\n print(f'Created build artifact for {tag}')\n\n json.dump(tags, file)\n\n return artifacts_file\n\n\ndef patch_skaffold_file(config):\n\n skaffold_file = os.path.join(SOURCE_DIR, config['name'], 'skaffold.yaml')\n\n with open(skaffold_file) as file:\n data = yaml.load(file, Loader=yaml.FullLoader)\n\n values_files = []\n\n for r in data['deploy']['helm']['releases']:\n if r['chartPath'].startswith('charts/'):\n r['chartPath'] = os.path.join(SOURCE_DIR, config[\"name\"], r['chartPath'])\n if 'valuesFiles' in r:\n values_files.extend(r['valuesFiles'])\n\n with open(skaffold_file, 'w') as file:\n yaml.dump(data, file)\n\n for values_file in values_files:\n patch_values_file(config, os.path.join(SOURCE_DIR, config['name'], values_file))\n return skaffold_file\n\n\ndef patch_values_file(config, value_file):\n with open(value_file) as file:\n data = yaml.load(file, Loader=yaml.FullLoader)\n\n if config['name'] == 'substra-backend':\n data['celeryworker']['concurrency'] = BACKEND_CELERY_CONCURRENCY\n if config['name'] == 'hlf-k8s':\n if 'chaincodes' in data:\n data['chaincodes'][0]['image']['repository'] = \\\n f'eu.gcr.io/{CLUSTER_PROJECT}/substra-chaincode'\n data['chaincodes'][0]['image']['tag'] = f'ci-{CHAINCODE_COMMIT}'\n\n with open(value_file, 'w') as file:\n yaml.dump(data, file)\n\n\ndef run_tests():\n print('# Wait for the substra-tests pod to be ready')\n substra_tests_pod = call_output(\n f'kubectl --context {KUBE_CONTEXT} get pods -n substra-tests | grep substra-tests'\n ).split(' ')[0]\n\n try:\n call(f'kubectl --context {KUBE_CONTEXT} wait pod/{substra_tests_pod} '\n f'-n substra-tests --for=condition=ready --timeout=590s')\n except Exception:\n print('ERROR: Timeout while waiting for the substra-tests pod. '\n 'This means the `substra-backend-server` pods never reached the \"ready\" state.')\n\n print('\\n# Run tests')\n\n try:\n # Run the tests on the remote and local backend\n call(f'kubectl --context {KUBE_CONTEXT} exec {substra_tests_pod} -n substra-tests -- '\n f'env SUBSTRA_TESTS_FUTURE_TIMEOUT={TESTS_FUTURE_TIMEOUT} '\n f'make test-remote PARALLELISM={TESTS_CONCURRENCY}')\n return True\n except subprocess.CalledProcessError:\n print('FATAL: `make test-remote` completed with a non-zero exit code. Did some test(s) fail?')\n return False\n\n\ndef main():\n is_success = False\n arg_parse()\n\n try:\n gcloud_login()\n create_cluster_async()\n configs = clone_repos()\n build_images(configs)\n wait_for_cluster()\n get_kube_context()\n setup_helm()\n deploy_all(configs)\n is_success = run_tests()\n print(\"Completed test run:\")\n print_args()\n\n except Exception as e:\n print(f'FATAL: {e}')\n logging.exception(e)\n is_success = False\n\n finally:\n print('\\n# Perform final teardown')\n if os.path.exists(SOURCE_DIR):\n shutil.rmtree(SOURCE_DIR)\n delete_cluster()\n delete_disks()\n\n sys.exit(0 if is_success else 1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ci/run-ci.py","file_name":"run-ci.py","file_ext":"py","file_size_in_byte":21324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"502958160","text":"from file_handler import TAB\nfrom layout import *\nfrom html_converter import build_html_from_node\n\nfrom debugs import DEBUG_JSON_INTERIM\n\n\ndef isolate_layout_section(lines):\n layout_lines = []\n layout_switch = False\n string_switch = False\n string_line = ''\n for line in lines:\n if line in ['scripts():', 'scripts:', 'styles():', 'style:']:\n layout_switch = False\n if line in ['layout():', 'layout:']:\n layout_switch = True\n if layout_switch:\n if \"'''\" in line or '\"\"\"' in line:\n if string_switch:\n string_line += line.lstrip(TAB)\n layout_lines.append(string_line)\n string_line = ''\n else:\n string_line = line\n string_switch = not string_switch\n else:\n if string_switch:\n string_line += line.lstrip(TAB)\n else:\n layout_lines.append(line)\n return layout_lines\n\n\ndef build_level_list(lines):\n level_list = []\n tab_length = len(TAB)\n for line in lines:\n if len(line) == 0:\n continue\n\n level = 0\n while TAB in line[0:tab_length]:\n level += 1\n line = line[tab_length:]\n pair = line, level\n level_list.append(pair)\n return level_list\n\n\ndef process_layout(filename, file_as_lines, project_directory):\n print('Processing layouts section...')\n layout_selection = isolate_layout_section(file_as_lines)\n # print(layout_selection)\n level_list = build_level_list(layout_selection)\n # print(level_list)\n\n layout_tree = build_layout_tree(level_list)\n layout_json = dump_tree_as_json(layout_tree)\n print(layout_json)\n\n repair_tree_content(layout_tree)\n layout_json = dump_tree_as_json(layout_tree)\n new_filename = project_directory + '/' + filename.replace('src/', '').replace('.pypg', '')\n if DEBUG_HTML_JSON_INTERIM:\n dump_directory = new_filename + '.json'\n print(f'DEBUG: Printing JSON dump to \\\"{dump_directory}\\\"')\n with open(dump_directory, 'w+') as json_out:\n json_out.write(layout_json)\n json_out.close()\n\n html_str = build_html_from_node(layout_tree)\n html_filename = new_filename + '.html'\n print(f'Outputting HTML source to \\\"{html_filename}\\\"')\n with open(html_filename, 'w+') as html_out:\n html_out.write(html_str)\n html_out.close()\n\n print(f'Finished outputting HTML source to \\\"{html_filename}\\\"')\n\n","sub_path":"layout_handler.py","file_name":"layout_handler.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"578988502","text":"import copy\n# import keras\nfrom skimage.morphology import opening, closing\n\nfrom preprocessor import *\n\n\n\n# clf, pp = joblib.load('./models/digits_cls.pkl')\nmodel = keras.models.load_model('../models/double_digits_cnn_nonbinary')\nmodel_single = keras.models.load_model('../models/digits_cnn_new')\n\n\ndef extract_numbers(\n im,\n grayscale=False,\n thresh=30,\n invert=True,\n blue_thresh=False,\n binary_roi=False,\n separate_c=False,\n blur=0,\n contrast_inc=0,\n brightness_inc=0,\n opening_shape=None,\n closing_shape=None,\n dilation_size=0,\n erosion_size=0,\n should_deskew=False):\n\n print(\"Extracting...\")\n\n im_c = im.copy()\n\n # Convert to grayscale\n if grayscale:\n im_gray = cv2.cvtColor(im_c, cv2.COLOR_BGR2GRAY)\n else:\n # Just use blue channel\n im_gray = im_c.astype(np.uint8)[:, :, 2]\n\n # Invert the image (todo - use im_gray?)\n if invert:\n im_gray = (255 - im_gray)\n\n # Blue thresholding uses original image,\n # regular thresholding uses im_gray\n if blue_thresh:\n im_th = thresh_img(im, thresh, blue_thresh=True)\n else:\n im_th = thresh_img(im_gray, thresh, blue_thresh=False)\n\n # Opening / Closing (also for contours)\n if hasattr(opening_shape, 'shape'):\n im_th = opening(im_th, opening_shape)\n if hasattr(closing_shape, 'shape'):\n im_th = closing(im_th, closing_shape)\n\n # Apply all preprocessing\n im_gray = im_preprocessing(im_gray, blur, brightness_inc, contrast_inc, dilation_size, erosion_size)\n\n rects, ctrs = find_rects_ctrs(im_th)\n # Skip short artifacts\n ctrs = [c for i, c in enumerate(ctrs) if rects[i][3] > 10]\n rects = [r for i, r in enumerate(rects) if r[3] > 10]\n # Skip skinny artifacts\n ctrs = [c for i, c in enumerate(ctrs) if rects[i][2] > 2]\n rects = [r for i, r in enumerate(rects) if r[2] > 2]\n\n # Separate connected digits\n if separate_c:\n rects, ctrs = split_dbls(rects, ctrs, im_gray)\n\n # Sorted order bounding boxes\n sorted_rects, sorted_ctrs = sort_rects(zip(rects, ctrs))\n\n rois = []\n probs = []\n date_possibs = []\n cur_date_possibs = []\n prev_not_one_width = 99999\n prev_end_x = sorted_rects[0][0] + sorted_rects[0][2]\n prev_end_y = sorted_rects[0][1] + sorted_rects[0][3]\n\n # For each rectangular region,\n # extract the roi from the preprocessed image,\n # and predict the digit using classifier\n for i, rect in enumerate(sorted_rects):\n x_start = rect[0]\n y_start = rect[1]\n width = rect[2]\n height = rect[3]\n # Skip short artifacts\n if rect[3] < 10: continue\n # Skip long artifacts\n if rect[2] > 100: continue\n\n roi_pad = draw_roi(rect, i, sorted_ctrs, im_gray, binary_roi)\n\n # Create new date possib (for newlines)\n newline = True\n if abs(x_start - prev_end_x) < 80 and abs(y_start - prev_end_y) < 80:\n newline = False\n if newline:\n date_possibs += cur_date_possibs\n cur_date_possibs = []\n\n dbl = False\n # Differentiate single from connected digits\n if width > 1.2 * prev_not_one_width:\n dbl = True\n roi_resized = cv2.resize(roi_pad, (38, 28), interpolation=cv2.INTER_NEAREST)\n roi_cnn = np.expand_dims(roi_resized, axis=2)\n\n prob = model.predict_proba(np.array([roi_cnn]), verbose=0)\n dbl_nbr = np.argmax(prob)\n\n nbr_prob = prob[0]\n\n # copy the current possibs\n new_cur_date_possibs = copy.deepcopy(cur_date_possibs)\n\n if len(new_cur_date_possibs) == 0:\n new_cur_date_possibs = [[dbl_nbr]]\n else:\n for date_possib in new_cur_date_possibs:\n date_possib.append(dbl_nbr)\n\n # Deskew\n if should_deskew:\n roi_pad = deskew(roi_pad)\n\n roi_cnn = np.expand_dims(roi_pad, axis=2)\n prob = model_single.predict_proba(np.array([roi_cnn]), verbose=0)\n nbr = np.argmax(prob)\n nbr_prob = prob[0]\n\n if len(cur_date_possibs) == 0:\n cur_date_possibs = [[nbr]]\n else:\n for date_possib in cur_date_possibs:\n date_possib.append(nbr)\n\n if dbl:\n cur_date_possibs += new_cur_date_possibs\n\n prev_end_x = x_start\n prev_end_y = y_start\n\n # Mark the roi, label, and hierarchy\n cv2.rectangle(im_c, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (0, 100, 255), 1)\n cv2.putText(im_c, str(int(nbr)), (rect[0], rect[1]), cv2.FONT_ITALIC, 0.4, (255, 0, 100), 1)\n # cv2.putText(im_c, str(hierarchy[0][i]) + str(int(nbr)), (rect[0], rect[1] - (250 - i*20)), cv2.FONT_ITALIC, 0.4, (randint(0,255), 0, 255), 1)\n\n if dbl:\n dbl_label = str(int(dbl_nbr))\n cv2.putText(im_c, dbl_label, (rect[0], rect[1] - 15), cv2.FONT_ITALIC, 0.3, (255, 0, 200), 1)\n\n probs.append(0)\n rois.append(roi_pad)\n\n if nbr != 1:\n prev_not_one_width = width\n\n # Append the final date possibility\n date_possibs += cur_date_possibs\n\n return im_c, rois, date_possibs, probs\n","sub_path":"app/dates_recognition/digits_extractor.py","file_name":"digits_extractor.py","file_ext":"py","file_size_in_byte":5265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"654493692","text":"from RSAData.db_builder.infra.column_types import ColumnTypes\nfrom RSAData.db_builder.infra.primary_key_column import PrimaryKey\nimport csv\n\nfrom RSAData.db_builder.infra.sql_statements import CreateTableStatement\n\nDEFAULT_PK_COLUMN_NAME = 'ID'\nDEFAULT_PK_COLUMN_TYPE = ColumnTypes.INT\n\n'''\nRepresents a Simple My SQL Table.\nThe type of the columns in columns and of the primary key should be TableColumn.\nThe table has always a primary key. If it is not given to the ctor, then a new 'ID' column is added and\nfunctions as PK.\nThe primary key should not be given in the columns list (if given it will be moved to the head of the list).\n'''\nclass SimpleMySQLTable(object):\n\n def __init__(self, columns, table_name, primary_key=None):\n\n self.columns = columns\n if primary_key is not None:\n self.primary_key = primary_key\n else:\n self.primary_key = PrimaryKey(DEFAULT_PK_COLUMN_NAME, DEFAULT_PK_COLUMN_TYPE)\n\n # put the primary key in the head of the columns list\n if primary_key in self.columns:\n self.columns.remove(primary_key)\n self.columns = [self.primary_key, ] + self.columns\n\n self.should_auto_increment_pk = primary_key is None\n self.table_name = table_name\n self.current_id = 0\n self.values = dict()\n\n def _is_row_in_table(self, row, key):\n if key is not None:\n return key in self.values\n else:\n return row in self.values.values()\n\n '''\n Inserts the row values to the table.\n The dict should include the primary key if it was specified by the client at the ctor\n Returns the id of the row\n '''\n def insert_row(self, row_values_dict, allow_duplicates=True):\n row = []\n for col in self.columns:\n row.append(row_values_dict[col.column_name])\n\n self.current_id += 1\n if self.should_auto_increment_pk:\n key = self.current_id\n else:\n key = row_values_dict[self.primary_key.column_name]\n # ignore duplicate values\n if not allow_duplicates:\n if self._is_row_in_table(row, key):\n return\n\n self.values[key] = row\n\n def get_create_table_statement(self):\n return CreateTableStatement(self.table_name, self.columns)\n\n def dump_to_csv(self, filename):\n with open(filename, 'w') as csv_file:\n csv_writer = csv.writer(csv_file, dialect='unix', quoting=csv.QUOTE_NONE)\n csv_writer.writerow([col.column_name for col in self.columns])\n csv_writer.writerows(self.values.values())\n\n def get_number_of_elements(self):\n return self.current_id\n","sub_path":"py/RuleRefinement/RSAData/db_builder/infra/simple_mysql_table.py","file_name":"simple_mysql_table.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"243371231","text":"#!/usr/bin/env python\n# coding=utf-8\n# Copyright 2015 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\n\"\"\"Unit tests for gatekeeper_ng_config.py.\n\n\"\"\"\n\n# Needs to be at the top, otherwise coverage will spit nonsense.\nimport utils # \"relative import\" pylint: disable=W0403\n\nimport json\nimport os\nimport tempfile\nimport unittest\n\nimport test_env # pylint: disable=W0403,W0611\n\nfrom slave import gatekeeper_ng_config\n\nSCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))\n\n# TODO(stip, martiniss): convert rest of old config tests to this style\n\nclass GatekeeperTest(unittest.TestCase):\n def setUp(self):\n _, self.fname = tempfile.mkstemp(\"gc.json\")\n\n self.cfg = {}\n\n def load_config(self):\n with open(self.fname, 'w') as cfg_file:\n cfg_file.write(json.dumps(self.cfg))\n\n return gatekeeper_ng_config.load_gatekeeper_config(self.fname)\n\n def add_master_config(self, master, cfg):\n self.cfg['masters'] = self.cfg.get('masters', {})\n\n self.assertNotIn(master, self.cfg['masters'])\n self.cfg['masters'][master] = [cfg]\n\n def add_builder_config(self, master, builder, cfg):\n self.add_master_config(master, {'builders': {builder: cfg}})\n\n def add_category(self, name, contents):\n self.cfg['categories'] = self.cfg.get('categories', {})\n\n self.assertNotIn(name, self.cfg['categories'])\n self.cfg['categories'][name] = contents\n\n def testInheritCategoryFromMasterWithBuilderForgive(self):\n self.add_master_config(\n \"http://example.com/test_master\",\n {\n \"categories\": [\"test\"],\n \"builders\": {\n \"*\": { \"categories\": [ \"other_test\" ] }\n }\n },\n )\n\n self.add_category(\n \"test\",\n {\n \"closing_optional\": [\n \"bot_update\",\n \"update\",\n ],\n },\n )\n\n self.add_category(\n \"other_test\",\n {\n \"forgiving_optional\": [\n \"bot_update\",\n \"package build\",\n ],\n },\n )\n\n config = self.load_config()\n\n cfg = config['http://example.com/test_master'][0]['*']\n fo, co = cfg['forgiving_optional'], cfg['closing_optional']\n self.assertEqual(fo, set(['bot_update', 'package build']))\n self.assertEqual(co, set(['update']))\n\n def testConflictingMultipleBuilderEntries(self):\n self.add_builder_config(\n \"http://example.com/master\",\n \"builder1\",\n {\n \"categories\": ['test1', 'test2'],\n })\n\n self.add_category(\n \"test1\",\n {\n \"closing_optional\": [\n \"bot_update\",\n ],\n },\n )\n\n self.add_category(\n \"test2\",\n {\n \"forgiving_optional\": [\n \"bot_update\",\n ],\n },\n )\n\n with self.assertRaises(ValueError):\n self.load_config()\n\n\nif __name__ == '__main__':\n with utils.print_coverage(include=['gatekeeper_ng.py']):\n unittest.main()\n","sub_path":"scripts/slave/unittests/gatekeeper_ng_config_test.py","file_name":"gatekeeper_ng_config_test.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"576245944","text":"\"\"\"Main module. Receive input info from console, parse it and print result to stdout.\"\"\"\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\nimport argparse\nimport logging\nimport logging.handlers\nimport sys\nimport dateparser\nimport os\nfrom datetime import datetime\nfrom os import sep as os_sep\nfrom xhtml2pdf import pisa\n\n\ndef command_arguments_parser(args):\n \"\"\"Adds positional and optional arguments\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-v\", \"--version\", action=\"version\", help=\"Print version info\", version=\"Version 4.1\")\n parser.add_argument(\"source\", type=str, nargs=\"?\", default=None, help=\"RSS URL\")\n parser.add_argument(\"-j\", \"--json\", action=\"store_true\", help=\"Print result as JSON in stdout\")\n parser.add_argument(\"--verbose\", action=\"store_true\", help=\"Outputs verbose status messages\")\n parser.add_argument(\"-l\", \"--limit\", type=int, help=\"Limit news topics if this parameter provided\")\n parser.add_argument(\"--date\", type=str, help=\"Return news from date yyyymmdd from cash\")\n parser.add_argument(\"--to_html\", type=str, help=\"Convert news to html file. Path example 'd:/rss_news\")\n parser.add_argument(\"--to_pdf\", type=str, help=\"Convert news to html file. Path example 'd:/rss_news\")\n args = parser.parse_args(args)\n return args\n\n\ndef create_logger(verbose):\n \"\"\"Create the output for logs\"\"\"\n\n handlers = [logging.StreamHandler(sys.stdout)] if verbose else [logging.FileHandler(\"logs.log\")]\n logging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s - %(levelname)s - %(message)s\",\n handlers=handlers,\n )\n logger = logging.getLogger()\n return logger\n\n\ndef server_answer(source):\n \"\"\"Getting answer from server\"\"\"\n try:\n answer = requests.get(source)\n if answer.status_code == 404:\n print(\"Error 404. Please try to reload the page or check the link you entered\")\n sys.exit()\n elif not source:\n print(\"Input url, please\")\n sys.exit()\n elif answer.status_code == 200:\n print(f\"Starting reading link {source}\")\n return answer\n except (requests.exceptions.ConnectionError, requests.exceptions.InvalidURL):\n print(\"ConnectionError or wrong link, try again, please\")\n sys.exit()\n except requests.exceptions.MissingSchema:\n print(\"Incorrect URL. This is not the rss feed address\")\n sys.exit()\n\n\ndef parses_data(answer, source):\n \"\"\"Parses data from the xml\"\"\"\n list_of_news = []\n data = {}\n\n try:\n buitiful_soup = BeautifulSoup(answer, \"xml\")\n data[\"feed\"] = buitiful_soup.find(\"title\").text\n data[\"source\"] = source\n news_for_print = buitiful_soup.findAll(\"item\")\n for alone_news in news_for_print:\n title = alone_news.find(\"title\").text\n pub_date = alone_news.find(\"pubDate\").text\n link = alone_news.find(\"link\").text\n images = []\n images_find = alone_news.findAll(\"media:content\")\n for image in images_find:\n link_of_image = image.get(\"url\")\n images.append(link_of_image)\n news_dictionary = {\"title\": title, \"pubDate\": pub_date, \"link\": link, \"images\": images}\n list_of_news.append(news_dictionary)\n data[\"news\"] = list_of_news\n except Exception:\n print(\"Xml was failed\")\n return data\n\n\ndef printing_news(data, limit):\n \"\"\"Print news on console\"\"\"\n for num, part in enumerate(data[\"news\"]):\n if num == limit:\n break\n print(\"title:\", part[\"title\"])\n print(\"pubDate:\", part[\"pubDate\"])\n print(\"link:\", part[\"link\"])\n print(\"images:\", len(part[\"images\"]))\n print('\\n'.join(part[\"images\"]), \"\\n\")\n\n\ndef printing_json(data, limit):\n \"\"\"Print json news on console\"\"\"\n limited_data_json = data[\"news\"][:limit]\n data[\"news\"] = limited_data_json\n print(json.dumps(limited_data_json, indent=3))\n\n\ndef compare_dates(date_of_publication, user_date_in_converted_format):\n \"\"\"Compare date given by user(user_date_in_converted_format) and date from news(date_of_publication)\"\"\"\n converted_date_of_publication = dateparser.parse(date_of_publication, date_formats=[\"%y/%m/%d\"])\n return converted_date_of_publication.date() == user_date_in_converted_format.date()\n\n\ndef news_cashing(data):\n \"\"\"Save data in the file \"cashed_news.txt\" in json format\"\"\"\n file_for_cashing = os.path.join(os.getcwd(), \"cashing_news.txt\")\n with open(file_for_cashing, \"a\") as cash_file:\n cash_file.write(json.dumps(data))\n cash_file.write(\"\\n\")\n\n\ndef find_cashed_news(user_date_in_converted_format, source=None):\n \"\"\"Checks the news data file\"\"\"\n cash_file = os.path.join(os.getcwd(), \"cashing_news.txt\")\n with open(cash_file, \"r\") as cash_file:\n list_of_news = []\n data_from_cash = {\"source\": \"from cash file\", \"main_title\": \"Cashed news\"}\n for json_dict in cash_file:\n data = json.loads(json_dict)\n\n if source and source != data[\"source\"]:\n continue\n for num, part in enumerate(data[\"news\"]):\n if compare_dates(part[\"pubDate\"], user_date_in_converted_format):\n list_of_news = [print(\"title:\", part[\"title\"]),\n print(\"pubDate:\", part[\"pubDate\"]),\n print(\"link:\", part[\"link\"]),\n print(\"images:\", len(part[\"images\"])),\n print('\\n'.join(part[\"images\"]), \"\\n\")]\n if data:\n data_from_cash[\"news\"] = list_of_news\n return data_from_cash\n else:\n raise AttributeError\n\n\ndef creating_cashing_news_data(user_date, source: str = None):\n \"\"\"Receive user date from user, convert it into datetime and find cashed news\"\"\"\n user_date_in_converted_format = datetime.strptime(user_date, \"%Y%m%d\")\n if user_date_in_converted_format < datetime.strptime(\"20210601\", \"%Y%m%d\"):\n print(\"Cashing news starts from June 1, 2021\")\n sys.exit()\n data = find_cashed_news(user_date_in_converted_format, source)\n return data\n\n\ndef to_html(data, save_path, date):\n \"\"\"Saving news in html format\"\"\"\n path = r\"{0}rss_feed_time {1}.html\".format(save_path + os_sep, date)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n with open(path, \"w\", encoding=\"utf-8\") as path_file:\n path_file.write('''\n \n \n RSS reader feed\n \n \n ''')\n for num, part in enumerate(data[\"news\"]):\n path_file.write('''\n

{}

\n Feed URL\n

Date of publication: {}

\n \"Image\n
\n '''.format(part[\"title\"], part[\"link\"], part[\"pubDate\"], part[\"images\"]))\n path_file.write('''\n \n \n ''')\n\n\ndef to_pdf(data, save_path, date):\n \"\"\"Saving news in pdf format\"\"\"\n path = r\"{0}rss_feed_time {1}.pdf\".format(save_path + os_sep, date)\n img = False\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n try:\n answer = requests.get(data[\"source\"])\n img = True\n except requests.exceptions.ConnectionError:\n pass\n pdf_news = '''\n \n RSS reader feed\n \n \n '''\n with open(path, \"w+b\") as path_file:\n for num, part in enumerate(data[\"news\"]):\n pdf_news += '''\n

{}

\n Feed URL\n

Publication date: {}

\n {}\n
\n '''.format(part[\"title\"],\n part[\"link\"],\n part[\"pubDate\"],\n f'' if img else \"Image can not be \"\n \"displaed\")\n pdf_news += '''\n \n \n '''\n pisa.CreatePDF(pdf_news, dest=path_file)\n\n\ndef main():\n args = command_arguments_parser(sys.argv[1:])\n logger = create_logger(args.verbose)\n\n if args.limit is not None:\n if args.limit <= 0:\n print(\"Invalid limit. Enter the limit (greater than 0), please\")\n sys.exit()\n if args.date:\n try:\n data = creating_cashing_news_data(args.date, args.source)\n except (ValueError, TypeError, AttributeError, FileNotFoundError) as e:\n logger.error(f\"{e} in parsing date '{args.date}'\")\n print(\"Incorrect date (insert date like'20210601') or no news from this date or cashed news was not found.\")\n sys.exit()\n\n else:\n try:\n answer = server_answer(args.source)\n data = parses_data(answer.text, args.source)\n if args.limit:\n logger.info(f\"Reads amount of news - {args.limit}\")\n if args.json:\n printing_json(data, args.limit)\n news_cashing(data)\n else:\n printing_news(data, args.limit)\n news_cashing(data)\n except (requests.exceptions.ConnectionError, requests.exceptions.InvalidURL, requests.exceptions.MissingSchema):\n return print()\n if args.to_html:\n to_html(data, args.to_html, datetime.now().strftime(\"%m.%d %H.%M.%S\"))\n if args.to_pdf:\n to_pdf(data, args.to_pdf, datetime.now().strftime(\"%m.%d %H.%M.%S\"))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"rss_reader/rss_reader/rss_reader.py","file_name":"rss_reader.py","file_ext":"py","file_size_in_byte":9890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"78899424","text":"import pandas as pd\nfrom ta.trend import SMAIndicator\nimport matplotlib.pyplot as plt\nfrom mplfinance.original_flavor import candlestick_ohlc\nimport matplotlib.dates as mpl_dates\n\ndef Plot_OHCL(df, ax1_indicators=[], ax2_indicators=[]):\n df_original = df.copy()\n # necessary convert to datetime\n df[\"Date\"] = pd.to_datetime(df.Date)\n df[\"Date\"] = df[\"Date\"].apply(mpl_dates.date2num)\n\n df = df[['Date', 'Open', 'High', 'Low', 'Close', 'Volume']]\n \n # We are using the style ‘ggplot’\n plt.style.use('ggplot')\n \n # figsize attribute allows us to specify the width and height of a figure in unit inches\n fig = plt.figure(figsize=(16,8)) \n\n # Create top subplot for price axis\n ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)\n\n # Create bottom subplot for volume which shares its x-axis\n ax2 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1, sharex=ax1)\n\n candlestick_ohlc(ax1, df.values, width=0.8/24, colorup='green', colordown='red', alpha=0.8)\n ax1.set_ylabel('Price', fontsize=12)\n plt.xlabel('Date')\n plt.xticks(rotation=45)\n\n # plot all ax1 indicators\n for indicator in ax1_indicators:\n ax1.plot(df[\"Date\"], df_original[indicator],'-')\n\n # plot all ax2 indicators\n for indicator in ax2_indicators:\n ax2.plot(df[\"Date\"], df_original[indicator],'-')\n\n # beautify the x-labels (Our Date format)\n ax1.xaxis.set_major_formatter(mpl_dates.DateFormatter('%y-%m-%d'))\n fig.autofmt_xdate()\n fig.tight_layout()\n \n plt.show()\n\ndef AddIndicators(df):\n # Add Simple Moving Average (SMA) indicators\n df[\"sma7\"] = SMAIndicator(close=df[\"Close\"], window=7, fillna=True).sma_indicator()\n df[\"sma25\"] = SMAIndicator(close=df[\"Close\"], window=25, fillna=True).sma_indicator()\n df[\"sma99\"] = SMAIndicator(close=df[\"Close\"], window=99, fillna=True).sma_indicator()\n \n return df\n\nif __name__ == \"__main__\": \n df = pd.read_csv('./pricedata.csv')\n df = df.sort_values('Date')\n df = AddIndicators(df)\n\n test_df = df[-400:]\n\n # Add Simple Moving Average\n Plot_OHCL(test_df, ax1_indicators=[\"sma7\", \"sma25\", \"sma99\"])\n","sub_path":"RL-Bitcoin-trading-bot_5/TA examples/SMA.py","file_name":"SMA.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"442208090","text":"import pyautogui as ag\nimport pygetwindow as gw\nimport os\nimport subprocess\nimport signal\nfrom time import time\nimport platform\nimport shutil\nfrom PIL import Image\n\nOS_is_MAC = False\n\nif platform.system() == \"Windows\":\n bar = '\\\\'\n\nelif platform.system() == \"Darwin\":\n\tOS_is_MAC = True\n\tbar = '/'\nelse:\n bar = '/'\n\n# Perceptor\nclass state():\n\tn = 0\n\tnt = 0\n\tct = 0.0\n\tdef __init__(self, window,path, name):\n\t\tself.win = window\n\t\tself.name = name\n\t\tself.path = path\n\t\tif not os.path.exists(self.path+bar+'img'):\n\t\t\tos.makedirs(self.path+bar+'img')\n\t\telse: \n\t\t\tshutil.rmtree(self.path+bar+'img')\n\t\t\tos.makedirs(self.path+bar+'img')\n\t\t\n\tdef print(self):\n\t\tif self.win.isActive:\n\t\t\tself.n = self.n+1\n\t\t\tprint_name = self.path+bar+'img'+bar+self.name+str(self.n)+'.png'\n\n\t\t\t# if OS_is_MAC:\n\t\t\t# \tscreen_capt_command = 'screencapture -R ' + str(self.win.left) + ',' + str(self.win.top) + ',' + str(self.win.width) + ',' + str(self.win.height) + ' ' + print_name\n\t\t\t# \tsubprocess.call(screen_capt_command,shell=True)\n\t\t\t# \treturn Image.open(print_name)\n\n\t\t\treturn ag.screenshot(print_name, region=(self.win.left, self.win.top, self.win.width, self.win.height))\n\t\t\n\n\tdef print_clock(self, name, t):\n\t\twhile self.win.isActive:\n\t\t\tif time() - self.ct > t:\n\t\t\t\tself.ct = time()\n\t\t\t\tself.nt = self.nt+1\n\t\t\t\tag.screenshot('img\\\\'+name+'_t_'+str(self.nt)+'.png', region=(self.win.left, self.win.top, self.win.width, self.win.height))\n\n# Atuador\nclass ctrl:\n\tdef __init__(self,fexe,title,locate_on_screen=None,box_height=None,box_width=None,adjust_top=0,adjust_left=0):\n\t\tself.locate_on_screen = locate_on_screen\n\t\t# Inicia o programa em um novo proocesso\n\t\tself.process = subprocess.Popen(fexe, stdout=subprocess.PIPE, shell=True)\n\t\tself.window = self.getWindowMac(title,locate_on_screen,box_height,box_width,adjust_top,adjust_left) if OS_is_MAC else self.getWindowWindows(title)\n\n\tdef getWindowWindows(self,title):\n\t\t# Espera a janela abrir e a ativa \n\t\twhile True:\t\n\t\t\ttry: \n\t\t\t\twindow = gw.getWindowsWithTitle(title)[0]\n\t\t\t\twindow.activate()\n\t\t\t\tbreak\n\t\t\texcept:\n\t\t\t\tpass \n\n\t\treturn window;\n\n\tdef getWindowMac(self,title,locate_on_screen,box_height,box_width=None,adjust_top=0,adjust_left=0): # !!!! Workaround - NOT RECOMENDED !!!!\n\t\t#Obtem janela\n\t\treturn window_for_mac(title,locate_on_screen,box_height,box_width,adjust_top,adjust_left)\n\n\tdef edges(self):\n\t\treturn self.window.left, self.window.left+self.window.width, self.window.top, self.window.top+self.window.height\n\n\tdef stop(self):\n\t\tself.process.terminate()\n\t\tif OS_is_MAC:\n\t\t\tself.window.isActive = ag.locateOnScreen(self.locate_on_screen) is not None\n\t\telse:\n\t\t\twhile self.window.isActive:\n\t\t\t\tpass\n# Classe de janela para Mac !!!! Workaround - NOT RECOMENDED !!!!\nclass window_for_mac:\n\tdef __init__(self,title,locate_on_screen,box_height,box_width=None,adjust_top=0,adjust_left=0):\n\t\tself.title = title\n\t\tself.isActive = False\n\t\tself.box_region = None\n\t\twhile not self.isActive:\n\t\t\ttry:\n\t\t\t\tself.box_region=ag.locateOnScreen(locate_on_screen)\n\t\t\t\tself.isActive = self.box_region is not None\n\t\t\texcept:\n\t\t\t\tpass\n\n\t\tself.top = self.box_region.top + self.box_region.height + adjust_top\n\t\tself.left = self.box_region.left + adjust_left\n\t\tself.width = box_width if box_width is not None else self.box_region.width\n\t\tself.height = box_height\n\n# Identificador\nclass finder:\n\tkeyboard = False\n\tmouse = False\n\n\tdef __init__(self, file_name):\n\t\t# Abre o arquivo *.c\n\t\ttry:\n\t\t\tself.file = open(file_name, 'r').read()\n\t\texcept:\n\t\t\tprint(\"File {} not found.\".format(file_name))\n\t\t\treturn\n\t\t\n\t\t# Guarda todas as palavras do arquivo \n\t\tself.words = self.to_list(self.file)\n\n\t\tif self.search('mouse'):\n\t\t\tself.mouse = True\n\n\t\t# Recupera todas as teclas pressionaveis\n\t\tself.keys = self.get_keys('ALLEGRO_KEY_')\n\n\t\tif len(self.keys)>0:\n\t\t\tself.keyboard = True\n\n\t\t\n\t# Transforma um arquivo.c em uma lista de palavras\n\tdef to_list(self, txt):\n\t\t# Aprende todos osimbolos utilizados\n\t\tsimbols = []\n\t\tvalids = [' ','_']\n\t\tfor a in txt:\n\t\t\tif not a.isalnum() and a not in valids:\n\t\t\t\tif a not in simbols:\n\t\t\t\t\tsimbols.append(a)\n\t\t\n\t\tnew_txt = txt\n\t\t\n\t\t# Retira os simbolos do texto para facilitar a separacao\n\t\tfor s in simbols:\n\t\t\tnew_txt = new_txt.replace(s, ' ')\n\n\t\t# Separa todas as palavras e cria uma lista das validas\n\t\treturn [w for w in new_txt.split(' ') if len(w) > 0 ]\n\n\t# Retorna todas as palavras que contem um termo\n\tdef search(self, name):\n\t\tword_list = []\n\n\t\tfor word in self.words:\n\t\t\tif len(word) < len(name):\n\t\t\t\tcontinue\n\n\t\t\tfor i in range(len(word)):\n\t\t\t\tif len(word)-i < len(name):\n\t\t\t\t\tbreak\n\n\t\t\t\tif name[0] == word[i]:\n\t\t\t\t\tfound = False\n\n\t\t\t\t\tfor j in range(len(name)):\n\t\t\t\t\t\tif name[j] == word[i+j]:\n\t\t\t\t\t\t\tfound = True\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tfound = False\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\tif found and word not in word_list:\n\t\t\t\t\t\tword_list.append(word)\n\t\t\t\t\t\tbreak\n\n\t\treturn word_list\n\n\t# Retorna todas as teclas validas\n\tdef get_keys(self, prefix):\n\t\t# Lista as palavras com comandos de tecla\n\t\tw_list = self.search(prefix)\n\t\tk_list = []\n\t\t\n\t\t# Retira o prefixo de comando\n\t\tfor w in w_list:\n\t\t\tk_list.append(w.replace(prefix, ''))\n\t\t\n\t\t# Lista as teclas \n\t\treturn [k.lower() for k in k_list if len(k) > 0 ]\n","sub_path":"code/api_allegro/src/game_api.py","file_name":"game_api.py","file_ext":"py","file_size_in_byte":5160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"369260696","text":"import pickle\nimport uuid\nfrom birdyboard import configuration\n\n\nusers = list()\n\ndef add(user):\n global users\n users.append(user)\n _serialize()\n\n\ndef load():\n global users\n _deserialize()\n return users\n\n\ndef _serialize():\n global users\n path = configuration.get_path() + \"users\"\n with open(path, \"wb+\") as c:\n pickle.dump(users, c)\n\n\ndef _deserialize():\n global users\n path = configuration.get_path() + \"users\"\n\n try:\n with open(path, \"rb+\") as c:\n users = pickle.load(c)\n except EOFError:\n pass\n\ndef list():\n global users\n [print(c) for c in users]\n\n\ndef get(id):\n global users\n user = [c for c in users if c.id == id]\n return user[0]\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"birdyboard/helpers/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"21322116","text":"import time\nimport threading\n\ndef lo1():\n time.sleep(4)\n print('<------lo1-------->')\n\n\ndef lo2():\n time.sleep(2)\n print('<------lo1-------->')\n\n\ndef main():\n t1 = time.time()\n f1 = threading.Thread(target=lo1)\n f2 = threading.Thread(target=lo2)\n f1.start()\n f2.start()\n f1.join()\n f2.join()\n t2 = time.time()\n\n print('total time: {}'.format(t2-t1))\n\nif __name__ == \"__main__\":\n main()","sub_path":"rimi_linux_mysql/tcp_ip_socket/multi/v1_basic/thread.py","file_name":"thread.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"354833507","text":"#####continue and break usage#####\n\nshopping_list = [\"milk\", \"pasta\", \"eggs\", \"spam\", \"bread\", \"rice\"]\nfor item in shopping_list:\n #skips item using continue\n if item == \"spam\":\n #continue\n #break skips the remainder of the items\n break\n print(\"Buy \" + item)\n\n#####practicing with break#####\n\nmeal = [\"egg\", \"bacon\", \"spam\", \"sausages\"]\n\nfor item in meal:\n if item == \"spam\":\n nasty_food_item = item\n break\n\nif nasty_food_item:\n print(\"Can I have anything without spam in it?\")\n\n#Bug; if no spam, nasty_food_item is never defined\n\n#####fixing previous bug#####\n\nmeal = [\"egg\", \"bacon\", \"spam\", \"sausages\"]\n#fixes previous bug and initializes nasty_food_item\nnasty_food_item = \"\"\nfor item in meal:\n if item == \"spam\":\n nasty_food_item = item\n break\n#break supersedes the else\nelse:\n print(\"I'll have a plate of that then\")\nif nasty_food_item:\n print(\"Can I have anything without spam in it?\")\n\n#####practice questions#####\n\n#print numbers up to divisible by 11\nfor i in range(0, 100, 7):\n print(i)\n if i > 0 and i % 11 == 0:\n break\n\n#prints number BUT those divisible by 3 or 5\nfor number in range(20):\n if number % 3 == 0 or number % 5 == 0:\n continue\n print(number)\n","sub_path":"flow_control/break_continue_else.py","file_name":"break_continue_else.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"573208578","text":"\"\"\"\r\nContains each type of run as a function\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\nfrom numexpr import evaluate as evl\r\nfrom numpy.linalg import multi_dot as mdot\r\nfrom quijy import (\r\n sig,\r\n eyepad,\r\n qjf,\r\n QuEvo,\r\n asvds,\r\n )\r\nfrom xyzpy import progbar\r\nimport quijy as qj\r\nfrom .hamiltonian import ham_qd\r\n\r\n\r\ndef qid_evo(n, dh, ts, run=None, j=1, bz=0, cyclic=False,\r\n m1=sig('z'), m1n=[0], m2s=None, m2n=None, solve=True,\r\n progess=True, tol=1e-4):\r\n \"\"\" Single run of 'quantum information density' for qdmbl hamtiloanian.\r\n\r\n Parameters\r\n ----------\r\n n: number of spins\r\n dh: random field strength\r\n ts: time-steps\r\n run: random seed for hamiltonian\r\n j: coupling strength\r\n bz: random field strength\r\n cyclic: whether to use cyclic boundary conditions\r\n m1: initial operator state\r\n m1n: position(s) of initial operator state\r\n m2s: list of operators to use for qid calculation\r\n m2n: list of sites to use for qid calculation\r\n solve: whether to solve the hamiltonian and evolve\r\n progress: show progress\r\n tol: svd tolerance required for qid\r\n\r\n Returns\r\n -------\r\n qid_k_t: qid as a function of spin number `k` and time `t` \"\"\"\r\n # Measurement Operators\r\n a = eyepad(qjf(m1, sparse=False), [2]*n, m1n)\r\n\r\n if m2s is None:\r\n m2s = [sig(s) for s in \"xyz\"]\r\n if m2n is None:\r\n m2n = range(n)\r\n\r\n bi_ks = [[eyepad(qjf(m2, sparse=True), [2]*n, k)\r\n for m2 in m2s]\r\n for k in m2n]\r\n\r\n h = ham_qd(n, dh, j=j, bz=bz, run=run, cyclic=cyclic, sparse=not solve)\r\n sim = QuEvo(a, h, solve=solve)\r\n\r\n qid_k_t = np.zeros((len(m2n), len(ts)))\r\n\r\n with progbar(total=len(ts)*len(m2n)*len(m2s), disable=not progess) as pb:\r\n for ti, a_t in enumerate(sim.at_times(ts)):\r\n for ki, bi_k in enumerate(bi_ks):\r\n for bi in bi_k:\r\n commk = bi @ a_t\r\n commk -= commk.H\r\n qid_k_t[ki, ti] += asvds(commk, k=1, tol=tol)[0]**2\r\n pb.update()\r\n\r\n return qid_k_t\r\n\r\n\r\n# Functions for generating data\r\ndef liebrob_evo_uni(n, j, bz, dhs, m1, m1n, m2, m2n, ntype, ts, runs):\r\n \"\"\" Evolve the operator m1, placed on sites m1n, then check how the norm of\r\n its coomutator with operator m2, placed *individually* on sites m2n,\r\n evolves with time.\r\n Desconstucst ham into v * l * v' then evolves a as\r\n v * exp(-ilt) * v' * a * v * exp(ilt) * v' and finds norm with b_k \"\"\"\r\n # Output results array\r\n lr_k_t_dh = np.zeros((np.size(m2n), np.size(ts), np.size(dhs)))\r\n # Pre-allocate operators\r\n a = qj.eyepad(qj.quijify(m1, sparse=True), [2] * n, m1n)\r\n b_k = [qj.eyepad(qj.quijify(m2, sparse=True), [2] * n, k) for k in m2n]\r\n vb_k = np.empty((2**n, 2**n, np.size(m2n)), dtype=complex)\r\n\r\n # Cycle through random field strengths\r\n for dhi, dh in enumerate(dhs):\r\n print('*** dh number', dhi + 1, 'of ', np.size(dhs), '***')\r\n # Cycle through run numbers\r\n for runx, run in qj.progbar(enumerate(runs), total=len(runs)):\r\n # Build and solve hamiltonian\r\n ham = ham_qd(n, j, bz, dh, run=run)\r\n l, v = qj.eigsys(ham)\r\n # Precompute constant quantities\r\n vav = v.H * (a * v)\r\n for kx, k in enumerate(m2n):\r\n vb_k[:, :, kx] = v.H * b_k[kx]\r\n # Time evolution\r\n for tx, t in enumerate(ts):\r\n explt = np.exp((-1.0j * t) * l)\r\n expltc = np.conj(explt)\r\n for kx, k in enumerate(m2n):\r\n uaubn = mdot([v,\r\n qj.ldmul(explt, vav),\r\n qj.ldmul(expltc, vb_k[:, :, kx])])\r\n lr_k_t_dh[kx, tx, dhi] += \\\r\n qj.norm2(uaubn - uaubn.H) / np.size(runs)\r\n return lr_k_t_dh\r\n\r\n\r\ndef spinfidhot_evo_uni(n, jxyz, bz, dhs, p, pn, m, mn, ts, runs):\r\n \"\"\"\r\n Construct a state of p on sites pn, tensored with identity elsewhere.\r\n Evolve and find the fidelity of each site mn with operator m.\r\n \"\"\"\r\n # Output: fidelity at site k, time t, random field stength dh\r\n sfk_t_dh = np.zeros((np.size(mn), np.size(ts), np.size(dhs)))\r\n # State to evolve\r\n rho = qj.eyepad(qj.quijify(p, sparse=True), [2] * n, pn) \\\r\n / 2**(n-np.size(pn))\r\n # Fidelity measurements\r\n m_k = [qj.eyepad(qj.quijify(m, sparse=True), [2] * n, k) for k in mn]\r\n # Pre-allocate\r\n explt = np.empty((2**n, 1), dtype=complex)\r\n vrhov = np.empty((2**n, 2**n), dtype='complex')\r\n rhot = np.empty_like(vrhov)\r\n\r\n progbar = tqdm(total=np.size(ts) * np.size(dhs) * np.size(runs),\r\n leave=True, unit='runs', ascii=True, smoothing=0.0)\r\n\r\n # Cycle of random field strengths\r\n for dhi, dh in enumerate(dhs):\r\n # Cycle over repetitions\r\n for runi, run in enumerate(runs):\r\n # Generate and solve hamiltonian\r\n ham = ham_qd(n, jxyz, bz, dh, run=run)\r\n l, v = qj.eigsys(ham)\r\n # Precompute rho in energy basis\r\n vrhov = v.H * rho * v\r\n # Evolve\r\n for ti, t in enumerate(ts):\r\n dt = t - 0.0\r\n explt = evl(\"exp(-1.0j * dt * l)\", local_dict={'dt': dt})\r\n rhot = mdot([v,\r\n qj.ldmul(explt, vrhov),\r\n qj.ldmul(evl(\"conj(explt)\"), v.H)])\r\n # Cycle over spin sites\r\n for ki, k in enumerate(mn):\r\n sfk_t_dh[ki, ti, dhi] += qj.tr(rhot * m_k[ki])\r\n progbar.update()\r\n progbar.close()\r\n return sfk_t_dh / np.size(runs)\r\n\r\n\r\ndef echodist_t_dh(n, j, bz, dhs, m1, m1n, m2, m2n, ts, runs,\r\n psi0func=None,\r\n noisevecno=None,\r\n totvecno=None):\r\n \"\"\"\r\n Does projective measurement m1 on sites m1n of psi0func.\r\n Then evolves the system to each of ts, does projective measurements m2.\r\n The system is then 'unevolved' back to t=0, to find the disturbance that\r\n m2 has had on this spin echo.\r\n \"\"\"\r\n # Initial Projector\r\n p1 = qj.eyepad(qj.quijify(m1, sparse=True), [2] * n, m1n)\r\n # Range of disturbing projectors\r\n p2_k = [qj.eyepad(qj.quijify(m2, sparse=True), [2] * n, k) for k in m2n]\r\n\r\n # Output: p1 expectation after disturbed echo of time t\r\n edk_t_dh = np.zeros((np.size(m2n), np.size(ts), np.size(dhs)))\r\n\r\n progbar = tqdm(total=np.size(ts) * np.size(dhs) * np.size(runs),\r\n leave=True, unit='runs', ascii=True, smoothing=0.0)\r\n\r\n # Pre-allocate matices...\r\n explt = np.empty((2**n, 1), dtype=complex)\r\n\r\n # Cycle of random field strengths\r\n for dhi, dh in enumerate(dhs):\r\n # Cycle over repetitions\r\n for runi, run in enumerate(runs):\r\n # Generate random hamiltonian\r\n hamj = qj.ham_heis(n=n, j=j, bz=bz, cyclic=False)\r\n hamh = ham_qd(n, 0, bz, dh, run=run)\r\n l, v = qj.eigsys(hamh + hamj)\r\n\r\n # Initial state, projected and normalized\r\n if totvecno is not None:\r\n psi = qj.nmlz(p1 * v[:, totvecno])\r\n elif noisevecno is not None:\r\n vh = qj.eigvecs(hamh)\r\n psi = qj.nmlz(p1 * vh[:, noisevecno])\r\n elif psi0func is not None:\r\n psi = qj.nmlz(p1 * psi0func(n))\r\n\r\n # Precompute in energy basis\r\n vpsi = v.H * psi\r\n # Cycle through times\r\n for ti, t in enumerate(ts):\r\n dt = t - 0.0\r\n explt = evl('exp(-1.0j * dt * l)', local_dict={'dt': dt})\r\n # Evolve and return to computaitonal basis\r\n psit = v * qj.ldmul(explt, vpsi)\r\n explt = evl('conj(explt)') # refill diag\r\n for ki, p2 in enumerate(p2_k):\r\n # Projective measure\r\n psid = qj.nmlz(p2 * psit)\r\n # Un-evolve\r\n psid = mdot([v, qj.ldmul(explt, v.H), psid])\r\n edk_t_dh[ki, ti, dhi] += \\\r\n np.real(psid.H * p1 * psid) / np.size(runs)\r\n progbar.update()\r\n progbar.close()\r\n return edk_t_dh\r\n","sub_path":"qdmbl/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":8410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"295819460","text":"# coding: utf-8\n\"\"\"\nModule `chatette.modifiers.representation`\nContains structures that represent the possible modifiers\nthat could apply to unit declarations or sub-rules.\n\"\"\"\n\n\nclass ModifiersRepresentation(object):\n def __init__(self):\n self.casegen = False\n\n self.variation_name = None # Only for unit references\n\n self.randgen = False\n self.randgen_name = None\n self.randgen_percent = 50\n\n self.argument_name = None\n self.argument_value = None # Should be an OrderedDict {name -> value} sorted in decreasing length of keys (but should be just the arg value as a str at first for single argument)\n\n def __repr__(self):\n return \\\n self.__class__.__name__ + \"(casegen: \" + str(self.casegen) + \\\n \" randgen: \" + str(self.randgen_name) + \" (\" + \\\n str(self.randgen_percent) + \\\n \") arg name: \" + str(self.argument_name) + \" arg value: \" + \\\n str(self.argument_value) + \")\"\n def __str__(self):\n return self.__repr__()\n \n def short_description(self):\n \"\"\"\n Returns a short description (as a `str`) that can be displayed to the\n user.\n \"\"\"\n at_least_one_modifier = False\n desc = \"\"\n if self.casegen:\n desc += \"- case generation\\n\"\n at_least_one_modifier = True\n if self.randgen:\n desc += \"- random generation\"\n if self.randgen_name is not None:\n desc += \": \" + self.randgen_name\n desc += \" (\" + str(self.randgen_percent) + \"%)\\n\"\n at_least_one_modifier = True\n if self.argument_name is not None:\n desc += \"- argument name: \" + self.argument_name + \"\\n\"\n at_least_one_modifier = True\n if self.argument_value is not None:\n desc += \"- argument value: \" + self.argument_value + \"\\n\"\n at_least_one_modifier = True\n\n if not at_least_one_modifier:\n desc = \"No modifiers\\n\"\n else:\n desc = \"Modifiers:\\n\" + desc\n return desc\n","sub_path":"chatette/modifiers/representation.py","file_name":"representation.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"422889524","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nimport os\nimport shutil\nimport sqlite3\nimport tempfile\n\nfrom squint._compatibility.builtins import *\nfrom squint._compatibility.collections import namedtuple\nfrom .common import (\n StringIO,\n unittest,\n)\nfrom squint.select import Select\nfrom squint.select import Query\nfrom squint.result import Result\n\n\nclass HelperTestCase(unittest.TestCase):\n def setUp(self):\n data = [['label1', 'label2', 'value'],\n ['a', 'x', '17'],\n ['a', 'x', '13'],\n ['a', 'y', '20'],\n ['a', 'z', '15'],\n ['b', 'z', '5' ],\n ['b', 'y', '40'],\n ['b', 'x', '25']]\n self.select = Select(data)\n\n\nclass TestSelect(HelperTestCase):\n def test_empty_select(self):\n select = Select()\n\n def test_fieldnames(self):\n expected = ['label1', 'label2', 'value']\n self.assertEqual(self.select.fieldnames, expected)\n\n select = Select() # <- Empty select.\n self.assertEqual(select.fieldnames, [], msg='should be empty list')\n\n def test_load_data(self):\n select = Select() # <- Empty select.\n self.assertEqual(select.fieldnames, [])\n\n readerlike1 = [['col1', 'col2'], ['a', 1], ['b', 2]]\n select.load_data(readerlike1)\n self.assertEqual(select.fieldnames, ['col1', 'col2'])\n\n readerlike2 = [['col1', 'col3'], ['c', 'x'], ['d', 'y']]\n select.load_data(readerlike2)\n self.assertEqual(select.fieldnames, ['col1', 'col2', 'col3'])\n\n def test_repr(self):\n data = [['A', 'B'], ['x', 100], ['y', 200]]\n\n # Empty select.\n select = Select()\n self.assertEqual(repr(select), '\"\n self.assertEqual(repr(select), expected)\n\n # Data with args (args don't affect repr)\n iterable = iter(data)\n select = Select(iterable, 'foo', bar='baz')\n regex = '\"\n )\n self.assertEqual(repr(select), expected)\n\n # Test long repr truncation.\n select = Select([\n ['xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'],\n ['yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'],\n ])\n\n self.assertEqual(len(repr(select)), 72)\n\n expected = \"