create temporary table for picture in order to recover data.
175841
private function createTemporaryPicture()
    {
        $schema = $this->connection->getSchemaManager();
        if (!$schema->tablesExist('ujm_picture_temp')) {
            $this->log('Create ujm_picture_temp ...');
            $this->connection->exec('
                CREATE TABLE ujm_picture_temp (
                    id INT NOT NULL,
                    user_id INT DEFAULT NULL,
                    `label` VARCHAR(255) NOT NULL,
                    url VARCHAR(255) NOT NULL,
                    type VARCHAR(255) NOT NULL,
                    width INT NOT NULL,
                    height INT NOT NULL,
                    INDEX IDX_88AACC8AA76ED395 (user_id),
                    PRIMARY KEY(id)
                ) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB
            ');
        }

        $this->checkDocument();
    }
862796
def _load_image(cls, rkey):
        """"""

        v = cls._stock[rkey]
        img = None
        itype = v['type']
        if itype in ('stock', 'data'):
            img = tk.PhotoImage(format=v['format'], data=v['data'])
        elif itype == 'created':
            img = v['image']
        else:
            img = tk.PhotoImage(file=v['filename'])
        cls._cached[rkey] = img
        logger.info('Loaded resource %s.' % rkey)
        return img
1071732
public function prepareForRestart() {
		parent::prepareForRestart();
		// if the file we've been building is missing, lets fix it up
		if (!$this->tempFile || !file_exists($this->tempFile)) {
			$tmpfile = tempnam(getTempFolder(), 'postsitemap');
			if (file_exists($tmpfile)) {
				$this->tempFile = $tmpfile;
			}
			$this->currentStep = 0;
			$this->toProcess = $this->getProcessIds();
		}
	}
571676
def storedata(filename=None):
    """"""
    if filename is None:
        filename = 'credolib_state.pickle'
    ns = get_ipython().user_ns
    with open(filename, 'wb') as f:
        d = {}
        for var in ['_headers', '_loaders', '_data1d', '_data2d', '_data1dunited',
                    'allsamplenames', '_headers_sample', 'badfsns', '_rowavg',
                    'saveto_dir',
                    'badfsns_datcmp', 'auximages_dir', 'subtractedsamplenames', 'outputpath', 'saveto_dir_rel',
                    'auximages_dir_rel', 'crd_prefix']:
            try:
                d[var] = ns[var]
            except KeyError:
                warnings.warn('Skipping storage of unavailable variable "%s"' % var)
        pickle.dump(d, f)
1133017
def replace(self, photo, photo_file, **kwds):
        
        with open(photo_file, 'rb') as in_file:
            result = self._client.post("/photo/%s/replace.json" %
                                       self._extract_id(photo),
                                       files={'photo': in_file},
                                       **kwds)["result"]
        return Photo(self._client, result)
1053890
private void recoverState(int n) {
            TableStack<K,V> s; int len;
            while ((s = stack) != null && (index += (len = s.length)) >= n) {
                n = len;
                index = s.index;
                tab = s.tab;
                s.tab = null;
                TableStack<K,V> next = s.next;
                s.next = spare; // save for reuse
                stack = next;
                spare = s;
            }
            if (s == null && (index += baseSize) >= n)
                index = ++baseIndex;
        }
1010994
public function regenerate() {
		$operations = Configure::read('FileStorage.imageSizes.' . $this->args[0]);
		$options = [
			'overwrite' => !$this->params['keep-old-versions']
		];

		if (empty($operations)) {
			$this->abort(__d('file_storage', 'Invalid table or version.'));
		}

		foreach ($operations as $version => $operation) {
			try {
				$this->_loop($this->command, $this->args[0], [$version => $operation], $options);
			} catch (Exception $e) {
				$this->abort($e->getMessage());
			}
		}
	}
595698
function (picture) {
        if (options.destinationType === Camera.DestinationType.FILE_URI || options.destinationType === Camera.DestinationType.NATIVE_URI) {
            if (options.targetHeight > 0 && options.targetWidth > 0) {
                resizeImage(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight, options.encodingType);
            } else {
                // CB-11714: check if target content-type is PNG to just rename as *.jpg since camera is captured as JPEG
                if (options.encodingType === Camera.EncodingType.PNG) {
                    picture.name = picture.name.replace(/\.png$/, '.jpg');
                }

                picture.copyAsync(getAppData().localFolder, picture.name, OptUnique).done(function (copiedFile) {
                    successCallback('ms-appdata:///local/' + copiedFile.name);
                }, errorCallback);
            }
        } else {
            if (options.targetHeight > 0 && options.targetWidth > 0) {
                resizeImageBase64(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight);
            } else {
                fileIO.readBufferAsync(picture).done(function (buffer) {
                    var strBase64 = encodeToBase64String(buffer);
                    picture.deleteAsync().done(function () {
                        successCallback(strBase64);
                    }, function (err) {
                        errorCallback(err);
                    });
                }, errorCallback);
            }
        }
    }
815048
def to_picture(self, filename):
        
        fileformat = path.splitext(filename)[1][1:]
        with NamedTemporaryFile("wb", delete=False) as dotfile:
            dotfilename = dotfile.name
            for line in self:
                dotfile.write(("%s\n" % line).encode("utf-8"))
            dotfile.flush()
            cmd = ["dot", dotfilename, "-T", fileformat, "-o", filename]
            check_call(cmd)
        try:
            remove(dotfilename)
        except Exception:  # pragma: no cover
            msg = 'Could not remove temporary file %s' % dotfilename
            logging.getLogger(__name__).warn(msg)
338708
def make_tempfile(data=None):
    ""
    with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:
        temp.write(six.text_type(data if data is not None else os.getpid()))
        return temp.name
625826
def SaveData(self, raw_data):
    """"""
    if self.filename is None:
      raise IOError("Unknown filename")

    logging.info("Writing back configuration to file %s", self.filename)
    # Ensure intermediate directories exist
    try:
      os.makedirs(os.path.dirname(self.filename))
    except (IOError, OSError):
      pass

    try:
      # We can not use the standard open() call because we need to
      # enforce restrictive file permissions on the created file.
      mode = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
      fd = os.open(self.filename, mode, 0o600)
      with os.fdopen(fd, "wb") as config_file:
        self.SaveDataToFD(raw_data, config_file)

    except OSError as e:
      logging.warning("Unable to write config file %s: %s.", self.filename, e)
1018794
def _temporary_filenames(total):
    """"""
    temp_files = [_get_temporary_filename('optimage-') for i in range(total)]
    yield temp_files
    for temp_file in temp_files:
        try:
            os.remove(temp_file)
        except OSError:
            # Continue in case we could not remove the file. One reason is that
            # the fail was never created.
            pass
222723
def create(self, columns=None, type_map=None, overwrite=False):
        """"""
        # Check already exists #
        if self.count_bytes > 0:
            if overwrite: self.remove()
            else: raise Exception("File exists already at '%s'" % self)
        # If we want it empty #
        if columns is None:
            self.touch()
        # Make the table #
        else:
            self.add_table(self.main_table, columns=columns, type_map=type_map)
271957
def copy(self, *, shallow=False):
        """"""
        table = type(self)()
        for label in self.labels:
            if shallow:
                column = self[label]
            else:
                column = np.copy(self[label])
            self._add_column_and_format(table, label, column)
        return table
994738
def from_image(cls, image):
        
        (w, h) = image.size

        # Thermal paper is 512 pixels wide
        if w > 512:
            ratio = 512. / w
            h = int(h * ratio)
            image = image.resize((512, h), Image.ANTIALIAS)
        if image.mode != '1':
            image = image.convert('1')

        pixels = np.array(list(image.getdata())).reshape(h, w)

        # Add white pixels so that image fits into bytes
        extra_rows = int(math.ceil(h / 24)) * 24 - h
        extra_pixels = np.ones((extra_rows, w), dtype=bool)
        pixels = np.vstack((pixels, extra_pixels))
        h += extra_rows
        nb_stripes = h / 24
        pixels = pixels.reshape(nb_stripes, 24, w).swapaxes(1, 2).reshape(-1, 8)

        nh = int(w / 256)
        nl = w % 256
        data = []

        pixels = np.invert(np.packbits(pixels))
        stripes = np.split(pixels, nb_stripes)

        for stripe in stripes:

            data.extend([
                ESC,
                42,  # *
                33,  # double density mode
                nl,
                nh])

            data.extend(stripe)
            data.extend([
                27,   # ESC
                74,   # J
                48])

        # account for double density mode
        height = h * 2
        return cls(data, height)
815358
def _process_table(self, cache=True):
        """"""
        table = self.source()
        assert not isinstance(table, None.__class__), \
            "{}.source needs to return something, not None".format(self.__class__.__name__)
        table = post_process(table, self.post_processors())
        if cache:
            self.to_cache(table)
        return table
747263
def restoreWCS(self,prepend=None):
        
        # Open header for image
        image = self.rootname

        if prepend: _prepend = prepend
        elif self.prepend: _prepend = self.prepend
        else: _prepend = None

        # Open image as writable FITS object
        fimg = fileutil.openImage(image, mode='update')
        # extract the extension ID being updated
        _root,_iextn = fileutil.parseFilename(self.rootname)
        _extn = fileutil.getExtn(fimg,_iextn)

        if len(self.backup) > 0:
            # If it knows about the backup keywords already,
            # use this to restore the original values to the original keywords
            for newkey in self.revert.keys():
                if newkey != 'opscale':
                    _orig_key = self.revert[newkey]
                    _extn.header[_orig_key] = _extn.header[newkey]
        elif _prepend:
            for key in self.wcstrans.keys():
                # Get new keyword name based on old keyname
                #    and prepend string
                if key != 'pixel scale':
                    _okey = self._buildNewKeyname(key,_prepend)

                    if _okey in _extn.header:
                        _extn.header[key] = _extn.header[_okey]
                    else:
                        print('No original WCS values found. Exiting...')
                        break
        else:
            print('No original WCS values found. Exiting...')

        fimg.close()
        del fimg