Check if requester is compatible (os+browser)
Register compatibility
return json message
970844
public function check()
    {
        try {
            $data = $this->getData(true);
            $id   = $this->getId();

            $checker            = new CompatibilityCheckerModel($data);
            $isCompatible       = (int)$checker->isCompatibleConfig();
            $data['compatible'] = $isCompatible;

            try {
                $storageService = $this->getServiceLocator()->get(Storage::SERVICE_ID);
                $storageService->store($id, $data);
            } catch (StorageException $e) {
                $this->logInfo($e->getMessage());
            }

            $compatibilityMessage = [
                //Not compatible
                '0' => [
                    'success' => true,
                    'type'    => 'error',
                    'message' => __('Your system requires a compatibility update, please contact your system administrator.')
                ],
                //Compatible
                '1' => [
                    'success' => true,
                    'type'    => 'success',
                    'message' => __('Compatible')
                ],
                //Not tested
                '2' => [
                    'success' => true,
                    'type'    => 'warning',
                    'message' => __('This browser is not tested.')
                ],
            ];

            $this->returnJson($compatibilityMessage[$isCompatible]);

        } catch (\common_exception_MissingParameter $e) {
            $this->returnJson(array('success' => false, 'type' => 'error', 'message' => $e->getUserMessage()));
        }
    }
1148641
function isJSON(res) {
  debug('isJSON: content-type = %s', res.headers['content-type']);
  return (res.headers['content-type'] &&
          /^application\/json/.test(res.headers['content-type']));
}
1317675
def check_install_json(self):
        """"""
        if self.install_json_schema is None:
            return

        contents = os.listdir(self.app_path)
        if self.args.install_json is not None:
            contents = [self.args.install_json]

        for install_json in sorted(contents):
            # skip files that are not install.json files
            if 'install.json' not in install_json:
                continue

            error = None
            status = True

            try:
                # loading explicitly here to keep all error catching in this file
                with open(install_json) as fh:
                    data = json.loads(fh.read())
                validate(data, self.install_json_schema)
            except SchemaError as e:
                status = False
                error = e
            except ValidationError as e:
                status = False
                error = e.message
            except ValueError:
                # any JSON decode error will be caught during syntax validation
                return

            if error:
                # update validation data errors
                self.validation_data['errors'].append(
                    'Schema validation failed for {} ({}).'.format(install_json, error)
                )

            # update validation data for module
            self.validation_data['schema'].append({'filename': install_json, 'status': status})
1049206
function matchVersions() {
		var rl = regObjArr.length;
		if (rl > 0) {
			for (var i = 0; i < rl; i++) { // for each registered object element
				var id = regObjArr[i].id;
				var cb = regObjArr[i].callbackFn;
				var cbObj = {success:false, id:id};
				if (ua.pv[0] > 0) {
					var obj = getElementById(id);
					if (obj) {
						if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match!
							setVisibility(id, true);
							if (cb) {
								cbObj.success = true;
								cbObj.ref = getObjectById(id);
								cb(cbObj);
							}
						}
						else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported
							var att = {};
							att.data = regObjArr[i].expressInstall;
							att.width = obj.getAttribute("width") || "0";
							att.height = obj.getAttribute("height") || "0";
							if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); }
							if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); }
							// parse HTML object param element's name-value pairs
							var par = {};
							var p = obj.getElementsByTagName("param");
							var pl = p.length;
							for (var j = 0; j < pl; j++) {
								if (p[j].getAttribute("name").toLowerCase() != "movie") {
									par[p[j].getAttribute("name")] = p[j].getAttribute("value");
								}
							}
							showExpressInstall(att, par, id, cb);
						}
						else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF
							displayAltContent(obj);
							if (cb) { cb(cbObj); }
						}
					}
				}
				else {	// if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content)
					setVisibility(id, true);
					if (cb) {
						var o = getObjectById(id); // test whether there is an HTML object element or not
						if (o && typeof o.SetVariable != UNDEF) { 
							cbObj.success = true;
							cbObj.ref = o;
						}
						cb(cbObj);
					}
				}
			}
		}
	}
86790
def spec_as_json
      json = {
        :name => spec.name,
        :version => spec.version,
        :manifest_version => calculate_manifest_version
      }

      json[:description] = spec.description if spec.description
      json[:icons] = spec.icons
      json[:default_locale] = spec.default_locale if spec.default_locale
      json[:browser_action] = action_as_json(spec.browser_action) if spec.browser_action
      json[:page_action] = action_as_json(spec.page_action) if spec.page_action
      json[:app] = packaged_app_as_json if spec.packaged_app
      if spec.background_page
        json[:background] = { :page => spec.background_page }
      end
      unless spec.background_scripts.empty?
        json[:background] = { :scripts => spec.background_scripts }
      end
      json[:chrome_url_overrides] = spec.overriden_pages unless spec.overriden_pages.empty?
      json[:content_scripts] = content_scripts_as_json unless spec.content_scripts.empty?
      json[:content_security_policy] = spec.content_security_policy if spec.content_security_policy
      json[:homepage_url] = spec.homepage if spec.homepage
      json[:incognito] = spec.incognito_mode if spec.incognito_mode
      json[:intents] = web_intents_as_json unless spec.web_intents.empty?
      json[:minimum_chrome_version] = spec.minimum_chrome_version if spec.minimum_chrome_version
      json[:nacl_modules] = nacl_modules_as_json unless spec.nacl_modules.empty?
      json[:offline_enabled] = spec.offline_enabled unless spec.offline_enabled.nil?
      json[:omnibox] = spec.omnibox_keyword if spec.omnibox_keyword
      json[:options_page] = spec.options_page if spec.options_page
      json[:permissions] = spec.permissions unless spec.permissions.empty?
      json[:requirements] = requirements_as_json if has_requirements?
      json[:update_url] = spec.update_url if spec.update_url
      json[:web_accessible_resources] = spec.web_accessible_resources unless spec.web_accessible_resources.empty?

      json
    end
978366
def select_header_accept(accepts)
      if accepts.empty?
        return
      elsif accepts.any?{ |s| s.casecmp('application/json') == 0 }
        'application/json' # look for json data by default
      else
        accepts.join(',')
      end
    end
411684
public function isCompatibleConfig()
    {
        $browser = $this->getBrowserDetector()->getName();
        $browserVersion = explode('.', $this->getBrowserDetector()->getVersion())[0];
        $os = $this->getOsDetector()->getName();
        $osVersion = $this->getOsDetector()->getVersion();
        $osVersion = explode('.', $osVersion);

        foreach ($this->compatibility as $rule) {
            //os name
            if ($rule->os === $os) {
                //os Version
                $validOs = true;
                if ($rule->osVersion !== "") {
                    foreach (explode('.', $rule->osVersion) as $key => $version) {
                        if (!isset($osVersion[$key]) || $osVersion[$key] !== $version) {
                            $validOs = false;
                        }
                    }
                }

                //browser validation
                if (empty($rule->versions)) {
                    // all versions work
                    $isValid = true;
                } else {
                    // it is valid if the version is in the array
                    // OR if the browser is chrome or firefox and it is a newer version than those in the array
                    $isValid = in_array($browserVersion, $rule->versions)
                        || (in_array($rule->browser,
                                array('Chrome', 'Firefox')) && $browserVersion > max($rule->versions));
                }

                if ($validOs && ($rule->browser === ""
                        || $rule->browser === $browser && $isValid)
                ) {
                    return $rule->compatible;
                }
            }
        }
        return 2;
    }
862605
public function wantsJson(): bool
    {
        $acceptable = $this->serverRequest->getHeaderLine('Accept');

        return $acceptable !== null && Strings::contains($acceptable, ['/json', '+json']);
    }
1269008
def check_compatibility(self):
        """"""
        message = ''
        value = True
        if PYQT4 or PYSIDE:
            message = _("You are working with Qt4 and in order to use this "
                        "plugin you need to have Qt5.<br><br>"
                        "Please update your Qt and/or PyQt packages to "
                        "meet this requirement.")
            value = False
        return value, message
140252
def on_same_fs(request):
    
    filename = request.POST['filename']
    checksum_in = request.POST['checksum']

    checksum = 0
    try:
        data = open(filename, 'rb').read(32)
        checksum = zlib.adler32(data, checksum) & 0xffffffff
        if checksum == int(checksum_in):
            return HttpResponse(content=json.dumps({'success': True}),
                                content_type=JSON, status=200)
    except (IOError, ValueError):
        pass

    return HttpResponse(content=json.dumps({'success': False}),
                        content_type=JSON, status=200)
825264
def register(context, request, load):
    """"""
    data = request.json
    res = validate(data, dataclass_to_jsl(
        RegistrationSchema).get_schema())
    if res:
        @request.after
        def set_error(response):
            response.status = 422
        return {
            'status': 'error',
            'field_errors': [{'message': res[x]} for x in res.keys()]
        }

    if data['password'] != data['password_validate']:
        @request.after
        def adjust_response(response):
            response.status = 422

        return {'status': 'error',
                'message': 'Password confirmation does not match'}

    if 'state' not in data.keys() or not data['state']:
        data['state'] = request.app.settings.application.new_user_state
    del data['password_validate']
    obj = context.create(data)
    return {'status': 'success'}
1153300
def select_header_accept(accepts)
      return nil if accepts.nil? || accepts.empty?
      # use JSON when present, otherwise use all of the provided
      json_accept = accepts.find { |s| json_mime?(s) }
      json_accept || accepts.join(',')
    end
121771
function check_json(string $json, bool $return_error = false)
  {
    json_decode($json);
    $error = json_last_error();
    if ( $error === JSON_ERROR_NONE ){
      return true;
    }
    if ( !$return_error ){
      return false;
    }
    switch ( $error ) {
      case JSON_ERROR_DEPTH:
        return _('Maximum stack depth exceeded');
      case JSON_ERROR_STATE_MISMATCH:
        return _('State mismatch (invalid or malformed JSON)');
      case JSON_ERROR_CTRL_CHAR:
        return _('Unexpected control character found');
      case JSON_ERROR_SYNTAX:
        return _('Syntax error, malformed JSON');
      case JSON_ERROR_UTF8:
        return _('Malformed UTF-8 characters, possibly incorrectly encoded');
      default:
        return _('Unknown error');
    }
  }
1243101
def _check_if_complete(self, url, json_response):
        
        if '__done' in json_response and isinstance(json_response, list):
            mr_parts = list(urlparse(url))
            mr_query = parse_qs(mr_parts[4])
            mr_query['mr'] = '"' + str(json_response[0]) + '"'
            mr_parts[4] = urlencode(mr_query, True)
            mr_link = urlunparse(mr_parts)
            mr_j, mr_r = self._ajax(mr_link)
            self.log.debug('MultipleRedirect link: %s', mr_link)
            return super(Installer, self)._check_if_complete(url, mr_j)

        return False
700169
function requestJson(options, callback) {
  const proto = options.protocol === 'https:' ? https
    : options.protocol === 'http:' ? http
      : null;
  if (!proto) {
    callback(
      new Error(`Unsupported protocol "${options.protocol}" for validator URL`)
    );
    return;
  }

  const req = proto.request(options)
    .once('error', callback)
    .once('response', (res) => {
      res.on('error', callback);
      const bodyData = [];
      res.on('data', (data) => { bodyData.push(data); });
      res.on('end', () => {
        const resBody = Buffer.concat(bodyData);
        let err, resBodyObj;
        try {
          resBodyObj = JSON.parse(resBody.toString());
        } catch (errJson) {
          err = new SyntaxError(
            `Error parsing server response as JSON: ${errJson.message}`
          );
        }

        if (res.statusCode >= 300) {
          let errMessage = `HTTP ${res.statusCode}`;
          if (res.statusMessage) {
            errMessage += `: ${res.statusMessage}`;
          }
          err = new Error(errMessage);
        }

        if (err) {
          err.statusCode = res.statusCode;
          err.statusMessage = res.statusMessage;
          err.headers = res.headers;
          err.trailers = res.trailers;
          err.body = resBodyObj !== undefined ? resBodyObj : resBody;
          callback(err);
        } else {
          callback(null, resBodyObj);
        }
      });
    });

  const {body} = options;
  if (typeof body === 'string' || Buffer.isBuffer(body)) {
    req.end(body);
  } else {
    body.on('error', (err) => {
      req.abort();
      callback(err);
    });
    body.pipe(req);
  }
}
341928
def __query_safebrowsing(self, search_value, search_type):
        
        return json.loads(
                self.session.post(
                    self.url,
                    json=self.__prepare_body(
                        search_value=search_value,
                        search_type=search_type
                    )
                ).text
            )
1103990
def workflow_is_stage_compatible(object_id, input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/%s/isStageCompatible' % object_id, input_params, always_retry=always_retry, **kwargs)