Internal: updates terms / translations

        File uploads are limited to one every 30 seconds
433193
def _upload(self, project_id, updating, file_path, language_code=None,
                overwrite=False, sync_terms=False, tags=None, fuzzy_trigger=None):
        
        options = [
            self.UPDATING_TERMS,
            self.UPDATING_TERMS_TRANSLATIONS,
            self.UPDATING_TRANSLATIONS
        ]
        if updating not in options:
            raise POEditorArgsException(
                'Updating arg must be in {}'.format(options)
            )

        options = [
            self.UPDATING_TERMS_TRANSLATIONS,
            self.UPDATING_TRANSLATIONS
        ]
        if language_code is None and updating in options:
            raise POEditorArgsException(
                'Language code is required only if updating is '
                'terms_translations or translations)'
            )

        if updating == self.UPDATING_TRANSLATIONS:
            tags = None
            sync_terms = None

        # Special content type:
        tags = tags or ''
        language_code = language_code or ''
        sync_terms = '1' if sync_terms else '0'
        overwrite = '1' if overwrite else '0'
        fuzzy_trigger = '1' if fuzzy_trigger else '0'
        project_id = str(project_id)

        with open(file_path, 'r+b') as local_file:
            data = self._run(
                url_path="projects/upload",
                id=project_id,
                language=language_code,
                file=local_file,
                updating=updating,
                tags=tags,
                sync_terms=sync_terms,
                overwrite=overwrite,
                fuzzy_trigger=fuzzy_trigger
            )
        return data['result']
631970
@Override
    public void updateProgress(final long readBytes, final long contentLength) {
        if (readBytes > maxSize || contentLength > maxSize) {
            LOG.error("User tried to upload more than was allowed ({}).", maxSize);
            interruptUploadDueToFileSizeExceeded(maxSize);
            return;
        }
        if (isUploadInterrupted()) {
            // Upload interruption is delayed maybe another event is fired
            // before
            return;
        }

        publishUploadProgressEvent(fileUploadId, readBytes, contentLength);
    }
1290349
private function maxUploadFilesize(): string
    {
        $bytes = UploadedFile::getMaxFilesize();
        $kb    = intdiv($bytes + 1023, 1024);

        return I18N::translate('%s KB', I18N::number($kb));
    }
627902
@GuardedBy("lock")
  private void updateStats() {
    mInternalStatFs = updateStatsHelper(mInternalStatFs, mInternalPath);
    mExternalStatFs = updateStatsHelper(mExternalStatFs, mExternalPath);
    mLastRestatTime = SystemClock.uptimeMillis();
  }
361927
def refresh(self):
        
        self.setDirty(False)
        self.blockSignals(True)
        self.setUpdatesEnabled(False)
        self.clear()
        
        locales = self._availableLocales
        if not locales:
            locales = self.allLocales()
        
        if not self.showLanguage():
            if self.isTranslated():
                sorter = lambda x: x.get_territory_name(base)
            else:
                sorter = lambda x: x.get_territory_name()
        else:
            if self.isTranslated():
                sorter = lambda x: x.get_language_name(base)
            else:
                sorter = lambda x: x.get_language_name()
        
        locales = sorted(locales, key=sorter)
        index = 0
        for i, locale in enumerate(locales):
            babel_locale = babel.Locale.parse(locale)
            code = '{0}_{1}'.format(babel_locale.language,
                                    babel_locale.territory)
            keys = {}
            if self.isTranslated():
                keys['lang'] = babel_locale.get_language_name(base)
                keys['territory'] = babel_locale.get_territory_name(base)
                keys['script'] = babel_locale.get_script_name(base)
            else:
                keys['lang'] = babel_locale.get_language_name()
                keys['territory'] = babel_locale.get_territory_name()
                keys['script'] = babel_locale.get_script_name()
            
            if self.showLanguage():
                opts = ''
                if self.showScriptName() and keys['script']:
                    opts += keys['script']
                if self.showTerritory() and keys['territory']:
                    if opts:
                        opts += ', '
                    opts += keys['territory']
                if opts:
                    opts = ' (' + opts + ')'
                
                label = keys['lang'] + opts
                
            elif self.showTerritory():
                label = keys['territory']
            else:
                label = code
            
            self.addItem(label)
            self.setItemData(i, wrapVariant(str(code)))
            
            name = babel_locale.territory.lower()
            ico = 'img/flags/{0}.png'.format(name)
            flag = QtGui.QIcon(resources.find(ico))
            if flag.isNull():
                ico = 'img/flags/_United Nations.png'
                flag = QtGui.QIcon(resources.find(ico))
            
            self.setItemIcon(i, flag)
            if code == self.baseLocale():
                index = i
        
        self.setCurrentIndex(index)
        self.setUpdatesEnabled(True)
        self.blockSignals(False)
161781
static function getUploadError($iErrorNumber)
    {
        //  Upload was aborted, I wonder why?
        switch ($iErrorNumber) {

            case UPLOAD_ERR_INI_SIZE:

                $iMaxFileSize = function_exists('ini_get') ? ini_get('upload_max_filesize') : null;

                if (!is_null($iMaxFileSize)) {

                    $iMaxFileSize = static::returnBytes($iMaxFileSize);
                    $iMaxFileSize = static::formatBytes($iMaxFileSize);
                    $sError       = sprintf(
                        'The file exceeds the maximum size accepted by this server (which is %s).',
                        $iMaxFileSize
                    );

                } else {
                    $sError = 'The file exceeds the maximum size accepted by this server.';
                }
                break;

            case UPLOAD_ERR_FORM_SIZE:
                $sError = 'The file exceeds the maximum size accepted by this server.';
                break;

            case UPLOAD_ERR_PARTIAL:
                $sError = 'The file was only partially uploaded.';
                break;

            case UPLOAD_ERR_NO_FILE:
                $sError = 'No file was uploaded.';
                break;

            case UPLOAD_ERR_NO_TMP_DIR:
                $sError = 'This server cannot accept uploads at this time.';
                break;

            case UPLOAD_ERR_CANT_WRITE:
                $sError = 'Failed to write uploaded file to disk, you can try again.';
                break;

            case UPLOAD_ERR_EXTENSION:
                $sError = 'The file failed to upload due to a server configuration.';
                break;

            default:
                $sError = 'The file failed to upload.';
                break;
        }

        return $sError;
    }
260286
def upload(data)
      connect do |http|
        response = http.post(uri('draft_blurbs'), data.to_json, 'Content-Type' => 'application/json')
        check response
        log 'Uploaded missing translations'
      end
    end
498411
def update
      success = true
      tries ||= 3
      request = Net::HTTP::Put.new("/api/projects/#{Connection.api_key}/strings/#{self.id}.yaml")
      WebTranslateIt::Util.add_fields(request)
      request.body = self.to_json
      
      self.translations.each do |translation|
        translation.string_id = self.id
        translation.save
      end
      
      begin
        Util.handle_response(Connection.http_connection.request(request), true, true)
      rescue Timeout::Error
        puts "Request timeout. Will retry in 5 seconds."
        if (tries -= 1) > 0
          sleep(5)
          retry
        else
          success = false
        end
      end
      success
    end
571415
void refresh() {
    // Request latest expressions from the server
    try {
      HttpResponse res = client.get(uri)
          .withConnectTimeout(connectTimeout)
          .withReadTimeout(readTimeout)
          .addHeader("If-None-Match", etag)
          .send()
          .decompress();
      if (res.status() == 304) {
        LOGGER.debug("no modification to subscriptions");
      } else if (res.status() != 200) {
        LOGGER.warn("failed to update subscriptions, received status {}", res.status());
      } else {
        etag = res.header("ETag");
        payload = filterByStep(mapper.readValue(res.entity(), Subscriptions.class));
      }
    } catch (Exception e) {
      LOGGER.warn("failed to update subscriptions (uri={})", uri, e);
    }

    // Update with the current payload, it will be null if there hasn't been a single
    // successful request
    if (payload != null) {
      long now = clock.wallTime();
      payload.update(subscriptions, now, now + configTTL);
    }
  }
19640
public function uploadToContentService() {
		/** @var \File $file */
		$file = $this->owner;
		$writer = $this->writer();
		if (!$writer) {
			return;
		}
		$path = $file->getFullPath();
		if (strlen($path) && is_file($path) && file_exists($path)) {

			$mtime = @filemtime($path);
            $name = trim($file->getFilename(), '/');
		if (!$mtime) {
                    $mtime = '0';
                }

			//Insert the file modified time to make file unique-ish
			if ($lastPos = strrpos($name, '/')) {
				// Add in at as last folder name
				$name = substr($name, 0, $lastPos) . '/' . $mtime . substr($name, $lastPos);
			} else {
				//No folder found create one for the mtime
				$name = $mtime . '/' . $name;
			}

			$fileKeyLength = strlen($name);
			if ($fileKeyLength > CDNFile::MAX_FILE_PATH_LENGTH) {
				$lastPos = strrpos($name, '/');
				$ext = '';
				$filename = substr($name, $lastPos + 1);
				// Try and find a file extension
				if (strrpos($name, '.') !== false) {
					// Store and trim extension for later replacement
					$ext = substr($name, strrpos($name, '.'));
					$filename = substr($filename, 0, strrpos($filename, '.'));
				}
				// add 1 here so we can add in a ~ to indictate truncation
				$truncateLength = ($fileKeyLength + strlen($ext) + 1) - CDNFile::MAX_FILE_PATH_LENGTH;
				if (strlen($filename) <= $truncateLength) {
					// Folder length exceeds CDNFile::MAX_FILE_PATH_LENGTH. MD5 file to prevent file loss log error
					SS_Log::log("CDNFile: Total file length (folders + name) exceeds " . CDNFile::MAX_FILE_PATH_LENGTH . " characters and can't be "
							. "trimmed. File key has been MD5 encoded. File key: " . md5($name) . $ext . " Filename: "
							. "$name", SS_Log::ERR);
					$name = md5($name) . $ext;
				} else {
					// Recombine folder and file name while truncating the filename and appending a ~ then extension
					$name = substr($name, 0, $lastPos) . '/' . substr($filename, 0, (0 - $truncateLength)) . '~' . $ext;
				}
			}


			$writer->write(fopen($path, 'r'), $name);

			// writer should now have an id
			$file->CDNFile = $writer->getContentId();
            $file->FileSize = @filesize($path);

            // check whether it's an image, and handle its dimensions
            if ($file instanceof CdnImage) {
                $file->storeDimensions();
            }

			$file->write();

            // confirm the remote upload is there, and delete the local file
            // Oct 2016 - UNLESS the versioned files extension is on, we have to treat it slightly different
            $this->deleteLocalIfExistsOnContentService();
		}
	}
1096264
@Override
    public void uploadStarted(final StartedEvent event) {
        // reset internal state here because instance is reused for next upload!
        resetState();

        final SoftwareModule softwareModule = getSelectedSoftwareModule();

        this.fileUploadId = new FileUploadId(event.getFilename(), softwareModule);

        if (getUploadState().isFileInUploadState(this.fileUploadId)) {
            // actual interrupt will happen a bit late so setting the below
            // flag
            interruptUploadDueToDuplicateFile();
            event.getUpload().interruptUpload();
        } else {
            LOG.info("Uploading file {}", fileUploadId);
            publishUploadStarted(fileUploadId);

            if (RegexCharacterCollection.stringContainsCharacter(event.getFilename(), ILLEGAL_FILENAME_CHARACTERS)) {
                LOG.info("Filename contains illegal characters {} for upload {}", fileUploadId.getFilename(),
                        fileUploadId);
                interruptUploadDueToIllegalFilename();
                event.getUpload().interruptUpload();
            } else if (isFileAlreadyContainedInSoftwareModule(fileUploadId, softwareModule)) {
                LOG.info("File {} already contained in Software Module {}", fileUploadId.getFilename(), softwareModule);
                interruptUploadDueToDuplicateFile();
                event.getUpload().interruptUpload();
            }
        }
    }
207678
function checkFileUploads()
    {
        $isFileUploadsEnabled = ini_get( 'file_uploads' ) != 0;
        if ( !$isFileUploadsEnabled )
        {
            if ( empty( $GLOBALS['eZMediaTypeWarningAdded'] ) )
            {
                eZAppendWarningItem( array( 'error' => array( 'type' => 'kernel',
                                                              'number' => eZError::KERNEL_NOT_AVAILABLE ),
                                            'text' => ezpI18n::tr( 'kernel/classes/datatypes',
                                                              'File uploading is not enabled. Please contact the site administrator to enable it.' ) ) );
                $GLOBALS['eZMediaTypeWarningAdded'] = true;
            }
        }
    }
868261
function ($placeholder, files, that) {
			var acceptedTypes = {
				'image/png': true,
				'image/jpeg': true,
				'image/gif': true
			};

			for (var i = 0; i < files.length; i++) {
				var file = files[i];

				if (acceptedTypes[file.type] === true) {
					$placeholder.append('<progress class="progress" min="0" max="100" value="0">0</progress>');

					that.uploadFile($placeholder, file, that);
				}
			}
		}
1362478
public function upload()
    {
        //as upload may be called multiple times, we remove the session lock as soon as possible
        try{
            session_write_close();
            if ($this->hasRequestParameter('uri')) {
                $itemUri = $this->getRequestParameter('uri');
                $item = $this->getResource($itemUri);
            }

            if ($this->hasRequestParameter('lang')) {
                $itemLang = $this->getRequestParameter('lang');
            }

            if (!$this->hasRequestParameter('path')) {
                throw new common_exception_MissingParameter('path', __METHOD__);
            }

            if (!$this->hasRequestParameter('filters')) {
                throw new common_exception_MissingParameter('filters', __METHOD__);
            }
            $filters = $this->getRequestParameter('filters');

            $resolver = new ItemMediaResolver($item, $itemLang);
            $asset = $resolver->resolve($this->getRequestParameter('relPath'));

            $file = tao_helpers_Http::getUploadedFile('content');
            $fileTmpName = $file['tmp_name'].'_'.$file['name'];

            if (!tao_helpers_File::copy($file['tmp_name'], $fileTmpName)) {
                throw new common_exception_Error('impossible to copy '.$file['tmp_name'].' to '.$fileTmpName);
            }

            $mime = \tao_helpers_File::getMimeType($fileTmpName);
            if (is_string($filters)) {
                // the mime type is part of the $filters
                $filters = explode(',', $filters);
                if ((in_array($mime, $filters))) {
                    $filedata = $asset->getMediaSource()->add($fileTmpName, $file['name'],
                        $asset->getMediaIdentifier());
                } else {
                    throw new FileUploadException(__('The file you tried to upload is not valid'));
                }
            } else {
                $valid = false;
                // OR the extension is part of the filter and it correspond to the mime type
                foreach ($filters as $filter) {
                    if ($filter['mime'] === $mime &&
                        (!isset($filter['extension']) || $filter['extension'] === \tao_helpers_File::getFileExtention($fileTmpName))
                    ) {
                        $valid = true;
                    }
                }
                if ($valid) {
                    $filedata = $asset->getMediaSource()->add($fileTmpName, $file['name'],
                        $asset->getMediaIdentifier());
                } else {
                    throw new FileUploadException(__('The file you tried to upload is not valid'));
                }
            }

            $this->returnJson($filedata);
            return;
        }
        catch(PermissionException $e){
            $message = $e->getMessage();
        }
        catch(FileUploadException $e){
            $message = $e->getMessage();
        }
        catch(common_Exception $e){
            $this->logWarning($e->getMessage());
            $message = _('Unable to upload file');
        }
        $this->returnJson(array('error' => $message));

    }
170433
function(reloads) {
				var tmbs = [],
					reload = false;
				
				if (fm.oldAPI) {
					fm.request({
						data : {cmd : 'tmb', current : fm.cwd().hash},
						preventFail : true
					})
					.done(function(data) {
						if (data.images && Object.keys(data.images).length) {
							attachThumbnails(data.images);
						}
						if (data.tmb) {
							loadThumbnails();
						}
					});
					return;
				} 

				if (reloads) {
					reload = true;
					tmbs = reloads.splice(0, tmbNum);
				} else {
					tmbs = bufferExt.getTmbs.splice(0, tmbNum);
				}
				if (tmbs.length) {
					if (reload || inViewHashes[tmbs[0]] || inViewHashes[tmbs[tmbs.length-1]]) {
						$.each(tmbs, function(i, h) {
							bufferExt.tmbLoading[h] = true;
						});
						fm.request({
							data : {cmd : 'tmb', targets : tmbs},
							preventFail : true
						})
						.done(function(data) {
							var errs = [],
								resLen;
							if (data.images) {
								if (resLen = Object.keys(data.images).length) {
									if (resLen < tmbs.length) {
										$.each(tmbs, function(i, h) {
											if (! data.images[h]) {
												errs.push(h);
											}
										});
									}
									attachThumbnails(data.images, reload);
								} else {
									errs = tmbs;
								}
								// unset error items from bufferExt.attachTmbs
								if (errs.length) {
									$.each(errs, function(i, h) {
										delete bufferExt.attachTmbs[h];
									});
								}
							}
							if (reload) {
								if (reloads.length) {
									loadThumbnails(reloads);
								}
							}
						})
						.always(function() {
							bufferExt.tmbLoading = {};
							if (! reload && bufferExt.getTmbs.length) {
								loadThumbnails();
							}
						});
					}
				}
			}
65324
function upload() {
      stop_loop = false;

      if (!files) {
        opts.error(errors[0]);
        return false;
      }

      if (opts.allowedfiletypes.push && opts.allowedfiletypes.length) {
        for(var fileIndex = files.length;fileIndex--;) {
          if(!files[fileIndex].type || $.inArray(files[fileIndex].type, opts.allowedfiletypes) < 0) {
            opts.error(errors[3], files[fileIndex]);
            return false;
          }
        }
      }

      var filesDone = 0,
          filesRejected = 0;

      if (files_count > opts.maxfiles && opts.queuefiles === 0) {
        opts.error(errors[1]);
        return false;
      }

      // Define queues to manage upload process
      var workQueue = [];
      var processingQueue = [];
      var doneQueue = [];

      // Add everything to the workQueue
      for (var i = 0; i < files_count; i++) {
        workQueue.push(i);
      }

      // Helper function to enable pause of processing to wait
      // for in process queue to complete
      var pause = function(timeout) {
        setTimeout(process, timeout);
        return;
      };

      // Process an upload, recursive
      var process = function() {

        var fileIndex;

        if (stop_loop) {
          return false;
        }

        // Check to see if are in queue mode
        if (opts.queuefiles > 0 && processingQueue.length >= opts.queuefiles) {
          return pause(opts.queuewait);
        } else {
          // Take first thing off work queue
          fileIndex = workQueue[0];
          workQueue.splice(0, 1);

          // Add to processing queue
          processingQueue.push(fileIndex);
        }

        try {
          if (beforeEach(files[fileIndex]) !== false) {
            if (fileIndex === files_count) {
              return;
            }
            var reader = new FileReader(),
                max_file_size = 1048576 * opts.maxfilesize;

            reader.index = fileIndex;
            if (files[fileIndex].size > max_file_size) {
              opts.error(errors[2], files[fileIndex], fileIndex);
              // Remove from queue
              processingQueue.forEach(function(value, key) {
                if (value === fileIndex) {
                  processingQueue.splice(key, 1);
                }
              });
              filesRejected++;
              return true;
            }

            reader.onloadend = !opts.beforeSend ? send : function (e) {
              opts.beforeSend(files[fileIndex], fileIndex, function () { send(e); });
            };

            reader.readAsBinaryString(files[fileIndex]);

          } else {
            filesRejected++;
          }
        } catch (err) {
          // Remove from queue
          processingQueue.forEach(function(value, key) {
            if (value === fileIndex) {
              processingQueue.splice(key, 1);
            }
          });
          opts.error(errors[0]);
          return false;
        }

        // If we still have work to do,
        if (workQueue.length > 0) {
          process();
        }
      };

      var send = function(e) {

        var fileIndex = ((typeof(e.srcElement) === "undefined") ? e.target : e.srcElement).index;

        // Sometimes the index is not attached to the
        // event object. Find it by size. Hack for sure.
        if (e.target.index === undefined) {
          e.target.index = getIndexBySize(e.total);
        }

        var xhr = new XMLHttpRequest(),
            upload = xhr.upload,
            file = files[e.target.index],
            index = e.target.index,
            start_time = new Date().getTime(),
            boundary = '------multipartformboundary' + (new Date()).getTime(),
            global_progress_index = global_progress.length,
            builder,
            newName = rename(file.name),
            mime = file.type;

        if (typeof newName === "string") {
          builder = getBuilder(newName, e.target.result, mime, boundary);
        } else {
          builder = getBuilder(file.name, e.target.result, mime, boundary);
        }

        upload.index = index;
        upload.file = file;
        upload.downloadStartTime = start_time;
        upload.currentStart = start_time;
        upload.currentProgress = 0;
        upload.global_progress_index = global_progress_index;
        upload.startData = 0;
        upload.addEventListener("progress", progress, false);

        xhr.open("POST", opts.url, true);
        xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);

        // Add headers
        $.each(opts.headers, function(k, v) {
          xhr.setRequestHeader(k, v);
        });

        xhr.sendAsBinary(builder);

        global_progress[global_progress_index] = 0;
        globalProgress();

        opts.uploadStarted(index, file, files_count);

        xhr.onload = function() {
            var serverResponse = null;

            if (xhr.responseText) {
              try {
                serverResponse = jQuery.parseJSON(xhr.responseText);
              }
              catch (e) {
                serverResponse = xhr.responseText;
              }
            }

            var now = new Date().getTime(),
                timeDiff = now - start_time,
                result = opts.uploadFinished(index, file, serverResponse, timeDiff, xhr);
            filesDone++;

            // Remove from processing queue
            processingQueue.forEach(function(value, key) {
              if (value === fileIndex) {
                processingQueue.splice(key, 1);
              }
            });

            // Add to donequeue
            doneQueue.push(fileIndex);

            // Make sure the global progress is updated
            global_progress[global_progress_index] = 100;
            globalProgress();

            if (filesDone === (files_count - filesRejected)) {
              afterAll();
            }
            if (result === false) {
              stop_loop = true;
            }
          

          // Pass any errors to the error option
          if (xhr.status < 200 && xhr.status > 299) {
            opts.error(xhr.statusText);
          }
        };
      };

      // Initiate the processing loop
      process();
    }
283659
function upload(filesPaths) {
  const promises = filesPaths.map((v, i) => {
    const file = fs.createReadStream(v)
    const formData = {
      projectName: 'FrontEndResource',
      files: [file],
      path: 'frontend',
      usrName: '飞鱼籽',
    };
    return new Promise((resolve, reject) =>
      request.post({
        url: 'http://upload.2dfire-daily.com/upfileandlist',
        formData,
      }, function (error, response, body) {
        if (!error) {
          if (response.statusCode == 200) {
            try {
              const obj = JSON.parse(body)
              resolve({ file: v, response: obj })
              // console.log('success');
            } catch (error) {
              console.error(error);
            }
          } else {
            console.error('upload failed:', response.statusCode);
            reject()
          }
        } else {
          console.error('upload failed:', err);
          reject()
        }
      })
    )
  })

  return Promise.all(promises)
    .then((posts) => posts)
    .catch((e) => { console.error(e) });
}