body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
e2364269e351b3b02e99961368dfdd5c5e3da0e94aaa105e2deca1ce86e9c664
def __validate_node(self, node: Node) -> None: '\n Raises:\n NodeNotFound\n NicNotFound\n ' if (not node.name): raise NodeNotFound('Node must have a name') if (not node.nics): raise NicNotFound(('Node [%s] has no associated nics' % node.name))
Raises: NodeNotFound NicNotFound
src/installer/src/tortuga/os/rhel/osSupport.py
__validate_node
sutasu/tortuga
33
python
def __validate_node(self, node: Node) -> None: '\n Raises:\n NodeNotFound\n NicNotFound\n ' if (not node.name): raise NodeNotFound('Node must have a name') if (not node.nics): raise NicNotFound(('Node [%s] has no associated nics' % node.name))
def __validate_node(self, node: Node) -> None: '\n Raises:\n NodeNotFound\n NicNotFound\n ' if (not node.name): raise NodeNotFound('Node must have a name') if (not node.nics): raise NicNotFound(('Node [%s] has no associated nics' % node.name))<|docstring|>Raises: NodeNotFound NicNotFound<|endoftext|>
979f11fd8989e86d2e7c6e5729d68d2d5789a688e78bba2292a2031848b070c1
def __get_template_subst_dict(self, session: Session, node: Node, hardwareprofile: HardwareProfile, softwareprofile: SoftwareProfile) -> Dict[(str, Any)]: '\n :param node: Object\n :param hardwareprofile: Object\n :param softwareprofile: Object\n :return: Dictionary\n ' hardwareprofile = (hardwareprofile if hardwareprofile else node.hardwareprofile) softwareprofile = (softwareprofile if softwareprofile else node.softwareprofile) installer_public_fqdn: str = getfqdn() installer_hostname: str = installer_public_fqdn.split('.')[0] installer_private_ip: str = hardwareprofile.nics[0].ip try: private_domain: Optional[str] = self._globalParameterDbApi.getParameter(session, 'DNSZone').getValue() except ParameterNotFound: private_domain: Optional[str] = None installer_private_fqdn: str = ('%s%s%s' % (installer_hostname, get_installer_hostname_suffix(hardwareprofile.nics[0], enable_interface_aliases=None), (('.%s' % private_domain) if private_domain else ''))) values: List[str] = node.name.split('.', 1) domain: str = (values[1].lower() if (len(values) == 2) else '') return {'fqdn': node.name, 'domain': domain, 'hostname': installer_hostname, 'installer_private_fqdn': installer_private_fqdn, 'installer_private_domain': private_domain, 'installer_private_ip': installer_private_ip, 'puppet_master_fqdn': installer_public_fqdn, 'installer_public_fqdn': installer_public_fqdn, 'ntpserver': installer_private_ip, 'os': softwareprofile.os.name, 'osfamily': softwareprofile.os.family.name, 'osfamilyvers': int(softwareprofile.os.family.version), 'primaryinstaller': installer_private_fqdn, 'puppetserver': installer_public_fqdn, 'installerip': installer_private_ip, 'url': ('%s/%s/%s/%s' % (self._cm.getYumRootUrl(installer_private_fqdn), softwareprofile.os.name, softwareprofile.os.version, softwareprofile.os.arch)), 'lang': 'en_US.UTF-8', 'keyboard': 'us', 'networkcfg': self.__kickstart_get_network_section(node, hardwareprofile), 'rootpw': self._generatePassword(), 'timezone': self.__kickstart_get_timezone(session), 'includes': '%include /tmp/partinfo', 'repos': '\n'.join(self.__kickstart_get_repos(session, softwareprofile, installer_private_fqdn)), 'packages': '\n'.join([]), 'prescript': self.__kickstart_get_partition_section(softwareprofile), 'installer_url': self._cm.getInstallerUrl(installer_private_fqdn), 'cfmstring': self._cm.getCfmPassword()}
:param node: Object :param hardwareprofile: Object :param softwareprofile: Object :return: Dictionary
src/installer/src/tortuga/os/rhel/osSupport.py
__get_template_subst_dict
sutasu/tortuga
33
python
def __get_template_subst_dict(self, session: Session, node: Node, hardwareprofile: HardwareProfile, softwareprofile: SoftwareProfile) -> Dict[(str, Any)]: '\n :param node: Object\n :param hardwareprofile: Object\n :param softwareprofile: Object\n :return: Dictionary\n ' hardwareprofile = (hardwareprofile if hardwareprofile else node.hardwareprofile) softwareprofile = (softwareprofile if softwareprofile else node.softwareprofile) installer_public_fqdn: str = getfqdn() installer_hostname: str = installer_public_fqdn.split('.')[0] installer_private_ip: str = hardwareprofile.nics[0].ip try: private_domain: Optional[str] = self._globalParameterDbApi.getParameter(session, 'DNSZone').getValue() except ParameterNotFound: private_domain: Optional[str] = None installer_private_fqdn: str = ('%s%s%s' % (installer_hostname, get_installer_hostname_suffix(hardwareprofile.nics[0], enable_interface_aliases=None), (('.%s' % private_domain) if private_domain else ))) values: List[str] = node.name.split('.', 1) domain: str = (values[1].lower() if (len(values) == 2) else ) return {'fqdn': node.name, 'domain': domain, 'hostname': installer_hostname, 'installer_private_fqdn': installer_private_fqdn, 'installer_private_domain': private_domain, 'installer_private_ip': installer_private_ip, 'puppet_master_fqdn': installer_public_fqdn, 'installer_public_fqdn': installer_public_fqdn, 'ntpserver': installer_private_ip, 'os': softwareprofile.os.name, 'osfamily': softwareprofile.os.family.name, 'osfamilyvers': int(softwareprofile.os.family.version), 'primaryinstaller': installer_private_fqdn, 'puppetserver': installer_public_fqdn, 'installerip': installer_private_ip, 'url': ('%s/%s/%s/%s' % (self._cm.getYumRootUrl(installer_private_fqdn), softwareprofile.os.name, softwareprofile.os.version, softwareprofile.os.arch)), 'lang': 'en_US.UTF-8', 'keyboard': 'us', 'networkcfg': self.__kickstart_get_network_section(node, hardwareprofile), 'rootpw': self._generatePassword(), 'timezone': self.__kickstart_get_timezone(session), 'includes': '%include /tmp/partinfo', 'repos': '\n'.join(self.__kickstart_get_repos(session, softwareprofile, installer_private_fqdn)), 'packages': '\n'.join([]), 'prescript': self.__kickstart_get_partition_section(softwareprofile), 'installer_url': self._cm.getInstallerUrl(installer_private_fqdn), 'cfmstring': self._cm.getCfmPassword()}
def __get_template_subst_dict(self, session: Session, node: Node, hardwareprofile: HardwareProfile, softwareprofile: SoftwareProfile) -> Dict[(str, Any)]: '\n :param node: Object\n :param hardwareprofile: Object\n :param softwareprofile: Object\n :return: Dictionary\n ' hardwareprofile = (hardwareprofile if hardwareprofile else node.hardwareprofile) softwareprofile = (softwareprofile if softwareprofile else node.softwareprofile) installer_public_fqdn: str = getfqdn() installer_hostname: str = installer_public_fqdn.split('.')[0] installer_private_ip: str = hardwareprofile.nics[0].ip try: private_domain: Optional[str] = self._globalParameterDbApi.getParameter(session, 'DNSZone').getValue() except ParameterNotFound: private_domain: Optional[str] = None installer_private_fqdn: str = ('%s%s%s' % (installer_hostname, get_installer_hostname_suffix(hardwareprofile.nics[0], enable_interface_aliases=None), (('.%s' % private_domain) if private_domain else ))) values: List[str] = node.name.split('.', 1) domain: str = (values[1].lower() if (len(values) == 2) else ) return {'fqdn': node.name, 'domain': domain, 'hostname': installer_hostname, 'installer_private_fqdn': installer_private_fqdn, 'installer_private_domain': private_domain, 'installer_private_ip': installer_private_ip, 'puppet_master_fqdn': installer_public_fqdn, 'installer_public_fqdn': installer_public_fqdn, 'ntpserver': installer_private_ip, 'os': softwareprofile.os.name, 'osfamily': softwareprofile.os.family.name, 'osfamilyvers': int(softwareprofile.os.family.version), 'primaryinstaller': installer_private_fqdn, 'puppetserver': installer_public_fqdn, 'installerip': installer_private_ip, 'url': ('%s/%s/%s/%s' % (self._cm.getYumRootUrl(installer_private_fqdn), softwareprofile.os.name, softwareprofile.os.version, softwareprofile.os.arch)), 'lang': 'en_US.UTF-8', 'keyboard': 'us', 'networkcfg': self.__kickstart_get_network_section(node, hardwareprofile), 'rootpw': self._generatePassword(), 'timezone': self.__kickstart_get_timezone(session), 'includes': '%include /tmp/partinfo', 'repos': '\n'.join(self.__kickstart_get_repos(session, softwareprofile, installer_private_fqdn)), 'packages': '\n'.join([]), 'prescript': self.__kickstart_get_partition_section(softwareprofile), 'installer_url': self._cm.getInstallerUrl(installer_private_fqdn), 'cfmstring': self._cm.getCfmPassword()}<|docstring|>:param node: Object :param hardwareprofile: Object :param softwareprofile: Object :return: Dictionary<|endoftext|>
73b7b4d95a73ea3f9ff5a1609fa66974ef04cb7d1501205e612bb54578df3205
def __init__(self, device=None, batch_size=12, display=False, detection_threshold=0.7, detector_type='yolo', yolo_img_size=608, output_format='list'): "\n Multi Person Tracker\n\n :param device (str, 'cuda' or 'cpu'): torch device for model and inputs\n :param batch_size (int): batch size for detection model\n :param display (bool): display the results of multi person tracking\n :param detection_threshold (float): threshold to filter detector predictions\n :param detector_type (str, 'maskrcnn' or 'yolo'): detector architecture\n :param yolo_img_size (int): yolo detector input image size\n :param output_format (str, 'dict' or 'list'): result output format\n " if (device is not None): self.device = device else: self.device = ('cuda' if torch.cuda.is_available() else 'cpu') self.batch_size = batch_size self.display = display self.detection_threshold = detection_threshold self.output_format = output_format if (detector_type == 'maskrcnn'): self.detector = keypointrcnn_resnet50_fpn(pretrained=True).to(self.device).eval() elif (detector_type == 'yolo'): self.detector = YOLOv3(device=self.device, img_size=yolo_img_size, person_detector=True, video=True, return_dict=True) else: raise ModuleNotFoundError self.tracker = Sort()
Multi Person Tracker :param device (str, 'cuda' or 'cpu'): torch device for model and inputs :param batch_size (int): batch size for detection model :param display (bool): display the results of multi person tracking :param detection_threshold (float): threshold to filter detector predictions :param detector_type (str, 'maskrcnn' or 'yolo'): detector architecture :param yolo_img_size (int): yolo detector input image size :param output_format (str, 'dict' or 'list'): result output format
multi_person_tracker/mpt.py
__init__
mkocabas/multi-person-tracker
121
python
def __init__(self, device=None, batch_size=12, display=False, detection_threshold=0.7, detector_type='yolo', yolo_img_size=608, output_format='list'): "\n Multi Person Tracker\n\n :param device (str, 'cuda' or 'cpu'): torch device for model and inputs\n :param batch_size (int): batch size for detection model\n :param display (bool): display the results of multi person tracking\n :param detection_threshold (float): threshold to filter detector predictions\n :param detector_type (str, 'maskrcnn' or 'yolo'): detector architecture\n :param yolo_img_size (int): yolo detector input image size\n :param output_format (str, 'dict' or 'list'): result output format\n " if (device is not None): self.device = device else: self.device = ('cuda' if torch.cuda.is_available() else 'cpu') self.batch_size = batch_size self.display = display self.detection_threshold = detection_threshold self.output_format = output_format if (detector_type == 'maskrcnn'): self.detector = keypointrcnn_resnet50_fpn(pretrained=True).to(self.device).eval() elif (detector_type == 'yolo'): self.detector = YOLOv3(device=self.device, img_size=yolo_img_size, person_detector=True, video=True, return_dict=True) else: raise ModuleNotFoundError self.tracker = Sort()
def __init__(self, device=None, batch_size=12, display=False, detection_threshold=0.7, detector_type='yolo', yolo_img_size=608, output_format='list'): "\n Multi Person Tracker\n\n :param device (str, 'cuda' or 'cpu'): torch device for model and inputs\n :param batch_size (int): batch size for detection model\n :param display (bool): display the results of multi person tracking\n :param detection_threshold (float): threshold to filter detector predictions\n :param detector_type (str, 'maskrcnn' or 'yolo'): detector architecture\n :param yolo_img_size (int): yolo detector input image size\n :param output_format (str, 'dict' or 'list'): result output format\n " if (device is not None): self.device = device else: self.device = ('cuda' if torch.cuda.is_available() else 'cpu') self.batch_size = batch_size self.display = display self.detection_threshold = detection_threshold self.output_format = output_format if (detector_type == 'maskrcnn'): self.detector = keypointrcnn_resnet50_fpn(pretrained=True).to(self.device).eval() elif (detector_type == 'yolo'): self.detector = YOLOv3(device=self.device, img_size=yolo_img_size, person_detector=True, video=True, return_dict=True) else: raise ModuleNotFoundError self.tracker = Sort()<|docstring|>Multi Person Tracker :param device (str, 'cuda' or 'cpu'): torch device for model and inputs :param batch_size (int): batch size for detection model :param display (bool): display the results of multi person tracking :param detection_threshold (float): threshold to filter detector predictions :param detector_type (str, 'maskrcnn' or 'yolo'): detector architecture :param yolo_img_size (int): yolo detector input image size :param output_format (str, 'dict' or 'list'): result output format<|endoftext|>
058d5acfd4f4d0c49a66e3c627aab42a797c9df5fb1d02d2a0633c73e4e0f0a3
@torch.no_grad() def run_tracker(self, dataloader): '\n Run tracker on an input video\n\n :param video (ndarray): input video tensor of shape NxHxWxC. Preferable use skvideo to read videos\n :return: trackers (ndarray): output tracklets of shape Nx5 [x1,y1,x2,y2,track_id]\n ' self.tracker = Sort() start = time.time() print('Running Multi-Person-Tracker') trackers = [] for batch in tqdm(dataloader): batch = batch.to(self.device) predictions = self.detector(batch) for pred in predictions: bb = pred['boxes'].cpu().numpy() sc = pred['scores'].cpu().numpy()[(..., None)] dets = np.hstack([bb, sc]) dets = dets[(sc[(:, 0)] > self.detection_threshold)] if (dets.shape[0] > 0): track_bbs_ids = self.tracker.update(dets) else: track_bbs_ids = np.empty((0, 5)) trackers.append(track_bbs_ids) runtime = (time.time() - start) fps = (len(dataloader.dataset) / runtime) print(f'Finished. Detection + Tracking FPS {fps:.2f}') return trackers
Run tracker on an input video :param video (ndarray): input video tensor of shape NxHxWxC. Preferable use skvideo to read videos :return: trackers (ndarray): output tracklets of shape Nx5 [x1,y1,x2,y2,track_id]
multi_person_tracker/mpt.py
run_tracker
mkocabas/multi-person-tracker
121
python
@torch.no_grad() def run_tracker(self, dataloader): '\n Run tracker on an input video\n\n :param video (ndarray): input video tensor of shape NxHxWxC. Preferable use skvideo to read videos\n :return: trackers (ndarray): output tracklets of shape Nx5 [x1,y1,x2,y2,track_id]\n ' self.tracker = Sort() start = time.time() print('Running Multi-Person-Tracker') trackers = [] for batch in tqdm(dataloader): batch = batch.to(self.device) predictions = self.detector(batch) for pred in predictions: bb = pred['boxes'].cpu().numpy() sc = pred['scores'].cpu().numpy()[(..., None)] dets = np.hstack([bb, sc]) dets = dets[(sc[(:, 0)] > self.detection_threshold)] if (dets.shape[0] > 0): track_bbs_ids = self.tracker.update(dets) else: track_bbs_ids = np.empty((0, 5)) trackers.append(track_bbs_ids) runtime = (time.time() - start) fps = (len(dataloader.dataset) / runtime) print(f'Finished. Detection + Tracking FPS {fps:.2f}') return trackers
@torch.no_grad() def run_tracker(self, dataloader): '\n Run tracker on an input video\n\n :param video (ndarray): input video tensor of shape NxHxWxC. Preferable use skvideo to read videos\n :return: trackers (ndarray): output tracklets of shape Nx5 [x1,y1,x2,y2,track_id]\n ' self.tracker = Sort() start = time.time() print('Running Multi-Person-Tracker') trackers = [] for batch in tqdm(dataloader): batch = batch.to(self.device) predictions = self.detector(batch) for pred in predictions: bb = pred['boxes'].cpu().numpy() sc = pred['scores'].cpu().numpy()[(..., None)] dets = np.hstack([bb, sc]) dets = dets[(sc[(:, 0)] > self.detection_threshold)] if (dets.shape[0] > 0): track_bbs_ids = self.tracker.update(dets) else: track_bbs_ids = np.empty((0, 5)) trackers.append(track_bbs_ids) runtime = (time.time() - start) fps = (len(dataloader.dataset) / runtime) print(f'Finished. Detection + Tracking FPS {fps:.2f}') return trackers<|docstring|>Run tracker on an input video :param video (ndarray): input video tensor of shape NxHxWxC. Preferable use skvideo to read videos :return: trackers (ndarray): output tracklets of shape Nx5 [x1,y1,x2,y2,track_id]<|endoftext|>
cbee89461f466a04a1a782cff515a53811fb47c0f51b65dc5e6422c41dfa9783
@torch.no_grad() def run_detector(self, dataloader): '\n Run tracker on an input video\n\n :param video (ndarray): input video tensor of shape NxHxWxC. Preferable use skvideo to read videos\n :return: trackers (ndarray): output tracklets of shape Nx5 [x1,y1,x2,y2,track_id]\n ' start = time.time() print('Running Multi-Person-Tracker') detections = [] for batch in tqdm(dataloader): batch = batch.to(self.device) predictions = self.detector(batch) for pred in predictions: bb = pred['boxes'].cpu().numpy() sc = pred['scores'].cpu().numpy()[(..., None)] dets = np.hstack([bb, sc]) dets = dets[(sc[(:, 0)] > self.detection_threshold)] detections.append(dets) runtime = (time.time() - start) fps = (len(dataloader.dataset) / runtime) print(f'Finished. Detection + Tracking FPS {fps:.2f}') return detections
Run tracker on an input video :param video (ndarray): input video tensor of shape NxHxWxC. Preferable use skvideo to read videos :return: trackers (ndarray): output tracklets of shape Nx5 [x1,y1,x2,y2,track_id]
multi_person_tracker/mpt.py
run_detector
mkocabas/multi-person-tracker
121
python
@torch.no_grad() def run_detector(self, dataloader): '\n Run tracker on an input video\n\n :param video (ndarray): input video tensor of shape NxHxWxC. Preferable use skvideo to read videos\n :return: trackers (ndarray): output tracklets of shape Nx5 [x1,y1,x2,y2,track_id]\n ' start = time.time() print('Running Multi-Person-Tracker') detections = [] for batch in tqdm(dataloader): batch = batch.to(self.device) predictions = self.detector(batch) for pred in predictions: bb = pred['boxes'].cpu().numpy() sc = pred['scores'].cpu().numpy()[(..., None)] dets = np.hstack([bb, sc]) dets = dets[(sc[(:, 0)] > self.detection_threshold)] detections.append(dets) runtime = (time.time() - start) fps = (len(dataloader.dataset) / runtime) print(f'Finished. Detection + Tracking FPS {fps:.2f}') return detections
@torch.no_grad() def run_detector(self, dataloader): '\n Run tracker on an input video\n\n :param video (ndarray): input video tensor of shape NxHxWxC. Preferable use skvideo to read videos\n :return: trackers (ndarray): output tracklets of shape Nx5 [x1,y1,x2,y2,track_id]\n ' start = time.time() print('Running Multi-Person-Tracker') detections = [] for batch in tqdm(dataloader): batch = batch.to(self.device) predictions = self.detector(batch) for pred in predictions: bb = pred['boxes'].cpu().numpy() sc = pred['scores'].cpu().numpy()[(..., None)] dets = np.hstack([bb, sc]) dets = dets[(sc[(:, 0)] > self.detection_threshold)] detections.append(dets) runtime = (time.time() - start) fps = (len(dataloader.dataset) / runtime) print(f'Finished. Detection + Tracking FPS {fps:.2f}') return detections<|docstring|>Run tracker on an input video :param video (ndarray): input video tensor of shape NxHxWxC. Preferable use skvideo to read videos :return: trackers (ndarray): output tracklets of shape Nx5 [x1,y1,x2,y2,track_id]<|endoftext|>
b271407c92fc59ad979c35cc11a37cea6bb636144137e94a143467cbf3005194
def prepare_output_tracks(self, trackers): '\n Put results into a dictionary consists of detected people\n :param trackers (ndarray): input tracklets of shape Nx5 [x1,y1,x2,y2,track_id]\n :return: dict: of people. each key represent single person with detected bboxes and frame_ids\n ' people = dict() for (frame_idx, tracks) in enumerate(trackers): for d in tracks: person_id = int(d[4]) (w, h) = ((d[2] - d[0]), (d[3] - d[1])) (c_x, c_y) = ((d[0] + (w / 2)), (d[1] + (h / 2))) w = h = np.where(((w / h) > 1), w, h) bbox = np.array([c_x, c_y, w, h]) if (person_id in people.keys()): people[person_id]['bbox'].append(bbox) people[person_id]['frames'].append(frame_idx) else: people[person_id] = {'bbox': [], 'frames': []} people[person_id]['bbox'].append(bbox) people[person_id]['frames'].append(frame_idx) for k in people.keys(): people[k]['bbox'] = np.array(people[k]['bbox']).reshape((len(people[k]['bbox']), 4)) people[k]['frames'] = np.array(people[k]['frames']) return people
Put results into a dictionary consists of detected people :param trackers (ndarray): input tracklets of shape Nx5 [x1,y1,x2,y2,track_id] :return: dict: of people. each key represent single person with detected bboxes and frame_ids
multi_person_tracker/mpt.py
prepare_output_tracks
mkocabas/multi-person-tracker
121
python
def prepare_output_tracks(self, trackers): '\n Put results into a dictionary consists of detected people\n :param trackers (ndarray): input tracklets of shape Nx5 [x1,y1,x2,y2,track_id]\n :return: dict: of people. each key represent single person with detected bboxes and frame_ids\n ' people = dict() for (frame_idx, tracks) in enumerate(trackers): for d in tracks: person_id = int(d[4]) (w, h) = ((d[2] - d[0]), (d[3] - d[1])) (c_x, c_y) = ((d[0] + (w / 2)), (d[1] + (h / 2))) w = h = np.where(((w / h) > 1), w, h) bbox = np.array([c_x, c_y, w, h]) if (person_id in people.keys()): people[person_id]['bbox'].append(bbox) people[person_id]['frames'].append(frame_idx) else: people[person_id] = {'bbox': [], 'frames': []} people[person_id]['bbox'].append(bbox) people[person_id]['frames'].append(frame_idx) for k in people.keys(): people[k]['bbox'] = np.array(people[k]['bbox']).reshape((len(people[k]['bbox']), 4)) people[k]['frames'] = np.array(people[k]['frames']) return people
def prepare_output_tracks(self, trackers): '\n Put results into a dictionary consists of detected people\n :param trackers (ndarray): input tracklets of shape Nx5 [x1,y1,x2,y2,track_id]\n :return: dict: of people. each key represent single person with detected bboxes and frame_ids\n ' people = dict() for (frame_idx, tracks) in enumerate(trackers): for d in tracks: person_id = int(d[4]) (w, h) = ((d[2] - d[0]), (d[3] - d[1])) (c_x, c_y) = ((d[0] + (w / 2)), (d[1] + (h / 2))) w = h = np.where(((w / h) > 1), w, h) bbox = np.array([c_x, c_y, w, h]) if (person_id in people.keys()): people[person_id]['bbox'].append(bbox) people[person_id]['frames'].append(frame_idx) else: people[person_id] = {'bbox': [], 'frames': []} people[person_id]['bbox'].append(bbox) people[person_id]['frames'].append(frame_idx) for k in people.keys(): people[k]['bbox'] = np.array(people[k]['bbox']).reshape((len(people[k]['bbox']), 4)) people[k]['frames'] = np.array(people[k]['frames']) return people<|docstring|>Put results into a dictionary consists of detected people :param trackers (ndarray): input tracklets of shape Nx5 [x1,y1,x2,y2,track_id] :return: dict: of people. each key represent single person with detected bboxes and frame_ids<|endoftext|>
ddc454c9a2442d03805c5248f715c5f93535fa0ee8c62d806e505adcce903987
def display_results(self, image_folder, trackers, output_file=None): '\n Display the output of multi-person-tracking\n :param video (ndarray): input video tensor of shape NxHxWxC\n :param trackers (ndarray): tracklets of shape Nx5 [x1,y1,x2,y2,track_id]\n :return: None\n ' print('Displaying results..') save = (True if output_file else False) tmp_write_folder = osp.join('/tmp', f'{osp.basename(image_folder)}_mpt_results') os.makedirs(tmp_write_folder, exist_ok=True) colours = np.random.rand(32, 3) image_file_names = sorted([osp.join(image_folder, x) for x in os.listdir(image_folder) if (x.endswith('.png') or x.endswith('.jpg'))]) for (idx, (img_fname, tracker)) in enumerate(zip(image_file_names, trackers)): img = cv2.imread(img_fname) for d in tracker: d = d.astype(np.int32) c = (colours[((d[4] % 32), :)] * 255).astype(np.uint8).tolist() cv2.rectangle(img, (d[0], d[1]), (d[2], d[3]), color=c, thickness=int(round((img.shape[0] / 256)))) cv2.putText(img, f'{d[4]}', ((d[0] - 9), (d[1] - 9)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0)) cv2.putText(img, f'{d[4]}', ((d[0] - 8), (d[1] - 8)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255)) cv2.imshow('result video', img) if ((cv2.waitKey(1) & 255) == ord('q')): break if save: cv2.imwrite(osp.join(tmp_write_folder, f'{idx:06d}.png'), img) cv2.destroyAllWindows() if save: print(f'Saving output video to {output_file}') images_to_video(img_folder=tmp_write_folder, output_vid_file=output_file) shutil.rmtree(tmp_write_folder)
Display the output of multi-person-tracking :param video (ndarray): input video tensor of shape NxHxWxC :param trackers (ndarray): tracklets of shape Nx5 [x1,y1,x2,y2,track_id] :return: None
multi_person_tracker/mpt.py
display_results
mkocabas/multi-person-tracker
121
python
def display_results(self, image_folder, trackers, output_file=None): '\n Display the output of multi-person-tracking\n :param video (ndarray): input video tensor of shape NxHxWxC\n :param trackers (ndarray): tracklets of shape Nx5 [x1,y1,x2,y2,track_id]\n :return: None\n ' print('Displaying results..') save = (True if output_file else False) tmp_write_folder = osp.join('/tmp', f'{osp.basename(image_folder)}_mpt_results') os.makedirs(tmp_write_folder, exist_ok=True) colours = np.random.rand(32, 3) image_file_names = sorted([osp.join(image_folder, x) for x in os.listdir(image_folder) if (x.endswith('.png') or x.endswith('.jpg'))]) for (idx, (img_fname, tracker)) in enumerate(zip(image_file_names, trackers)): img = cv2.imread(img_fname) for d in tracker: d = d.astype(np.int32) c = (colours[((d[4] % 32), :)] * 255).astype(np.uint8).tolist() cv2.rectangle(img, (d[0], d[1]), (d[2], d[3]), color=c, thickness=int(round((img.shape[0] / 256)))) cv2.putText(img, f'{d[4]}', ((d[0] - 9), (d[1] - 9)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0)) cv2.putText(img, f'{d[4]}', ((d[0] - 8), (d[1] - 8)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255)) cv2.imshow('result video', img) if ((cv2.waitKey(1) & 255) == ord('q')): break if save: cv2.imwrite(osp.join(tmp_write_folder, f'{idx:06d}.png'), img) cv2.destroyAllWindows() if save: print(f'Saving output video to {output_file}') images_to_video(img_folder=tmp_write_folder, output_vid_file=output_file) shutil.rmtree(tmp_write_folder)
def display_results(self, image_folder, trackers, output_file=None): '\n Display the output of multi-person-tracking\n :param video (ndarray): input video tensor of shape NxHxWxC\n :param trackers (ndarray): tracklets of shape Nx5 [x1,y1,x2,y2,track_id]\n :return: None\n ' print('Displaying results..') save = (True if output_file else False) tmp_write_folder = osp.join('/tmp', f'{osp.basename(image_folder)}_mpt_results') os.makedirs(tmp_write_folder, exist_ok=True) colours = np.random.rand(32, 3) image_file_names = sorted([osp.join(image_folder, x) for x in os.listdir(image_folder) if (x.endswith('.png') or x.endswith('.jpg'))]) for (idx, (img_fname, tracker)) in enumerate(zip(image_file_names, trackers)): img = cv2.imread(img_fname) for d in tracker: d = d.astype(np.int32) c = (colours[((d[4] % 32), :)] * 255).astype(np.uint8).tolist() cv2.rectangle(img, (d[0], d[1]), (d[2], d[3]), color=c, thickness=int(round((img.shape[0] / 256)))) cv2.putText(img, f'{d[4]}', ((d[0] - 9), (d[1] - 9)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0)) cv2.putText(img, f'{d[4]}', ((d[0] - 8), (d[1] - 8)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255)) cv2.imshow('result video', img) if ((cv2.waitKey(1) & 255) == ord('q')): break if save: cv2.imwrite(osp.join(tmp_write_folder, f'{idx:06d}.png'), img) cv2.destroyAllWindows() if save: print(f'Saving output video to {output_file}') images_to_video(img_folder=tmp_write_folder, output_vid_file=output_file) shutil.rmtree(tmp_write_folder)<|docstring|>Display the output of multi-person-tracking :param video (ndarray): input video tensor of shape NxHxWxC :param trackers (ndarray): tracklets of shape Nx5 [x1,y1,x2,y2,track_id] :return: None<|endoftext|>
19c877ad7ccff7b43fa486b975bd9dccdbf3f49740672bcfbdcd2ded4c7b57c4
def display_detection_results(self, image_folder, detections, output_file=None): '\n Display the output of detector\n :param video (ndarray): input video tensor of shape NxHxWxC\n :param detections (ndarray): detections of shape Nx4 [x1,y1,x2,y2,track_id]\n :return: None\n ' print('Displaying results..') save = (True if output_file else False) tmp_write_folder = osp.join('/tmp', f'{osp.basename(image_folder)}_mpt_results') os.makedirs(tmp_write_folder, exist_ok=True) colours = np.random.rand(32, 3) image_file_names = sorted([osp.join(image_folder, x) for x in os.listdir(image_folder) if (x.endswith('.png') or x.endswith('.jpg'))]) for (idx, (img_fname, dets)) in enumerate(zip(image_file_names, detections)): print(img_fname) img = cv2.imread(img_fname) for d in dets: d = d.astype(np.int32) c = (0, 255, 0) cv2.rectangle(img, (d[0], d[1]), (d[2], d[3]), color=c, thickness=int(round((img.shape[0] / 256)))) cv2.imshow('result image', img) if ((cv2.waitKey(1) & 255) == ord('q')): break if save: cv2.imwrite(osp.join(tmp_write_folder, f'{idx:06d}.png'), img) cv2.destroyAllWindows() if save: print(f'Saving output video to {output_file}') images_to_video(img_folder=tmp_write_folder, output_vid_file=output_file) shutil.rmtree(tmp_write_folder)
Display the output of detector :param video (ndarray): input video tensor of shape NxHxWxC :param detections (ndarray): detections of shape Nx4 [x1,y1,x2,y2,track_id] :return: None
multi_person_tracker/mpt.py
display_detection_results
mkocabas/multi-person-tracker
121
python
def display_detection_results(self, image_folder, detections, output_file=None): '\n Display the output of detector\n :param video (ndarray): input video tensor of shape NxHxWxC\n :param detections (ndarray): detections of shape Nx4 [x1,y1,x2,y2,track_id]\n :return: None\n ' print('Displaying results..') save = (True if output_file else False) tmp_write_folder = osp.join('/tmp', f'{osp.basename(image_folder)}_mpt_results') os.makedirs(tmp_write_folder, exist_ok=True) colours = np.random.rand(32, 3) image_file_names = sorted([osp.join(image_folder, x) for x in os.listdir(image_folder) if (x.endswith('.png') or x.endswith('.jpg'))]) for (idx, (img_fname, dets)) in enumerate(zip(image_file_names, detections)): print(img_fname) img = cv2.imread(img_fname) for d in dets: d = d.astype(np.int32) c = (0, 255, 0) cv2.rectangle(img, (d[0], d[1]), (d[2], d[3]), color=c, thickness=int(round((img.shape[0] / 256)))) cv2.imshow('result image', img) if ((cv2.waitKey(1) & 255) == ord('q')): break if save: cv2.imwrite(osp.join(tmp_write_folder, f'{idx:06d}.png'), img) cv2.destroyAllWindows() if save: print(f'Saving output video to {output_file}') images_to_video(img_folder=tmp_write_folder, output_vid_file=output_file) shutil.rmtree(tmp_write_folder)
def display_detection_results(self, image_folder, detections, output_file=None): '\n Display the output of detector\n :param video (ndarray): input video tensor of shape NxHxWxC\n :param detections (ndarray): detections of shape Nx4 [x1,y1,x2,y2,track_id]\n :return: None\n ' print('Displaying results..') save = (True if output_file else False) tmp_write_folder = osp.join('/tmp', f'{osp.basename(image_folder)}_mpt_results') os.makedirs(tmp_write_folder, exist_ok=True) colours = np.random.rand(32, 3) image_file_names = sorted([osp.join(image_folder, x) for x in os.listdir(image_folder) if (x.endswith('.png') or x.endswith('.jpg'))]) for (idx, (img_fname, dets)) in enumerate(zip(image_file_names, detections)): print(img_fname) img = cv2.imread(img_fname) for d in dets: d = d.astype(np.int32) c = (0, 255, 0) cv2.rectangle(img, (d[0], d[1]), (d[2], d[3]), color=c, thickness=int(round((img.shape[0] / 256)))) cv2.imshow('result image', img) if ((cv2.waitKey(1) & 255) == ord('q')): break if save: cv2.imwrite(osp.join(tmp_write_folder, f'{idx:06d}.png'), img) cv2.destroyAllWindows() if save: print(f'Saving output video to {output_file}') images_to_video(img_folder=tmp_write_folder, output_vid_file=output_file) shutil.rmtree(tmp_write_folder)<|docstring|>Display the output of detector :param video (ndarray): input video tensor of shape NxHxWxC :param detections (ndarray): detections of shape Nx4 [x1,y1,x2,y2,track_id] :return: None<|endoftext|>
c33fd8d66534430a5559e19dfc0287a571eed1b20a62d020bb01c5d1996b852c
def __call__(self, image_folder, output_file=None): '\n Execute MPT and return results as a dictionary of person instances\n\n :param video (ndarray): input video tensor of shape NxHxWxC\n :return: a dictionary of person instances\n ' image_dataset = ImageFolder(image_folder) dataloader = DataLoader(image_dataset, batch_size=self.batch_size, num_workers=0) trackers = self.run_tracker(dataloader) if self.display: self.display_results(image_folder, trackers, output_file) if (self.output_format == 'dict'): result = self.prepare_output_tracks(trackers) elif (self.output_format == 'list'): result = trackers return result
Execute MPT and return results as a dictionary of person instances :param video (ndarray): input video tensor of shape NxHxWxC :return: a dictionary of person instances
multi_person_tracker/mpt.py
__call__
mkocabas/multi-person-tracker
121
python
def __call__(self, image_folder, output_file=None): '\n Execute MPT and return results as a dictionary of person instances\n\n :param video (ndarray): input video tensor of shape NxHxWxC\n :return: a dictionary of person instances\n ' image_dataset = ImageFolder(image_folder) dataloader = DataLoader(image_dataset, batch_size=self.batch_size, num_workers=0) trackers = self.run_tracker(dataloader) if self.display: self.display_results(image_folder, trackers, output_file) if (self.output_format == 'dict'): result = self.prepare_output_tracks(trackers) elif (self.output_format == 'list'): result = trackers return result
def __call__(self, image_folder, output_file=None): '\n Execute MPT and return results as a dictionary of person instances\n\n :param video (ndarray): input video tensor of shape NxHxWxC\n :return: a dictionary of person instances\n ' image_dataset = ImageFolder(image_folder) dataloader = DataLoader(image_dataset, batch_size=self.batch_size, num_workers=0) trackers = self.run_tracker(dataloader) if self.display: self.display_results(image_folder, trackers, output_file) if (self.output_format == 'dict'): result = self.prepare_output_tracks(trackers) elif (self.output_format == 'list'): result = trackers return result<|docstring|>Execute MPT and return results as a dictionary of person instances :param video (ndarray): input video tensor of shape NxHxWxC :return: a dictionary of person instances<|endoftext|>
522cdd7c6e9069fdcfbd979b5cdbade8efeae7b6c63673ad5aea962a2d2821aa
@commands.group(pass_context=True) @has_permissions(manage_roles=True) async def em(self, ctx): 'Описание саб-команд em\n \n -em new [Создание личного embed]\n -em author [text] [Установка названия ивента][128 symbols]\n -em descrip [description] [Установка описания ивента][2048 symbols]\n -em f [1-4] ["Название категории"] ["Описание категории"] [Максимум 4 категории][2048 symbols]\n -em set_img [url] [Вставка картинки, нужен url]\n -em footer [text] [Вставка футера]\n -em send [#channel] [Отправка сообщения с @here]\n -em clear [Очистить embed]\n -em view [Предпросмотр вашего embed]' if (ctx.invoked_subcommand is None): msg = ctx.command.help em = discord.Embed(colour=ctx.message.author.colour) em.add_field(name='Command Helper', value=f'{msg}') (await ctx.send(embed=em))
Описание саб-команд em -em new [Создание личного embed] -em author [text] [Установка названия ивента][128 symbols] -em descrip [description] [Установка описания ивента][2048 symbols] -em f [1-4] ["Название категории"] ["Описание категории"] [Максимум 4 категории][2048 symbols] -em set_img [url] [Вставка картинки, нужен url] -em footer [text] [Вставка футера] -em send [#channel] [Отправка сообщения с @here] -em clear [Очистить embed] -em view [Предпросмотр вашего embed]
cogs/activity.py
em
MikoxMi/Batrack
1
python
@commands.group(pass_context=True) @has_permissions(manage_roles=True) async def em(self, ctx): 'Описание саб-команд em\n \n -em new [Создание личного embed]\n -em author [text] [Установка названия ивента][128 symbols]\n -em descrip [description] [Установка описания ивента][2048 symbols]\n -em f [1-4] ["Название категории"] ["Описание категории"] [Максимум 4 категории][2048 symbols]\n -em set_img [url] [Вставка картинки, нужен url]\n -em footer [text] [Вставка футера]\n -em send [#channel] [Отправка сообщения с @here]\n -em clear [Очистить embed]\n -em view [Предпросмотр вашего embed]' if (ctx.invoked_subcommand is None): msg = ctx.command.help em = discord.Embed(colour=ctx.message.author.colour) em.add_field(name='Command Helper', value=f'{msg}') (await ctx.send(embed=em))
@commands.group(pass_context=True) @has_permissions(manage_roles=True) async def em(self, ctx): 'Описание саб-команд em\n \n -em new [Создание личного embed]\n -em author [text] [Установка названия ивента][128 symbols]\n -em descrip [description] [Установка описания ивента][2048 symbols]\n -em f [1-4] ["Название категории"] ["Описание категории"] [Максимум 4 категории][2048 symbols]\n -em set_img [url] [Вставка картинки, нужен url]\n -em footer [text] [Вставка футера]\n -em send [#channel] [Отправка сообщения с @here]\n -em clear [Очистить embed]\n -em view [Предпросмотр вашего embed]' if (ctx.invoked_subcommand is None): msg = ctx.command.help em = discord.Embed(colour=ctx.message.author.colour) em.add_field(name='Command Helper', value=f'{msg}') (await ctx.send(embed=em))<|docstring|>Описание саб-команд em -em new [Создание личного embed] -em author [text] [Установка названия ивента][128 symbols] -em descrip [description] [Установка описания ивента][2048 symbols] -em f [1-4] ["Название категории"] ["Описание категории"] [Максимум 4 категории][2048 symbols] -em set_img [url] [Вставка картинки, нужен url] -em footer [text] [Вставка футера] -em send [#channel] [Отправка сообщения с @here] -em clear [Очистить embed] -em view [Предпросмотр вашего embed]<|endoftext|>
01d0e96b86a28288dedb9fc3e6041ef68eec071762692f1bca7cf631b06e0779
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def new(self, ctx): 'Создание личного embed\n \n -em new' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): upg = {'embed_owner': author_id, 'author': '', 'description': '', 'field_1': '', 'name_1': '', 'field_2': '', 'name_2': '', 'field_3': '', 'name_3': '', 'field_4': '', 'name_4': '', 'set_image': '', 'footer': ''} (await Mongo.record_insert('embed', upg)) (await ctx.send('Создание вашего личного embed успешно.:white_check_mark:')) else: (await ctx.send("У вас уже есть свои личный embed\nВы можете использовать 'em clear', для его очистки."))
Создание личного embed -em new
cogs/activity.py
new
MikoxMi/Batrack
1
python
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def new(self, ctx): 'Создание личного embed\n \n -em new' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): upg = {'embed_owner': author_id, 'author': , 'description': , 'field_1': , 'name_1': , 'field_2': , 'name_2': , 'field_3': , 'name_3': , 'field_4': , 'name_4': , 'set_image': , 'footer': } (await Mongo.record_insert('embed', upg)) (await ctx.send('Создание вашего личного embed успешно.:white_check_mark:')) else: (await ctx.send("У вас уже есть свои личный embed\nВы можете использовать 'em clear', для его очистки."))
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def new(self, ctx): 'Создание личного embed\n \n -em new' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): upg = {'embed_owner': author_id, 'author': , 'description': , 'field_1': , 'name_1': , 'field_2': , 'name_2': , 'field_3': , 'name_3': , 'field_4': , 'name_4': , 'set_image': , 'footer': } (await Mongo.record_insert('embed', upg)) (await ctx.send('Создание вашего личного embed успешно.:white_check_mark:')) else: (await ctx.send("У вас уже есть свои личный embed\nВы можете использовать 'em clear', для его очистки."))<|docstring|>Создание личного embed -em new<|endoftext|>
9692165026a0867d790b43e5dde87d859df3d0464d2de928bd359d99e801aff4
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def author(self, ctx, *, text): 'Установка заголовка эмбеда\n \n -em author "text" ' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (len(text) > 128): (await ctx.send('Слишком много символов. Максимальное количество: 128')) else: upg = {'author': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка заголовка успешна'))
Установка заголовка эмбеда -em author "text"
cogs/activity.py
author
MikoxMi/Batrack
1
python
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def author(self, ctx, *, text): 'Установка заголовка эмбеда\n \n -em author "text" ' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (len(text) > 128): (await ctx.send('Слишком много символов. Максимальное количество: 128')) else: upg = {'author': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка заголовка успешна'))
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def author(self, ctx, *, text): 'Установка заголовка эмбеда\n \n -em author "text" ' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (len(text) > 128): (await ctx.send('Слишком много символов. Максимальное количество: 128')) else: upg = {'author': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка заголовка успешна'))<|docstring|>Установка заголовка эмбеда -em author "text"<|endoftext|>
2cd98b343c9f04562bf0a67204758ae0fa8afab02f64987e2b621cb11768e998
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def descrip(self, ctx, *, text): 'Установка описания ивента\n \n -em descrip "text" ' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n 'em new'")) pass if (len(text) > 2048): (await ctx.send('Слишком много символов. Максимальное количество: 2048')) else: upg = {'description': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Description введен успешно.'))
Установка описания ивента -em descrip "text"
cogs/activity.py
descrip
MikoxMi/Batrack
1
python
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def descrip(self, ctx, *, text): 'Установка описания ивента\n \n -em descrip "text" ' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n 'em new'")) pass if (len(text) > 2048): (await ctx.send('Слишком много символов. Максимальное количество: 2048')) else: upg = {'description': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Description введен успешно.'))
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def descrip(self, ctx, *, text): 'Установка описания ивента\n \n -em descrip "text" ' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n 'em new'")) pass if (len(text) > 2048): (await ctx.send('Слишком много символов. Максимальное количество: 2048')) else: upg = {'description': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Description введен успешно.'))<|docstring|>Установка описания ивента -em descrip "text"<|endoftext|>
7ab76d6bcdf541a026b9435516fcff19c1b6b02f0c373b90d48a60d97ddc7346
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def set_img(self, ctx, *, url): 'Установка главного изображения\n \n -em set_img "url" ' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass else: upg = {'set_image': url} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка изображения успешно!'))
Установка главного изображения -em set_img "url"
cogs/activity.py
set_img
MikoxMi/Batrack
1
python
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def set_img(self, ctx, *, url): 'Установка главного изображения\n \n -em set_img "url" ' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass else: upg = {'set_image': url} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка изображения успешно!'))
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def set_img(self, ctx, *, url): 'Установка главного изображения\n \n -em set_img "url" ' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass else: upg = {'set_image': url} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка изображения успешно!'))<|docstring|>Установка главного изображения -em set_img "url"<|endoftext|>
d11b47d478f9519d03991d03d6509871370a2fbec565e59d6530aeeba2585d77
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def f(self, ctx, field: int, header, text): 'Установка f\n \n -em f (1-4) "header" "text" ' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass if (field == 1): upg = {'field_1': header, 'name_1': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка первого field успешно')) elif (field == 2): upg = {'field_2': header, 'name_2': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка второго field успешно')) elif (field == 3): upg = {'field_3': header, 'name_3': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка третьего field успешно')) elif (field == 4): upg = {'field_4': header, 'name_4': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка четвертого field успешно')) else: (await ctx.send('Более fields недоступны'))
Установка f -em f (1-4) "header" "text"
cogs/activity.py
f
MikoxMi/Batrack
1
python
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def f(self, ctx, field: int, header, text): 'Установка f\n \n -em f (1-4) "header" "text" ' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass if (field == 1): upg = {'field_1': header, 'name_1': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка первого field успешно')) elif (field == 2): upg = {'field_2': header, 'name_2': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка второго field успешно')) elif (field == 3): upg = {'field_3': header, 'name_3': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка третьего field успешно')) elif (field == 4): upg = {'field_4': header, 'name_4': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка четвертого field успешно')) else: (await ctx.send('Более fields недоступны'))
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def f(self, ctx, field: int, header, text): 'Установка f\n \n -em f (1-4) "header" "text" ' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass if (field == 1): upg = {'field_1': header, 'name_1': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка первого field успешно')) elif (field == 2): upg = {'field_2': header, 'name_2': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка второго field успешно')) elif (field == 3): upg = {'field_3': header, 'name_3': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка третьего field успешно')) elif (field == 4): upg = {'field_4': header, 'name_4': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка четвертого field успешно')) else: (await ctx.send('Более fields недоступны'))<|docstring|>Установка f -em f (1-4) "header" "text"<|endoftext|>
d77fd841f6a979d546687718efedf6e19583f16b91d92337a077295d5ff10c18
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def view(self, ctx): 'Просмотр предварительного сообщения\n\n -em view' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass if (record['description'] != ''): e = discord.Embed(colour=int('0x36393f', 0), description=record['description']) else: e = discord.Embed(colour=int('0x36393f', 0)) if (record['author'] != ''): e.set_author(name=record['author']) if (record['field_1'] != ''): e.add_field(name=record['field_1'], value=f"{record['name_1']}") if (record['field_2'] != ''): e.add_field(name=record['field_2'], value=f"{record['name_2']}") if (record['field_3'] != ''): e.add_field(name=record['field_3'], value=f"{record['name_3']}") if (record['field_4'] != ''): e.add_field(name=record['field_4'], value=f"{record['name_4']}") if (record['set_image'] != ''): e.set_image(url=record['set_image']) if (record['footer'] != ''): e.set_footer(text=record['footer'], icon_url=ctx.message.server.icon_url) (await ctx.send(embed=e))
Просмотр предварительного сообщения -em view
cogs/activity.py
view
MikoxMi/Batrack
1
python
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def view(self, ctx): 'Просмотр предварительного сообщения\n\n -em view' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass if (record['description'] != ): e = discord.Embed(colour=int('0x36393f', 0), description=record['description']) else: e = discord.Embed(colour=int('0x36393f', 0)) if (record['author'] != ): e.set_author(name=record['author']) if (record['field_1'] != ): e.add_field(name=record['field_1'], value=f"{record['name_1']}") if (record['field_2'] != ): e.add_field(name=record['field_2'], value=f"{record['name_2']}") if (record['field_3'] != ): e.add_field(name=record['field_3'], value=f"{record['name_3']}") if (record['field_4'] != ): e.add_field(name=record['field_4'], value=f"{record['name_4']}") if (record['set_image'] != ): e.set_image(url=record['set_image']) if (record['footer'] != ): e.set_footer(text=record['footer'], icon_url=ctx.message.server.icon_url) (await ctx.send(embed=e))
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def view(self, ctx): 'Просмотр предварительного сообщения\n\n -em view' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass if (record['description'] != ): e = discord.Embed(colour=int('0x36393f', 0), description=record['description']) else: e = discord.Embed(colour=int('0x36393f', 0)) if (record['author'] != ): e.set_author(name=record['author']) if (record['field_1'] != ): e.add_field(name=record['field_1'], value=f"{record['name_1']}") if (record['field_2'] != ): e.add_field(name=record['field_2'], value=f"{record['name_2']}") if (record['field_3'] != ): e.add_field(name=record['field_3'], value=f"{record['name_3']}") if (record['field_4'] != ): e.add_field(name=record['field_4'], value=f"{record['name_4']}") if (record['set_image'] != ): e.set_image(url=record['set_image']) if (record['footer'] != ): e.set_footer(text=record['footer'], icon_url=ctx.message.server.icon_url) (await ctx.send(embed=e))<|docstring|>Просмотр предварительного сообщения -em view<|endoftext|>
201988f721e28412fad6d36b9271034be2908e9c1127266e47d3c06d915434fb
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def clear(self, ctx): 'Очистить ваш embed' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass upg = {'embed_owner': ctx.message.author.id, 'author': '', 'description': '', 'field_1': '', 'name_1': '', 'field_2': '', 'name_2': '', 'field_3': '', 'name_3': '', 'field_4': '', 'name_4': '', 'set_image': '', 'footer': ''} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Очистка вашего embed успешна'))
Очистить ваш embed
cogs/activity.py
clear
MikoxMi/Batrack
1
python
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def clear(self, ctx): author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass upg = {'embed_owner': ctx.message.author.id, 'author': , 'description': , 'field_1': , 'name_1': , 'field_2': , 'name_2': , 'field_3': , 'name_3': , 'field_4': , 'name_4': , 'set_image': , 'footer': } (await Mongo.update_record('embed', record, upg)) (await ctx.send('Очистка вашего embed успешна'))
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def clear(self, ctx): author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass upg = {'embed_owner': ctx.message.author.id, 'author': , 'description': , 'field_1': , 'name_1': , 'field_2': , 'name_2': , 'field_3': , 'name_3': , 'field_4': , 'name_4': , 'set_image': , 'footer': } (await Mongo.update_record('embed', record, upg)) (await ctx.send('Очистка вашего embed успешна'))<|docstring|>Очистить ваш embed<|endoftext|>
7970af12099ebb86b99346a9d69c9e917f7fd49b805f8121197362da23674b15
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def footer(self, ctx, *, text): 'Установка текста в footer\n \n -em footer <text>' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass else: upg = {'footer': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка футера успешно!'))
Установка текста в footer -em footer <text>
cogs/activity.py
footer
MikoxMi/Batrack
1
python
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def footer(self, ctx, *, text): 'Установка текста в footer\n \n -em footer <text>' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass else: upg = {'footer': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка футера успешно!'))
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def footer(self, ctx, *, text): 'Установка текста в footer\n \n -em footer <text>' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass else: upg = {'footer': text} (await Mongo.update_record('embed', record, upg)) (await ctx.send('Установка футера успешно!'))<|docstring|>Установка текста в footer -em footer <text><|endoftext|>
ee12eaedfec1e004becc2eea2e123b9e07124079528354e569b6ba14bb7bb14d
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def send(self, ctx, channel): 'Отправка сообщения в определенный канал. DANGER пингует @here\n \n -em send <channel_name>' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass if (record['description'] != ''): e = discord.Embed(colour=int('0x36393f', 0), description=record['description']) else: e = discord.Embed(colour=ctx.message.author.colour) if (record['author'] != ''): e.set_author(name=record['author']) if (record['field_1'] != ''): e.add_field(name=record['field_1'], value=f"{record['name_1']}") if (record['field_2'] != ''): e.add_field(name=record['field_2'], value=f"{record['name_2']}") if (record['field_3'] != ''): e.add_field(name=record['field_3'], value=f"{record['name_3']}") if (record['field_4'] != ''): e.add_field(name=record['field_4'], value=f"{record['name_4']}") if (record['set_image'] != ''): e.set_image(url=record['set_image']) if (record['footer'] != ''): e.set_footer(text=record['footer'], icon_url=ctx.message.server.icon_url) ch = discord.utils.get(self.bot.get_all_channels(), guild__name=ctx.guild.name, name=channel) (await ch.send('@here')) (await ch.send(embed=e))
Отправка сообщения в определенный канал. DANGER пингует @here -em send <channel_name>
cogs/activity.py
send
MikoxMi/Batrack
1
python
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def send(self, ctx, channel): 'Отправка сообщения в определенный канал. DANGER пингует @here\n \n -em send <channel_name>' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass if (record['description'] != ): e = discord.Embed(colour=int('0x36393f', 0), description=record['description']) else: e = discord.Embed(colour=ctx.message.author.colour) if (record['author'] != ): e.set_author(name=record['author']) if (record['field_1'] != ): e.add_field(name=record['field_1'], value=f"{record['name_1']}") if (record['field_2'] != ): e.add_field(name=record['field_2'], value=f"{record['name_2']}") if (record['field_3'] != ): e.add_field(name=record['field_3'], value=f"{record['name_3']}") if (record['field_4'] != ): e.add_field(name=record['field_4'], value=f"{record['name_4']}") if (record['set_image'] != ): e.set_image(url=record['set_image']) if (record['footer'] != ): e.set_footer(text=record['footer'], icon_url=ctx.message.server.icon_url) ch = discord.utils.get(self.bot.get_all_channels(), guild__name=ctx.guild.name, name=channel) (await ch.send('@here')) (await ch.send(embed=e))
@em.group(pass_context=True) @has_permissions(manage_roles=True) async def send(self, ctx, channel): 'Отправка сообщения в определенный канал. DANGER пингует @here\n \n -em send <channel_name>' author_id = ctx.message.author.id record = (await Mongo.get_record('embed', 'embed_owner', author_id)) if (record is None): (await ctx.send("Для начала нужно создать свой личный embed\n '-em new'")) pass if (record['description'] != ): e = discord.Embed(colour=int('0x36393f', 0), description=record['description']) else: e = discord.Embed(colour=ctx.message.author.colour) if (record['author'] != ): e.set_author(name=record['author']) if (record['field_1'] != ): e.add_field(name=record['field_1'], value=f"{record['name_1']}") if (record['field_2'] != ): e.add_field(name=record['field_2'], value=f"{record['name_2']}") if (record['field_3'] != ): e.add_field(name=record['field_3'], value=f"{record['name_3']}") if (record['field_4'] != ): e.add_field(name=record['field_4'], value=f"{record['name_4']}") if (record['set_image'] != ): e.set_image(url=record['set_image']) if (record['footer'] != ): e.set_footer(text=record['footer'], icon_url=ctx.message.server.icon_url) ch = discord.utils.get(self.bot.get_all_channels(), guild__name=ctx.guild.name, name=channel) (await ch.send('@here')) (await ch.send(embed=e))<|docstring|>Отправка сообщения в определенный канал. DANGER пингует @here -em send <channel_name><|endoftext|>
cb0f7693e71d623412572800015be6476ecdae449fdc9abf68f9f839e1c9d91f
@abstractmethod def fit(self, item_users): '\n Trains the model on a sparse matrix of item/user/weight\n\n Parameters\n ----------\n item_user : csr_matrix\n A matrix of shape (number_of_items, number_of_users). The nonzero\n entries in this matrix are the items that are liked by each user.\n The values are how confidant you are that the item is liked by the user.\n ' pass
Trains the model on a sparse matrix of item/user/weight Parameters ---------- item_user : csr_matrix A matrix of shape (number_of_items, number_of_users). The nonzero entries in this matrix are the items that are liked by each user. The values are how confidant you are that the item is liked by the user.
implicit/recommender_base.py
fit
zhouyonglong/Fast-Python-Collaborative-Filtering-for-Implicit-Datasets
0
python
@abstractmethod def fit(self, item_users): '\n Trains the model on a sparse matrix of item/user/weight\n\n Parameters\n ----------\n item_user : csr_matrix\n A matrix of shape (number_of_items, number_of_users). The nonzero\n entries in this matrix are the items that are liked by each user.\n The values are how confidant you are that the item is liked by the user.\n ' pass
@abstractmethod def fit(self, item_users): '\n Trains the model on a sparse matrix of item/user/weight\n\n Parameters\n ----------\n item_user : csr_matrix\n A matrix of shape (number_of_items, number_of_users). The nonzero\n entries in this matrix are the items that are liked by each user.\n The values are how confidant you are that the item is liked by the user.\n ' pass<|docstring|>Trains the model on a sparse matrix of item/user/weight Parameters ---------- item_user : csr_matrix A matrix of shape (number_of_items, number_of_users). The nonzero entries in this matrix are the items that are liked by each user. The values are how confidant you are that the item is liked by the user.<|endoftext|>
50813f19740696ace77f7663ef81ce01cee9e14db336e2ca8af1765298c9da4c
@abstractmethod def recommend(self, userid, user_items, N=10, filter_items=None, recalculate_user=False): "\n Recommends items for a user\n\n Calculates the N best recommendations for a user, and returns a list of itemids, score.\n\n Parameters\n ----------\n userid : int\n The userid to calculate recommendations for\n user_items : csr_matrix\n A sparse matrix of shape (number_users, number_items). This lets us look\n up the liked items and their weights for the user. This is used to filter out\n items that have already been liked from the output, and to also potentially\n calculate the best items for this user.\n N : int, optional\n The number of results to return\n filter_items : sequence of ints, optional\n List of extra item ids to filter out from the output\n recalculate_user : bool, optional\n When true, don't rely on stored user state and instead recalculate from the\n passed in user_items\n\n Returns\n -------\n list\n List of (itemid, score) tuples\n " pass
Recommends items for a user Calculates the N best recommendations for a user, and returns a list of itemids, score. Parameters ---------- userid : int The userid to calculate recommendations for user_items : csr_matrix A sparse matrix of shape (number_users, number_items). This lets us look up the liked items and their weights for the user. This is used to filter out items that have already been liked from the output, and to also potentially calculate the best items for this user. N : int, optional The number of results to return filter_items : sequence of ints, optional List of extra item ids to filter out from the output recalculate_user : bool, optional When true, don't rely on stored user state and instead recalculate from the passed in user_items Returns ------- list List of (itemid, score) tuples
implicit/recommender_base.py
recommend
zhouyonglong/Fast-Python-Collaborative-Filtering-for-Implicit-Datasets
0
python
@abstractmethod def recommend(self, userid, user_items, N=10, filter_items=None, recalculate_user=False): "\n Recommends items for a user\n\n Calculates the N best recommendations for a user, and returns a list of itemids, score.\n\n Parameters\n ----------\n userid : int\n The userid to calculate recommendations for\n user_items : csr_matrix\n A sparse matrix of shape (number_users, number_items). This lets us look\n up the liked items and their weights for the user. This is used to filter out\n items that have already been liked from the output, and to also potentially\n calculate the best items for this user.\n N : int, optional\n The number of results to return\n filter_items : sequence of ints, optional\n List of extra item ids to filter out from the output\n recalculate_user : bool, optional\n When true, don't rely on stored user state and instead recalculate from the\n passed in user_items\n\n Returns\n -------\n list\n List of (itemid, score) tuples\n " pass
@abstractmethod def recommend(self, userid, user_items, N=10, filter_items=None, recalculate_user=False): "\n Recommends items for a user\n\n Calculates the N best recommendations for a user, and returns a list of itemids, score.\n\n Parameters\n ----------\n userid : int\n The userid to calculate recommendations for\n user_items : csr_matrix\n A sparse matrix of shape (number_users, number_items). This lets us look\n up the liked items and their weights for the user. This is used to filter out\n items that have already been liked from the output, and to also potentially\n calculate the best items for this user.\n N : int, optional\n The number of results to return\n filter_items : sequence of ints, optional\n List of extra item ids to filter out from the output\n recalculate_user : bool, optional\n When true, don't rely on stored user state and instead recalculate from the\n passed in user_items\n\n Returns\n -------\n list\n List of (itemid, score) tuples\n " pass<|docstring|>Recommends items for a user Calculates the N best recommendations for a user, and returns a list of itemids, score. Parameters ---------- userid : int The userid to calculate recommendations for user_items : csr_matrix A sparse matrix of shape (number_users, number_items). This lets us look up the liked items and their weights for the user. This is used to filter out items that have already been liked from the output, and to also potentially calculate the best items for this user. N : int, optional The number of results to return filter_items : sequence of ints, optional List of extra item ids to filter out from the output recalculate_user : bool, optional When true, don't rely on stored user state and instead recalculate from the passed in user_items Returns ------- list List of (itemid, score) tuples<|endoftext|>
df51230fe8c0c93ec89b58ebc612775cba4bddd518091a5b2784c3043cf89bf9
@abstractmethod def similar_items(self, itemid, N=10): '\n Calculates a list of similar items\n\n Parameters\n ----------\n itemid : int\n The row id of the item to retrieve similar items for\n N : int, optional\n The number of similar items to return\n\n Returns\n -------\n list\n List of (itemid, score) tuples\n ' pass
Calculates a list of similar items Parameters ---------- itemid : int The row id of the item to retrieve similar items for N : int, optional The number of similar items to return Returns ------- list List of (itemid, score) tuples
implicit/recommender_base.py
similar_items
zhouyonglong/Fast-Python-Collaborative-Filtering-for-Implicit-Datasets
0
python
@abstractmethod def similar_items(self, itemid, N=10): '\n Calculates a list of similar items\n\n Parameters\n ----------\n itemid : int\n The row id of the item to retrieve similar items for\n N : int, optional\n The number of similar items to return\n\n Returns\n -------\n list\n List of (itemid, score) tuples\n ' pass
@abstractmethod def similar_items(self, itemid, N=10): '\n Calculates a list of similar items\n\n Parameters\n ----------\n itemid : int\n The row id of the item to retrieve similar items for\n N : int, optional\n The number of similar items to return\n\n Returns\n -------\n list\n List of (itemid, score) tuples\n ' pass<|docstring|>Calculates a list of similar items Parameters ---------- itemid : int The row id of the item to retrieve similar items for N : int, optional The number of similar items to return Returns ------- list List of (itemid, score) tuples<|endoftext|>
31302ca5c0f2bf691f579bad6f2f91024ed2d01c41daa93fa8cdacfb1502749a
def set_is_valid_rss(self): 'Check to if this is actually a valid RSS feed' if (self.title and self.link and self.description): self.is_valid_rss = True else: self.is_valid_rss = False
Check to if this is actually a valid RSS feed
pyPodcastParser/Podcast.py
set_is_valid_rss
nick-symon/pyPodcastParser
16
python
def set_is_valid_rss(self): if (self.title and self.link and self.description): self.is_valid_rss = True else: self.is_valid_rss = False
def set_is_valid_rss(self): if (self.title and self.link and self.description): self.is_valid_rss = True else: self.is_valid_rss = False<|docstring|>Check to if this is actually a valid RSS feed<|endoftext|>
2f1dcc1ab84fdfca5548a677a87fa481057c58edd0e9c8dad428b7c7f1f8c82e
def set_extended_elements(self): 'Parses and sets non required elements' self.set_creative_commons() self.set_owner() self.set_subtitle() self.set_summary()
Parses and sets non required elements
pyPodcastParser/Podcast.py
set_extended_elements
nick-symon/pyPodcastParser
16
python
def set_extended_elements(self): self.set_creative_commons() self.set_owner() self.set_subtitle() self.set_summary()
def set_extended_elements(self): self.set_creative_commons() self.set_owner() self.set_subtitle() self.set_summary()<|docstring|>Parses and sets non required elements<|endoftext|>
adda2cdd2133dc91ef3142589a93e1c89134f1f48f8211b81fe71d971c7779e9
def set_itunes(self): 'Sets elements related to itunes' self.set_itunes_author_name() self.set_itunes_block() self.set_itunes_complete() self.set_itunes_explicit() self.set_itune_image() self.set_itunes_keywords() self.set_itunes_new_feed_url() self.set_itunes_categories() self.set_items()
Sets elements related to itunes
pyPodcastParser/Podcast.py
set_itunes
nick-symon/pyPodcastParser
16
python
def set_itunes(self): self.set_itunes_author_name() self.set_itunes_block() self.set_itunes_complete() self.set_itunes_explicit() self.set_itune_image() self.set_itunes_keywords() self.set_itunes_new_feed_url() self.set_itunes_categories() self.set_items()
def set_itunes(self): self.set_itunes_author_name() self.set_itunes_block() self.set_itunes_complete() self.set_itunes_explicit() self.set_itune_image() self.set_itunes_keywords() self.set_itunes_new_feed_url() self.set_itunes_categories() self.set_items()<|docstring|>Sets elements related to itunes<|endoftext|>
7dd5f4f64de5e1c781bcc5ea8e06e9bbcae21189302768500b8766622bd5b29b
def set_optional_elements(self): 'Sets elements considered option by RSS spec' self.set_categories() self.set_copyright() self.set_generator() self.set_image() self.set_language() self.set_last_build_date() self.set_managing_editor() self.set_published_date() self.set_pubsubhubbub() self.set_ttl() self.set_web_master()
Sets elements considered option by RSS spec
pyPodcastParser/Podcast.py
set_optional_elements
nick-symon/pyPodcastParser
16
python
def set_optional_elements(self): self.set_categories() self.set_copyright() self.set_generator() self.set_image() self.set_language() self.set_last_build_date() self.set_managing_editor() self.set_published_date() self.set_pubsubhubbub() self.set_ttl() self.set_web_master()
def set_optional_elements(self): self.set_categories() self.set_copyright() self.set_generator() self.set_image() self.set_language() self.set_last_build_date() self.set_managing_editor() self.set_published_date() self.set_pubsubhubbub() self.set_ttl() self.set_web_master()<|docstring|>Sets elements considered option by RSS spec<|endoftext|>
9dd81c040031c583bb781f0dd1786d5ad117c39c139335982b0b64ed8bf41675
def set_required_elements(self): 'Sets elements required by RSS spec' self.set_title() self.set_link() self.set_description()
Sets elements required by RSS spec
pyPodcastParser/Podcast.py
set_required_elements
nick-symon/pyPodcastParser
16
python
def set_required_elements(self): self.set_title() self.set_link() self.set_description()
def set_required_elements(self): self.set_title() self.set_link() self.set_description()<|docstring|>Sets elements required by RSS spec<|endoftext|>
cf564728087bde631195a65c942aefc04bbe9344c5c8424a4c0e2bbd4bb28405
def set_soup(self): 'Sets soup and strips items' self.soup = BeautifulSoup(self.feed_content, 'html.parser') for item in self.soup.findAll('item'): item.decompose() for image in self.soup.findAll('image'): image.decompose()
Sets soup and strips items
pyPodcastParser/Podcast.py
set_soup
nick-symon/pyPodcastParser
16
python
def set_soup(self): self.soup = BeautifulSoup(self.feed_content, 'html.parser') for item in self.soup.findAll('item'): item.decompose() for image in self.soup.findAll('image'): image.decompose()
def set_soup(self): self.soup = BeautifulSoup(self.feed_content, 'html.parser') for item in self.soup.findAll('item'): item.decompose() for image in self.soup.findAll('image'): image.decompose()<|docstring|>Sets soup and strips items<|endoftext|>
221da13b1a3861a1ff385046968c9cc5d1c316c21929cf67d9fd86db37e6790b
def set_full_soup(self): 'Sets soup and keeps items' self.full_soup = BeautifulSoup(self.feed_content, 'html.parser')
Sets soup and keeps items
pyPodcastParser/Podcast.py
set_full_soup
nick-symon/pyPodcastParser
16
python
def set_full_soup(self): self.full_soup = BeautifulSoup(self.feed_content, 'html.parser')
def set_full_soup(self): self.full_soup = BeautifulSoup(self.feed_content, 'html.parser')<|docstring|>Sets soup and keeps items<|endoftext|>
7cc77a71a8ced2ca54a2bd4e708032fd9f54c14d814582770ea927981e346293
def set_categories(self): 'Parses and set feed categories' self.categories = [] temp_categories = self.soup.findAll('category') for category in temp_categories: category_text = category.string self.categories.append(category_text)
Parses and set feed categories
pyPodcastParser/Podcast.py
set_categories
nick-symon/pyPodcastParser
16
python
def set_categories(self): self.categories = [] temp_categories = self.soup.findAll('category') for category in temp_categories: category_text = category.string self.categories.append(category_text)
def set_categories(self): self.categories = [] temp_categories = self.soup.findAll('category') for category in temp_categories: category_text = category.string self.categories.append(category_text)<|docstring|>Parses and set feed categories<|endoftext|>
16225647cfc04006b35a813863b440e3e2758144c26bb1c278c8a746ad40780f
def count_items(self): 'Counts Items in full_soup and soup. For debugging' soup_items = self.soup.findAll('item') full_soup_items = self.full_soup.findAll('item') return (len(soup_items), len(full_soup_items))
Counts Items in full_soup and soup. For debugging
pyPodcastParser/Podcast.py
count_items
nick-symon/pyPodcastParser
16
python
def count_items(self): soup_items = self.soup.findAll('item') full_soup_items = self.full_soup.findAll('item') return (len(soup_items), len(full_soup_items))
def count_items(self): soup_items = self.soup.findAll('item') full_soup_items = self.full_soup.findAll('item') return (len(soup_items), len(full_soup_items))<|docstring|>Counts Items in full_soup and soup. For debugging<|endoftext|>
5d637378f54e33e1d9e26beddbb5e9f9b01834803bba86ac97cb6924fe1b4940
def set_copyright(self): 'Parses copyright and set value' try: self.copyright = self.soup.find('copyright').string except AttributeError: self.copyright = None
Parses copyright and set value
pyPodcastParser/Podcast.py
set_copyright
nick-symon/pyPodcastParser
16
python
def set_copyright(self): try: self.copyright = self.soup.find('copyright').string except AttributeError: self.copyright = None
def set_copyright(self): try: self.copyright = self.soup.find('copyright').string except AttributeError: self.copyright = None<|docstring|>Parses copyright and set value<|endoftext|>
53be6c0b1ac996d05a0a6e77fa2a1d0311f2b9b24b4c14959eef5a4073582f27
def set_creative_commons(self): 'Parses creative commons for item and sets value' try: self.creative_commons = self.soup.find('creativecommons:license').string except AttributeError: self.creative_commons = None
Parses creative commons for item and sets value
pyPodcastParser/Podcast.py
set_creative_commons
nick-symon/pyPodcastParser
16
python
def set_creative_commons(self): try: self.creative_commons = self.soup.find('creativecommons:license').string except AttributeError: self.creative_commons = None
def set_creative_commons(self): try: self.creative_commons = self.soup.find('creativecommons:license').string except AttributeError: self.creative_commons = None<|docstring|>Parses creative commons for item and sets value<|endoftext|>
d34b2ff6656d373e015dd3bfe313a469f82215e1dccafbe3c100b40ebd00a635
def set_description(self): 'Parses description and sets value' try: self.description = self.soup.find('description').string except AttributeError: self.description = None
Parses description and sets value
pyPodcastParser/Podcast.py
set_description
nick-symon/pyPodcastParser
16
python
def set_description(self): try: self.description = self.soup.find('description').string except AttributeError: self.description = None
def set_description(self): try: self.description = self.soup.find('description').string except AttributeError: self.description = None<|docstring|>Parses description and sets value<|endoftext|>
0a01645a076148e7ea7935f5459579c9399ecee93b2bb2bcfe95af77834f2c1f
def set_generator(self): 'Parses feed generator and sets value' try: self.generator = self.soup.find('generator').string except AttributeError: self.generator = None
Parses feed generator and sets value
pyPodcastParser/Podcast.py
set_generator
nick-symon/pyPodcastParser
16
python
def set_generator(self): try: self.generator = self.soup.find('generator').string except AttributeError: self.generator = None
def set_generator(self): try: self.generator = self.soup.find('generator').string except AttributeError: self.generator = None<|docstring|>Parses feed generator and sets value<|endoftext|>
90904ac7553bc525b255e6d4eba9639d80ee8ed63dbdc6be590b5fd75e29447e
def set_image(self): 'Parses image element and set values' temp_soup = self.full_soup for item in temp_soup.findAll('item'): item.decompose() image = temp_soup.find('image') try: self.image_title = image.find('title').string except AttributeError: self.image_title = None try: self.image_url = image.find('url').string except AttributeError: self.image_url = None try: self.image_link = image.find('link').string except AttributeError: self.image_link = None try: self.image_width = image.find('width').string except AttributeError: self.image_width = None try: self.image_height = image.find('height').string except AttributeError: self.image_height = None
Parses image element and set values
pyPodcastParser/Podcast.py
set_image
nick-symon/pyPodcastParser
16
python
def set_image(self): temp_soup = self.full_soup for item in temp_soup.findAll('item'): item.decompose() image = temp_soup.find('image') try: self.image_title = image.find('title').string except AttributeError: self.image_title = None try: self.image_url = image.find('url').string except AttributeError: self.image_url = None try: self.image_link = image.find('link').string except AttributeError: self.image_link = None try: self.image_width = image.find('width').string except AttributeError: self.image_width = None try: self.image_height = image.find('height').string except AttributeError: self.image_height = None
def set_image(self): temp_soup = self.full_soup for item in temp_soup.findAll('item'): item.decompose() image = temp_soup.find('image') try: self.image_title = image.find('title').string except AttributeError: self.image_title = None try: self.image_url = image.find('url').string except AttributeError: self.image_url = None try: self.image_link = image.find('link').string except AttributeError: self.image_link = None try: self.image_width = image.find('width').string except AttributeError: self.image_width = None try: self.image_height = image.find('height').string except AttributeError: self.image_height = None<|docstring|>Parses image element and set values<|endoftext|>
4da7da491adc7d8a2b18f0f3f473d413edf457ec62b0c7341741d15a16414ea3
def set_itunes_author_name(self): 'Parses author name from itunes tags and sets value' try: self.itunes_author_name = self.soup.find('itunes:author').string except AttributeError: self.itunes_author_name = None
Parses author name from itunes tags and sets value
pyPodcastParser/Podcast.py
set_itunes_author_name
nick-symon/pyPodcastParser
16
python
def set_itunes_author_name(self): try: self.itunes_author_name = self.soup.find('itunes:author').string except AttributeError: self.itunes_author_name = None
def set_itunes_author_name(self): try: self.itunes_author_name = self.soup.find('itunes:author').string except AttributeError: self.itunes_author_name = None<|docstring|>Parses author name from itunes tags and sets value<|endoftext|>
bb802483450e4a332556ee1abf7dedec2b581a41e0232bb91502a0e76bd2fd61
def set_itunes_block(self): 'Check and see if podcast is blocked from iTunes and sets value' try: block = self.soup.find('itunes:block').string.lower() except AttributeError: block = '' if (block == 'yes'): self.itunes_block = True else: self.itunes_block = False
Check and see if podcast is blocked from iTunes and sets value
pyPodcastParser/Podcast.py
set_itunes_block
nick-symon/pyPodcastParser
16
python
def set_itunes_block(self): try: block = self.soup.find('itunes:block').string.lower() except AttributeError: block = if (block == 'yes'): self.itunes_block = True else: self.itunes_block = False
def set_itunes_block(self): try: block = self.soup.find('itunes:block').string.lower() except AttributeError: block = if (block == 'yes'): self.itunes_block = True else: self.itunes_block = False<|docstring|>Check and see if podcast is blocked from iTunes and sets value<|endoftext|>
54b6745d3234b41d2400bf3ac488194961bb0616f6617cd88f4a9aa364d55431
def set_itunes_categories(self): 'Parses and set itunes categories' self.itunes_categories = [] temp_categories = self.soup.findAll('itunes:category') for category in temp_categories: category_text = category.get('text') self.itunes_categories.append(category_text)
Parses and set itunes categories
pyPodcastParser/Podcast.py
set_itunes_categories
nick-symon/pyPodcastParser
16
python
def set_itunes_categories(self): self.itunes_categories = [] temp_categories = self.soup.findAll('itunes:category') for category in temp_categories: category_text = category.get('text') self.itunes_categories.append(category_text)
def set_itunes_categories(self): self.itunes_categories = [] temp_categories = self.soup.findAll('itunes:category') for category in temp_categories: category_text = category.get('text') self.itunes_categories.append(category_text)<|docstring|>Parses and set itunes categories<|endoftext|>
bcb701dbef30554efebe18abaaf45e635b4910a5a6a634ee9232eca726ce3140
def set_itunes_complete(self): 'Parses complete from itunes tags and sets value' try: self.itunes_complete = self.soup.find('itunes:complete').string self.itunes_complete = self.itunes_complete.lower() except AttributeError: self.itunes_complete = None
Parses complete from itunes tags and sets value
pyPodcastParser/Podcast.py
set_itunes_complete
nick-symon/pyPodcastParser
16
python
def set_itunes_complete(self): try: self.itunes_complete = self.soup.find('itunes:complete').string self.itunes_complete = self.itunes_complete.lower() except AttributeError: self.itunes_complete = None
def set_itunes_complete(self): try: self.itunes_complete = self.soup.find('itunes:complete').string self.itunes_complete = self.itunes_complete.lower() except AttributeError: self.itunes_complete = None<|docstring|>Parses complete from itunes tags and sets value<|endoftext|>
177e7003da430d0817483ac991a45299924c406fafeb1613b2c3cfb21f72665e
def set_itunes_explicit(self): 'Parses explicit from itunes tags and sets value' try: self.itunes_explicit = self.soup.find('itunes:explicit').string self.itunes_explicit = self.itunes_explicit.lower() except AttributeError: self.itunes_explicit = None
Parses explicit from itunes tags and sets value
pyPodcastParser/Podcast.py
set_itunes_explicit
nick-symon/pyPodcastParser
16
python
def set_itunes_explicit(self): try: self.itunes_explicit = self.soup.find('itunes:explicit').string self.itunes_explicit = self.itunes_explicit.lower() except AttributeError: self.itunes_explicit = None
def set_itunes_explicit(self): try: self.itunes_explicit = self.soup.find('itunes:explicit').string self.itunes_explicit = self.itunes_explicit.lower() except AttributeError: self.itunes_explicit = None<|docstring|>Parses explicit from itunes tags and sets value<|endoftext|>
2ea303c66e0395ac21c8d7365e340e5ebf59b52de538aa7fd8943fed23d11398
def set_itune_image(self): 'Parses itunes images and set url as value' try: self.itune_image = self.soup.find('itunes:image').get('href') except AttributeError: self.itune_image = None
Parses itunes images and set url as value
pyPodcastParser/Podcast.py
set_itune_image
nick-symon/pyPodcastParser
16
python
def set_itune_image(self): try: self.itune_image = self.soup.find('itunes:image').get('href') except AttributeError: self.itune_image = None
def set_itune_image(self): try: self.itune_image = self.soup.find('itunes:image').get('href') except AttributeError: self.itune_image = None<|docstring|>Parses itunes images and set url as value<|endoftext|>
4d9108f268fd5503a524e845035a590f0ec977af4d2345e6c0d9962e7041af1a
def set_itunes_keywords(self): 'Parses itunes keywords and set value' try: keywords = self.soup.find('itunes:keywords').string except AttributeError: keywords = None try: self.itunes_keywords = [keyword.strip() for keyword in keywords.split(',')] self.itunes_keywords = list(set(self.itunes_keywords)) except AttributeError: self.itunes_keywords = []
Parses itunes keywords and set value
pyPodcastParser/Podcast.py
set_itunes_keywords
nick-symon/pyPodcastParser
16
python
def set_itunes_keywords(self): try: keywords = self.soup.find('itunes:keywords').string except AttributeError: keywords = None try: self.itunes_keywords = [keyword.strip() for keyword in keywords.split(',')] self.itunes_keywords = list(set(self.itunes_keywords)) except AttributeError: self.itunes_keywords = []
def set_itunes_keywords(self): try: keywords = self.soup.find('itunes:keywords').string except AttributeError: keywords = None try: self.itunes_keywords = [keyword.strip() for keyword in keywords.split(',')] self.itunes_keywords = list(set(self.itunes_keywords)) except AttributeError: self.itunes_keywords = []<|docstring|>Parses itunes keywords and set value<|endoftext|>
236b269b79906f14bdbbb3a1b92966653520ca7b175fc8bdb27553fa021e4955
def set_itunes_new_feed_url(self): 'Parses new feed url from itunes tags and sets value' try: self.itunes_new_feed_url = self.soup.find('itunes:new-feed-url').string except AttributeError: self.itunes_new_feed_url = None
Parses new feed url from itunes tags and sets value
pyPodcastParser/Podcast.py
set_itunes_new_feed_url
nick-symon/pyPodcastParser
16
python
def set_itunes_new_feed_url(self): try: self.itunes_new_feed_url = self.soup.find('itunes:new-feed-url').string except AttributeError: self.itunes_new_feed_url = None
def set_itunes_new_feed_url(self): try: self.itunes_new_feed_url = self.soup.find('itunes:new-feed-url').string except AttributeError: self.itunes_new_feed_url = None<|docstring|>Parses new feed url from itunes tags and sets value<|endoftext|>
fbc3cfadeb855a821536a030f5d694fd67460806dddb74d58c37acee79d2e393
def set_language(self): 'Parses feed language and set value' try: self.language = self.soup.find('language').string except AttributeError: self.language = None
Parses feed language and set value
pyPodcastParser/Podcast.py
set_language
nick-symon/pyPodcastParser
16
python
def set_language(self): try: self.language = self.soup.find('language').string except AttributeError: self.language = None
def set_language(self): try: self.language = self.soup.find('language').string except AttributeError: self.language = None<|docstring|>Parses feed language and set value<|endoftext|>
11438837642f6f057978bc38e354af3c863b5103f5f36cab41be344301b74ea2
def set_last_build_date(self): 'Parses last build date and set value' try: self.last_build_date = self.soup.find('lastbuilddate').string except AttributeError: self.last_build_date = None
Parses last build date and set value
pyPodcastParser/Podcast.py
set_last_build_date
nick-symon/pyPodcastParser
16
python
def set_last_build_date(self): try: self.last_build_date = self.soup.find('lastbuilddate').string except AttributeError: self.last_build_date = None
def set_last_build_date(self): try: self.last_build_date = self.soup.find('lastbuilddate').string except AttributeError: self.last_build_date = None<|docstring|>Parses last build date and set value<|endoftext|>
24a993000d907be92183a3a0fb65da023670b9d1ee96b710ec690cd6c58fce55
def set_link(self): 'Parses link to homepage and set value' try: self.link = self.soup.find('link').string except AttributeError: self.link = None
Parses link to homepage and set value
pyPodcastParser/Podcast.py
set_link
nick-symon/pyPodcastParser
16
python
def set_link(self): try: self.link = self.soup.find('link').string except AttributeError: self.link = None
def set_link(self): try: self.link = self.soup.find('link').string except AttributeError: self.link = None<|docstring|>Parses link to homepage and set value<|endoftext|>
d8843e22454b5ed1c117011018c16ed58bcb02b279a589b3ede87950f6b31bc7
def set_managing_editor(self): 'Parses managing editor and set value' try: self.managing_editor = self.soup.find('managingeditor').string except AttributeError: self.managing_editor = None
Parses managing editor and set value
pyPodcastParser/Podcast.py
set_managing_editor
nick-symon/pyPodcastParser
16
python
def set_managing_editor(self): try: self.managing_editor = self.soup.find('managingeditor').string except AttributeError: self.managing_editor = None
def set_managing_editor(self): try: self.managing_editor = self.soup.find('managingeditor').string except AttributeError: self.managing_editor = None<|docstring|>Parses managing editor and set value<|endoftext|>
f3537b888662594612921e1a56aa1a532aab4e2212503d7ed73d345f9ae32014
def set_published_date(self): 'Parses published date and set value' try: self.published_date = self.soup.find('pubdate').string except AttributeError: self.published_date = None
Parses published date and set value
pyPodcastParser/Podcast.py
set_published_date
nick-symon/pyPodcastParser
16
python
def set_published_date(self): try: self.published_date = self.soup.find('pubdate').string except AttributeError: self.published_date = None
def set_published_date(self): try: self.published_date = self.soup.find('pubdate').string except AttributeError: self.published_date = None<|docstring|>Parses published date and set value<|endoftext|>
7835b490050ea545cf8d5bd8c5b4a03276c269d6fbdd2ae89967aa286d4cf2d2
def set_pubsubhubbub(self): 'Parses pubsubhubbub and email then sets value' self.pubsubhubbub = None atom_links = self.soup.findAll('atom:link') for atom_link in atom_links: rel = atom_link.get('rel') if (rel == 'hub'): self.pubsubhubbub = atom_link.get('href')
Parses pubsubhubbub and email then sets value
pyPodcastParser/Podcast.py
set_pubsubhubbub
nick-symon/pyPodcastParser
16
python
def set_pubsubhubbub(self): self.pubsubhubbub = None atom_links = self.soup.findAll('atom:link') for atom_link in atom_links: rel = atom_link.get('rel') if (rel == 'hub'): self.pubsubhubbub = atom_link.get('href')
def set_pubsubhubbub(self): self.pubsubhubbub = None atom_links = self.soup.findAll('atom:link') for atom_link in atom_links: rel = atom_link.get('rel') if (rel == 'hub'): self.pubsubhubbub = atom_link.get('href')<|docstring|>Parses pubsubhubbub and email then sets value<|endoftext|>
7270e7f5c2b97b1949795a8c901e1fc2757d878ff9b4330e0958022ef5198bfb
def set_owner(self): 'Parses owner name and email then sets value' owner = self.soup.find('itunes:owner') try: self.owner_name = owner.find('itunes:name').string except AttributeError: self.owner_name = None try: self.owner_email = owner.find('itunes:email').string except AttributeError: self.owner_email = None
Parses owner name and email then sets value
pyPodcastParser/Podcast.py
set_owner
nick-symon/pyPodcastParser
16
python
def set_owner(self): owner = self.soup.find('itunes:owner') try: self.owner_name = owner.find('itunes:name').string except AttributeError: self.owner_name = None try: self.owner_email = owner.find('itunes:email').string except AttributeError: self.owner_email = None
def set_owner(self): owner = self.soup.find('itunes:owner') try: self.owner_name = owner.find('itunes:name').string except AttributeError: self.owner_name = None try: self.owner_email = owner.find('itunes:email').string except AttributeError: self.owner_email = None<|docstring|>Parses owner name and email then sets value<|endoftext|>
2f8d0a1a8518b6889ef769f6a079859c7a8361afb1e885ce439ca8ca0387518c
def set_subtitle(self): 'Parses subtitle and sets value' try: self.subtitle = self.soup.find('itunes:subtitle').string except AttributeError: self.subtitle = None
Parses subtitle and sets value
pyPodcastParser/Podcast.py
set_subtitle
nick-symon/pyPodcastParser
16
python
def set_subtitle(self): try: self.subtitle = self.soup.find('itunes:subtitle').string except AttributeError: self.subtitle = None
def set_subtitle(self): try: self.subtitle = self.soup.find('itunes:subtitle').string except AttributeError: self.subtitle = None<|docstring|>Parses subtitle and sets value<|endoftext|>
42d229ae115de731367db4a0aed9a3cbae0e7aac62410a97a402cf80332bc62e
def set_summary(self): 'Parses summary and set value' try: self.summary = self.soup.find('itunes:summary').string except AttributeError: self.summary = None
Parses summary and set value
pyPodcastParser/Podcast.py
set_summary
nick-symon/pyPodcastParser
16
python
def set_summary(self): try: self.summary = self.soup.find('itunes:summary').string except AttributeError: self.summary = None
def set_summary(self): try: self.summary = self.soup.find('itunes:summary').string except AttributeError: self.summary = None<|docstring|>Parses summary and set value<|endoftext|>
3f930183a35867a2e22b9867c201758c0956878132653fc829287c4af20896b0
def set_title(self): 'Parses title and set value' try: self.title = self.soup.title.string except AttributeError: self.title = None
Parses title and set value
pyPodcastParser/Podcast.py
set_title
nick-symon/pyPodcastParser
16
python
def set_title(self): try: self.title = self.soup.title.string except AttributeError: self.title = None
def set_title(self): try: self.title = self.soup.title.string except AttributeError: self.title = None<|docstring|>Parses title and set value<|endoftext|>
888919ab5c86556ef12b62f60644b5f2fba9785feeeb1be9f90c39fb2e76ec95
def set_ttl(self): 'Parses summary and set value' try: self.ttl = self.soup.find('ttl').string except AttributeError: self.ttl = None
Parses summary and set value
pyPodcastParser/Podcast.py
set_ttl
nick-symon/pyPodcastParser
16
python
def set_ttl(self): try: self.ttl = self.soup.find('ttl').string except AttributeError: self.ttl = None
def set_ttl(self): try: self.ttl = self.soup.find('ttl').string except AttributeError: self.ttl = None<|docstring|>Parses summary and set value<|endoftext|>
afd966b08f081e0d425108463abe6baae11292beda16c293e3b0ea13303d56e5
def set_web_master(self): "Parses the feed's webmaster and sets value" try: self.web_master = self.soup.find('webmaster').string except AttributeError: self.web_master = None
Parses the feed's webmaster and sets value
pyPodcastParser/Podcast.py
set_web_master
nick-symon/pyPodcastParser
16
python
def set_web_master(self): try: self.web_master = self.soup.find('webmaster').string except AttributeError: self.web_master = None
def set_web_master(self): try: self.web_master = self.soup.find('webmaster').string except AttributeError: self.web_master = None<|docstring|>Parses the feed's webmaster and sets value<|endoftext|>
232a39dfed2262d2d7b98f2a03fdd01816463c9a5eefb95ddaedea905258bc5c
@IPython.core.magic.register_line_cell_magic def ml(line, cell=None): 'Implements the datalab cell magic for MLWorkbench operations.\n\n Args:\n line: the contents of the ml command line.\n Returns:\n The results of executing the cell.\n ' parser = google.datalab.utils.commands.CommandParser(prog='%ml', description=textwrap.dedent(' Execute MLWorkbench operations\n\n Use "%ml <command> -h" for help on a specific command.\n ')) dataset_parser = parser.subcommand('dataset', formatter_class=argparse.RawTextHelpFormatter, help='Create or explore datasets.') dataset_sub_commands = dataset_parser.add_subparsers(dest='command') dataset_create_parser = dataset_sub_commands.add_parser('create', help='Create datasets', formatter_class=argparse.RawTextHelpFormatter, epilog=textwrap.dedent(' Example usage:\n\n %%ml dataset\n name: mydata\n format: csv\n train: path/to/train.csv\n eval: path/to/eval.csv\n schema:\n - name: news_label\n type: STRING\n - name: text\n type: STRING')) dataset_create_parser.add_argument('--name', required=True, help='the name of the dataset to define. ') dataset_create_parser.add_argument('--format', required=True, choices=['csv', 'bigquery', 'transformed'], help='The format of the data.') dataset_create_parser.add_argument('--train', required=True, help=(('The path of the training file pattern if format ' + 'is csv or transformed, or table name if format ') + 'is bigquery.')) dataset_create_parser.add_argument('--eval', required=True, help=(('The path of the eval file pattern if format ' + 'is csv or transformed, or table name if format ') + 'is bigquery.')) dataset_create_parser.add_cell_argument('schema', help=('yaml representation of CSV schema, or path to ' + 'schema file. Only needed if format is csv.')) dataset_create_parser.set_defaults(func=_dataset_create) dataset_explore_parser = dataset_sub_commands.add_parser('explore', help='Explore training data.') dataset_explore_parser.add_argument('--name', required=True, help='The name of the dataset to explore.') dataset_explore_parser.add_argument('--overview', action='store_true', default=False, help=('Plot overview of sampled data. Set "sample_size" ' + 'to change the default sample size.')) dataset_explore_parser.add_argument('--facets', action='store_true', default=False, help=('Plot facets view of sampled data. Set ' + '"sample_size" to change the default sample size.')) dataset_explore_parser.add_argument('--sample_size', type=int, default=1000, help=('sample size for overview or facets view. Only ' + 'used if either --overview or --facets is set.')) dataset_explore_parser.set_defaults(func=_dataset_explore) analyze_parser = parser.subcommand('analyze', formatter_class=argparse.RawTextHelpFormatter, help='Analyze training data and generate stats, such as min/max/mean for numeric values, vocabulary for text columns.', epilog=textwrap.dedent(' Example usage:\n\n %%ml analyze [--cloud]\n output: path/to/dir\n data: $mydataset\n features:\n serialId:\n transform: key\n num1:\n transform: scale\n value: 1\n num2:\n transform: identity\n text1:\n transform: bag_of_words\n\n Also supports in-notebook variables, such as:\n %%ml analyze --output path/to/dir\n training_data: $my_csv_dataset\n features: $features_def')) analyze_parser.add_argument('--output', required=True, help='path of output directory.') analyze_parser.add_argument('--cloud', action='store_true', default=False, help='whether to run analysis in cloud or local.') analyze_parser.add_argument('--package', required=False, help='A local or GCS tarball path to use as the source. If not set, the default source package will be used.') analyze_parser.add_cell_argument('data', required=True, help='Training data. A dataset defined by "%%ml dataset".') analyze_parser.add_cell_argument('features', required=True, help=textwrap.dedent(' features config indicating how to transform data into features. The\n list of supported transforms:\n "transform: identity"\n does nothing (for numerical columns).\n "transform: scale\n value: x"\n scale a numerical column to [-a, a]. If value is missing, x\n defaults to 1.\n "transform: one_hot"\n treats the string column as categorical and makes one-hot\n encoding of it.\n "transform: embedding\n embedding_dim: d"\n treats the string column as categorical and makes embeddings of\n it with specified dimension size.\n "transform: bag_of_words"\n treats the string column as text and make bag of words\n transform of it.\n "transform: tfidf"\n treats the string column as text and make TFIDF transform of it.\n "transform: image_to_vec\n checkpoint: gs://b/o"\n from image gs url to embeddings. "checkpoint" is a inception v3\n checkpoint. If absent, a default checkpoint is used.\n "transform: target"\n denotes the column is the target. If the schema type of this\n column is string, a one_hot encoding is automatically applied.\n If numerical, an identity transform is automatically applied.\n "transform: key"\n column contains metadata-like information and will be output\n as-is in prediction.')) analyze_parser.set_defaults(func=_analyze) transform_parser = parser.subcommand('transform', formatter_class=argparse.RawTextHelpFormatter, help='Transform the data into tf.example which is more efficient in training.', epilog=textwrap.dedent(' Example usage:\n\n %%ml transform [--cloud] [--shuffle]\n analysis: path/to/analysis_output_folder\n output: path/to/dir\n batch_size: 100\n data: $mydataset\n cloud:\n num_workers: 3\n worker_machine_type: n1-standard-1\n project_id: my_project_id')) transform_parser.add_argument('--analysis', required=True, help='path of analysis output directory.') transform_parser.add_argument('--output', required=True, help='path of output directory.') transform_parser.add_argument('--cloud', action='store_true', default=False, help='whether to run transform in cloud or local.') transform_parser.add_argument('--shuffle', action='store_true', default=False, help='whether to shuffle the training data in output.') transform_parser.add_argument('--batch_size', type=int, default=100, help='number of instances in a batch to process once. Larger batch is more efficient but may consume more memory.') transform_parser.add_argument('--package', required=False, help='A local or GCS tarball path to use as the source. If not set, the default source package will be used.') transform_parser.add_cell_argument('data', required=True, help='Training data. A dataset defined by "%%ml dataset".') transform_parser.add_cell_argument('cloud_config', help=textwrap.dedent(" A dictionary of cloud config. All of them are optional.\n num_workers: Dataflow number of workers. If not set, DataFlow\n service will determine the number.\n worker_machine_type: a machine name from\n https://cloud.google.com/compute/docs/machine-types\n If not given, the service uses the default machine type.\n project_id: id of the project to use for DataFlow service. If not set,\n Datalab's default project (set by %%datalab project set) is used.\n job_name: Unique name for a Dataflow job to use. If not set, a\n random name will be used.")) transform_parser.set_defaults(func=_transform) train_parser = parser.subcommand('train', formatter_class=argparse.RawTextHelpFormatter, help='Train a model.', epilog=textwrap.dedent(' Example usage:\n\n %%ml train [--cloud]\n analysis: path/to/analysis_output\n output: path/to/dir\n data: $mydataset\n model_args:\n model: linear_regression\n cloud_config:\n region: us-central1')) train_parser.add_argument('--analysis', required=True, help='path of analysis output directory.') train_parser.add_argument('--output', required=True, help='path of trained model directory.') train_parser.add_argument('--cloud', action='store_true', default=False, help='whether to run training in cloud or local.') train_parser.add_argument('--notb', action='store_true', default=False, help='If set, tensorboard is not automatically started.') train_parser.add_argument('--package', required=False, help='A local or GCS tarball path to use as the source. If not set, the default source package will be used.') train_parser.add_cell_argument('data', required=True, help='Training data. A dataset defined by "%%ml dataset".') package_model_help = subprocess.Popen(['python', '-m', 'trainer.task', '--datalab-help'], cwd=DEFAULT_PACKAGE_PATH, stdout=subprocess.PIPE).communicate()[0] package_model_help = ('model_args: a dictionary of model specific args, including:\n\n' + package_model_help.decode()) train_parser.add_cell_argument('model_args', help=package_model_help) train_parser.add_cell_argument('cloud_config', help=textwrap.dedent(' A dictionary of cloud training config, including:\n job_id: the name of the job. If not provided, a default job name is created.\n region: see {url}\n runtime_version: see "region". Must be a string like \'1.2\'.\n scale_tier: see "region".'.format(url='https://cloud.google.com/sdk/gcloud/reference/ml-engine/jobs/submit/training'))) train_parser.set_defaults(func=_train) predict_parser = parser.subcommand('predict', formatter_class=argparse.RawTextHelpFormatter, help='Predict with local or deployed models. (Good for small datasets).', epilog=textwrap.dedent(" Example usage:\n\n %%ml predict\n headers: key,num\n model: path/to/model\n data:\n - key1,value1\n - key2,value2\n\n Or, in another cell, define a list of dict:\n\n my_data = [{'key': 1, 'num': 1.2}, {'key': 2, 'num': 2.8}]\n\n Then:\n\n %%ml predict\n headers: key,num\n model: path/to/model\n data: $my_data")) predict_parser.add_argument('--model', required=True, help='The model path.') predict_parser.add_argument('--no_show_image', action='store_true', default=False, help='If not set, add a column of images in output.') predict_parser.add_cell_argument('data', required=True, help=textwrap.dedent(' Prediction data can be\n 1) CSV lines in the input cell in yaml format or\n 2) a local variable which is one of\n a) list of dict\n b) list of strings of csv lines\n c) a Pandas DataFrame')) predict_parser.set_defaults(func=_predict) batch_predict_parser = parser.subcommand('batch_predict', formatter_class=argparse.RawTextHelpFormatter, help='Batch prediction with local or deployed models. (Good for large datasets)', epilog=textwrap.dedent('\n Example usage:\n\n %%ml batch_predict [--cloud]\n model: path/to/model\n output: path/to/output\n format: csv\n data:\n csv: path/to/file_pattern')) batch_predict_parser.add_argument('--model', required=True, help='The model path if not --cloud, or the id in the form of model.version if --cloud.') batch_predict_parser.add_argument('--output', required=True, help='The path of output directory with prediction results. If --cloud, it has to be GCS path.') batch_predict_parser.add_argument('--format', help='csv or json. For cloud run, the only supported format is json.') batch_predict_parser.add_argument('--batch_size', type=int, default=100, help='number of instances in a batch to process once. Larger batch is more efficient but may consume more memory. Only used in local run.') batch_predict_parser.add_argument('--cloud', action='store_true', default=False, help='whether to run prediction in cloud or local.') batch_predict_parser.add_cell_argument('data', required=True, help='Data to predict with. Only csv is supported.') batch_predict_parser.add_cell_argument('cloud_config', help=textwrap.dedent(' A dictionary of cloud batch prediction config.\n job_id: the name of the job. If not provided, a default job name is created.\n region: see {url}\n max_worker_count: see reference in "region".'.format(url='https://cloud.google.com/sdk/gcloud/reference/ml-engine/jobs/submit/prediction'))) batch_predict_parser.set_defaults(func=_batch_predict) explain_parser = parser.subcommand('explain', formatter_class=argparse.RawTextHelpFormatter, help='Explain a prediction with LIME tool.') explain_parser.add_argument('--type', default='all', choices=['text', 'image', 'tabular', 'all'], help='the type of column to explain.') explain_parser.add_argument('--algorithm', choices=['lime', 'ig'], default='lime', help=(('"lime" is the open sourced project for prediction explainer.' + '"ig" means integrated gradients and currently only applies ') + 'to image.')) explain_parser.add_argument('--model', required=True, help='path of the model directory used for prediction.') explain_parser.add_argument('--labels', required=True, help='comma separated labels to explain.') explain_parser.add_argument('--column_name', help=(('the name of the column to explain. Optional if text type ' + 'and there is only one text column, or image type and ') + 'there is only one image column.')) explain_parser.add_cell_argument('data', required=True, help='Prediction Data. Can be a csv line, or a dict.') explain_parser.add_cell_argument('training_data', help=((('A csv or bigquery dataset defined by %%ml dataset. ' + 'Used by tabular explainer only to determine the ') + 'distribution of numeric and categorical values. ') + 'Suggest using original training dataset.')) explain_parser.add_argument('--num_features', type=int, help=('number of features to analyze. In text, it is number of ' + 'words. In image, it is number of areas. For lime only.')) explain_parser.add_argument('--num_samples', type=int, help=('size of the neighborhood to learn the linear model. ' + 'For lime only.')) explain_parser.add_argument('--hide_color', type=int, default=0, help=('the color to use for perturbed area. If -1, average of ' + 'each channel is used for each channel. For image only.')) explain_parser.add_argument('--include_negative', action='store_true', default=False, help='whether to show only positive areas. For lime image only.') explain_parser.add_argument('--overview', action='store_true', default=False, help=('whether to show overview instead of details view.' + 'For lime text and tabular only.')) explain_parser.add_argument('--batch_size', type=int, default=100, help='size of batches passed to prediction. For lime only.') explain_parser.add_argument('--num_gradients', type=int, default=50, help=('the number of scaled images to get gradients from. Larger ' + 'number usually produces better results but slower.')) explain_parser.add_argument('--percent_show', type=int, default=10, help='the percentage of top impactful pixels to show.') explain_parser.set_defaults(func=_explain) tensorboard_parser = parser.subcommand('tensorboard', formatter_class=argparse.RawTextHelpFormatter, help='Start/stop/list TensorBoard instances.') tensorboard_sub_commands = tensorboard_parser.add_subparsers(dest='command') tensorboard_start_parser = tensorboard_sub_commands.add_parser('start', help='Start a tensorboard instance.') tensorboard_start_parser.add_argument('--logdir', required=True, help='The local or GCS logdir path.') tensorboard_start_parser.set_defaults(func=_tensorboard_start) tensorboard_stop_parser = tensorboard_sub_commands.add_parser('stop', help='Stop a tensorboard instance.') tensorboard_stop_parser.add_argument('--pid', required=True, type=int, help='The pid of the tensorboard instance.') tensorboard_stop_parser.set_defaults(func=_tensorboard_stop) tensorboard_list_parser = tensorboard_sub_commands.add_parser('list', help='List tensorboard instances.') tensorboard_list_parser.set_defaults(func=_tensorboard_list) evaluate_parser = parser.subcommand('evaluate', formatter_class=argparse.RawTextHelpFormatter, help='Analyze model evaluation results, such as confusion matrix, ROC, RMSE.') evaluate_sub_commands = evaluate_parser.add_subparsers(dest='command') def _add_data_params_for_evaluate(parser): parser.add_argument('--csv', help='csv file path patterns.') parser.add_argument('--headers', help=('csv file headers. Required if csv is specified and ' + 'predict_results_schema.json does not exist in the same directory.')) parser.add_argument('--bigquery', help=('can be bigquery table, query as a string, or ' + 'a pre-defined query (%%bq query --name).')) evaluate_cm_parser = evaluate_sub_commands.add_parser('confusion_matrix', help='Get confusion matrix from evaluation results.') _add_data_params_for_evaluate(evaluate_cm_parser) evaluate_cm_parser.add_argument('--plot', action='store_true', default=False, help='Whether to plot confusion matrix as graph.') evaluate_cm_parser.add_argument('--size', type=int, default=10, help='The size of the confusion matrix.') evaluate_cm_parser.set_defaults(func=_evaluate_cm) evaluate_accuracy_parser = evaluate_sub_commands.add_parser('accuracy', help='Get accuracy results from classification evaluation results.') _add_data_params_for_evaluate(evaluate_accuracy_parser) evaluate_accuracy_parser.set_defaults(func=_evaluate_accuracy) evaluate_pr_parser = evaluate_sub_commands.add_parser('precision_recall', help='Get precision recall metrics from evaluation results.') _add_data_params_for_evaluate(evaluate_pr_parser) evaluate_pr_parser.add_argument('--plot', action='store_true', default=False, help='Whether to plot precision recall as graph.') evaluate_pr_parser.add_argument('--num_thresholds', type=int, default=20, help=('Number of thresholds which determines how many ' + 'points in the graph.')) evaluate_pr_parser.add_argument('--target_class', required=True, help=('The target class to determine correctness of ' + 'a prediction.')) evaluate_pr_parser.add_argument('--probability_column', help=(('The name of the column holding the probability ' + 'value of the target class. If absent, the value ') + 'of target class is used.')) evaluate_pr_parser.set_defaults(func=_evaluate_pr) evaluate_roc_parser = evaluate_sub_commands.add_parser('roc', help='Get ROC metrics from evaluation results.') _add_data_params_for_evaluate(evaluate_roc_parser) evaluate_roc_parser.add_argument('--plot', action='store_true', default=False, help='Whether to plot ROC as graph.') evaluate_roc_parser.add_argument('--num_thresholds', type=int, default=20, help=('Number of thresholds which determines how many ' + 'points in the graph.')) evaluate_roc_parser.add_argument('--target_class', required=True, help=('The target class to determine correctness of ' + 'a prediction.')) evaluate_roc_parser.add_argument('--probability_column', help=(('The name of the column holding the probability ' + 'value of the target class. If absent, the value ') + 'of target class is used.')) evaluate_roc_parser.set_defaults(func=_evaluate_roc) evaluate_regression_parser = evaluate_sub_commands.add_parser('regression', help='Get regression metrics from evaluation results.') _add_data_params_for_evaluate(evaluate_regression_parser) evaluate_regression_parser.set_defaults(func=_evaluate_regression) model_parser = parser.subcommand('model', help='Models and versions management such as deployment, deletion, listing.') model_sub_commands = model_parser.add_subparsers(dest='command') model_list_parser = model_sub_commands.add_parser('list', help='List models and versions.') model_list_parser.add_argument('--name', help=(('If absent, list all models of specified or current ' + 'project. If provided, list all versions of the ') + 'model.')) model_list_parser.add_argument('--project', help=('The project to list model(s) or version(s). If absent, ' + "use Datalab's default project.")) model_list_parser.set_defaults(func=_model_list) model_delete_parser = model_sub_commands.add_parser('delete', help='Delete models or versions.') model_delete_parser.add_argument('--name', required=True, help=(('If no "." in the name, try deleting the specified ' + 'model. If "model.version" is provided, try deleting ') + 'the specified version.')) model_delete_parser.add_argument('--project', help=('The project to delete model or version. If absent, ' + "use Datalab's default project.")) model_delete_parser.set_defaults(func=_model_delete) model_deploy_parser = model_sub_commands.add_parser('deploy', help='Deploy a model version.') model_deploy_parser.add_argument('--name', required=True, help=('Must be model.version to indicate the model ' + 'and version name to deploy.')) model_deploy_parser.add_argument('--path', required=True, help='The GCS path of the model to be deployed.') model_deploy_parser.add_argument('--runtime_version', help=(('The TensorFlow version to use for this model. ' + 'For example, "1.2.1". If absent, the current ') + 'TensorFlow version installed in Datalab will be used.')) model_deploy_parser.add_argument('--project', help=('The project to deploy a model version. If absent, ' + "use Datalab's default project.")) model_deploy_parser.set_defaults(func=_model_deploy) return google.datalab.utils.commands.handle_magic_line(line, cell, parser)
Implements the datalab cell magic for MLWorkbench operations. Args: line: the contents of the ml command line. Returns: The results of executing the cell.
google/datalab/contrib/mlworkbench/commands/_ml.py
ml
alienczf/pydatalab
198
python
@IPython.core.magic.register_line_cell_magic def ml(line, cell=None): 'Implements the datalab cell magic for MLWorkbench operations.\n\n Args:\n line: the contents of the ml command line.\n Returns:\n The results of executing the cell.\n ' parser = google.datalab.utils.commands.CommandParser(prog='%ml', description=textwrap.dedent(' Execute MLWorkbench operations\n\n Use "%ml <command> -h" for help on a specific command.\n ')) dataset_parser = parser.subcommand('dataset', formatter_class=argparse.RawTextHelpFormatter, help='Create or explore datasets.') dataset_sub_commands = dataset_parser.add_subparsers(dest='command') dataset_create_parser = dataset_sub_commands.add_parser('create', help='Create datasets', formatter_class=argparse.RawTextHelpFormatter, epilog=textwrap.dedent(' Example usage:\n\n %%ml dataset\n name: mydata\n format: csv\n train: path/to/train.csv\n eval: path/to/eval.csv\n schema:\n - name: news_label\n type: STRING\n - name: text\n type: STRING')) dataset_create_parser.add_argument('--name', required=True, help='the name of the dataset to define. ') dataset_create_parser.add_argument('--format', required=True, choices=['csv', 'bigquery', 'transformed'], help='The format of the data.') dataset_create_parser.add_argument('--train', required=True, help=(('The path of the training file pattern if format ' + 'is csv or transformed, or table name if format ') + 'is bigquery.')) dataset_create_parser.add_argument('--eval', required=True, help=(('The path of the eval file pattern if format ' + 'is csv or transformed, or table name if format ') + 'is bigquery.')) dataset_create_parser.add_cell_argument('schema', help=('yaml representation of CSV schema, or path to ' + 'schema file. Only needed if format is csv.')) dataset_create_parser.set_defaults(func=_dataset_create) dataset_explore_parser = dataset_sub_commands.add_parser('explore', help='Explore training data.') dataset_explore_parser.add_argument('--name', required=True, help='The name of the dataset to explore.') dataset_explore_parser.add_argument('--overview', action='store_true', default=False, help=('Plot overview of sampled data. Set "sample_size" ' + 'to change the default sample size.')) dataset_explore_parser.add_argument('--facets', action='store_true', default=False, help=('Plot facets view of sampled data. Set ' + '"sample_size" to change the default sample size.')) dataset_explore_parser.add_argument('--sample_size', type=int, default=1000, help=('sample size for overview or facets view. Only ' + 'used if either --overview or --facets is set.')) dataset_explore_parser.set_defaults(func=_dataset_explore) analyze_parser = parser.subcommand('analyze', formatter_class=argparse.RawTextHelpFormatter, help='Analyze training data and generate stats, such as min/max/mean for numeric values, vocabulary for text columns.', epilog=textwrap.dedent(' Example usage:\n\n %%ml analyze [--cloud]\n output: path/to/dir\n data: $mydataset\n features:\n serialId:\n transform: key\n num1:\n transform: scale\n value: 1\n num2:\n transform: identity\n text1:\n transform: bag_of_words\n\n Also supports in-notebook variables, such as:\n %%ml analyze --output path/to/dir\n training_data: $my_csv_dataset\n features: $features_def')) analyze_parser.add_argument('--output', required=True, help='path of output directory.') analyze_parser.add_argument('--cloud', action='store_true', default=False, help='whether to run analysis in cloud or local.') analyze_parser.add_argument('--package', required=False, help='A local or GCS tarball path to use as the source. If not set, the default source package will be used.') analyze_parser.add_cell_argument('data', required=True, help='Training data. A dataset defined by "%%ml dataset".') analyze_parser.add_cell_argument('features', required=True, help=textwrap.dedent(' features config indicating how to transform data into features. The\n list of supported transforms:\n "transform: identity"\n does nothing (for numerical columns).\n "transform: scale\n value: x"\n scale a numerical column to [-a, a]. If value is missing, x\n defaults to 1.\n "transform: one_hot"\n treats the string column as categorical and makes one-hot\n encoding of it.\n "transform: embedding\n embedding_dim: d"\n treats the string column as categorical and makes embeddings of\n it with specified dimension size.\n "transform: bag_of_words"\n treats the string column as text and make bag of words\n transform of it.\n "transform: tfidf"\n treats the string column as text and make TFIDF transform of it.\n "transform: image_to_vec\n checkpoint: gs://b/o"\n from image gs url to embeddings. "checkpoint" is a inception v3\n checkpoint. If absent, a default checkpoint is used.\n "transform: target"\n denotes the column is the target. If the schema type of this\n column is string, a one_hot encoding is automatically applied.\n If numerical, an identity transform is automatically applied.\n "transform: key"\n column contains metadata-like information and will be output\n as-is in prediction.')) analyze_parser.set_defaults(func=_analyze) transform_parser = parser.subcommand('transform', formatter_class=argparse.RawTextHelpFormatter, help='Transform the data into tf.example which is more efficient in training.', epilog=textwrap.dedent(' Example usage:\n\n %%ml transform [--cloud] [--shuffle]\n analysis: path/to/analysis_output_folder\n output: path/to/dir\n batch_size: 100\n data: $mydataset\n cloud:\n num_workers: 3\n worker_machine_type: n1-standard-1\n project_id: my_project_id')) transform_parser.add_argument('--analysis', required=True, help='path of analysis output directory.') transform_parser.add_argument('--output', required=True, help='path of output directory.') transform_parser.add_argument('--cloud', action='store_true', default=False, help='whether to run transform in cloud or local.') transform_parser.add_argument('--shuffle', action='store_true', default=False, help='whether to shuffle the training data in output.') transform_parser.add_argument('--batch_size', type=int, default=100, help='number of instances in a batch to process once. Larger batch is more efficient but may consume more memory.') transform_parser.add_argument('--package', required=False, help='A local or GCS tarball path to use as the source. If not set, the default source package will be used.') transform_parser.add_cell_argument('data', required=True, help='Training data. A dataset defined by "%%ml dataset".') transform_parser.add_cell_argument('cloud_config', help=textwrap.dedent(" A dictionary of cloud config. All of them are optional.\n num_workers: Dataflow number of workers. If not set, DataFlow\n service will determine the number.\n worker_machine_type: a machine name from\n https://cloud.google.com/compute/docs/machine-types\n If not given, the service uses the default machine type.\n project_id: id of the project to use for DataFlow service. If not set,\n Datalab's default project (set by %%datalab project set) is used.\n job_name: Unique name for a Dataflow job to use. If not set, a\n random name will be used.")) transform_parser.set_defaults(func=_transform) train_parser = parser.subcommand('train', formatter_class=argparse.RawTextHelpFormatter, help='Train a model.', epilog=textwrap.dedent(' Example usage:\n\n %%ml train [--cloud]\n analysis: path/to/analysis_output\n output: path/to/dir\n data: $mydataset\n model_args:\n model: linear_regression\n cloud_config:\n region: us-central1')) train_parser.add_argument('--analysis', required=True, help='path of analysis output directory.') train_parser.add_argument('--output', required=True, help='path of trained model directory.') train_parser.add_argument('--cloud', action='store_true', default=False, help='whether to run training in cloud or local.') train_parser.add_argument('--notb', action='store_true', default=False, help='If set, tensorboard is not automatically started.') train_parser.add_argument('--package', required=False, help='A local or GCS tarball path to use as the source. If not set, the default source package will be used.') train_parser.add_cell_argument('data', required=True, help='Training data. A dataset defined by "%%ml dataset".') package_model_help = subprocess.Popen(['python', '-m', 'trainer.task', '--datalab-help'], cwd=DEFAULT_PACKAGE_PATH, stdout=subprocess.PIPE).communicate()[0] package_model_help = ('model_args: a dictionary of model specific args, including:\n\n' + package_model_help.decode()) train_parser.add_cell_argument('model_args', help=package_model_help) train_parser.add_cell_argument('cloud_config', help=textwrap.dedent(' A dictionary of cloud training config, including:\n job_id: the name of the job. If not provided, a default job name is created.\n region: see {url}\n runtime_version: see "region". Must be a string like \'1.2\'.\n scale_tier: see "region".'.format(url='https://cloud.google.com/sdk/gcloud/reference/ml-engine/jobs/submit/training'))) train_parser.set_defaults(func=_train) predict_parser = parser.subcommand('predict', formatter_class=argparse.RawTextHelpFormatter, help='Predict with local or deployed models. (Good for small datasets).', epilog=textwrap.dedent(" Example usage:\n\n %%ml predict\n headers: key,num\n model: path/to/model\n data:\n - key1,value1\n - key2,value2\n\n Or, in another cell, define a list of dict:\n\n my_data = [{'key': 1, 'num': 1.2}, {'key': 2, 'num': 2.8}]\n\n Then:\n\n %%ml predict\n headers: key,num\n model: path/to/model\n data: $my_data")) predict_parser.add_argument('--model', required=True, help='The model path.') predict_parser.add_argument('--no_show_image', action='store_true', default=False, help='If not set, add a column of images in output.') predict_parser.add_cell_argument('data', required=True, help=textwrap.dedent(' Prediction data can be\n 1) CSV lines in the input cell in yaml format or\n 2) a local variable which is one of\n a) list of dict\n b) list of strings of csv lines\n c) a Pandas DataFrame')) predict_parser.set_defaults(func=_predict) batch_predict_parser = parser.subcommand('batch_predict', formatter_class=argparse.RawTextHelpFormatter, help='Batch prediction with local or deployed models. (Good for large datasets)', epilog=textwrap.dedent('\n Example usage:\n\n %%ml batch_predict [--cloud]\n model: path/to/model\n output: path/to/output\n format: csv\n data:\n csv: path/to/file_pattern')) batch_predict_parser.add_argument('--model', required=True, help='The model path if not --cloud, or the id in the form of model.version if --cloud.') batch_predict_parser.add_argument('--output', required=True, help='The path of output directory with prediction results. If --cloud, it has to be GCS path.') batch_predict_parser.add_argument('--format', help='csv or json. For cloud run, the only supported format is json.') batch_predict_parser.add_argument('--batch_size', type=int, default=100, help='number of instances in a batch to process once. Larger batch is more efficient but may consume more memory. Only used in local run.') batch_predict_parser.add_argument('--cloud', action='store_true', default=False, help='whether to run prediction in cloud or local.') batch_predict_parser.add_cell_argument('data', required=True, help='Data to predict with. Only csv is supported.') batch_predict_parser.add_cell_argument('cloud_config', help=textwrap.dedent(' A dictionary of cloud batch prediction config.\n job_id: the name of the job. If not provided, a default job name is created.\n region: see {url}\n max_worker_count: see reference in "region".'.format(url='https://cloud.google.com/sdk/gcloud/reference/ml-engine/jobs/submit/prediction'))) batch_predict_parser.set_defaults(func=_batch_predict) explain_parser = parser.subcommand('explain', formatter_class=argparse.RawTextHelpFormatter, help='Explain a prediction with LIME tool.') explain_parser.add_argument('--type', default='all', choices=['text', 'image', 'tabular', 'all'], help='the type of column to explain.') explain_parser.add_argument('--algorithm', choices=['lime', 'ig'], default='lime', help=(('"lime" is the open sourced project for prediction explainer.' + '"ig" means integrated gradients and currently only applies ') + 'to image.')) explain_parser.add_argument('--model', required=True, help='path of the model directory used for prediction.') explain_parser.add_argument('--labels', required=True, help='comma separated labels to explain.') explain_parser.add_argument('--column_name', help=(('the name of the column to explain. Optional if text type ' + 'and there is only one text column, or image type and ') + 'there is only one image column.')) explain_parser.add_cell_argument('data', required=True, help='Prediction Data. Can be a csv line, or a dict.') explain_parser.add_cell_argument('training_data', help=((('A csv or bigquery dataset defined by %%ml dataset. ' + 'Used by tabular explainer only to determine the ') + 'distribution of numeric and categorical values. ') + 'Suggest using original training dataset.')) explain_parser.add_argument('--num_features', type=int, help=('number of features to analyze. In text, it is number of ' + 'words. In image, it is number of areas. For lime only.')) explain_parser.add_argument('--num_samples', type=int, help=('size of the neighborhood to learn the linear model. ' + 'For lime only.')) explain_parser.add_argument('--hide_color', type=int, default=0, help=('the color to use for perturbed area. If -1, average of ' + 'each channel is used for each channel. For image only.')) explain_parser.add_argument('--include_negative', action='store_true', default=False, help='whether to show only positive areas. For lime image only.') explain_parser.add_argument('--overview', action='store_true', default=False, help=('whether to show overview instead of details view.' + 'For lime text and tabular only.')) explain_parser.add_argument('--batch_size', type=int, default=100, help='size of batches passed to prediction. For lime only.') explain_parser.add_argument('--num_gradients', type=int, default=50, help=('the number of scaled images to get gradients from. Larger ' + 'number usually produces better results but slower.')) explain_parser.add_argument('--percent_show', type=int, default=10, help='the percentage of top impactful pixels to show.') explain_parser.set_defaults(func=_explain) tensorboard_parser = parser.subcommand('tensorboard', formatter_class=argparse.RawTextHelpFormatter, help='Start/stop/list TensorBoard instances.') tensorboard_sub_commands = tensorboard_parser.add_subparsers(dest='command') tensorboard_start_parser = tensorboard_sub_commands.add_parser('start', help='Start a tensorboard instance.') tensorboard_start_parser.add_argument('--logdir', required=True, help='The local or GCS logdir path.') tensorboard_start_parser.set_defaults(func=_tensorboard_start) tensorboard_stop_parser = tensorboard_sub_commands.add_parser('stop', help='Stop a tensorboard instance.') tensorboard_stop_parser.add_argument('--pid', required=True, type=int, help='The pid of the tensorboard instance.') tensorboard_stop_parser.set_defaults(func=_tensorboard_stop) tensorboard_list_parser = tensorboard_sub_commands.add_parser('list', help='List tensorboard instances.') tensorboard_list_parser.set_defaults(func=_tensorboard_list) evaluate_parser = parser.subcommand('evaluate', formatter_class=argparse.RawTextHelpFormatter, help='Analyze model evaluation results, such as confusion matrix, ROC, RMSE.') evaluate_sub_commands = evaluate_parser.add_subparsers(dest='command') def _add_data_params_for_evaluate(parser): parser.add_argument('--csv', help='csv file path patterns.') parser.add_argument('--headers', help=('csv file headers. Required if csv is specified and ' + 'predict_results_schema.json does not exist in the same directory.')) parser.add_argument('--bigquery', help=('can be bigquery table, query as a string, or ' + 'a pre-defined query (%%bq query --name).')) evaluate_cm_parser = evaluate_sub_commands.add_parser('confusion_matrix', help='Get confusion matrix from evaluation results.') _add_data_params_for_evaluate(evaluate_cm_parser) evaluate_cm_parser.add_argument('--plot', action='store_true', default=False, help='Whether to plot confusion matrix as graph.') evaluate_cm_parser.add_argument('--size', type=int, default=10, help='The size of the confusion matrix.') evaluate_cm_parser.set_defaults(func=_evaluate_cm) evaluate_accuracy_parser = evaluate_sub_commands.add_parser('accuracy', help='Get accuracy results from classification evaluation results.') _add_data_params_for_evaluate(evaluate_accuracy_parser) evaluate_accuracy_parser.set_defaults(func=_evaluate_accuracy) evaluate_pr_parser = evaluate_sub_commands.add_parser('precision_recall', help='Get precision recall metrics from evaluation results.') _add_data_params_for_evaluate(evaluate_pr_parser) evaluate_pr_parser.add_argument('--plot', action='store_true', default=False, help='Whether to plot precision recall as graph.') evaluate_pr_parser.add_argument('--num_thresholds', type=int, default=20, help=('Number of thresholds which determines how many ' + 'points in the graph.')) evaluate_pr_parser.add_argument('--target_class', required=True, help=('The target class to determine correctness of ' + 'a prediction.')) evaluate_pr_parser.add_argument('--probability_column', help=(('The name of the column holding the probability ' + 'value of the target class. If absent, the value ') + 'of target class is used.')) evaluate_pr_parser.set_defaults(func=_evaluate_pr) evaluate_roc_parser = evaluate_sub_commands.add_parser('roc', help='Get ROC metrics from evaluation results.') _add_data_params_for_evaluate(evaluate_roc_parser) evaluate_roc_parser.add_argument('--plot', action='store_true', default=False, help='Whether to plot ROC as graph.') evaluate_roc_parser.add_argument('--num_thresholds', type=int, default=20, help=('Number of thresholds which determines how many ' + 'points in the graph.')) evaluate_roc_parser.add_argument('--target_class', required=True, help=('The target class to determine correctness of ' + 'a prediction.')) evaluate_roc_parser.add_argument('--probability_column', help=(('The name of the column holding the probability ' + 'value of the target class. If absent, the value ') + 'of target class is used.')) evaluate_roc_parser.set_defaults(func=_evaluate_roc) evaluate_regression_parser = evaluate_sub_commands.add_parser('regression', help='Get regression metrics from evaluation results.') _add_data_params_for_evaluate(evaluate_regression_parser) evaluate_regression_parser.set_defaults(func=_evaluate_regression) model_parser = parser.subcommand('model', help='Models and versions management such as deployment, deletion, listing.') model_sub_commands = model_parser.add_subparsers(dest='command') model_list_parser = model_sub_commands.add_parser('list', help='List models and versions.') model_list_parser.add_argument('--name', help=(('If absent, list all models of specified or current ' + 'project. If provided, list all versions of the ') + 'model.')) model_list_parser.add_argument('--project', help=('The project to list model(s) or version(s). If absent, ' + "use Datalab's default project.")) model_list_parser.set_defaults(func=_model_list) model_delete_parser = model_sub_commands.add_parser('delete', help='Delete models or versions.') model_delete_parser.add_argument('--name', required=True, help=(('If no "." in the name, try deleting the specified ' + 'model. If "model.version" is provided, try deleting ') + 'the specified version.')) model_delete_parser.add_argument('--project', help=('The project to delete model or version. If absent, ' + "use Datalab's default project.")) model_delete_parser.set_defaults(func=_model_delete) model_deploy_parser = model_sub_commands.add_parser('deploy', help='Deploy a model version.') model_deploy_parser.add_argument('--name', required=True, help=('Must be model.version to indicate the model ' + 'and version name to deploy.')) model_deploy_parser.add_argument('--path', required=True, help='The GCS path of the model to be deployed.') model_deploy_parser.add_argument('--runtime_version', help=(('The TensorFlow version to use for this model. ' + 'For example, "1.2.1". If absent, the current ') + 'TensorFlow version installed in Datalab will be used.')) model_deploy_parser.add_argument('--project', help=('The project to deploy a model version. If absent, ' + "use Datalab's default project.")) model_deploy_parser.set_defaults(func=_model_deploy) return google.datalab.utils.commands.handle_magic_line(line, cell, parser)
@IPython.core.magic.register_line_cell_magic def ml(line, cell=None): 'Implements the datalab cell magic for MLWorkbench operations.\n\n Args:\n line: the contents of the ml command line.\n Returns:\n The results of executing the cell.\n ' parser = google.datalab.utils.commands.CommandParser(prog='%ml', description=textwrap.dedent(' Execute MLWorkbench operations\n\n Use "%ml <command> -h" for help on a specific command.\n ')) dataset_parser = parser.subcommand('dataset', formatter_class=argparse.RawTextHelpFormatter, help='Create or explore datasets.') dataset_sub_commands = dataset_parser.add_subparsers(dest='command') dataset_create_parser = dataset_sub_commands.add_parser('create', help='Create datasets', formatter_class=argparse.RawTextHelpFormatter, epilog=textwrap.dedent(' Example usage:\n\n %%ml dataset\n name: mydata\n format: csv\n train: path/to/train.csv\n eval: path/to/eval.csv\n schema:\n - name: news_label\n type: STRING\n - name: text\n type: STRING')) dataset_create_parser.add_argument('--name', required=True, help='the name of the dataset to define. ') dataset_create_parser.add_argument('--format', required=True, choices=['csv', 'bigquery', 'transformed'], help='The format of the data.') dataset_create_parser.add_argument('--train', required=True, help=(('The path of the training file pattern if format ' + 'is csv or transformed, or table name if format ') + 'is bigquery.')) dataset_create_parser.add_argument('--eval', required=True, help=(('The path of the eval file pattern if format ' + 'is csv or transformed, or table name if format ') + 'is bigquery.')) dataset_create_parser.add_cell_argument('schema', help=('yaml representation of CSV schema, or path to ' + 'schema file. Only needed if format is csv.')) dataset_create_parser.set_defaults(func=_dataset_create) dataset_explore_parser = dataset_sub_commands.add_parser('explore', help='Explore training data.') dataset_explore_parser.add_argument('--name', required=True, help='The name of the dataset to explore.') dataset_explore_parser.add_argument('--overview', action='store_true', default=False, help=('Plot overview of sampled data. Set "sample_size" ' + 'to change the default sample size.')) dataset_explore_parser.add_argument('--facets', action='store_true', default=False, help=('Plot facets view of sampled data. Set ' + '"sample_size" to change the default sample size.')) dataset_explore_parser.add_argument('--sample_size', type=int, default=1000, help=('sample size for overview or facets view. Only ' + 'used if either --overview or --facets is set.')) dataset_explore_parser.set_defaults(func=_dataset_explore) analyze_parser = parser.subcommand('analyze', formatter_class=argparse.RawTextHelpFormatter, help='Analyze training data and generate stats, such as min/max/mean for numeric values, vocabulary for text columns.', epilog=textwrap.dedent(' Example usage:\n\n %%ml analyze [--cloud]\n output: path/to/dir\n data: $mydataset\n features:\n serialId:\n transform: key\n num1:\n transform: scale\n value: 1\n num2:\n transform: identity\n text1:\n transform: bag_of_words\n\n Also supports in-notebook variables, such as:\n %%ml analyze --output path/to/dir\n training_data: $my_csv_dataset\n features: $features_def')) analyze_parser.add_argument('--output', required=True, help='path of output directory.') analyze_parser.add_argument('--cloud', action='store_true', default=False, help='whether to run analysis in cloud or local.') analyze_parser.add_argument('--package', required=False, help='A local or GCS tarball path to use as the source. If not set, the default source package will be used.') analyze_parser.add_cell_argument('data', required=True, help='Training data. A dataset defined by "%%ml dataset".') analyze_parser.add_cell_argument('features', required=True, help=textwrap.dedent(' features config indicating how to transform data into features. The\n list of supported transforms:\n "transform: identity"\n does nothing (for numerical columns).\n "transform: scale\n value: x"\n scale a numerical column to [-a, a]. If value is missing, x\n defaults to 1.\n "transform: one_hot"\n treats the string column as categorical and makes one-hot\n encoding of it.\n "transform: embedding\n embedding_dim: d"\n treats the string column as categorical and makes embeddings of\n it with specified dimension size.\n "transform: bag_of_words"\n treats the string column as text and make bag of words\n transform of it.\n "transform: tfidf"\n treats the string column as text and make TFIDF transform of it.\n "transform: image_to_vec\n checkpoint: gs://b/o"\n from image gs url to embeddings. "checkpoint" is a inception v3\n checkpoint. If absent, a default checkpoint is used.\n "transform: target"\n denotes the column is the target. If the schema type of this\n column is string, a one_hot encoding is automatically applied.\n If numerical, an identity transform is automatically applied.\n "transform: key"\n column contains metadata-like information and will be output\n as-is in prediction.')) analyze_parser.set_defaults(func=_analyze) transform_parser = parser.subcommand('transform', formatter_class=argparse.RawTextHelpFormatter, help='Transform the data into tf.example which is more efficient in training.', epilog=textwrap.dedent(' Example usage:\n\n %%ml transform [--cloud] [--shuffle]\n analysis: path/to/analysis_output_folder\n output: path/to/dir\n batch_size: 100\n data: $mydataset\n cloud:\n num_workers: 3\n worker_machine_type: n1-standard-1\n project_id: my_project_id')) transform_parser.add_argument('--analysis', required=True, help='path of analysis output directory.') transform_parser.add_argument('--output', required=True, help='path of output directory.') transform_parser.add_argument('--cloud', action='store_true', default=False, help='whether to run transform in cloud or local.') transform_parser.add_argument('--shuffle', action='store_true', default=False, help='whether to shuffle the training data in output.') transform_parser.add_argument('--batch_size', type=int, default=100, help='number of instances in a batch to process once. Larger batch is more efficient but may consume more memory.') transform_parser.add_argument('--package', required=False, help='A local or GCS tarball path to use as the source. If not set, the default source package will be used.') transform_parser.add_cell_argument('data', required=True, help='Training data. A dataset defined by "%%ml dataset".') transform_parser.add_cell_argument('cloud_config', help=textwrap.dedent(" A dictionary of cloud config. All of them are optional.\n num_workers: Dataflow number of workers. If not set, DataFlow\n service will determine the number.\n worker_machine_type: a machine name from\n https://cloud.google.com/compute/docs/machine-types\n If not given, the service uses the default machine type.\n project_id: id of the project to use for DataFlow service. If not set,\n Datalab's default project (set by %%datalab project set) is used.\n job_name: Unique name for a Dataflow job to use. If not set, a\n random name will be used.")) transform_parser.set_defaults(func=_transform) train_parser = parser.subcommand('train', formatter_class=argparse.RawTextHelpFormatter, help='Train a model.', epilog=textwrap.dedent(' Example usage:\n\n %%ml train [--cloud]\n analysis: path/to/analysis_output\n output: path/to/dir\n data: $mydataset\n model_args:\n model: linear_regression\n cloud_config:\n region: us-central1')) train_parser.add_argument('--analysis', required=True, help='path of analysis output directory.') train_parser.add_argument('--output', required=True, help='path of trained model directory.') train_parser.add_argument('--cloud', action='store_true', default=False, help='whether to run training in cloud or local.') train_parser.add_argument('--notb', action='store_true', default=False, help='If set, tensorboard is not automatically started.') train_parser.add_argument('--package', required=False, help='A local or GCS tarball path to use as the source. If not set, the default source package will be used.') train_parser.add_cell_argument('data', required=True, help='Training data. A dataset defined by "%%ml dataset".') package_model_help = subprocess.Popen(['python', '-m', 'trainer.task', '--datalab-help'], cwd=DEFAULT_PACKAGE_PATH, stdout=subprocess.PIPE).communicate()[0] package_model_help = ('model_args: a dictionary of model specific args, including:\n\n' + package_model_help.decode()) train_parser.add_cell_argument('model_args', help=package_model_help) train_parser.add_cell_argument('cloud_config', help=textwrap.dedent(' A dictionary of cloud training config, including:\n job_id: the name of the job. If not provided, a default job name is created.\n region: see {url}\n runtime_version: see "region". Must be a string like \'1.2\'.\n scale_tier: see "region".'.format(url='https://cloud.google.com/sdk/gcloud/reference/ml-engine/jobs/submit/training'))) train_parser.set_defaults(func=_train) predict_parser = parser.subcommand('predict', formatter_class=argparse.RawTextHelpFormatter, help='Predict with local or deployed models. (Good for small datasets).', epilog=textwrap.dedent(" Example usage:\n\n %%ml predict\n headers: key,num\n model: path/to/model\n data:\n - key1,value1\n - key2,value2\n\n Or, in another cell, define a list of dict:\n\n my_data = [{'key': 1, 'num': 1.2}, {'key': 2, 'num': 2.8}]\n\n Then:\n\n %%ml predict\n headers: key,num\n model: path/to/model\n data: $my_data")) predict_parser.add_argument('--model', required=True, help='The model path.') predict_parser.add_argument('--no_show_image', action='store_true', default=False, help='If not set, add a column of images in output.') predict_parser.add_cell_argument('data', required=True, help=textwrap.dedent(' Prediction data can be\n 1) CSV lines in the input cell in yaml format or\n 2) a local variable which is one of\n a) list of dict\n b) list of strings of csv lines\n c) a Pandas DataFrame')) predict_parser.set_defaults(func=_predict) batch_predict_parser = parser.subcommand('batch_predict', formatter_class=argparse.RawTextHelpFormatter, help='Batch prediction with local or deployed models. (Good for large datasets)', epilog=textwrap.dedent('\n Example usage:\n\n %%ml batch_predict [--cloud]\n model: path/to/model\n output: path/to/output\n format: csv\n data:\n csv: path/to/file_pattern')) batch_predict_parser.add_argument('--model', required=True, help='The model path if not --cloud, or the id in the form of model.version if --cloud.') batch_predict_parser.add_argument('--output', required=True, help='The path of output directory with prediction results. If --cloud, it has to be GCS path.') batch_predict_parser.add_argument('--format', help='csv or json. For cloud run, the only supported format is json.') batch_predict_parser.add_argument('--batch_size', type=int, default=100, help='number of instances in a batch to process once. Larger batch is more efficient but may consume more memory. Only used in local run.') batch_predict_parser.add_argument('--cloud', action='store_true', default=False, help='whether to run prediction in cloud or local.') batch_predict_parser.add_cell_argument('data', required=True, help='Data to predict with. Only csv is supported.') batch_predict_parser.add_cell_argument('cloud_config', help=textwrap.dedent(' A dictionary of cloud batch prediction config.\n job_id: the name of the job. If not provided, a default job name is created.\n region: see {url}\n max_worker_count: see reference in "region".'.format(url='https://cloud.google.com/sdk/gcloud/reference/ml-engine/jobs/submit/prediction'))) batch_predict_parser.set_defaults(func=_batch_predict) explain_parser = parser.subcommand('explain', formatter_class=argparse.RawTextHelpFormatter, help='Explain a prediction with LIME tool.') explain_parser.add_argument('--type', default='all', choices=['text', 'image', 'tabular', 'all'], help='the type of column to explain.') explain_parser.add_argument('--algorithm', choices=['lime', 'ig'], default='lime', help=(('"lime" is the open sourced project for prediction explainer.' + '"ig" means integrated gradients and currently only applies ') + 'to image.')) explain_parser.add_argument('--model', required=True, help='path of the model directory used for prediction.') explain_parser.add_argument('--labels', required=True, help='comma separated labels to explain.') explain_parser.add_argument('--column_name', help=(('the name of the column to explain. Optional if text type ' + 'and there is only one text column, or image type and ') + 'there is only one image column.')) explain_parser.add_cell_argument('data', required=True, help='Prediction Data. Can be a csv line, or a dict.') explain_parser.add_cell_argument('training_data', help=((('A csv or bigquery dataset defined by %%ml dataset. ' + 'Used by tabular explainer only to determine the ') + 'distribution of numeric and categorical values. ') + 'Suggest using original training dataset.')) explain_parser.add_argument('--num_features', type=int, help=('number of features to analyze. In text, it is number of ' + 'words. In image, it is number of areas. For lime only.')) explain_parser.add_argument('--num_samples', type=int, help=('size of the neighborhood to learn the linear model. ' + 'For lime only.')) explain_parser.add_argument('--hide_color', type=int, default=0, help=('the color to use for perturbed area. If -1, average of ' + 'each channel is used for each channel. For image only.')) explain_parser.add_argument('--include_negative', action='store_true', default=False, help='whether to show only positive areas. For lime image only.') explain_parser.add_argument('--overview', action='store_true', default=False, help=('whether to show overview instead of details view.' + 'For lime text and tabular only.')) explain_parser.add_argument('--batch_size', type=int, default=100, help='size of batches passed to prediction. For lime only.') explain_parser.add_argument('--num_gradients', type=int, default=50, help=('the number of scaled images to get gradients from. Larger ' + 'number usually produces better results but slower.')) explain_parser.add_argument('--percent_show', type=int, default=10, help='the percentage of top impactful pixels to show.') explain_parser.set_defaults(func=_explain) tensorboard_parser = parser.subcommand('tensorboard', formatter_class=argparse.RawTextHelpFormatter, help='Start/stop/list TensorBoard instances.') tensorboard_sub_commands = tensorboard_parser.add_subparsers(dest='command') tensorboard_start_parser = tensorboard_sub_commands.add_parser('start', help='Start a tensorboard instance.') tensorboard_start_parser.add_argument('--logdir', required=True, help='The local or GCS logdir path.') tensorboard_start_parser.set_defaults(func=_tensorboard_start) tensorboard_stop_parser = tensorboard_sub_commands.add_parser('stop', help='Stop a tensorboard instance.') tensorboard_stop_parser.add_argument('--pid', required=True, type=int, help='The pid of the tensorboard instance.') tensorboard_stop_parser.set_defaults(func=_tensorboard_stop) tensorboard_list_parser = tensorboard_sub_commands.add_parser('list', help='List tensorboard instances.') tensorboard_list_parser.set_defaults(func=_tensorboard_list) evaluate_parser = parser.subcommand('evaluate', formatter_class=argparse.RawTextHelpFormatter, help='Analyze model evaluation results, such as confusion matrix, ROC, RMSE.') evaluate_sub_commands = evaluate_parser.add_subparsers(dest='command') def _add_data_params_for_evaluate(parser): parser.add_argument('--csv', help='csv file path patterns.') parser.add_argument('--headers', help=('csv file headers. Required if csv is specified and ' + 'predict_results_schema.json does not exist in the same directory.')) parser.add_argument('--bigquery', help=('can be bigquery table, query as a string, or ' + 'a pre-defined query (%%bq query --name).')) evaluate_cm_parser = evaluate_sub_commands.add_parser('confusion_matrix', help='Get confusion matrix from evaluation results.') _add_data_params_for_evaluate(evaluate_cm_parser) evaluate_cm_parser.add_argument('--plot', action='store_true', default=False, help='Whether to plot confusion matrix as graph.') evaluate_cm_parser.add_argument('--size', type=int, default=10, help='The size of the confusion matrix.') evaluate_cm_parser.set_defaults(func=_evaluate_cm) evaluate_accuracy_parser = evaluate_sub_commands.add_parser('accuracy', help='Get accuracy results from classification evaluation results.') _add_data_params_for_evaluate(evaluate_accuracy_parser) evaluate_accuracy_parser.set_defaults(func=_evaluate_accuracy) evaluate_pr_parser = evaluate_sub_commands.add_parser('precision_recall', help='Get precision recall metrics from evaluation results.') _add_data_params_for_evaluate(evaluate_pr_parser) evaluate_pr_parser.add_argument('--plot', action='store_true', default=False, help='Whether to plot precision recall as graph.') evaluate_pr_parser.add_argument('--num_thresholds', type=int, default=20, help=('Number of thresholds which determines how many ' + 'points in the graph.')) evaluate_pr_parser.add_argument('--target_class', required=True, help=('The target class to determine correctness of ' + 'a prediction.')) evaluate_pr_parser.add_argument('--probability_column', help=(('The name of the column holding the probability ' + 'value of the target class. If absent, the value ') + 'of target class is used.')) evaluate_pr_parser.set_defaults(func=_evaluate_pr) evaluate_roc_parser = evaluate_sub_commands.add_parser('roc', help='Get ROC metrics from evaluation results.') _add_data_params_for_evaluate(evaluate_roc_parser) evaluate_roc_parser.add_argument('--plot', action='store_true', default=False, help='Whether to plot ROC as graph.') evaluate_roc_parser.add_argument('--num_thresholds', type=int, default=20, help=('Number of thresholds which determines how many ' + 'points in the graph.')) evaluate_roc_parser.add_argument('--target_class', required=True, help=('The target class to determine correctness of ' + 'a prediction.')) evaluate_roc_parser.add_argument('--probability_column', help=(('The name of the column holding the probability ' + 'value of the target class. If absent, the value ') + 'of target class is used.')) evaluate_roc_parser.set_defaults(func=_evaluate_roc) evaluate_regression_parser = evaluate_sub_commands.add_parser('regression', help='Get regression metrics from evaluation results.') _add_data_params_for_evaluate(evaluate_regression_parser) evaluate_regression_parser.set_defaults(func=_evaluate_regression) model_parser = parser.subcommand('model', help='Models and versions management such as deployment, deletion, listing.') model_sub_commands = model_parser.add_subparsers(dest='command') model_list_parser = model_sub_commands.add_parser('list', help='List models and versions.') model_list_parser.add_argument('--name', help=(('If absent, list all models of specified or current ' + 'project. If provided, list all versions of the ') + 'model.')) model_list_parser.add_argument('--project', help=('The project to list model(s) or version(s). If absent, ' + "use Datalab's default project.")) model_list_parser.set_defaults(func=_model_list) model_delete_parser = model_sub_commands.add_parser('delete', help='Delete models or versions.') model_delete_parser.add_argument('--name', required=True, help=(('If no "." in the name, try deleting the specified ' + 'model. If "model.version" is provided, try deleting ') + 'the specified version.')) model_delete_parser.add_argument('--project', help=('The project to delete model or version. If absent, ' + "use Datalab's default project.")) model_delete_parser.set_defaults(func=_model_delete) model_deploy_parser = model_sub_commands.add_parser('deploy', help='Deploy a model version.') model_deploy_parser.add_argument('--name', required=True, help=('Must be model.version to indicate the model ' + 'and version name to deploy.')) model_deploy_parser.add_argument('--path', required=True, help='The GCS path of the model to be deployed.') model_deploy_parser.add_argument('--runtime_version', help=(('The TensorFlow version to use for this model. ' + 'For example, "1.2.1". If absent, the current ') + 'TensorFlow version installed in Datalab will be used.')) model_deploy_parser.add_argument('--project', help=('The project to deploy a model version. If absent, ' + "use Datalab's default project.")) model_deploy_parser.set_defaults(func=_model_deploy) return google.datalab.utils.commands.handle_magic_line(line, cell, parser)<|docstring|>Implements the datalab cell magic for MLWorkbench operations. Args: line: the contents of the ml command line. Returns: The results of executing the cell.<|endoftext|>
155307dd45a4bf113f6867631c9563c268ecc006ea1689037c0553a0df62b23c
def _abs_path(path): "Convert a non-GCS path to its absolute path.\n\n path can contain special filepath characters like '..', '*' and '.'.\n\n Example: If the current folder is /content/datalab/folder1 and path is\n '../folder2/files*', then this function returns the string\n '/content/datalab/folder2/files*'.\n\n This function is needed if using _shell_process.run_and_monitor() as that\n function runs a command in a different folder.\n\n Args:\n path: string.\n " if path.startswith('gs://'): return path return os.path.abspath(path)
Convert a non-GCS path to its absolute path. path can contain special filepath characters like '..', '*' and '.'. Example: If the current folder is /content/datalab/folder1 and path is '../folder2/files*', then this function returns the string '/content/datalab/folder2/files*'. This function is needed if using _shell_process.run_and_monitor() as that function runs a command in a different folder. Args: path: string.
google/datalab/contrib/mlworkbench/commands/_ml.py
_abs_path
alienczf/pydatalab
198
python
def _abs_path(path): "Convert a non-GCS path to its absolute path.\n\n path can contain special filepath characters like '..', '*' and '.'.\n\n Example: If the current folder is /content/datalab/folder1 and path is\n '../folder2/files*', then this function returns the string\n '/content/datalab/folder2/files*'.\n\n This function is needed if using _shell_process.run_and_monitor() as that\n function runs a command in a different folder.\n\n Args:\n path: string.\n " if path.startswith('gs://'): return path return os.path.abspath(path)
def _abs_path(path): "Convert a non-GCS path to its absolute path.\n\n path can contain special filepath characters like '..', '*' and '.'.\n\n Example: If the current folder is /content/datalab/folder1 and path is\n '../folder2/files*', then this function returns the string\n '/content/datalab/folder2/files*'.\n\n This function is needed if using _shell_process.run_and_monitor() as that\n function runs a command in a different folder.\n\n Args:\n path: string.\n " if path.startswith('gs://'): return path return os.path.abspath(path)<|docstring|>Convert a non-GCS path to its absolute path. path can contain special filepath characters like '..', '*' and '.'. Example: If the current folder is /content/datalab/folder1 and path is '../folder2/files*', then this function returns the string '/content/datalab/folder2/files*'. This function is needed if using _shell_process.run_and_monitor() as that function runs a command in a different folder. Args: path: string.<|endoftext|>
3b3e836d06cdadb1fddb9fb6df4dc29344b6b0fe754d4313b458625b7798e896
def read(self) -> List[int]: 'Возвращает текущее показание сенсора в виде массива\n из трёх элементов, соответствующих показаниям сенсора\n по каждой из осей.\n ' raise NotImplementedError
Возвращает текущее показание сенсора в виде массива из трёх элементов, соответствующих показаниям сенсора по каждой из осей.
trik/brick.py
read
m1raynee/trikset.py-typehint
1
python
def read(self) -> List[int]: 'Возвращает текущее показание сенсора в виде массива\n из трёх элементов, соответствующих показаниям сенсора\n по каждой из осей.\n ' raise NotImplementedError
def read(self) -> List[int]: 'Возвращает текущее показание сенсора в виде массива\n из трёх элементов, соответствующих показаниям сенсора\n по каждой из осей.\n ' raise NotImplementedError<|docstring|>Возвращает текущее показание сенсора в виде массива из трёх элементов, соответствующих показаниям сенсора по каждой из осей.<|endoftext|>
2490f576ddebe876cf2a2c7f7573613845035707709d5e73640d625b4754cc78
def readVoltage(self) -> int: 'Возвращает текущий вольтаж батареи (или блока питания) в вольтах.' raise NotImplementedError
Возвращает текущий вольтаж батареи (или блока питания) в вольтах.
trik/brick.py
readVoltage
m1raynee/trikset.py-typehint
1
python
def readVoltage(self) -> int: raise NotImplementedError
def readVoltage(self) -> int: raise NotImplementedError<|docstring|>Возвращает текущий вольтаж батареи (или блока питания) в вольтах.<|endoftext|>
1773f9bfb3c4fff621689257567550244de477ca7c0421698fc8415ad5ec8ce0
def init(self, show_to_screen: bool) -> None: 'Включает видеокамеру и инициализирует её в режиме датчика цвета.' raise NotImplementedError
Включает видеокамеру и инициализирует её в режиме датчика цвета.
trik/brick.py
init
m1raynee/trikset.py-typehint
1
python
def init(self, show_to_screen: bool) -> None: raise NotImplementedError
def init(self, show_to_screen: bool) -> None: raise NotImplementedError<|docstring|>Включает видеокамеру и инициализирует её в режиме датчика цвета.<|endoftext|>
f116e4a48dc5b0c57b3bc3f4cbad2f1e04ef28c0ed021a84a9c2f30d46657ea7
def read(self, x: int, y: int) -> List[int]: 'Возвращает массив с координатами доминирующего цвета\n в цветовой шкале RGB в указанном участке кадра.\n\n Кадр делится на квадраты сеткой, по умолчанию 3 на 3, размерность сетки\n можно задать в `model-config.xml` на роботе. Квадраты индексируются с 1.\n То есть (1, 1) — это левый верхний край кадра, (2, 2) — его центр.\n Возвращаемое значение — массив из трёх элементов от 0 до 255, индексирующийся с 0.\n Нулевой элемент содержит интенсивность красного (0 — совсем нет, 255 — очень много),\n первый — интенсивность зелёного, второй — интенсивность синего.\n Например, (0, 0, 0) — чёрный, (255, 255, 255) — белый, (255, 0, 0) — красный.\n\n Параметры\n ---------\n x: :class:`int`\n Координата участке кадра по оси Ох\n y: :class:`int`\n Координата участке кадра по оси Оy\n ' raise NotImplementedError
Возвращает массив с координатами доминирующего цвета в цветовой шкале RGB в указанном участке кадра. Кадр делится на квадраты сеткой, по умолчанию 3 на 3, размерность сетки можно задать в `model-config.xml` на роботе. Квадраты индексируются с 1. То есть (1, 1) — это левый верхний край кадра, (2, 2) — его центр. Возвращаемое значение — массив из трёх элементов от 0 до 255, индексирующийся с 0. Нулевой элемент содержит интенсивность красного (0 — совсем нет, 255 — очень много), первый — интенсивность зелёного, второй — интенсивность синего. Например, (0, 0, 0) — чёрный, (255, 255, 255) — белый, (255, 0, 0) — красный. Параметры --------- x: :class:`int` Координата участке кадра по оси Ох y: :class:`int` Координата участке кадра по оси Оy
trik/brick.py
read
m1raynee/trikset.py-typehint
1
python
def read(self, x: int, y: int) -> List[int]: 'Возвращает массив с координатами доминирующего цвета\n в цветовой шкале RGB в указанном участке кадра.\n\n Кадр делится на квадраты сеткой, по умолчанию 3 на 3, размерность сетки\n можно задать в `model-config.xml` на роботе. Квадраты индексируются с 1.\n То есть (1, 1) — это левый верхний край кадра, (2, 2) — его центр.\n Возвращаемое значение — массив из трёх элементов от 0 до 255, индексирующийся с 0.\n Нулевой элемент содержит интенсивность красного (0 — совсем нет, 255 — очень много),\n первый — интенсивность зелёного, второй — интенсивность синего.\n Например, (0, 0, 0) — чёрный, (255, 255, 255) — белый, (255, 0, 0) — красный.\n\n Параметры\n ---------\n x: :class:`int`\n Координата участке кадра по оси Ох\n y: :class:`int`\n Координата участке кадра по оси Оy\n ' raise NotImplementedError
def read(self, x: int, y: int) -> List[int]: 'Возвращает массив с координатами доминирующего цвета\n в цветовой шкале RGB в указанном участке кадра.\n\n Кадр делится на квадраты сеткой, по умолчанию 3 на 3, размерность сетки\n можно задать в `model-config.xml` на роботе. Квадраты индексируются с 1.\n То есть (1, 1) — это левый верхний край кадра, (2, 2) — его центр.\n Возвращаемое значение — массив из трёх элементов от 0 до 255, индексирующийся с 0.\n Нулевой элемент содержит интенсивность красного (0 — совсем нет, 255 — очень много),\n первый — интенсивность зелёного, второй — интенсивность синего.\n Например, (0, 0, 0) — чёрный, (255, 255, 255) — белый, (255, 0, 0) — красный.\n\n Параметры\n ---------\n x: :class:`int`\n Координата участке кадра по оси Ох\n y: :class:`int`\n Координата участке кадра по оси Оy\n ' raise NotImplementedError<|docstring|>Возвращает массив с координатами доминирующего цвета в цветовой шкале RGB в указанном участке кадра. Кадр делится на квадраты сеткой, по умолчанию 3 на 3, размерность сетки можно задать в `model-config.xml` на роботе. Квадраты индексируются с 1. То есть (1, 1) — это левый верхний край кадра, (2, 2) — его центр. Возвращаемое значение — массив из трёх элементов от 0 до 255, индексирующийся с 0. Нулевой элемент содержит интенсивность красного (0 — совсем нет, 255 — очень много), первый — интенсивность зелёного, второй — интенсивность синего. Например, (0, 0, 0) — чёрный, (255, 255, 255) — белый, (255, 0, 0) — красный. Параметры --------- x: :class:`int` Координата участке кадра по оси Ох y: :class:`int` Координата участке кадра по оси Оy<|endoftext|>
f7db3fc17c9d14c95d56c570e5a55f1e6c00f3716623a481ed9ba3685a137ddd
def stop(self) -> None: 'Выключает видеокамеру и прекращает работу датчика.' raise NotImplementedError
Выключает видеокамеру и прекращает работу датчика.
trik/brick.py
stop
m1raynee/trikset.py-typehint
1
python
def stop(self) -> None: raise NotImplementedError
def stop(self) -> None: raise NotImplementedError<|docstring|>Выключает видеокамеру и прекращает работу датчика.<|endoftext|>
ae12e3064656b6523ad762649a33d0f60105cd653eae1a282ce6e3e08caafb51
def addLabel(self, text: str, x: int, y: int): 'Вывести на экран указанный текст в указанные координаты.\n Если в указанных координатах уже был текст, он будет заменён новым.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n text: :class:`str`\n Выводимый текст\n x: :class:`int`\n Координата экрана по оси Ох\n y: :class:`int`\n Координата экрана по оси Оy\n ' raise NotImplementedError
Вывести на экран указанный текст в указанные координаты. Если в указанных координатах уже был текст, он будет заменён новым. Изменения на дисплее произойдут только после вызова метода «redraw». Параметры --------- text: :class:`str` Выводимый текст x: :class:`int` Координата экрана по оси Ох y: :class:`int` Координата экрана по оси Оy
trik/brick.py
addLabel
m1raynee/trikset.py-typehint
1
python
def addLabel(self, text: str, x: int, y: int): 'Вывести на экран указанный текст в указанные координаты.\n Если в указанных координатах уже был текст, он будет заменён новым.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n text: :class:`str`\n Выводимый текст\n x: :class:`int`\n Координата экрана по оси Ох\n y: :class:`int`\n Координата экрана по оси Оy\n ' raise NotImplementedError
def addLabel(self, text: str, x: int, y: int): 'Вывести на экран указанный текст в указанные координаты.\n Если в указанных координатах уже был текст, он будет заменён новым.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n text: :class:`str`\n Выводимый текст\n x: :class:`int`\n Координата экрана по оси Ох\n y: :class:`int`\n Координата экрана по оси Оy\n ' raise NotImplementedError<|docstring|>Вывести на экран указанный текст в указанные координаты. Если в указанных координатах уже был текст, он будет заменён новым. Изменения на дисплее произойдут только после вызова метода «redraw». Параметры --------- text: :class:`str` Выводимый текст x: :class:`int` Координата экрана по оси Ох y: :class:`int` Координата экрана по оси Оy<|endoftext|>
627c544bec9c544ca9c437200bcc8ca277c1467f9b2dd0a492d670f3ab9331bb
def clear(self) -> None: 'Очистить окно для рисования.' raise NotImplementedError
Очистить окно для рисования.
trik/brick.py
clear
m1raynee/trikset.py-typehint
1
python
def clear(self) -> None: raise NotImplementedError
def clear(self) -> None: raise NotImplementedError<|docstring|>Очистить окно для рисования.<|endoftext|>
69308befd2f0ded0fb658a9cf507a342143ea37bbb7a01d7172bdef4a6acf7ec
def drawArc(self, x: int, y: int, l: int, h: int, _from: int, to: int) -> None: 'Нарисовать дугу эллипса, вписанного в прямоугольник с левым верхним углом в указанных\n координатах и имеющий заданную ширину и высоту.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x: :class:`int`\n Координата левого верхнего угла по оси Ох\n y: :class:`int`\n Координата левого верхнего угла по оси Оy\n l: :class:`int`\n Ширина прямоугольника\n h: :class:`int`\n Высота прямоугольника\n from: :class:`int`\n Начальный угол, ограничивающий дугу\n to: :class:`int`\n Конечный угол, ограничивающий дугу\n ' raise NotImplementedError
Нарисовать дугу эллипса, вписанного в прямоугольник с левым верхним углом в указанных координатах и имеющий заданную ширину и высоту. Изменения на дисплее произойдут только после вызова метода «redraw». Параметры --------- x: :class:`int` Координата левого верхнего угла по оси Ох y: :class:`int` Координата левого верхнего угла по оси Оy l: :class:`int` Ширина прямоугольника h: :class:`int` Высота прямоугольника from: :class:`int` Начальный угол, ограничивающий дугу to: :class:`int` Конечный угол, ограничивающий дугу
trik/brick.py
drawArc
m1raynee/trikset.py-typehint
1
python
def drawArc(self, x: int, y: int, l: int, h: int, _from: int, to: int) -> None: 'Нарисовать дугу эллипса, вписанного в прямоугольник с левым верхним углом в указанных\n координатах и имеющий заданную ширину и высоту.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x: :class:`int`\n Координата левого верхнего угла по оси Ох\n y: :class:`int`\n Координата левого верхнего угла по оси Оy\n l: :class:`int`\n Ширина прямоугольника\n h: :class:`int`\n Высота прямоугольника\n from: :class:`int`\n Начальный угол, ограничивающий дугу\n to: :class:`int`\n Конечный угол, ограничивающий дугу\n ' raise NotImplementedError
def drawArc(self, x: int, y: int, l: int, h: int, _from: int, to: int) -> None: 'Нарисовать дугу эллипса, вписанного в прямоугольник с левым верхним углом в указанных\n координатах и имеющий заданную ширину и высоту.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x: :class:`int`\n Координата левого верхнего угла по оси Ох\n y: :class:`int`\n Координата левого верхнего угла по оси Оy\n l: :class:`int`\n Ширина прямоугольника\n h: :class:`int`\n Высота прямоугольника\n from: :class:`int`\n Начальный угол, ограничивающий дугу\n to: :class:`int`\n Конечный угол, ограничивающий дугу\n ' raise NotImplementedError<|docstring|>Нарисовать дугу эллипса, вписанного в прямоугольник с левым верхним углом в указанных координатах и имеющий заданную ширину и высоту. Изменения на дисплее произойдут только после вызова метода «redraw». Параметры --------- x: :class:`int` Координата левого верхнего угла по оси Ох y: :class:`int` Координата левого верхнего угла по оси Оy l: :class:`int` Ширина прямоугольника h: :class:`int` Высота прямоугольника from: :class:`int` Начальный угол, ограничивающий дугу to: :class:`int` Конечный угол, ограничивающий дугу<|endoftext|>
3985b6b8eeca059fafd22fbad9d02b72369282ea8bd39aebf9ac5043970edbd7
def drawEllipse(self, x: int, y: int, l: int, h: int, filled: bool=False) -> None: 'Нарисовать эллипс, вписанный в прямоугольник с левым верхним углом в указанных\n координатах и имеющий заданную ширину и высоту.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x: :class:`int`\n Координата левого верхнего угла по оси Ох\n y: :class:`int`\n Координата левого верхнего угла по оси Оy\n l: :class:`int`\n Ширина прямоугольника\n h: :class:`int`\n Высота прямоугольника\n filled: :class:`bool`\n Заливать фигуру или нет, по умолчанию False\n ' raise NotImplementedError
Нарисовать эллипс, вписанный в прямоугольник с левым верхним углом в указанных координатах и имеющий заданную ширину и высоту. Изменения на дисплее произойдут только после вызова метода «redraw». Параметры --------- x: :class:`int` Координата левого верхнего угла по оси Ох y: :class:`int` Координата левого верхнего угла по оси Оy l: :class:`int` Ширина прямоугольника h: :class:`int` Высота прямоугольника filled: :class:`bool` Заливать фигуру или нет, по умолчанию False
trik/brick.py
drawEllipse
m1raynee/trikset.py-typehint
1
python
def drawEllipse(self, x: int, y: int, l: int, h: int, filled: bool=False) -> None: 'Нарисовать эллипс, вписанный в прямоугольник с левым верхним углом в указанных\n координатах и имеющий заданную ширину и высоту.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x: :class:`int`\n Координата левого верхнего угла по оси Ох\n y: :class:`int`\n Координата левого верхнего угла по оси Оy\n l: :class:`int`\n Ширина прямоугольника\n h: :class:`int`\n Высота прямоугольника\n filled: :class:`bool`\n Заливать фигуру или нет, по умолчанию False\n ' raise NotImplementedError
def drawEllipse(self, x: int, y: int, l: int, h: int, filled: bool=False) -> None: 'Нарисовать эллипс, вписанный в прямоугольник с левым верхним углом в указанных\n координатах и имеющий заданную ширину и высоту.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x: :class:`int`\n Координата левого верхнего угла по оси Ох\n y: :class:`int`\n Координата левого верхнего угла по оси Оy\n l: :class:`int`\n Ширина прямоугольника\n h: :class:`int`\n Высота прямоугольника\n filled: :class:`bool`\n Заливать фигуру или нет, по умолчанию False\n ' raise NotImplementedError<|docstring|>Нарисовать эллипс, вписанный в прямоугольник с левым верхним углом в указанных координатах и имеющий заданную ширину и высоту. Изменения на дисплее произойдут только после вызова метода «redraw». Параметры --------- x: :class:`int` Координата левого верхнего угла по оси Ох y: :class:`int` Координата левого верхнего угла по оси Оy l: :class:`int` Ширина прямоугольника h: :class:`int` Высота прямоугольника filled: :class:`bool` Заливать фигуру или нет, по умолчанию False<|endoftext|>
d18a61975dc8eaa624340fb8ff60c59e38a0dee454a5ccbe511213aeb45db306
def drawLine(self, x0: int, y0: int, x1: int, y1: int) -> None: 'Нарисовать линию с началом и концом в заданных координатах.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x0: :class:`int`\n Координата начала линии по оси Ох\n y0: :class:`int`\n Координата начала линии по оси Оy\n x1: :class:`int`\n Координата конца линии угла по оси Ох\n y1: :class:`int`\n Координата конца линии угла по оси Оy\n ' raise NotImplementedError
Нарисовать линию с началом и концом в заданных координатах. Изменения на дисплее произойдут только после вызова метода «redraw». Параметры --------- x0: :class:`int` Координата начала линии по оси Ох y0: :class:`int` Координата начала линии по оси Оy x1: :class:`int` Координата конца линии угла по оси Ох y1: :class:`int` Координата конца линии угла по оси Оy
trik/brick.py
drawLine
m1raynee/trikset.py-typehint
1
python
def drawLine(self, x0: int, y0: int, x1: int, y1: int) -> None: 'Нарисовать линию с началом и концом в заданных координатах.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x0: :class:`int`\n Координата начала линии по оси Ох\n y0: :class:`int`\n Координата начала линии по оси Оy\n x1: :class:`int`\n Координата конца линии угла по оси Ох\n y1: :class:`int`\n Координата конца линии угла по оси Оy\n ' raise NotImplementedError
def drawLine(self, x0: int, y0: int, x1: int, y1: int) -> None: 'Нарисовать линию с началом и концом в заданных координатах.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x0: :class:`int`\n Координата начала линии по оси Ох\n y0: :class:`int`\n Координата начала линии по оси Оy\n x1: :class:`int`\n Координата конца линии угла по оси Ох\n y1: :class:`int`\n Координата конца линии угла по оси Оy\n ' raise NotImplementedError<|docstring|>Нарисовать линию с началом и концом в заданных координатах. Изменения на дисплее произойдут только после вызова метода «redraw». Параметры --------- x0: :class:`int` Координата начала линии по оси Ох y0: :class:`int` Координата начала линии по оси Оy x1: :class:`int` Координата конца линии угла по оси Ох y1: :class:`int` Координата конца линии угла по оси Оy<|endoftext|>
6dec68132058cb5bf1024084f95c9d07fa62e8f1d1292d0d3c78b8c88b212c70
def drawPoint(self, x: int, y: int) -> None: 'Нарисовать точку в заданных координатах.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x0: :class:`int`\n Координата точки по оси Ох\n y0: :class:`int`\n Координата точки по оси Оy\n ' raise NotImplementedError
Нарисовать точку в заданных координатах. Изменения на дисплее произойдут только после вызова метода «redraw». Параметры --------- x0: :class:`int` Координата точки по оси Ох y0: :class:`int` Координата точки по оси Оy
trik/brick.py
drawPoint
m1raynee/trikset.py-typehint
1
python
def drawPoint(self, x: int, y: int) -> None: 'Нарисовать точку в заданных координатах.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x0: :class:`int`\n Координата точки по оси Ох\n y0: :class:`int`\n Координата точки по оси Оy\n ' raise NotImplementedError
def drawPoint(self, x: int, y: int) -> None: 'Нарисовать точку в заданных координатах.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x0: :class:`int`\n Координата точки по оси Ох\n y0: :class:`int`\n Координата точки по оси Оy\n ' raise NotImplementedError<|docstring|>Нарисовать точку в заданных координатах. Изменения на дисплее произойдут только после вызова метода «redraw». Параметры --------- x0: :class:`int` Координата точки по оси Ох y0: :class:`int` Координата точки по оси Оy<|endoftext|>
6586a3dee4b625758dbb79b4068eabdc2d36bb6059550f5ad5b11dcff8bcd8de
def drawRect(self, x: int, y: int, l: int, h: int, filled: bool=False) -> None: 'Нарисовать прямоугольник с левым верхним углом в указанных координатах\n и имеющий заданную ширину и высоту.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x: :class:`int`\n Координата левого верхнего угла по оси Ох\n y: :class:`int`\n Координата левого верхнего угла по оси Оy\n l: :class:`int`\n Ширина прямоугольника\n h: :class:`int`\n Высота прямоугольника\n filled: :class:`bool`\n Заливать фигуру или нет, по умолчанию False\n ' raise NotImplementedError
Нарисовать прямоугольник с левым верхним углом в указанных координатах и имеющий заданную ширину и высоту. Изменения на дисплее произойдут только после вызова метода «redraw». Параметры --------- x: :class:`int` Координата левого верхнего угла по оси Ох y: :class:`int` Координата левого верхнего угла по оси Оy l: :class:`int` Ширина прямоугольника h: :class:`int` Высота прямоугольника filled: :class:`bool` Заливать фигуру или нет, по умолчанию False
trik/brick.py
drawRect
m1raynee/trikset.py-typehint
1
python
def drawRect(self, x: int, y: int, l: int, h: int, filled: bool=False) -> None: 'Нарисовать прямоугольник с левым верхним углом в указанных координатах\n и имеющий заданную ширину и высоту.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x: :class:`int`\n Координата левого верхнего угла по оси Ох\n y: :class:`int`\n Координата левого верхнего угла по оси Оy\n l: :class:`int`\n Ширина прямоугольника\n h: :class:`int`\n Высота прямоугольника\n filled: :class:`bool`\n Заливать фигуру или нет, по умолчанию False\n ' raise NotImplementedError
def drawRect(self, x: int, y: int, l: int, h: int, filled: bool=False) -> None: 'Нарисовать прямоугольник с левым верхним углом в указанных координатах\n и имеющий заданную ширину и высоту.\n\n Изменения на дисплее произойдут только после вызова метода «redraw».\n\n Параметры\n ---------\n x: :class:`int`\n Координата левого верхнего угла по оси Ох\n y: :class:`int`\n Координата левого верхнего угла по оси Оy\n l: :class:`int`\n Ширина прямоугольника\n h: :class:`int`\n Высота прямоугольника\n filled: :class:`bool`\n Заливать фигуру или нет, по умолчанию False\n ' raise NotImplementedError<|docstring|>Нарисовать прямоугольник с левым верхним углом в указанных координатах и имеющий заданную ширину и высоту. Изменения на дисплее произойдут только после вызова метода «redraw». Параметры --------- x: :class:`int` Координата левого верхнего угла по оси Ох y: :class:`int` Координата левого верхнего угла по оси Оy l: :class:`int` Ширина прямоугольника h: :class:`int` Высота прямоугольника filled: :class:`bool` Заливать фигуру или нет, по умолчанию False<|endoftext|>
5977b9371dfb655c83236c1f8115de04e7b9897dd9d56675cb89b84be7988935
def hide(self) -> None: 'Закрыть и очистить окно для рисования.' raise NotImplementedError
Закрыть и очистить окно для рисования.
trik/brick.py
hide
m1raynee/trikset.py-typehint
1
python
def hide(self) -> None: raise NotImplementedError
def hide(self) -> None: raise NotImplementedError<|docstring|>Закрыть и очистить окно для рисования.<|endoftext|>
81b982b9ff331e9f5f2dc90fd506d83c0b270013b1c1df3a524405db520decbd
def redraw(self) -> None: 'Перерисовать окно для рисования.\n\n Изменения на дисплее произойдут только после вызова этого метода.\n ' raise NotImplementedError
Перерисовать окно для рисования. Изменения на дисплее произойдут только после вызова этого метода.
trik/brick.py
redraw
m1raynee/trikset.py-typehint
1
python
def redraw(self) -> None: 'Перерисовать окно для рисования.\n\n Изменения на дисплее произойдут только после вызова этого метода.\n ' raise NotImplementedError
def redraw(self) -> None: 'Перерисовать окно для рисования.\n\n Изменения на дисплее произойдут только после вызова этого метода.\n ' raise NotImplementedError<|docstring|>Перерисовать окно для рисования. Изменения на дисплее произойдут только после вызова этого метода.<|endoftext|>
fc3ace39bf834054777af8b3da75725f5804b60b7392a0a669111983c8332fe9
def removeLabels(self) -> None: 'Удалить с экрана весь текст, добавленный на него вызовами метода «addLabel».' raise NotImplementedError
Удалить с экрана весь текст, добавленный на него вызовами метода «addLabel».
trik/brick.py
removeLabels
m1raynee/trikset.py-typehint
1
python
def removeLabels(self) -> None: raise NotImplementedError
def removeLabels(self) -> None: raise NotImplementedError<|docstring|>Удалить с экрана весь текст, добавленный на него вызовами метода «addLabel».<|endoftext|>
f147dffdbb0855add2c59eb004704abc97318061213670807ff3f9efd5596fb0
def setBackground(self, color: _COLOR) -> None: 'Установить фон экрана в указанный цвет.\n\n Параметры\n ---------\n color: :class:`str`\n Возможные цвета:\n - white,\n - red, darkRed,\n - green, darkGreen,\n - blue, darkBlue,\n - cyan, darkCyan,\n - magenta, darkMagenta,\n - yellow, darkYellow,\n - gray, darkGray, lightGray,\n - black.\n ' raise NotImplementedError
Установить фон экрана в указанный цвет. Параметры --------- color: :class:`str` Возможные цвета: - white, - red, darkRed, - green, darkGreen, - blue, darkBlue, - cyan, darkCyan, - magenta, darkMagenta, - yellow, darkYellow, - gray, darkGray, lightGray, - black.
trik/brick.py
setBackground
m1raynee/trikset.py-typehint
1
python
def setBackground(self, color: _COLOR) -> None: 'Установить фон экрана в указанный цвет.\n\n Параметры\n ---------\n color: :class:`str`\n Возможные цвета:\n - white,\n - red, darkRed,\n - green, darkGreen,\n - blue, darkBlue,\n - cyan, darkCyan,\n - magenta, darkMagenta,\n - yellow, darkYellow,\n - gray, darkGray, lightGray,\n - black.\n ' raise NotImplementedError
def setBackground(self, color: _COLOR) -> None: 'Установить фон экрана в указанный цвет.\n\n Параметры\n ---------\n color: :class:`str`\n Возможные цвета:\n - white,\n - red, darkRed,\n - green, darkGreen,\n - blue, darkBlue,\n - cyan, darkCyan,\n - magenta, darkMagenta,\n - yellow, darkYellow,\n - gray, darkGray, lightGray,\n - black.\n ' raise NotImplementedError<|docstring|>Установить фон экрана в указанный цвет. Параметры --------- color: :class:`str` Возможные цвета: - white, - red, darkRed, - green, darkGreen, - blue, darkBlue, - cyan, darkCyan, - magenta, darkMagenta, - yellow, darkYellow, - gray, darkGray, lightGray, - black.<|endoftext|>
1ea1b5dd3c45d6aced29746a1ec3346752f687af9d33e12c745629d6a5f9a930
def setPainterColor(self, color: _COLOR) -> None: 'Установить цвет кисти, которой рисуются графические примитивы.\n\n Параметры\n ---------\n color: :class:`str`\n Возможные цвета:\n - white,\n - red, darkRed,\n - green, darkGreen,\n - blue, darkBlue,\n - cyan, darkCyan,\n - magenta, darkMagenta,\n - yellow, darkYellow,\n - gray, darkGray, lightGray,\n - black.\n ' raise NotImplementedError
Установить цвет кисти, которой рисуются графические примитивы. Параметры --------- color: :class:`str` Возможные цвета: - white, - red, darkRed, - green, darkGreen, - blue, darkBlue, - cyan, darkCyan, - magenta, darkMagenta, - yellow, darkYellow, - gray, darkGray, lightGray, - black.
trik/brick.py
setPainterColor
m1raynee/trikset.py-typehint
1
python
def setPainterColor(self, color: _COLOR) -> None: 'Установить цвет кисти, которой рисуются графические примитивы.\n\n Параметры\n ---------\n color: :class:`str`\n Возможные цвета:\n - white,\n - red, darkRed,\n - green, darkGreen,\n - blue, darkBlue,\n - cyan, darkCyan,\n - magenta, darkMagenta,\n - yellow, darkYellow,\n - gray, darkGray, lightGray,\n - black.\n ' raise NotImplementedError
def setPainterColor(self, color: _COLOR) -> None: 'Установить цвет кисти, которой рисуются графические примитивы.\n\n Параметры\n ---------\n color: :class:`str`\n Возможные цвета:\n - white,\n - red, darkRed,\n - green, darkGreen,\n - blue, darkBlue,\n - cyan, darkCyan,\n - magenta, darkMagenta,\n - yellow, darkYellow,\n - gray, darkGray, lightGray,\n - black.\n ' raise NotImplementedError<|docstring|>Установить цвет кисти, которой рисуются графические примитивы. Параметры --------- color: :class:`str` Возможные цвета: - white, - red, darkRed, - green, darkGreen, - blue, darkBlue, - cyan, darkCyan, - magenta, darkMagenta, - yellow, darkYellow, - gray, darkGray, lightGray, - black.<|endoftext|>
58933b4b79b0fa0d5a054b5285c507dde275f1d436d1d1022d7c54b7d8f83c86
def setPainterWidth(self, d: int) -> None: 'Установить толщину кисти, которой рисуются графические примитивы, в пикселях.\n\n Параметры\n ---------\n d: :class:`int`\n Толщина\n ' raise NotImplementedError
Установить толщину кисти, которой рисуются графические примитивы, в пикселях. Параметры --------- d: :class:`int` Толщина
trik/brick.py
setPainterWidth
m1raynee/trikset.py-typehint
1
python
def setPainterWidth(self, d: int) -> None: 'Установить толщину кисти, которой рисуются графические примитивы, в пикселях.\n\n Параметры\n ---------\n d: :class:`int`\n Толщина\n ' raise NotImplementedError
def setPainterWidth(self, d: int) -> None: 'Установить толщину кисти, которой рисуются графические примитивы, в пикселях.\n\n Параметры\n ---------\n d: :class:`int`\n Толщина\n ' raise NotImplementedError<|docstring|>Установить толщину кисти, которой рисуются графические примитивы, в пикселях. Параметры --------- d: :class:`int` Толщина<|endoftext|>
553cdf6620256fedd166c6206cb9347225e5f5290b1356d5fb77f95f9846ccf8
def show(self, array: List[int], width: int, height: int, format: _ARRAY_FORMAT) -> None: 'Вывести на дисплей контроллера изображение, преобразованное из однородного массива данных.\n\n Параметры\n ---------\n array: list[:class:`int`]\n Одномерный целочисленный массив, имеющий размеры `width` на `height`\n width: :class:`int`\n Ширина изображения\n height: :class:`int`\n Высота изображения\n format: :class:`str`\n Формат, в котором представлен каждый элемент массива.\n Сейчас поддержаны форматы: «rgb32», «grayscale8», «rgb888»\n ' raise NotImplementedError
Вывести на дисплей контроллера изображение, преобразованное из однородного массива данных. Параметры --------- array: list[:class:`int`] Одномерный целочисленный массив, имеющий размеры `width` на `height` width: :class:`int` Ширина изображения height: :class:`int` Высота изображения format: :class:`str` Формат, в котором представлен каждый элемент массива. Сейчас поддержаны форматы: «rgb32», «grayscale8», «rgb888»
trik/brick.py
show
m1raynee/trikset.py-typehint
1
python
def show(self, array: List[int], width: int, height: int, format: _ARRAY_FORMAT) -> None: 'Вывести на дисплей контроллера изображение, преобразованное из однородного массива данных.\n\n Параметры\n ---------\n array: list[:class:`int`]\n Одномерный целочисленный массив, имеющий размеры `width` на `height`\n width: :class:`int`\n Ширина изображения\n height: :class:`int`\n Высота изображения\n format: :class:`str`\n Формат, в котором представлен каждый элемент массива.\n Сейчас поддержаны форматы: «rgb32», «grayscale8», «rgb888»\n ' raise NotImplementedError
def show(self, array: List[int], width: int, height: int, format: _ARRAY_FORMAT) -> None: 'Вывести на дисплей контроллера изображение, преобразованное из однородного массива данных.\n\n Параметры\n ---------\n array: list[:class:`int`]\n Одномерный целочисленный массив, имеющий размеры `width` на `height`\n width: :class:`int`\n Ширина изображения\n height: :class:`int`\n Высота изображения\n format: :class:`str`\n Формат, в котором представлен каждый элемент массива.\n Сейчас поддержаны форматы: «rgb32», «grayscale8», «rgb888»\n ' raise NotImplementedError<|docstring|>Вывести на дисплей контроллера изображение, преобразованное из однородного массива данных. Параметры --------- array: list[:class:`int`] Одномерный целочисленный массив, имеющий размеры `width` на `height` width: :class:`int` Ширина изображения height: :class:`int` Высота изображения format: :class:`str` Формат, в котором представлен каждый элемент массива. Сейчас поддержаны форматы: «rgb32», «grayscale8», «rgb888»<|endoftext|>
4f79b1fc3fedeeff26457904cc72dbee98a43b851c52bcc0203688755ce2a9ec
def showImage(self, imagePath: str) -> None: 'Вывести на экран изображение, предварительно загруженное на робот.\n\n Параметры\n ---------\n imagePath: :class:`str`\n Имя файла с изображением\n (в форматах BMP, GIF, JPG, JPEG, PNG, PBM, PGM, PPM, TIFF, XBM, XPM),\n путь указывается либо абсолютным, либо относительно папки trik.\n ' raise NotImplementedError
Вывести на экран изображение, предварительно загруженное на робот. Параметры --------- imagePath: :class:`str` Имя файла с изображением (в форматах BMP, GIF, JPG, JPEG, PNG, PBM, PGM, PPM, TIFF, XBM, XPM), путь указывается либо абсолютным, либо относительно папки trik.
trik/brick.py
showImage
m1raynee/trikset.py-typehint
1
python
def showImage(self, imagePath: str) -> None: 'Вывести на экран изображение, предварительно загруженное на робот.\n\n Параметры\n ---------\n imagePath: :class:`str`\n Имя файла с изображением\n (в форматах BMP, GIF, JPG, JPEG, PNG, PBM, PGM, PPM, TIFF, XBM, XPM),\n путь указывается либо абсолютным, либо относительно папки trik.\n ' raise NotImplementedError
def showImage(self, imagePath: str) -> None: 'Вывести на экран изображение, предварительно загруженное на робот.\n\n Параметры\n ---------\n imagePath: :class:`str`\n Имя файла с изображением\n (в форматах BMP, GIF, JPG, JPEG, PNG, PBM, PGM, PPM, TIFF, XBM, XPM),\n путь указывается либо абсолютным, либо относительно папки trik.\n ' raise NotImplementedError<|docstring|>Вывести на экран изображение, предварительно загруженное на робот. Параметры --------- imagePath: :class:`str` Имя файла с изображением (в форматах BMP, GIF, JPG, JPEG, PNG, PBM, PGM, PPM, TIFF, XBM, XPM), путь указывается либо абсолютным, либо относительно папки trik.<|endoftext|>
fde665b46960642a7c8d65257ba2ba5b527ba181e00c63ad1b5b4cd376c9e4f5
def read(self, portName: _PORT_NAME) -> int: 'Возвращает текущее показание энкодера в градусах на заданном порту.\n\n Параметры\n ---------\n portName: :class:`str`\n Порт\n ' raise NotImplementedError
Возвращает текущее показание энкодера в градусах на заданном порту. Параметры --------- portName: :class:`str` Порт
trik/brick.py
read
m1raynee/trikset.py-typehint
1
python
def read(self, portName: _PORT_NAME) -> int: 'Возвращает текущее показание энкодера в градусах на заданном порту.\n\n Параметры\n ---------\n portName: :class:`str`\n Порт\n ' raise NotImplementedError
def read(self, portName: _PORT_NAME) -> int: 'Возвращает текущее показание энкодера в градусах на заданном порту.\n\n Параметры\n ---------\n portName: :class:`str`\n Порт\n ' raise NotImplementedError<|docstring|>Возвращает текущее показание энкодера в градусах на заданном порту. Параметры --------- portName: :class:`str` Порт<|endoftext|>
c17f876083d5f099711330e9b5808ac559de2d74d52825c4e6e0fbedd3d66b4e
def reset(self, portName: _PORT_NAME) -> None: 'Сбрасывает в 0 текущее показание энкодера.\n\n Параметры\n ---------\n portName: :class:`str`\n Порт\n ' raise NotImplementedError
Сбрасывает в 0 текущее показание энкодера. Параметры --------- portName: :class:`str` Порт
trik/brick.py
reset
m1raynee/trikset.py-typehint
1
python
def reset(self, portName: _PORT_NAME) -> None: 'Сбрасывает в 0 текущее показание энкодера.\n\n Параметры\n ---------\n portName: :class:`str`\n Порт\n ' raise NotImplementedError
def reset(self, portName: _PORT_NAME) -> None: 'Сбрасывает в 0 текущее показание энкодера.\n\n Параметры\n ---------\n portName: :class:`str`\n Порт\n ' raise NotImplementedError<|docstring|>Сбрасывает в 0 текущее показание энкодера. Параметры --------- portName: :class:`str` Порт<|endoftext|>
fc16d668922ca28dc2de470157f281c90bff9626c462f4e4905a160e76d8f2c9
def readRawData(self, portName: _PORT_NAME) -> int: 'Возвращает текущее показание энкодера в «тиках» на заданном порту.\n\n Параметры\n ---------\n portName: :class:`str`\n Порт\n ' raise NotImplementedError
Возвращает текущее показание энкодера в «тиках» на заданном порту. Параметры --------- portName: :class:`str` Порт
trik/brick.py
readRawData
m1raynee/trikset.py-typehint
1
python
def readRawData(self, portName: _PORT_NAME) -> int: 'Возвращает текущее показание энкодера в «тиках» на заданном порту.\n\n Параметры\n ---------\n portName: :class:`str`\n Порт\n ' raise NotImplementedError
def readRawData(self, portName: _PORT_NAME) -> int: 'Возвращает текущее показание энкодера в «тиках» на заданном порту.\n\n Параметры\n ---------\n portName: :class:`str`\n Порт\n ' raise NotImplementedError<|docstring|>Возвращает текущее показание энкодера в «тиках» на заданном порту. Параметры --------- portName: :class:`str` Порт<|endoftext|>
663fcd505cb087821a42f429c8ff727abf993ff576c4ac900bd31cff5f493c7c
def calibrate(self, mesc: int) -> None: 'Вычисляет смещение нуля в течение указанного времени и инициализирует\n гироскоп этим параметром, сбрасывает текущие углы наклона.\n\n Параметры\n ---------\n mesc: :class:`int`\n Время калибровки в миллисекундах.\n Рекомендуемое время калибровки — 10-20 секунд.\n ' raise NotImplementedError
Вычисляет смещение нуля в течение указанного времени и инициализирует гироскоп этим параметром, сбрасывает текущие углы наклона. Параметры --------- mesc: :class:`int` Время калибровки в миллисекундах. Рекомендуемое время калибровки — 10-20 секунд.
trik/brick.py
calibrate
m1raynee/trikset.py-typehint
1
python
def calibrate(self, mesc: int) -> None: 'Вычисляет смещение нуля в течение указанного времени и инициализирует\n гироскоп этим параметром, сбрасывает текущие углы наклона.\n\n Параметры\n ---------\n mesc: :class:`int`\n Время калибровки в миллисекундах.\n Рекомендуемое время калибровки — 10-20 секунд.\n ' raise NotImplementedError
def calibrate(self, mesc: int) -> None: 'Вычисляет смещение нуля в течение указанного времени и инициализирует\n гироскоп этим параметром, сбрасывает текущие углы наклона.\n\n Параметры\n ---------\n mesc: :class:`int`\n Время калибровки в миллисекундах.\n Рекомендуемое время калибровки — 10-20 секунд.\n ' raise NotImplementedError<|docstring|>Вычисляет смещение нуля в течение указанного времени и инициализирует гироскоп этим параметром, сбрасывает текущие углы наклона. Параметры --------- mesc: :class:`int` Время калибровки в миллисекундах. Рекомендуемое время калибровки — 10-20 секунд.<|endoftext|>
186ba852f885cb9382283704ea9a342f488f132b58b8c2e6c568a93a65318f16
def getCalibrationValues(self) -> BIOS: 'Возвращает объект, в котором содержатся необходимые данные о смещении нуля.' raise NotImplementedError
Возвращает объект, в котором содержатся необходимые данные о смещении нуля.
trik/brick.py
getCalibrationValues
m1raynee/trikset.py-typehint
1
python
def getCalibrationValues(self) -> BIOS: raise NotImplementedError
def getCalibrationValues(self) -> BIOS: raise NotImplementedError<|docstring|>Возвращает объект, в котором содержатся необходимые данные о смещении нуля.<|endoftext|>
e72edfb266ccbdbb34f612daaa141fe4cd6a6914d0458de343cde2d26f593633
def isCalibrated(self) -> bool: 'Возвращает `True` в случае завершении калибровки, `False` — в противном случае.' raise NotImplementedError
Возвращает `True` в случае завершении калибровки, `False` — в противном случае.
trik/brick.py
isCalibrated
m1raynee/trikset.py-typehint
1
python
def isCalibrated(self) -> bool: raise NotImplementedError
def isCalibrated(self) -> bool: raise NotImplementedError<|docstring|>Возвращает `True` в случае завершении калибровки, `False` — в противном случае.<|endoftext|>
cc3c228cf9f1a4fe6550ea81393ff02af379b0fcdd5930f73d5c7c97da51fcf6
def read(self) -> List[int]: 'Возвращает массив из семи элементов:\n - 0-2 — угловые скорости по трем осям (в миллиградусах/секунды),\n - 3 — время последнего замера (в микросекундах),\n - 4-6 — углы наклона по трем осям (в миллиградусах).\n ' raise NotImplementedError
Возвращает массив из семи элементов: - 0-2 — угловые скорости по трем осям (в миллиградусах/секунды), - 3 — время последнего замера (в микросекундах), - 4-6 — углы наклона по трем осям (в миллиградусах).
trik/brick.py
read
m1raynee/trikset.py-typehint
1
python
def read(self) -> List[int]: 'Возвращает массив из семи элементов:\n - 0-2 — угловые скорости по трем осям (в миллиградусах/секунды),\n - 3 — время последнего замера (в микросекундах),\n - 4-6 — углы наклона по трем осям (в миллиградусах).\n ' raise NotImplementedError
def read(self) -> List[int]: 'Возвращает массив из семи элементов:\n - 0-2 — угловые скорости по трем осям (в миллиградусах/секунды),\n - 3 — время последнего замера (в микросекундах),\n - 4-6 — углы наклона по трем осям (в миллиградусах).\n ' raise NotImplementedError<|docstring|>Возвращает массив из семи элементов: - 0-2 — угловые скорости по трем осям (в миллиградусах/секунды), - 3 — время последнего замера (в микросекундах), - 4-6 — углы наклона по трем осям (в миллиградусах).<|endoftext|>
71e6c53874b075b817d8baae6efc63738d2f6f72e6b858835c544d4d4b5eb3d1
def readRawData(self) -> List[int]: 'Возвращает массив из трех элементов с угловыми скоростями по трем осям.' raise NotImplementedError
Возвращает массив из трех элементов с угловыми скоростями по трем осям.
trik/brick.py
readRawData
m1raynee/trikset.py-typehint
1
python
def readRawData(self) -> List[int]: raise NotImplementedError
def readRawData(self) -> List[int]: raise NotImplementedError<|docstring|>Возвращает массив из трех элементов с угловыми скоростями по трем осям.<|endoftext|>
73dfad8648f3f6523f33fa33b56a1753daa762e7116093275966256e19ee9e43
def setCalibrationValues(self, values: BIOS) -> None: 'Устанавливает объект, содержащий необходимые параметры о смещении нуля.\n Параметры\n ---------\n mesc: :class:`int`\n Время калибровки в миллисекундах.\n Рекомендуемое время калибровки — 10-20 секунд.\n ' raise NotImplementedError
Устанавливает объект, содержащий необходимые параметры о смещении нуля. Параметры --------- mesc: :class:`int` Время калибровки в миллисекундах. Рекомендуемое время калибровки — 10-20 секунд.
trik/brick.py
setCalibrationValues
m1raynee/trikset.py-typehint
1
python
def setCalibrationValues(self, values: BIOS) -> None: 'Устанавливает объект, содержащий необходимые параметры о смещении нуля.\n Параметры\n ---------\n mesc: :class:`int`\n Время калибровки в миллисекундах.\n Рекомендуемое время калибровки — 10-20 секунд.\n ' raise NotImplementedError
def setCalibrationValues(self, values: BIOS) -> None: 'Устанавливает объект, содержащий необходимые параметры о смещении нуля.\n Параметры\n ---------\n mesc: :class:`int`\n Время калибровки в миллисекундах.\n Рекомендуемое время калибровки — 10-20 секунд.\n ' raise NotImplementedError<|docstring|>Устанавливает объект, содержащий необходимые параметры о смещении нуля. Параметры --------- mesc: :class:`int` Время калибровки в миллисекундах. Рекомендуемое время калибровки — 10-20 секунд.<|endoftext|>
c7df09db18f3abc4f976f3256a239370263700db6c0ab815e66fa4febaceeb1d
def isPressed(self, key: KeysEnum) -> bool: 'Возвращает `True`, если кнопка с указанным кодом нажата в данный момент.\n\n Параметры\n ---------\n key: :class:`KeysEnum`\n Кнопка с кодом\n ' raise NotImplementedError
Возвращает `True`, если кнопка с указанным кодом нажата в данный момент. Параметры --------- key: :class:`KeysEnum` Кнопка с кодом
trik/brick.py
isPressed
m1raynee/trikset.py-typehint
1
python
def isPressed(self, key: KeysEnum) -> bool: 'Возвращает `True`, если кнопка с указанным кодом нажата в данный момент.\n\n Параметры\n ---------\n key: :class:`KeysEnum`\n Кнопка с кодом\n ' raise NotImplementedError
def isPressed(self, key: KeysEnum) -> bool: 'Возвращает `True`, если кнопка с указанным кодом нажата в данный момент.\n\n Параметры\n ---------\n key: :class:`KeysEnum`\n Кнопка с кодом\n ' raise NotImplementedError<|docstring|>Возвращает `True`, если кнопка с указанным кодом нажата в данный момент. Параметры --------- key: :class:`KeysEnum` Кнопка с кодом<|endoftext|>
4fd3f8e4103538771e4a8f7aa4b09a6a5fd19d2218bdb9a0b4b0d357702a9e31
def reset(self) -> None: 'Сбрасывает запомненные нажатия кнопок.' raise NotImplementedError
Сбрасывает запомненные нажатия кнопок.
trik/brick.py
reset
m1raynee/trikset.py-typehint
1
python
def reset(self) -> None: raise NotImplementedError
def reset(self) -> None: raise NotImplementedError<|docstring|>Сбрасывает запомненные нажатия кнопок.<|endoftext|>
5ea7f21d13f2056a2d7bdc251b969685965dc39cf2658636ac5e7e56037a7471
def wasPressed(self, key: KeysEnum) -> bool: 'Возвращает, была ли нажата кнопка с указанным кодом,\n сбрасывает запомненные нажатия для этой кнопки.\n\n Параметры\n ---------\n key: :class:`KeysEnum`\n Кнопка с кодом\n ' raise NotImplementedError
Возвращает, была ли нажата кнопка с указанным кодом, сбрасывает запомненные нажатия для этой кнопки. Параметры --------- key: :class:`KeysEnum` Кнопка с кодом
trik/brick.py
wasPressed
m1raynee/trikset.py-typehint
1
python
def wasPressed(self, key: KeysEnum) -> bool: 'Возвращает, была ли нажата кнопка с указанным кодом,\n сбрасывает запомненные нажатия для этой кнопки.\n\n Параметры\n ---------\n key: :class:`KeysEnum`\n Кнопка с кодом\n ' raise NotImplementedError
def wasPressed(self, key: KeysEnum) -> bool: 'Возвращает, была ли нажата кнопка с указанным кодом,\n сбрасывает запомненные нажатия для этой кнопки.\n\n Параметры\n ---------\n key: :class:`KeysEnum`\n Кнопка с кодом\n ' raise NotImplementedError<|docstring|>Возвращает, была ли нажата кнопка с указанным кодом, сбрасывает запомненные нажатия для этой кнопки. Параметры --------- key: :class:`KeysEnum` Кнопка с кодом<|endoftext|>
b656a2ee981f30fca75418bfdfde19e9ec4f475c83155eb0bf891f14ad0076df
def red(self) -> None: 'Включает светодиод в режим «красный».' raise NotImplementedError
Включает светодиод в режим «красный».
trik/brick.py
red
m1raynee/trikset.py-typehint
1
python
def red(self) -> None: raise NotImplementedError
def red(self) -> None: raise NotImplementedError<|docstring|>Включает светодиод в режим «красный».<|endoftext|>
a3c5daf5d30462a19f806f51391919a3ce55276d488447dabe3277a7a10ffc0d
def green(self) -> None: 'Включает светодиод в режим «зелёный».' raise NotImplementedError
Включает светодиод в режим «зелёный».
trik/brick.py
green
m1raynee/trikset.py-typehint
1
python
def green(self) -> None: raise NotImplementedError
def green(self) -> None: raise NotImplementedError<|docstring|>Включает светодиод в режим «зелёный».<|endoftext|>
59062e95c0eb20e3ae8be27137ff5656c12206c67ea71e665c9299ee0bc7b6c8
def orange(self) -> None: 'Включает светодиод в режим «оранжевый».' raise NotImplementedError
Включает светодиод в режим «оранжевый».
trik/brick.py
orange
m1raynee/trikset.py-typehint
1
python
def orange(self) -> None: raise NotImplementedError
def orange(self) -> None: raise NotImplementedError<|docstring|>Включает светодиод в режим «оранжевый».<|endoftext|>
6fbdf7fb526118fd2c61926f80bf1628dcdf19a2cbd1d74c20d7d7644879ee4b
def off(self) -> None: 'Выключает светодиод.' raise NotImplementedError
Выключает светодиод.
trik/brick.py
off
m1raynee/trikset.py-typehint
1
python
def off(self) -> None: raise NotImplementedError
def off(self) -> None: raise NotImplementedError<|docstring|>Выключает светодиод.<|endoftext|>
a902b015c2e4a3e76030a1ad4898a0490e3c017845bd26f97f0976beaf68d045
def detect(self) -> None: 'Определяет доминирующий цвет в вертикальной полосе в центре кадра\n и запоминает его как цвет линии. После этого метод «read» начинает\n возвращать данные для этой линии.\n ' raise NotImplementedError
Определяет доминирующий цвет в вертикальной полосе в центре кадра и запоминает его как цвет линии. После этого метод «read» начинает возвращать данные для этой линии.
trik/brick.py
detect
m1raynee/trikset.py-typehint
1
python
def detect(self) -> None: 'Определяет доминирующий цвет в вертикальной полосе в центре кадра\n и запоминает его как цвет линии. После этого метод «read» начинает\n возвращать данные для этой линии.\n ' raise NotImplementedError
def detect(self) -> None: 'Определяет доминирующий цвет в вертикальной полосе в центре кадра\n и запоминает его как цвет линии. После этого метод «read» начинает\n возвращать данные для этой линии.\n ' raise NotImplementedError<|docstring|>Определяет доминирующий цвет в вертикальной полосе в центре кадра и запоминает его как цвет линии. После этого метод «read» начинает возвращать данные для этой линии.<|endoftext|>
59792553d268b3c44d61cdfd2e647f7be3de584f28f3e107ade23993ca087100
def init(self, show_to_screen: bool) -> None: 'Включает видеокамеру и инициализирует её в режиме датчика линии.\n Булевый параметр определяет, выводить ли на экран изображение с камеры.\n\n Параметры\n ---------\n show_to_screen: :class:`bool`\n Выводить ли на экран изображение с камеры\n ' raise NotImplementedError
Включает видеокамеру и инициализирует её в режиме датчика линии. Булевый параметр определяет, выводить ли на экран изображение с камеры. Параметры --------- show_to_screen: :class:`bool` Выводить ли на экран изображение с камеры
trik/brick.py
init
m1raynee/trikset.py-typehint
1
python
def init(self, show_to_screen: bool) -> None: 'Включает видеокамеру и инициализирует её в режиме датчика линии.\n Булевый параметр определяет, выводить ли на экран изображение с камеры.\n\n Параметры\n ---------\n show_to_screen: :class:`bool`\n Выводить ли на экран изображение с камеры\n ' raise NotImplementedError
def init(self, show_to_screen: bool) -> None: 'Включает видеокамеру и инициализирует её в режиме датчика линии.\n Булевый параметр определяет, выводить ли на экран изображение с камеры.\n\n Параметры\n ---------\n show_to_screen: :class:`bool`\n Выводить ли на экран изображение с камеры\n ' raise NotImplementedError<|docstring|>Включает видеокамеру и инициализирует её в режиме датчика линии. Булевый параметр определяет, выводить ли на экран изображение с камеры. Параметры --------- show_to_screen: :class:`bool` Выводить ли на экран изображение с камеры<|endoftext|>
5043809048b053afb3d3caa6cac280a0c30472383f234af386194dbab44a89f7
def read(self) -> List[int]: 'Возвращает массив, в ячейках которого находятся следующие данные:\n - в нулевой ячейке координата по оси X центра линии относительно центра кадра\n (от -100 до 100, -100 — центр линии на краю кадра слева);\n - в первой ячейке — вероятность перекрёстка\n (число от 0 до 100, показывающее сколько точек цвета линии находится в горизонтальной полосе в центре кадра);\n - во второй ячейке — относительный размер линии, число от 0 до 100\n (100 — линия занимает почти весь кадр, 0 — линии нет на кадре).\n ' raise NotImplementedError
Возвращает массив, в ячейках которого находятся следующие данные: - в нулевой ячейке координата по оси X центра линии относительно центра кадра (от -100 до 100, -100 — центр линии на краю кадра слева); - в первой ячейке — вероятность перекрёстка (число от 0 до 100, показывающее сколько точек цвета линии находится в горизонтальной полосе в центре кадра); - во второй ячейке — относительный размер линии, число от 0 до 100 (100 — линия занимает почти весь кадр, 0 — линии нет на кадре).
trik/brick.py
read
m1raynee/trikset.py-typehint
1
python
def read(self) -> List[int]: 'Возвращает массив, в ячейках которого находятся следующие данные:\n - в нулевой ячейке координата по оси X центра линии относительно центра кадра\n (от -100 до 100, -100 — центр линии на краю кадра слева);\n - в первой ячейке — вероятность перекрёстка\n (число от 0 до 100, показывающее сколько точек цвета линии находится в горизонтальной полосе в центре кадра);\n - во второй ячейке — относительный размер линии, число от 0 до 100\n (100 — линия занимает почти весь кадр, 0 — линии нет на кадре).\n ' raise NotImplementedError
def read(self) -> List[int]: 'Возвращает массив, в ячейках которого находятся следующие данные:\n - в нулевой ячейке координата по оси X центра линии относительно центра кадра\n (от -100 до 100, -100 — центр линии на краю кадра слева);\n - в первой ячейке — вероятность перекрёстка\n (число от 0 до 100, показывающее сколько точек цвета линии находится в горизонтальной полосе в центре кадра);\n - во второй ячейке — относительный размер линии, число от 0 до 100\n (100 — линия занимает почти весь кадр, 0 — линии нет на кадре).\n ' raise NotImplementedError<|docstring|>Возвращает массив, в ячейках которого находятся следующие данные: - в нулевой ячейке координата по оси X центра линии относительно центра кадра (от -100 до 100, -100 — центр линии на краю кадра слева); - в первой ячейке — вероятность перекрёстка (число от 0 до 100, показывающее сколько точек цвета линии находится в горизонтальной полосе в центре кадра); - во второй ячейке — относительный размер линии, число от 0 до 100 (100 — линия занимает почти весь кадр, 0 — линии нет на кадре).<|endoftext|>
f7db3fc17c9d14c95d56c570e5a55f1e6c00f3716623a481ed9ba3685a137ddd
def stop(self) -> None: 'Выключает видеокамеру и прекращает работу датчика.' raise NotImplementedError
Выключает видеокамеру и прекращает работу датчика.
trik/brick.py
stop
m1raynee/trikset.py-typehint
1
python
def stop(self) -> None: raise NotImplementedError
def stop(self) -> None: raise NotImplementedError<|docstring|>Выключает видеокамеру и прекращает работу датчика.<|endoftext|>
935bada67ad47712b175d3efcfc27beca0f25a2de349ae58c31c31c49ba332dd
def brake(self, durationMs: int) -> None: 'Блокировка моторов для торможения в течение указанного времени в миллисекундах.\n\n Параметры\n ---------\n durationMs: :class:`int`\n Время в миллисекундах\n ' raise NotImplementedError
Блокировка моторов для торможения в течение указанного времени в миллисекундах. Параметры --------- durationMs: :class:`int` Время в миллисекундах
trik/brick.py
brake
m1raynee/trikset.py-typehint
1
python
def brake(self, durationMs: int) -> None: 'Блокировка моторов для торможения в течение указанного времени в миллисекундах.\n\n Параметры\n ---------\n durationMs: :class:`int`\n Время в миллисекундах\n ' raise NotImplementedError
def brake(self, durationMs: int) -> None: 'Блокировка моторов для торможения в течение указанного времени в миллисекундах.\n\n Параметры\n ---------\n durationMs: :class:`int`\n Время в миллисекундах\n ' raise NotImplementedError<|docstring|>Блокировка моторов для торможения в течение указанного времени в миллисекундах. Параметры --------- durationMs: :class:`int` Время в миллисекундах<|endoftext|>
97f49954b2d61c814b971794160a9f416426185e853f4235e866d5da2e4ca904
def power(self) -> int: 'Возвращает текущую мощность мотора (от -100 до 100).' raise NotImplementedError
Возвращает текущую мощность мотора (от -100 до 100).
trik/brick.py
power
m1raynee/trikset.py-typehint
1
python
def power(self) -> int: raise NotImplementedError
def power(self) -> int: raise NotImplementedError<|docstring|>Возвращает текущую мощность мотора (от -100 до 100).<|endoftext|>