Convert data into CourseVideo instance and image filename tuple.
500488
def to_internal_value(self, data):
        
        course_id = data
        course_video = image = ''
        if data:
            if isinstance(data, dict):
                (course_id, image), = list(data.items())

            course_video = CourseVideo(course_id=course_id)
            course_video.full_clean(exclude=['video'])

        return course_video, image
1321103
def _generate_examples(self, num_examples, data_path, label_path):
    
    images = _extract_mnist_images(data_path, num_examples)
    labels = _extract_mnist_labels(label_path, num_examples)
    data = list(zip(images, labels))

    # Data is shuffled automatically to distribute classes uniformly.
    for image, label in data:
      yield {
          "image": image,
          "label": label,
      }
526464
def to_tuple(self):
        """"""
        return (
            self.data_type,
            self.unit,
            self.analysis_period,
            self.metadata
        )
760525
def __getFilename(self, data, scene=1):
        """"""
        try:
            filename = None
            if scene == 1:
                plugin_filename = [i for i in parse_qs(urlsplit(data).query).get("plugin_filename") or [] if i]
                if plugin_filename and len(plugin_filename) == 1:
                    filename = plugin_filename[0]
            elif scene == 2:
                filename = basename(urlsplit(data).path)
            elif scene == 3:
                if PY2:
                    cd = data.headers.getheader("Content-Disposition", "")
                else:
                    cd = data.getheader("Content-Disposition", "")
                filename = parse_header(cd)[-1].get("filename")
            elif scene == 4:
                if PY2:
                    cd = data.info().subtype
                else:
                    cd = data.info().get_content_subtype()
                mt = {'zip': 'zip', 'x-compressed-tar': 'tar.gz', 'x-gzip': 'tar.gz'}
                subtype = mt.get(cd)
                if subtype:
                    filename = "." + subtype
        except Exception as e:
            self.logger.warning(e)
        else:
            if self.__isValidFilename(filename):
                return filename
551082
def to_array(self):
        
        array = super(VideoNoteMessage, self).to_array()
        if isinstance(self.video_note, InputFile):
            array['video_note'] = self.video_note.to_array()  # type InputFile
        elif isinstance(self.video_note, str):
            array['video_note'] = u(self.video_note)  # py2: type unicode, py3: type str
        else:
            raise TypeError('Unknown type, must be one of InputFile, str.')
        # end if

        if self.receiver is not None:
            if isinstance(self.receiver, None):
                array['chat_id'] = None(self.receiver)  # type Noneelif isinstance(self.receiver, str):
                array['chat_id'] = u(self.receiver)  # py2: type unicode, py3: type str
            elif isinstance(self.receiver, int):
                array['chat_id'] = int(self.receiver)  # type intelse:
                raise TypeError('Unknown type, must be one of None, str, int.')
            # end if

        if self.reply_id is not None:
            if isinstance(self.reply_id, DEFAULT_MESSAGE_ID):
                array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id)  # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int):
                array['reply_to_message_id'] = int(self.reply_id)  # type intelse:
                raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.')
            # end if

        if self.duration is not None:
            array['duration'] = int(self.duration)  # type int
        if self.length is not None:
            array['length'] = int(self.length)  # type int
        if self.thumb is not None:
            if isinstance(self.thumb, InputFile):
                array['thumb'] = self.thumb.to_array()  # type InputFile
            elif isinstance(self.thumb, str):
                array['thumb'] = u(self.thumb)  # py2: type unicode, py3: type str
            else:
                raise TypeError('Unknown type, must be one of InputFile, str.')
            # end if

        if self.disable_notification is not None:
            array['disable_notification'] = bool(self.disable_notification)  # type bool
        if self.reply_markup is not None:
            if isinstance(self.reply_markup, InlineKeyboardMarkup):
                array['reply_markup'] = self.reply_markup.to_array()  # type InlineKeyboardMarkup
            elif isinstance(self.reply_markup, ReplyKeyboardMarkup):
                array['reply_markup'] = self.reply_markup.to_array()  # type ReplyKeyboardMarkup
            elif isinstance(self.reply_markup, ReplyKeyboardRemove):
                array['reply_markup'] = self.reply_markup.to_array()  # type ReplyKeyboardRemove
            elif isinstance(self.reply_markup, ForceReply):
                array['reply_markup'] = self.reply_markup.to_array()  # type ForceReply
            else:
                raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.')
            # end if

        return array
77419
def encode_example(self, image_or_path_or_fobj):
    """"""
    if isinstance(image_or_path_or_fobj, np.ndarray):
      encoded_image = self._encode_image(image_or_path_or_fobj)
    elif isinstance(image_or_path_or_fobj, six.string_types):
      with tf.io.gfile.GFile(image_or_path_or_fobj, 'rb') as image_f:
        encoded_image = image_f.read()
    else:
      encoded_image = image_or_path_or_fobj.read()
    return encoded_image
771734
def get_zipped_dataset_from_predictions(predictions):
  """"""
  targets = stack_data_given_key(predictions, "targets")
  outputs = stack_data_given_key(predictions, "outputs")
  num_videos, num_steps = targets.shape[:2]

  # Truncate output time-steps to match target time-steps
  outputs = outputs[:, :num_steps]

  targets_placeholder = tf.placeholder(targets.dtype, targets.shape)
  outputs_placeholder = tf.placeholder(outputs.dtype, outputs.shape)
  dataset = tf.data.Dataset.from_tensor_slices(
      (targets_placeholder, outputs_placeholder))
  iterator = dataset.make_initializable_iterator()
  feed_dict = {targets_placeholder: targets,
               outputs_placeholder: outputs}
  return iterator, feed_dict, num_videos
683029
function _buildVideo(videoDescriptor) {
		this.url = videoDescriptor.url;
		this.appData = videoDescriptor.appData;
		descriptor = videoDescriptor;
	}
1018713
def to_dict(self):
        
        data = {
            'name': self.name,
            'video_id': self.video_id,
            'time': self.time,
            'forceStop': self.force_stop,
            'type': self.type,
            'metadata': self.metadata}
        for key in data.keys():
            if data[key] == None:
                data.pop(key)
        return data
490828
def to_vobjects(self, filename, uids=None):
        
        self._update()

        if not uids:
            uids = self.get_uids(filename)

        items = []

        for uid in uids:
            entry = self._book[uid.split('@')[0]]
            # TODO add getmtime of photo
            etag = sha1(str(dict(entry)).encode('utf-8'))
            items.append((uid, self._to_vcard(entry), '"%s"' % etag.hexdigest()))
        return items
1129079
def get_course_video_image_url(course_id, edx_video_id):
    
    try:
        video_image = CourseVideo.objects.select_related('video_image').get(
            course_id=course_id, video__edx_video_id=edx_video_id
        ).video_image
        return video_image.image_url()
    except ObjectDoesNotExist:
        return None
414305
def from_array(array):
        
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")

        data = {}
        data['file_id'] = u(array.get('file_id'))
        data['length'] = int(array.get('length'))
        data['duration'] = int(array.get('duration'))
        data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
        data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
        data['_raw'] = array
        return VideoNote(**data)
81903
function () {

			var images = {};
			var blobs = {};

			if ( 'Video' in fbxTree.Objects ) {

				var videoNodes = fbxTree.Objects.Video;

				for ( var nodeID in videoNodes ) {

					var videoNode = videoNodes[ nodeID ];

					var id = parseInt( nodeID );

					images[ id ] = videoNode.RelativeFilename || videoNode.Filename;

					// raw image data is in videoNode.Content
					if ( 'Content' in videoNode ) {

						var arrayBufferContent = ( videoNode.Content instanceof ArrayBuffer ) && ( videoNode.Content.byteLength > 0 );
						var base64Content = ( typeof videoNode.Content === 'string' ) && ( videoNode.Content !== '' );

						if ( arrayBufferContent || base64Content ) {

							var image = this.parseImage( videoNodes[ nodeID ] );

							blobs[ videoNode.RelativeFilename || videoNode.Filename ] = image;

						}

					}

				}

			}

			for ( var id in images ) {

				var filename = images[ id ];

				if ( blobs[ filename ] !== undefined ) images[ id ] = blobs[ filename ];
				else images[ id ] = images[ id ].split( '\\' ).pop();

			}

			return images;

		}
1044383
def preprocess(self, data):
        

        print 'Beginning pre-process...'
        for url, video in data['media'][0]['clipData'].iteritems():
            print 'Downloading {0} from {1}.'.format(video['title'], url)

            # Removes all white spaces and non alphanumeric chars from title
            video['title'] = re.sub(
                '[^\w\.]',
                '',
                video['title']
            ) + '.webm'

            urllib.urlretrieve(url, video['title'])
            self.base_videos.append(video['title'])
            print 'video downloaded as %s!' % video['title']
        print 'All videos downloaded.'

        events = [event for track in data['media'][0]['tracks']
                  for event in track['trackEvents']]

        for event in events:
            if event['type'] == 'skip' or event['type'] == 'loopPlugin':
                edit = TrackEdit(event['type'], event['popcornOptions'])

                self.track_edits.append(edit)

            if event['type'] == 'text' or event['type'] == 'image':
                item = TrackItem(event['type'], event['popcornOptions'])

                item.options['start_stamp'] = \
                    item.options['start']
                item.options['end_stamp'] = \
                    item.options['end']
                item.options['x_px'] = percent_to_px(
                    item.options['left'],
                    self.size[0]
                )
                item.options['y_px'] = percent_to_px(
                    item.options['top'],
                    self.size[1]
                )

                self.track_items.append(item)

            if event['type'] == 'sequencer':
                video = TrackVideo(
                    event['type'],
                    event['popcornOptions']['source'][0],
                    event['popcornOptions']
                )
                self.track_videos.append(video)

        self.parse_duration()

        cfilter = r'color=c={0}:s={1}x{2}:d={3};aevalsrc=0:d={4}'.format(
            self.background_color,
            self.size[0],
            self.size[1],
            self.duration,
            self.duration,
        )
        call(['ffmpeg', '-filter_complex', cfilter, '-y',
              self.current_video.name])
374481
def from_data(cls, blob):
        """"""
        version, data = decompress_datablob(DATA_BLOB_MAGIC_RETRY, blob)

        if version == 1:
            for clazz in cls._all_subclasses():
                if clazz.__name__ == data["_class_name"]:
                    return clazz._from_data_v1(data)

        raise Exception("Invalid data blob data or version")
941396
def _collect_data(directory, input_ext, transcription_ext):
  """"""
  # Directory from string to tuple pair of strings
  # key: the filepath to a datafile including the datafile's basename. Example,
  #   if the datafile was "/path/to/datafile.wav" then the key would be
  #   "/path/to/datafile"
  # value: a pair of strings (media_filepath, label)
  data_files = {}
  for root, _, filenames in os.walk(directory):
    transcripts = [filename for filename in filenames
                   if transcription_ext in filename]
    for transcript in transcripts:
      transcript_path = os.path.join(root, transcript)
      with open(transcript_path, "r") as transcript_file:
        for transcript_line in transcript_file:
          line_contents = transcript_line.strip().split(" ", 1)
          media_base, label = line_contents
          key = os.path.join(root, media_base)
          assert key not in data_files
          media_name = "%s.%s"%(media_base, input_ext)
          media_path = os.path.join(root, media_name)
          data_files[key] = (media_base, media_path, label)
  return data_files
1091537
def make_content_node(channeldir, rel_path, filename, metadata):
    
    file_key, file_ext = os.path.splitext(filename)
    ext = file_ext[1:]
    kind = None
    if ext in content_kinds.MAPPING:
        kind = content_kinds.MAPPING[ext]   # guess what kind based on file extension
    elif 'questions' in metadata:
        kind = content_kinds.EXERCISE
    else:
        raise ValueError('Could not find kind for extension ' + str(ext) + ' in content_kinds.MAPPING')

    # Extract metadata fields
    source_id = metadata.get('source_id', None)
    if source_id is None:
        source_id = metadata['chan_path']

    filepath = os.path.join(rel_path, filename)
    title = metadata['title']
    description = metadata.get('description', None)
    author = metadata.get('author', None)
    lang =  metadata.get('language', None)
    license_dict = metadata.get('license', None)
    thumbnail_chan_path =  metadata.get('thumbnail_chan_path', None)
    if thumbnail_chan_path:
        thumbnail_rel_path = rel_path_from_chan_path(thumbnail_chan_path, channeldir)
    else:
        thumbnail_rel_path = None

    if kind == VIDEO_NODE:
        content_node = dict(
            kind=VIDEO_NODE,
            source_id=source_id,
            title=title,
            author=author,
            description=description,
            language=lang,
            license=license_dict,
            derive_thumbnail=True,  # video-specific option
            thumbnail=thumbnail_rel_path,
            files=[{'file_type':VIDEO_FILE, 'path':filepath, 'language':lang}], # ffmpeg_settings={"crf": 24},
        )

    elif kind == AUDIO_NODE:
        content_node = dict(
            kind=AUDIO_NODE,
            source_id=source_id,
            title=title,
            author=author,
            description=description,
            language=lang,
            license=license_dict,
            thumbnail=thumbnail_rel_path,
            files=[{'file_type':AUDIO_FILE, 'path':filepath, 'language':lang}],
        )

    elif kind == DOCUMENT_NODE:
        content_node = dict(
            kind=DOCUMENT_NODE,
            source_id=source_id,
            title=title,
            author=author,
            description=description,
            language=lang,
            license=license_dict,
            thumbnail=thumbnail_rel_path,
            files=[]
        )
        if ext == 'pdf':
            pdf_file = {
                'file_type':DOCUMENT_FILE,
                'path':filepath,
                'language':lang
            }
            content_node['files'].append(pdf_file)
        elif ext == 'epub':
            epub_file = {
                'file_type':EPUB_FILE,
                'path':filepath,
                'language':lang
            }
            content_node['files'].append(epub_file)
        else:
            raise ValueError('Ext {} not supported for kind {}'.format(ext, kind))

    elif kind == HTML5_NODE:
        content_node = dict(
            kind=HTML5_NODE,
            source_id=source_id,
            title=title,
            author=author,
            description=description,
            language=lang,
            license=license_dict,
            thumbnail=thumbnail_rel_path,
            files=[{'file_type':HTML5_FILE, 'path':filepath, 'language':lang}],
        )

    elif kind == EXERCISE_NODE:
        content_node = dict(
            kind=EXERCISE_NODE,
            source_id=source_id,
            title=title,
            author=author,
            description=description,
            language=lang,
            license=license_dict,
            exercise_data=metadata['exercise_data'],
            questions=metadata['questions'],
            thumbnail=thumbnail_rel_path,
            files=[],
        )

    else:
        raise ValueError('Not implemented case for kind ' + str(kind))

    return content_node