Record a single movie and store it on hard drive
186979
def record_take(self, model, env_instance, device, take_number):
        
        frames = []

        observation = env_instance.reset()

        if model.is_recurrent:
            hidden_state = model.zero_state(1).to(device)

        frames.append(env_instance.render('rgb_array'))

        print("Evaluating environment...")

        while True:
            observation_array = np.expand_dims(np.array(observation), axis=0)
            observation_tensor = torch.from_numpy(observation_array).to(device)

            if model.is_recurrent:
                output = model.step(observation_tensor, hidden_state, **self.sample_args)
                hidden_state = output['state']
                actions = output['actions']
            else:
                actions = model.step(observation_tensor, **self.sample_args)['actions']

            actions = actions.detach().cpu().numpy()

            observation, reward, done, epinfo = env_instance.step(actions[0])

            frames.append(env_instance.render('rgb_array'))

            if 'episode' in epinfo:
                # End of an episode
                break

        takename = self.model_config.output_dir('videos', self.model_config.run_name, self.videoname.format(take_number))
        pathlib.Path(os.path.dirname(takename)).mkdir(parents=True, exist_ok=True)

        fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
        video = cv2.VideoWriter(takename, fourcc, self.fps, (frames[0].shape[1], frames[0].shape[0]))

        for i in tqdm.trange(len(frames), file=sys.stdout):
            video.write(cv2.cvtColor(frames[i], cv2.COLOR_RGB2BGR))

        video.release()
        print("Written {}".format(takename))
715984
def save(self, create_multiple_renditions=True,
        preserve_source_rendition=True,
        encode_to=enums.EncodeToEnum.FLV):
        
        if is_ftp_connection(self.connection) and len(self.assets) > 0:
            self.connection.post(xml=self.to_xml(), assets=self.assets)
        elif not self.id and self._filename:
            self.id = self.connection.post('create_video', self._filename,
                create_multiple_renditions=create_multiple_renditions,
                preserve_source_rendition=preserve_source_rendition,
                encode_to=encode_to,
                video=self._to_dict())
        elif not self.id and len(self.renditions) > 0:
            self.id = self.connection.post('create_video',
                video=self._to_dict())
        elif self.id:
            data = self.connection.post('update_video', video=self._to_dict())
            if data:
                self._load(data)
932424
def save(self):
        """"""
        data = str.encode( json.dumps(self.simpleAttrs, indent=4, sort_keys=True) )
        with open(self.filename, "wb") as f:
            f.write(data)
165204
def save_video(video, save_path_template):
  """"""
  try:
    from PIL import Image  # pylint: disable=g-import-not-at-top
  except ImportError as e:
    tf.logging.warning(
        "Showing and saving an image requires PIL library to be "
        "installed: %s", e)
    raise NotImplementedError("Image display and save not implemented.")

  for i, frame in enumerate(video):
    save_path = save_path_template.format(i)
    with tf.gfile.Open(save_path, "wb") as sp:
      Image.fromarray(np.uint8(frame)).save(sp)
435576
function storeFileToDisk(i_oFile, i_sOutput) {
    var l_sDirname = path.dirname(i_oFile.filename),
        l_sFilename;

    console.log("File name: ", i_oFile.filename, " size: ", i_oFile.header.unpackedSize);
    console.log("Saving content of file ");

    l_sDirname = path.join(i_sOutput, path.dirname(i_oFile.filename));
    l_sFilename = path.join(l_sDirname, path.basename(i_oFile.filename));
    return new Promise(function(i_oResolve) {
        mkdirp(l_sDirname, function (err) {
            if (err) console.error(err);
            _writeFile(l_sFilename, i_oFile, i_oResolve);
        });
    });
}
1205860
def make_movie(workdir, pf, dpi=120, fps=1, format="pdf", engine="ffmpeg"):
    
    os.chdir(workdir)
    if format != "png":
        cmd  = "parallel convert -density {}".format(dpi)
        cmd += " {} {.}.png ::: " + "*.{}".format(format)
        sh(cmd)

    assert engine in ("ffmpeg", "gifsicle"), \
            "Only ffmpeg or gifsicle is currently supported"
    if engine == "ffmpeg":
        cmd = "ffmpeg -framerate {} -pattern_type glob -i '*.png' {}.mp4"\
                .format(fps, pf)
    elif engine == "gifsicle":
        cmd  = "convert *.png gif:- |"
        cmd += " gifsicle --delay {} --loop --optimize=3".format(100 / fps)
        cmd += " --colors=256 --multifile - > {}.gif".format(pf)

    sh(cmd)
928282
function MediaStreamRecorder(mediaStream) {
    if (!mediaStream) {
        throw 'MediaStream is mandatory.';
    }

    // void start(optional long timeSlice)
    // timestamp to fire "ondataavailable"
    this.start = function(timeSlice) {
        var Recorder;

        if (typeof MediaRecorder !== 'undefined') {
            Recorder = MediaRecorderWrapper;
        } else if (IsChrome || IsOpera || IsEdge) {
            if (this.mimeType.indexOf('video') !== -1) {
                Recorder = WhammyRecorder;
            } else if (this.mimeType.indexOf('audio') !== -1) {
                Recorder = StereoAudioRecorder;
            }
        }

        // video recorder (in GIF format)
        if (this.mimeType === 'image/gif') {
            Recorder = GifRecorder;
        }

        // audio/wav is supported only via StereoAudioRecorder
        // audio/pcm (int16) is supported only via StereoAudioRecorder
        if (this.mimeType === 'audio/wav' || this.mimeType === 'audio/pcm') {
            Recorder = StereoAudioRecorder;
        }

        // allows forcing StereoAudioRecorder.js on Edge/Firefox
        if (this.recorderType) {
            Recorder = this.recorderType;
        }

        mediaRecorder = new Recorder(mediaStream);
        mediaRecorder.blobs = [];

        var self = this;
        mediaRecorder.ondataavailable = function(data) {
            mediaRecorder.blobs.push(data);
            self.ondataavailable(data);
        };
        mediaRecorder.onstop = this.onstop;
        mediaRecorder.onStartedDrawingNonBlankFrames = this.onStartedDrawingNonBlankFrames;

        // Merge all data-types except "function"
        mediaRecorder = mergeProps(mediaRecorder, this);

        mediaRecorder.start(timeSlice);
    };

    this.onStartedDrawingNonBlankFrames = function() {};
    this.clearOldRecordedFrames = function() {
        if (!mediaRecorder) {
            return;
        }

        mediaRecorder.clearOldRecordedFrames();
    };

    this.stop = function() {
        if (mediaRecorder) {
            mediaRecorder.stop();
        }
    };

    this.ondataavailable = function(blob) {
        if (this.disableLogs) return;
        console.log('ondataavailable..', blob);
    };

    this.onstop = function(error) {
        console.warn('stopped..', error);
    };

    this.save = function(file, fileName) {
        if (!file) {
            if (!mediaRecorder) {
                return;
            }

            ConcatenateBlobs(mediaRecorder.blobs, mediaRecorder.blobs[0].type, function(concatenatedBlob) {
                invokeSaveAsDialog(concatenatedBlob);
            });
            return;
        }
        invokeSaveAsDialog(file, fileName);
    };

    this.pause = function() {
        if (!mediaRecorder) {
            return;
        }
        mediaRecorder.pause();

        if (this.disableLogs) return;
        console.log('Paused recording.', this.mimeType || mediaRecorder.mimeType);
    };

    this.resume = function() {
        if (!mediaRecorder) {
            return;
        }
        mediaRecorder.resume();

        if (this.disableLogs) return;
        console.log('Resumed recording.', this.mimeType || mediaRecorder.mimeType);
    };

    // StereoAudioRecorder || WhammyRecorder || MediaRecorderWrapper || GifRecorder
    this.recorderType = null;

    // video/webm or audio/webm or audio/ogg or audio/wav
    this.mimeType = 'video/webm';

    // logs are enabled by default
    this.disableLogs = false;

    // Reference to "MediaRecorder.js"
    var mediaRecorder;
}
734606
def save(self, filename, encoding ='ISO-8859-1', standalone='no'):
        
        f = codecs.open(filename, 'w', encoding)
        s = self.wrap_xml(self.getXML(), encoding, standalone)
        #s = s.replace("&", "&amp;")
        f.write(s)
        f.close()
502809
def combine_pyramid_and_save(g_video, orig_video, enlarge_multiple, fps, save_filename='media/output.avi'):
    """"""
    width, height = get_frame_dimensions(orig_video[0])
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    print("Outputting to %s" % save_filename)
    writer = cv2.VideoWriter(save_filename, fourcc, fps, (width, height), 1)
    for x in range(0, g_video.shape[0]):
        img = np.ndarray(shape=g_video[x].shape, dtype='float')
        img[:] = g_video[x]
        for i in range(enlarge_multiple):
            img = cv2.pyrUp(img)

        img[:height, :width] = img[:height, :width] + orig_video[x]
        res = cv2.convertScaleAbs(img[:height, :width])
        writer.write(res)
321596
def record(self, record=True, tag=None):
        
        path = '/startvideo?force=1' if record else '/stopvideo?force=1'
        if record and tag is not None:
            path = '/startvideo?force=1&tag={}'.format(URL(tag).raw_path)

        return self._request(path)
1180297
def create(model_config, model, vec_env, storage, takes, videoname, fps=30, sample_args=None):
    
    return RecordMovieCommand(
        model_config=model_config,
        model_factory=model,
        env_factory=vec_env,
        storage=storage,
        videoname=videoname,
        takes=takes,
        fps=fps,
        sample_args=sample_args
    )
540245
def to_vobject(self, filename=None, uid=None):
        
        self._update()
        return self._to_vcard(self._book[uid.split('@')[0]])
324612
def _write_recordio(f, data):
    """"""
    length = len(data)
    f.write(struct.pack('I', _kmagic))
    f.write(struct.pack('I', length))
    pad = (((length + 3) >> 2) << 2) - length
    f.write(data)
    f.write(padding[pad])
219525
def geist_replay(wrapped, instance, args, kwargs):
    """"""
    path_parts = []
    file_parts = []

    if hasattr(wrapped, '__module__'):
        module = wrapped.__module__
        module_file = sys.modules[module].__file__
        root, _file = os.path.split(module_file)
        path_parts.append(root)
        _file, _ = os.path.splitext(_file)
        file_parts.append(_file)
    if hasattr(wrapped, '__objclass__'):
        file_parts.append(wrapped.__objclass__.__name__)
    elif hasattr(wrapped, '__self__'):
        file_parts.append(wrapped.__self__.__class__.__name__)
    file_parts.append(wrapped.__name__ + '.log')
    path_parts.append('_'.join(file_parts))
    filename = os.path.join(*path_parts)

    if is_in_record_mode():
        platform_backend = get_platform_backend()
        backend = RecordingBackend(
            source_backend=platform_backend,
            recording_filename=filename
        )
    else:
        backend = PlaybackBackend(
            recording_filename=filename
        )
    gui = GUI(backend)
    return wrapped(gui, *args, **kwargs)
833263
def save_media(self):
        """"""
        chunk_path = fileops.get_chunk_path_from_string(
            self.model.unique_field
        )

        for i, mediafile in enumerate(self.model.media_list):
            filename = os.path.join(
                self._get_prefix(),
                chunk_path,
                "%s_%d" % (self.model.unique_field, i)
            )
            self.store.store_media(filename, mediafile)
103658
def vid2h5(data: np.ndarray, ut1, rawind, ticks, outfn: Path, P: dict, i: int=0,
           Nfile: int=1, det=None, tstart=None, cmdlog: str=None):
    assert outfn, 'must provide a filename to write'

    outfn = Path(outfn).expanduser()
    assert not outfn.is_dir(
    ), 'must provide FILEname, you provided directory {outfn}'
    outfn.parent.mkdir(exist_ok=True)

    txtupd = f'convert file {i} / {Nfile}'
    if 'spoolfn' in P:
        txtupd += f' {P["spoolfn"].name}'
    txtupd += f' => {outfn}'
    
    print(txtupd + '\r', end="")
    # %% saving
    if outfn.suffix == '.h5':
        """
        Reference: https://www.hdfgroup.org/HDF5/doc/ADGuide/ImageSpec.html
        Thanks to Eric Piel of Delmic for pointing out this spec
        * the HDF5 attributess set are necessary to put HDFView into image mode and enables
        other conforming readers to easily play images stacks as video.
        * the string_() calls are necessary to make fixed length strings per HDF5 spec
        """
        # NOTE write mode r+ to not overwrite incremental images
        if outfn.is_file():
            writemode = 'r+'  # append
        else:
            writemode = 'w'

        if data is not None:

            N = data.shape[0] * Nfile
            ind = slice(i * data.shape[0], (i + 1) * data.shape[0])
        else:  # FIXME haven't reevaluated for update only case
            for q in (ut1, rawind, ticks):
                if q is not None:
                    N = len(q)
                    break
            ind = slice(None)

        with h5py.File(outfn, writemode) as f:
            if data is not None:
                if 'rawimg' not in f:  # first run
                    setupimgh5(f, N, data.shape[1], data.shape[2])

                f['/rawimg'][ind, ...] = data

            if ut1 is not None:
                print(f'writing from {datetime.utcfromtimestamp(ut1[0])}'
                      f'to {datetime.utcfromtimestamp(ut1[-1])}')
                if 'ut1_unix' not in f:
                    fut1 = f.create_dataset(
                        '/ut1_unix', shape=(N,), dtype=float, fletcher32=True)
                    fut1.attrs['units'] = 'seconds since Unix epoch Jan 1 1970 midnight'

                f['/ut1_unix'][ind] = ut1

            if tstart is not None and 'tstart' not in f:
                f['/tstart'] = tstart

            if rawind is not None:
                if 'rawind' not in f:
                    fri = f.create_dataset(
                        '/rawind', shape=(N,), dtype=np.int64, fletcher32=True)
                    fri.attrs['units'] = 'one-based index since camera program started this session'

                f['/rawind'][ind] = rawind

            if ticks is not None:
                if 'ticks' not in f:
                    ftk = f.create_dataset(
                        '/ticks', shape=(N,), dtype=np.uint64, fletcher32=True)  # Uint64
                    ftk.attrs['units'] = 'FPGA tick counter for each image frame'

                f['/ticks'][ind] = ticks

            if 'spoolfn' in P:
                # http://docs.h5py.org/en/latest/strings.html
                if 'spoolfn' not in f:
                    fsp = f.create_dataset(
                        '/spoolfn', shape=(N,), dtype=h5py.special_dtype(vlen=bytes))
                    fsp.attrs['description'] = 'input filename data was extracted from'

                f['/spoolfn'][ind] = P['spoolfn'].name

            if det is not None:
                if 'detect' not in f:
                    fdt = f.create_dataset('/detect', shape=(N,), dtype=int)
                    fdt.attrs['description'] = '# of auroral detections this frame'

                f['/detect'][i] = det[i]

            if 'params' not in f:
                cparam = np.array((
                    P['kineticsec'],
                    P['rotccw'],
                    P['transpose'],
                    P['flipud'],
                    P['fliplr'],
                    1),
                    dtype=[('kineticsec', 'f8'),
                           ('rotccw', 'i1'),
                           ('transpose', 'i1'),
                           ('flipud', 'i1'),
                           ('fliplr', 'i1'),
                           ('questionable_ut1', 'i1')]
                )

                # cannot use fletcher32 here, typeerror
                f.create_dataset('/params', data=cparam)

            if 'sensorloc' not in f and 'sensorloc' in P:
                loc = P['sensorloc']
                lparam = np.array((loc[0], loc[1], loc[2]),
                                  dtype=[('lat', 'f8'), ('lon', 'f8'), ('alt_m', 'f8')])

                # cannot use fletcher32 here, typeerror
                Ld = f.create_dataset('/sensorloc', data=lparam)
                Ld.attrs['units'] = 'WGS-84 lat (deg),lon (deg), altitude (meters)'

            if 'cmdlog' not in f:
                if isinstance(cmdlog, (tuple, list)):
                    cmdlog = ' '.join(cmdlog)
                # cannot use fletcher32 here, typeerror
                f['/cmdlog'] = str(cmdlog)

            if 'header' not in f and 'header' in P:
                f['/header'] = str(P['header'])

            if 'hdf5version' not in f:
                f['/hdf5version'] = h5py.version.hdf5_version_tuple

    elif outfn.suffix == '.fits':
        from astropy.io import fits
        # NOTE the with... syntax does NOT yet work with astropy.io.fits
        hdu = fits.PrimaryHDU(data)
        hdu.writeto(outfn, clobber=False, checksum=True)
        # no close
        """
        Note: the orientation of this FITS in NASA FV program and the preview
        image shown in Python should/must have the same orientation and pixel indexing')
        """

    elif outfn.suffix == '.mat':
        from scipy.io import savemat
        # matlab is fortran order
        matdata = {'imgdata': data.transpose(1, 2, 0)}
        savemat(outfn, matdata, oned_as='column')
    else:
        raise ValueError(f'what kind of file is {outfn}')
697014
def record(self, i=0):
        """"""
        f = self.__getFileObj(self.dbf)
        if self.numRecords is None:
            self.__dbfHeader()
        i = self.__restrictIndex(i)
        recSize = self.__recStruct.size
        f.seek(0)
        f.seek(self.__dbfHdrLength + (i * recSize))
        return self.__record(oid=i)