_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q244200 | PhpSerial.confFlowControl | validation | public function confFlowControl($mode)
{
if ($this->_dState !== SERIAL_DEVICE_SET) {
trigger_error("Unable to set flow control mode : the device is " .
"either not set or opened", E_USER_WARNING);
return false;
}
$linuxModes = array(
"none" => "clocal -crtscts -ixon -ixoff",
"rts/cts" => "-clocal crtscts -ixon -ixoff",
"xon/xoff" => "-clocal -crtscts ixon ixoff"
);
$windowsModes = array(
"none" => "xon=off octs=off rts=on",
"rts/cts" => "xon=off octs=on rts=hs",
"xon/xoff" => "xon=on octs=off rts=on",
);
if ($mode !== "none" and $mode !== "rts/cts" and $mode !== "xon/xoff") {
trigger_error("Invalid flow control mode specified", E_USER_ERROR);
return false;
}
if ($this->_os === "linux") {
$ret = $this->_exec(
"stty -F " . $this->_device . " " . $linuxModes[$mode],
$out
);
} elseif ($this->_os === "osx") {
$ret = $this->_exec(
"stty -f " . $this->_device . " " . $linuxModes[$mode],
$out
);
} else {
$ret = $this->_exec(
"mode " . $this->_winDevice . " " . $windowsModes[$mode],
$out
);
}
if ($ret === 0) {
return true;
} else {
trigger_error(
"Unable to set flow control : " . $out[1],
E_USER_ERROR
);
return false;
}
} | php | {
"resource": ""
} |
q244201 | PhpSerial.sendMessage | validation | public function sendMessage($str, $waitForReply = 0.1)
{
$this->_buffer .= $str;
if ($this->autoFlush === true) {
$this->serialflush();
}
usleep((int) ($waitForReply * 1000000));
} | php | {
"resource": ""
} |
q244202 | PhpSerial.readPort | validation | public function readPort($count = 0)
{
if ($this->_dState !== SERIAL_DEVICE_OPENED) {
trigger_error("Device must be opened to read it", E_USER_WARNING);
return false;
}
if ($this->_os === "linux" || $this->_os === "osx") {
// Behavior in OSX isn't to wait for new data to recover, but just
// grabs what's there!
// Doesn't always work perfectly for me in OSX
$content = ""; $i = 0;
if ($count !== 0) {
do {
if ($i > $count) {
$content .= fread($this->_dHandle, ($count - $i));
} else {
$content .= fread($this->_dHandle, 128);
}
} while (($i += 128) === strlen($content));
} else {
do {
$content .= fread($this->_dHandle, 128);
} while (($i += 128) === strlen($content));
}
return $content;
} elseif ($this->_os === "windows") {
// Windows port reading procedures still buggy
$content = ""; $i = 0;
if ($count !== 0) {
do {
if ($i > $count) {
$content .= fread($this->_dHandle, ($count - $i));
} else {
$content .= fread($this->_dHandle, 128);
}
} while (($i += 128) === strlen($content));
} else {
do {
$content .= fread($this->_dHandle, 128);
} while (($i += 128) === strlen($content));
}
return $content;
}
return false;
} | php | {
"resource": ""
} |
q244203 | PhpSerial.serialflush | validation | public function serialflush()
{
if (!$this->_ckOpened()) {
return false;
}
if (fwrite($this->_dHandle, $this->_buffer) !== false) {
$this->_buffer = "";
return true;
} else {
$this->_buffer = "";
trigger_error("Error while sending message", E_USER_WARNING);
return false;
}
} | php | {
"resource": ""
} |
q244204 | Wechat.isAuthorized | validation | public function isAuthorized()
{
$hasSession = Yii::$app->session->has($this->sessionParam);
$sessionVal = Yii::$app->session->get($this->sessionParam);
return ($hasSession && !empty($sessionVal));
} | php | {
"resource": ""
} |
q244205 | BaseClientRemote.performRequest | validation | public function performRequest($method, $path, array $params = [])
{
$request = $this->buildRequest($method, $path, $params);
try {
$response = $this->httpClient->send($request);
$content = json_decode($response->getBody()->getContents(), true);
} catch (ClientException $ex) {
if ($ex->getResponse()->getStatusCode() == 401) {
if ($this->isPsr7Version()) {
$uri = $request->getUri();
} else {
$uri = $request->getUrl();
}
$message = sprintf('Unauthorized %s Request to %s', $request->getMethod(), $uri);
throw new UnauthorizedRequestException($message);
}
throw $ex;
}
return $this->createResponseFromData($content);
} | php | {
"resource": ""
} |
q244206 | BaseClientRemote.buildRequest | validation | public function buildRequest($method, $path, array $params = [])
{
$body = ArrayUtils::get($params, 'body', null);
$query = ArrayUtils::get($params, 'query', null);
$options = [];
if (in_array($method, ['POST', 'PUT', 'PATCH']) && $body) {
$options['body'] = $body;
}
if ($query) {
$options['query'] = $query;
}
return $this->createRequest($method, $path, $options);
} | php | {
"resource": ""
} |
q244207 | BaseClientRemote.createRequest | validation | public function createRequest($method, $path, $options)
{
if ($this->isPsr7Version()) {
$headers = [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->getAccessToken(),
];
$body = ArrayUtils::get($options, 'body', null);
$uri = UriResolver::resolve(new Uri($this->getBaseEndpoint() . '/'), new Uri($path));
if ($body) {
$body = json_encode($body);
}
if (ArrayUtils::has($options, 'query')) {
$query = $options['query'];
if (is_array($query)) {
$query = http_build_query($query, null, '&', PHP_QUERY_RFC3986);
}
if (!is_string($query)) {
throw new \InvalidArgumentException('query must be a string or array');
}
$uri = $uri->withQuery($query);
}
$request = new Request($method, $uri, $headers, $body);
} else {
$options['auth'] = [$this->accessToken, ''];
$request = $this->httpClient->createRequest($method, $path, $options);
$query = ArrayUtils::get($options, 'query');
if ($query) {
$q = $request->getQuery();
foreach($query as $key => $value) {
$q->set($key, $value);
}
}
}
return $request;
} | php | {
"resource": ""
} |
q244208 | AbstractClient.createResponseFromData | validation | protected function createResponseFromData($data)
{
if (isset($data['rows']) || (isset($data['data']) && ArrayUtils::isNumericKeys($data['data']))) {
$response = new EntryCollection($data);
} else {
$response = new Entry($data);
}
return $response;
} | php | {
"resource": ""
} |
q244209 | EntryCollection.pickMetadata | validation | protected function pickMetadata($data)
{
$metadata = [];
if (ArrayUtils::has($data, 'rows')) {
$metadata = ArrayUtils::omit($data, 'rows');
} else if (ArrayUtils::has($data, 'meta')) {
$metadata = ArrayUtils::get($data, 'meta');
}
return new Entry($metadata);
} | php | {
"resource": ""
} |
q244210 | ClientLocal.getTableGateway | validation | protected function getTableGateway($tableName)
{
if (!array_key_exists($tableName, $this->tableGateways)) {
$acl = TableSchema::getAclInstance();
$this->tableGateways[$tableName] = new RelationalTableGateway($tableName, $this->connection, $acl);
}
return $this->tableGateways[$tableName];
} | php | {
"resource": ""
} |
q244211 | Mailer.doSend | validation | private function doSend(MessageInterface $message)
{
$content = $this->format($message);
$headers = $this->getHeaders();
$files = $this->getFiles($message);
if (!empty($files)) {
// HTTP query content
parse_str($content, $fields);
$builder = new MultipartStreamBuilder();
foreach ($fields as $name => $value) {
if (is_array($value)) {
foreach ($value as $c) {
$builder->addResource($name.'[]', $c);
}
continue;
}
$builder->addResource($name, $value);
}
// Add files to request
foreach ($files as $key => $items) {
foreach ($items as $name => $path) {
$options = [];
if (!is_numeric($name)) {
$options['filename'] = $name;
}
$value = fopen($path, 'r');
$builder->addResource($key, $value, $options);
}
}
$content = $builder->build();
$headers['Content-Type'] = 'multipart/form-data; boundary="'.$builder->getBoundary().'"';
}
$request = $this->getMessageFactory()->createRequest('POST', $this->getEndpoint(), $headers, $content);
return $this->getHttpClient()->sendRequest($request);
} | php | {
"resource": ""
} |
q244212 | AttachmentUtils.processAttachments | validation | public static function processAttachments(array $attachments)
{
$processed = [];
foreach ($attachments as $attachment) {
if (!($attachment instanceof Attachment)) {
throw new \InvalidArgumentException('Attachments must implement Stampie\\Attachment');
}
$name = $attachment->getName();
if (isset($processed[$name])) {
// Name conflict
$name = static::findUniqueName($name, array_keys($processed));
}
$processed[$name] = $attachment;
}
return $processed;
} | php | {
"resource": ""
} |
q244213 | AstAnalyzer.determineContext | validation | protected function determineContext(array &$data)
{
// Get the variable names defined in the AST
$refs = 0;
$vars = array_map(function ($node) use (&$refs) {
if ($node->byRef) {
$refs++;
}
if ($node->var instanceof VariableNode) {
// For PHP-Parser >=4.0
return $node->var->name;
} else {
// For PHP-Parser <4.0
return $node->var;
}
}, $data['ast']->uses);
$data['hasRefs'] = ($refs > 0);
// Get the variable names and values using reflection
$values = $data['reflection']->getStaticVariables();
// Combine the names and values to create the canonical context.
foreach ($vars as $name) {
if (isset($values[$name])) {
$data['context'][$name] = $values[$name];
}
}
} | php | {
"resource": ""
} |
q244214 | Serializer.wrapClosures | validation | public static function wrapClosures(&$data, SerializerInterface $serializer)
{
if ($data instanceof \Closure) {
// Handle and wrap closure objects.
$reflection = new \ReflectionFunction($data);
if ($binding = $reflection->getClosureThis()) {
self::wrapClosures($binding, $serializer);
$scope = $reflection->getClosureScopeClass();
$scope = $scope ? $scope->getName() : 'static';
$data = $data->bindTo($binding, $scope);
}
$data = new SerializableClosure($data, $serializer);
} elseif (is_array($data) || $data instanceof \stdClass || $data instanceof \Traversable) {
// Handle members of traversable values.
foreach ($data as &$value) {
self::wrapClosures($value, $serializer);
}
} elseif (is_object($data) && !$data instanceof \Serializable) {
// Handle objects that are not already explicitly serializable.
$reflection = new \ReflectionObject($data);
if (!$reflection->hasMethod('__sleep')) {
foreach ($reflection->getProperties() as $property) {
if ($property->isPrivate() || $property->isProtected()) {
$property->setAccessible(true);
}
$value = $property->getValue($data);
self::wrapClosures($value, $serializer);
$property->setValue($data, $value);
}
}
}
} | php | {
"resource": ""
} |
q244215 | ClosureAnalyzer.analyze | validation | public function analyze(\Closure $closure)
{
$data = [
'reflection' => new \ReflectionFunction($closure),
'code' => null,
'hasThis' => false,
'context' => [],
'hasRefs' => false,
'binding' => null,
'scope' => null,
'isStatic' => $this->isClosureStatic($closure),
];
$this->determineCode($data);
$this->determineContext($data);
$this->determineBinding($data);
return $data;
} | php | {
"resource": ""
} |
q244216 | SerializableClosure.bindTo | validation | public function bindTo($newthis, $newscope = 'static')
{
return new self(
$this->closure->bindTo($newthis, $newscope),
$this->serializer
);
} | php | {
"resource": ""
} |
q244217 | SerializableClosure.serialize | validation | public function serialize()
{
try {
$this->data = $this->data ?: $this->serializer->getData($this->closure, true);
return serialize($this->data);
} catch (\Exception $e) {
trigger_error(
'Serialization of closure failed: ' . $e->getMessage(),
E_USER_NOTICE
);
// Note: The serialize() method of Serializable must return a string
// or null and cannot throw exceptions.
return null;
}
} | php | {
"resource": ""
} |
q244218 | SerializableClosure.unserialize | validation | public function unserialize($serialized)
{
// Unserialize the closure data and reconstruct the closure object.
$this->data = unserialize($serialized);
$this->closure = __reconstruct_closure($this->data);
// Throw an exception if the closure could not be reconstructed.
if (!$this->closure instanceof Closure) {
throw new ClosureUnserializationException(
'The closure is corrupted and cannot be unserialized.'
);
}
// Rebind the closure to its former binding and scope.
if ($this->data['binding'] || $this->data['isStatic']) {
$this->closure = $this->closure->bindTo(
$this->data['binding'],
$this->data['scope']
);
}
} | php | {
"resource": ""
} |
q244219 | SpdxLicenses.getLicenseByIdentifier | validation | public function getLicenseByIdentifier($identifier)
{
$key = strtolower($identifier);
if (!isset($this->licenses[$key])) {
return;
}
list($identifier, $name, $isOsiApproved, $isDeprecatedLicenseId) = $this->licenses[$key];
return array(
$name,
$isOsiApproved,
'https://spdx.org/licenses/' . $identifier . '.html#licenseText',
$isDeprecatedLicenseId,
);
} | php | {
"resource": ""
} |
q244220 | SpdxLicenses.getExceptionByIdentifier | validation | public function getExceptionByIdentifier($identifier)
{
$key = strtolower($identifier);
if (!isset($this->exceptions[$key])) {
return;
}
list($identifier, $name) = $this->exceptions[$key];
return array(
$name,
'https://spdx.org/licenses/' . $identifier . '.html#licenseExceptionText',
);
} | php | {
"resource": ""
} |
q244221 | ConfigurationManipulator.addResource | validation | public function addResource(Bundle $bundle)
{
// if the config.yml file doesn't exist, don't even try.
if (!file_exists($this->file)) {
throw new \RuntimeException(sprintf('The target config file %s does not exist', $this->file));
}
$code = $this->getImportCode($bundle);
$currentContents = file_get_contents($this->file);
// Don't add same bundle twice
if (false !== strpos($currentContents, $code)) {
throw new \RuntimeException(sprintf('The %s configuration file from %s is already imported', $bundle->getServicesConfigurationFilename(), $bundle->getName()));
}
// find the "imports" line and add this at the end of that list
$lastImportedPath = $this->findLastImportedPath($currentContents);
if (!$lastImportedPath) {
throw new \RuntimeException(sprintf('Could not find the imports key in %s', $this->file));
}
// find imports:
$importsPosition = strpos($currentContents, 'imports:');
// find the last import
$lastImportPosition = strpos($currentContents, $lastImportedPath, $importsPosition);
// find the line break after the last import
$targetLinebreakPosition = strpos($currentContents, "\n", $lastImportPosition);
$newContents = substr($currentContents, 0, $targetLinebreakPosition)."\n".$code.substr($currentContents, $targetLinebreakPosition);
if (false === Generator::dump($this->file, $newContents)) {
throw new \RuntimeException(sprintf('Could not write file %s ', $this->file));
}
} | php | {
"resource": ""
} |
q244222 | ConfigurationManipulator.findLastImportedPath | validation | private function findLastImportedPath($yamlContents)
{
$data = Yaml::parse($yamlContents);
if (!isset($data['imports'])) {
return false;
}
// find the last imports entry
$lastImport = end($data['imports']);
if (!isset($lastImport['resource'])) {
return false;
}
return $lastImport['resource'];
} | php | {
"resource": ""
} |
q244223 | KernelManipulator.addBundle | validation | public function addBundle($bundle)
{
if (!$this->getFilename()) {
return false;
}
$src = file($this->getFilename());
$method = $this->reflected->getMethod('registerBundles');
$lines = array_slice($src, $method->getStartLine() - 1, $method->getEndLine() - $method->getStartLine() + 1);
// Don't add same bundle twice
if (false !== strpos(implode('', $lines), $bundle)) {
throw new \RuntimeException(sprintf('Bundle "%s" is already defined in "AppKernel::registerBundles()".', $bundle));
}
$this->setCode(token_get_all('<?php '.implode('', $lines)), $method->getStartLine());
while ($token = $this->next()) {
// $bundles
if (T_VARIABLE !== $token[0] || '$bundles' !== $token[1]) {
continue;
}
// =
$this->next();
// array start with traditional or short syntax
$token = $this->next();
if (T_ARRAY !== $token[0] && '[' !== $this->value($token)) {
return false;
}
// add the bundle at the end of the array
while ($token = $this->next()) {
// look for ); or ];
if (')' !== $this->value($token) && ']' !== $this->value($token)) {
continue;
}
if (';' !== $this->value($this->peek())) {
continue;
}
$this->next();
$leadingContent = implode('', array_slice($src, 0, $this->line));
// trim semicolon
$leadingContent = rtrim(rtrim($leadingContent), ';');
// We want to match ) & ]
$closingSymbolRegex = '#(\)|])$#';
// get closing symbol used
preg_match($closingSymbolRegex, $leadingContent, $matches);
$closingSymbol = $matches[0];
// remove last close parentheses
$leadingContent = rtrim(preg_replace($closingSymbolRegex, '', rtrim($leadingContent)));
if ('(' !== substr($leadingContent, -1) && '[' !== substr($leadingContent, -1)) {
// end of leading content is not open parentheses or bracket, then assume that array contains at least one element
$leadingContent = rtrim($leadingContent, ',').',';
}
$lines = array_merge(
array($leadingContent, "\n"),
array(str_repeat(' ', 12), sprintf('new %s(),', $bundle), "\n"),
array(str_repeat(' ', 8), $closingSymbol.';', "\n"),
array_slice($src, $this->line)
);
Generator::dump($this->getFilename(), implode('', $lines));
return true;
}
}
} | php | {
"resource": ""
} |
q244224 | GeneratorCommand.makePathRelative | validation | protected function makePathRelative($absolutePath)
{
$projectRootDir = dirname($this->getContainer()->getParameter('kernel.root_dir'));
return str_replace($projectRootDir.'/', '', realpath($absolutePath) ?: $absolutePath);
} | php | {
"resource": ""
} |
q244225 | Manipulator.peek | validation | protected function peek($nb = 1)
{
$i = 0;
$tokens = $this->tokens;
while ($token = array_shift($tokens)) {
if (is_array($token) && in_array($token[0], array(T_WHITESPACE, T_COMMENT, T_DOC_COMMENT))) {
continue;
}
++$i;
if ($i == $nb) {
return $token;
}
}
} | php | {
"resource": ""
} |
q244226 | DoctrineCrudGenerator.generateIndexView | validation | protected function generateIndexView($dir)
{
$this->renderFile('crud/views/index.html.twig.twig', $dir.'/index.html.twig', array(
'bundle' => $this->bundle->getName(),
'entity' => $this->entity,
'entity_pluralized' => $this->entityPluralized,
'entity_singularized' => $this->entitySingularized,
'identifier' => $this->metadata->identifier[0],
'fields' => $this->metadata->fieldMappings,
'actions' => $this->actions,
'record_actions' => $this->getRecordActions(),
'route_prefix' => $this->routePrefix,
'route_name_prefix' => $this->routeNamePrefix,
));
} | php | {
"resource": ""
} |
q244227 | GenerateDoctrineCrudCommand.generateForm | validation | protected function generateForm($bundle, $entity, $metadata, $forceOverwrite = false)
{
$this->getFormGenerator($bundle)->generate($bundle, $entity, $metadata[0], $forceOverwrite);
} | php | {
"resource": ""
} |
q244228 | RoutingManipulator.addResource | validation | public function addResource($bundle, $format, $prefix = '/', $path = 'routing')
{
$current = '';
$code = sprintf("%s:\n", $this->getImportedResourceYamlKey($bundle, $prefix));
if (file_exists($this->file)) {
$current = file_get_contents($this->file);
// Don't add same bundle twice
if (false !== strpos($current, '@'.$bundle)) {
throw new \RuntimeException(sprintf('Bundle "%s" is already imported.', $bundle));
}
} elseif (!is_dir($dir = dirname($this->file))) {
Generator::mkdir($dir);
}
if ('annotation' == $format) {
$code .= sprintf(" resource: \"@%s/Controller/\"\n type: annotation\n", $bundle);
} else {
$code .= sprintf(" resource: \"@%s/Resources/config/%s.%s\"\n", $bundle, $path, $format);
}
$code .= sprintf(" prefix: %s\n", $prefix);
$code .= "\n";
$code .= $current;
if (false === Generator::dump($this->file, $code)) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q244229 | RoutingManipulator.hasResourceInAnnotation | validation | public function hasResourceInAnnotation($bundle)
{
if (!file_exists($this->file)) {
return false;
}
$config = Yaml::parse(file_get_contents($this->file));
$search = sprintf('@%s/Controller/', $bundle);
foreach ($config as $resource) {
if (array_key_exists('resource', $resource)) {
return $resource['resource'] === $search;
}
}
return false;
} | php | {
"resource": ""
} |
q244230 | AbstractTransportDecorator.setLogger | validation | public function setLogger(LoggerInterface $logger)
{
if ($this->transport instanceof LoggerAwareInterface) {
$this->transport->setLogger($logger);
}
} | php | {
"resource": ""
} |
q244231 | UploadFile.uploadFromPath | validation | public function uploadFromPath($path)
{
$file = new FormUpload($path);
$this->request->setParam('content', $file);
return $this;
} | php | {
"resource": ""
} |
q244232 | XmlDataTransportDecorator.encodeRecord | validation | private function encodeRecord($record, $childName, &$xml)
{
foreach ($record as $key => $value)
{
if ($value instanceof \DateTime)
{
if ($value->format('His') === '000000') {
$value = $value->format('m/d/Y');
} else {
$value = $value->format('Y-m-d H:i:s');
}
}
$keyValue = $xml->addChild($childName);
$keyValue->addAttribute('val', $key);
if(is_array($value)) {
$this->parseNestedValues($value, $keyValue);
}
else {
$keyValue[0] = $value;
}
}
} | php | {
"resource": ""
} |
q244233 | XmlDataTransportDecorator.parse | validation | private function parse($content)
{
if ($this->method == 'downloadFile') {
return $this->parseResponseDownloadFile($content);
}
$xml = new SimpleXMLElement($content);
if (isset($xml->error)) {
throw new Exception\ZohoErrorException(
new ZohoError(
(string) $xml->error->code,
(string) $xml->error->message
)
);
}
if (isset($xml->nodata)) {
throw new Exception\NoDataException(
new ZohoError(
(string)$xml->nodata->code, (string) $xml->nodata->message
)
);
}
if ($this->method == 'getFields') {
return $this->parseResponseGetFields($xml);
}
if ($this->method == 'deleteRecords') {
return $this->parseResponseDeleteRecords($xml);
}
if ($this->method == 'uploadFile') {
return $this->parseResponseUploadFile($xml);
}
if ($this->method == 'deleteFile') {
return $this->parseResponseDeleteFile($xml);
}
if ($this->method == 'getDeletedRecordIds') {
return $this->parseResponseGetDeletedRecordIds($xml);
}
if ($this->method == 'convertLead') {
return $this->parseResponseConvertLead($xml);
}
if ($this->method == 'updateRelatedRecords') {
return $this->parseUpdateRelatedRecords($xml);
}
if (isset($xml->result->{$this->module})) {
return $this->parseResponseGetRecords($xml);
}
if (isset($xml->result->row->success) || isset($xml->result->row->error)) {
return $this->parseResponsePostRecordsMultiple($xml);
}
throw new Exception\UnexpectedValueException('Xml doesn\'t contain expected fields');
} | php | {
"resource": ""
} |
q244234 | Mailer.initSMTP | validation | public function initSMTP() {
/** @var \Base $f3 */
$f3 = \Base::instance();
$this->smtp = new \SMTP(
$f3->get('mailer.smtp.host'),
$f3->get('mailer.smtp.port'),
$f3->get('mailer.smtp.scheme'),
$f3->get('mailer.smtp.user'),
$f3->get('mailer.smtp.pw'));
if (!$f3->devoid('mailer.errors_to',$errors_to))
$this->setErrors($errors_to);
if (!$f3->devoid('mailer.reply_to',$reply_to))
$this->setReply($reply_to);
if (!$f3->devoid('mailer.from_mail',$from_mail)) {
if ($f3->devoid('mailer.from_name',$from_name))
$from_name = NULL;
$this->setFrom($from_mail, $from_name);
}
} | php | {
"resource": ""
} |
q244235 | Mailer.encode | validation | protected function encode($str) {
if (empty($str) || $this->charset == 'UTF-8')
return $str;
if (extension_loaded('iconv'))
$out = @iconv("UTF-8", $this->charset."//IGNORE", $str);
if (!isset($out) || !$out)
$out = extension_loaded('mbstring')
? mb_convert_encoding($str,$this->charset,"UTF-8")
: utf8_decode($str);
return $out ?: $str;
} | php | {
"resource": ""
} |
q244236 | Mailer.encodeHeader | validation | protected function encodeHeader($str) {
if (extension_loaded('iconv')) {
$out = iconv_mime_encode('Subject', $str,
['input-charset' => 'UTF-8', 'output-charset' => $this->charset]);
$out = substr($out, strlen('Subject: '));
} elseif(extension_loaded('mbstring')) {
mb_internal_encoding('UTF-8');
$out = mb_encode_mimeheader($str, $this->charset, 'B', static::$EOL, strlen('Subject: '));
} else
$out = wordwrap($str,65,static::$EOL);
return $out;
} | php | {
"resource": ""
} |
q244237 | Mailer.set | validation | public function set($key, $val) {
$this->smtp->set($key, $this->encode($val));
} | php | {
"resource": ""
} |
q244238 | Mailer.setFrom | validation | public function setFrom($email, $title=null) {
$this->set('From', $this->buildMail($email,$title));
} | php | {
"resource": ""
} |
q244239 | Mailer.setReply | validation | public function setReply($email, $title=null) {
$this->set('Reply-To', $this->buildMail($email,$title));
} | php | {
"resource": ""
} |
q244240 | Mailer.setErrors | validation | public function setErrors($email, $title=null) {
$this->set('Sender', $this->buildMail($email,$title));
} | php | {
"resource": ""
} |
q244241 | Mailer.reset | validation | public function reset($key=null) {
if ($key) {
$key = ucfirst($key);
$this->smtp->clear($key);
if (isset($this->recipients[$key]))
unset($this->recipients[$key]);
} else {
$this->recipients = array();
$this->initSMTP();
}
} | php | {
"resource": ""
} |
q244242 | Mailer.setHTML | validation | public function setHTML($message) {
$f3 = \Base::instance();
// we need a clean template instance for extending it one-time
$tmpl = new \Template();
// create traceable jump links
if ($f3->exists('mailer.jumplinks',$jumplink) && $jumplink)
$tmpl->extend('a', function($node) use($f3, $tmpl) {
if (isset($node['@attrib'])) {
$attr = $node['@attrib'];
unset($node['@attrib']);
} else
$attr = array();
if (isset($attr['href'])) {
if (!$f3->exists('mailer.jump_route',$ping_route))
$ping_route = '/mailer-jump';
$attr['href'] = $f3->get('SCHEME').'://'.$f3->get('HOST').$f3->get('BASE').
$ping_route.'?target='.urlencode($attr['href']);
}
$params = '';
foreach ($attr as $key => $value)
$params.=' '.$key.'="'.$value.'"';
return '<a'.$params.'>'.$tmpl->build($node).'</a>';
});
$message = $tmpl->build($tmpl->parse($message));
$this->setContent($message,'text/html');
} | php | {
"resource": ""
} |
q244243 | Mailer.setContent | validation | public function setContent($data, $mime, $charset=NULL) {
if (!$charset)
$charset=$this->charset;
$this->message[$mime] = [
'content'=>$data,
'type'=>$mime.'; '.$charset
];
} | php | {
"resource": ""
} |
q244244 | Mailer.attachFile | validation | public function attachFile($path, $alias=null, $cid=null) {
$this->smtp->attach($path,$alias,$cid);
} | php | {
"resource": ""
} |
q244245 | Mailer.save | validation | public function save($filename) {
$f3 = \Base::instance();
$lines = explode("\n",$this->smtp->log());
$start = false;
$out = '';
for($i=0,$max=count($lines);$i<$max;$i++) {
if (!$start && preg_match('/^354.*?$/',$lines[$i],$matches)) {
$start=true;
continue;
} elseif (preg_match('/^250.*?$\s^QUIT/m',
$lines[$i].($i+1 < $max ? "\n".$lines[$i+1] : ''),$matches))
break;
if ($start)
$out.=$lines[$i]."\n";
}
if ($out) {
$path = $f3->get('mailer.storage_path');
if (!is_dir($path))
mkdir($path,0777,true);
$f3->write($path.$filename,$out);
}
} | php | {
"resource": ""
} |
q244246 | Mailer.ping | validation | static public function ping(\Base $f3, $params) {
$hash = $params['hash'];
// trigger ping event
if ($f3->exists('mailer.on.ping',$ping_handler))
$f3->call($ping_handler,array($hash));
$img = new \Image();
// 1x1 transparent 8bit PNG
$img->load(base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMA'.
'AAAl21bKAAAABGdBTUEAALGPC/xhBQAAAANQTFRFAAAAp3o92gAAAAF0U'.
'k5TAEDm2GYAAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC'));
$img->render();
} | php | {
"resource": ""
} |
q244247 | Mailer.jump | validation | static public function jump(\Base $f3, $params) {
$target = $f3->get('GET.target');
// trigger jump event
if ($f3->exists('mailer.on.jump',$jump_handler))
$f3->call($jump_handler,array($target,$params));
$f3->reroute(urldecode($target));
} | php | {
"resource": ""
} |
q244248 | PhpRenderer.setLayout | validation | public function setLayout($layout)
{
if ($layout === "" || $layout === null) {
$this->layout = null;
} else {
$layoutPath = $this->templatePath . $layout;
if (!is_file($layoutPath)) {
throw new \RuntimeException("Layout template `$layout` does not exist");
}
$this->layout = $layoutPath;
}
} | php | {
"resource": ""
} |
q244249 | PhpRenderer.getAttribute | validation | public function getAttribute($key) {
if (!isset($this->attributes[$key])) {
return false;
}
return $this->attributes[$key];
} | php | {
"resource": ""
} |
q244250 | PhpRenderer.fetch | validation | public function fetch($template, array $data = []) {
if (isset($data['template'])) {
throw new \InvalidArgumentException("Duplicate template key found");
}
if (!is_file($this->templatePath . $template)) {
throw new \RuntimeException("View cannot render `$template` because the template does not exist");
}
/*
foreach ($data as $k=>$val) {
if (in_array($k, array_keys($this->attributes))) {
throw new \InvalidArgumentException("Duplicate key found in data and renderer attributes. " . $k);
}
}
*/
$data = array_merge($this->attributes, $data);
try {
ob_start();
$this->protectedIncludeScope($this->templatePath . $template, $data);
$output = ob_get_clean();
if ($this->layout !== null) {
ob_start();
$data['content'] = $output;
$this->protectedIncludeScope($this->layout, $data);
$output = ob_get_clean();
}
} catch(\Throwable $e) { // PHP 7+
ob_end_clean();
throw $e;
} catch(\Exception $e) { // PHP < 7
ob_end_clean();
throw $e;
}
return $output;
} | php | {
"resource": ""
} |
q244251 | Client.setConsumer | validation | public function setConsumer($consumerKey, $consumerSecret)
{
$this->apiKey = $consumerKey;
$this->requestHandler->setConsumer($consumerKey, $consumerSecret);
} | php | {
"resource": ""
} |
q244252 | Client.follow | validation | public function follow($blogName)
{
$options = array('url' => $this->blogUrl($blogName));
return $this->postRequest('v2/user/follow', $options, false);
} | php | {
"resource": ""
} |
q244253 | Client.unfollow | validation | public function unfollow($blogName)
{
$options = array('url' => $this->blogUrl($blogName));
return $this->postRequest('v2/user/unfollow', $options, false);
} | php | {
"resource": ""
} |
q244254 | Client.like | validation | public function like($postId, $reblogKey)
{
$options = array('id' => $postId, 'reblog_key' => $reblogKey);
return $this->postRequest('v2/user/like', $options, false);
} | php | {
"resource": ""
} |
q244255 | Client.unlike | validation | public function unlike($postId, $reblogKey)
{
$options = array('id' => $postId, 'reblog_key' => $reblogKey);
return $this->postRequest('v2/user/unlike', $options, false);
} | php | {
"resource": ""
} |
q244256 | Client.deletePost | validation | public function deletePost($blogName, $postId, $reblogKey)
{
$options = array('id' => $postId, 'reblog_key' => $reblogKey);
$path = $this->blogPath($blogName, '/post/delete');
return $this->postRequest($path, $options, false);
} | php | {
"resource": ""
} |
q244257 | Client.reblogPost | validation | public function reblogPost($blogName, $postId, $reblogKey, $options = null)
{
$params = array('id' => $postId, 'reblog_key' => $reblogKey);
$params = array_merge($options ?: array(), $params);
$path = $this->blogPath($blogName, '/post/reblog');
return $this->postRequest($path, $params, false);
} | php | {
"resource": ""
} |
q244258 | Client.editPost | validation | public function editPost($blogName, $postId, $data)
{
$data['id'] = $postId;
$path = $this->blogPath($blogName, '/post/edit');
return $this->postRequest($path, $data, false);
} | php | {
"resource": ""
} |
q244259 | Client.createPost | validation | public function createPost($blogName, $data)
{
$path = $this->blogPath($blogName, '/post');
return $this->postRequest($path, $data, false);
} | php | {
"resource": ""
} |
q244260 | Client.getTaggedPosts | validation | public function getTaggedPosts($tag, $options = null)
{
if (!$options) {
$options = array();
}
$options['tag'] = $tag;
return $this->getRequest('v2/tagged', $options, true);
} | php | {
"resource": ""
} |
q244261 | Client.getBlogInfo | validation | public function getBlogInfo($blogName)
{
$path = $this->blogPath($blogName, '/info');
return $this->getRequest($path, null, true);
} | php | {
"resource": ""
} |
q244262 | Client.getBlogAvatar | validation | public function getBlogAvatar($blogName, $size = null)
{
$path = $this->blogPath($blogName, '/avatar');
if ($size) {
$path .= "/$size";
}
return $this->getRedirect($path, null, true);
} | php | {
"resource": ""
} |
q244263 | Client.getBlogLikes | validation | public function getBlogLikes($blogName, $options = null)
{
$path = $this->blogPath($blogName, '/likes');
return $this->getRequest($path, $options, true);
} | php | {
"resource": ""
} |
q244264 | Client.getBlogFollowers | validation | public function getBlogFollowers($blogName, $options = null)
{
$path = $this->blogPath($blogName, '/followers');
return $this->getRequest($path, $options, false);
} | php | {
"resource": ""
} |
q244265 | Client.getBlogPosts | validation | public function getBlogPosts($blogName, $options = null)
{
$path = $this->blogPath($blogName, '/posts');
if ($options && isset($options['type'])) {
$path .= '/' . $options['type'];
unset($options['type']);
}
return $this->getRequest($path, $options, true);
} | php | {
"resource": ""
} |
q244266 | Client.postRequest | validation | public function postRequest($path, $options, $addApiKey)
{
if (isset($options['source']) && is_array($options['source'])) {
$sources = $options['source'];
unset($options['source']);
foreach ($sources as $i => $source) {
$options["source[$i]"] = $source;
}
}
$response = $this->makeRequest('POST', $path, $options, $addApiKey);
return $this->parseResponse($response);
} | php | {
"resource": ""
} |
q244267 | Client.parseResponse | validation | private function parseResponse($response)
{
$response->json = json_decode($response->body);
if ($response->status < 400) {
return $response->json->response;
} else {
throw new RequestException($response);
}
} | php | {
"resource": ""
} |
q244268 | Client.makeRequest | validation | private function makeRequest($method, $path, $options, $addApiKey)
{
if ($addApiKey) {
$options = array_merge(
array('api_key' => $this->apiKey),
$options ?: array()
);
}
return $this->requestHandler->request($method, $path, $options);
} | php | {
"resource": ""
} |
q244269 | RequestHandler.setConsumer | validation | public function setConsumer($key, $secret)
{
$this->consumer = new \Eher\OAuth\Consumer($key, $secret);
} | php | {
"resource": ""
} |
q244270 | RequestHandler.setToken | validation | public function setToken($token, $secret)
{
$this->token = new \Eher\OAuth\Token($token, $secret);
} | php | {
"resource": ""
} |
q244271 | SessionStateService.pauseSession | validation | public function pauseSession(AssessmentTestSession $session) {
$session->updateDuration();
return $this->getDeliveryExecution($session)->setState(DeliveryExecution::STATE_PAUSED);
} | php | {
"resource": ""
} |
q244272 | SessionStateService.resumeSession | validation | public function resumeSession(AssessmentTestSession $session) {
$deliveryExecutionState = $this->getSessionState($session);
if ($deliveryExecutionState === DeliveryExecution::STATE_PAUSED) {
$this->updateTimeReference($session);
$this->getDeliveryExecution($session)->setState(DeliveryExecution::STATE_ACTIVE);
}
} | php | {
"resource": ""
} |
q244273 | SessionStateService.getSessionState | validation | public function getSessionState(AssessmentTestSession $session) {
$deliveryExecution = $this->getDeliveryExecution($session);
return $deliveryExecution->getState()->getUri();
} | php | {
"resource": ""
} |
q244274 | SessionStateService.getSessionDescription | validation | public function getSessionDescription(\taoQtiTest_helpers_TestSession $session)
{
if ($session->isRunning()) {
$config = \common_ext_ExtensionsManager::singleton()->getExtensionById('taoQtiTest')->getConfig('testRunner');
$progressScope = isset($config['progress-indicator-scope']) ? $config['progress-indicator-scope'] : 'test';
$progress = $this->getSessionProgress($session);
$itemPosition = $progress[$progressScope];
$itemCount = $progress[$progressScope . 'Length'];
$format = $this->hasOption(self::OPTION_STATE_FORMAT)
? $this->getOption(self::OPTION_STATE_FORMAT)
: __('%s - item %p/%c');
$map = array(
'%s' => $session->getCurrentAssessmentSection()->getTitle(),
'%p' => $itemPosition,
'%c' => $itemCount
);
return strtr($format, $map);
} else {
return __('finished');
}
} | php | {
"resource": ""
} |
q244275 | TreeItemLookup.getItems | validation | public function getItems(\core_kernel_classes_Class $itemClass, array $propertyFilters = [], $offset = 0, $limit = 30)
{
$data = $this->getTreeResourceLookupService()->getResources($itemClass, [], $propertyFilters, $offset, $limit);
return $this->formatTreeData($data);
} | php | {
"resource": ""
} |
q244276 | StorageManager.exists | validation | protected function exists($key)
{
return isset($this->cache[$key]) && in_array($this->cache[$key]['state'], [self::STATE_ALIGNED, self::STATE_PENDING_WRITE]);
} | php | {
"resource": ""
} |
q244277 | StorageManager.persistCacheEntry | validation | protected function persistCacheEntry($key)
{
$success = true;
if (isset($this->cache[$key])) {
$cache = $this->cache[$key];
switch ($cache['state']) {
case self::STATE_PENDING_WRITE:
$success = $this->getStorage()->set($cache['userId'], $cache['callId'], $cache['data']);
if (!$success) {
throw new \common_exception_Error('Can\'t write into test runner state storage at '.static::class);
}
$this->cache[$key]['state'] = self::STATE_ALIGNED;
break;
case self::STATE_PENDING_DELETE:
$success = $this->getStorage()->del($cache['userId'], $cache['callId']);
if ($success) {
unset($this->cache[$key]);
}
break;
}
}
return $success;
} | php | {
"resource": ""
} |
q244278 | StorageManager.set | validation | public function set($userId, $callId, $data)
{
$key = $this->getCacheKey($userId, $callId);
$cache = $this->getFromCache($key);
if (is_null($cache) || $cache != $data) {
$this->putInCache($key, $userId, $callId, $data, self::STATE_PENDING_WRITE);
}
return true;
} | php | {
"resource": ""
} |
q244279 | StorageManager.get | validation | public function get($userId, $callId)
{
$key = $this->getCacheKey($userId, $callId);
if (!isset($this->cache[$key])) {
$data = $this->getStorage()->get($userId, $callId);
$state = is_null($data) ? self::STATE_NOT_FOUND : self::STATE_ALIGNED;
$this->putInCache($key, $userId, $callId, $data, $state);
}
return $this->getFromCache($key);
} | php | {
"resource": ""
} |
q244280 | StorageManager.has | validation | public function has($userId, $callId)
{
$key = $this->getCacheKey($userId, $callId);
if (!isset($this->cache[$key])) {
return $this->getStorage()->has($userId, $callId);
}
return $this->exists($key);
} | php | {
"resource": ""
} |
q244281 | StorageManager.del | validation | public function del($userId, $callId)
{
$key = $this->getCacheKey($userId, $callId);
$this->putInCache($key, $userId, $callId, null, self::STATE_PENDING_DELETE);
return true;
} | php | {
"resource": ""
} |
q244282 | StorageManager.persist | validation | public function persist($userId = null, $callId = null)
{
if ($userId && $callId) {
$keys = [$this->getCacheKey($userId, $callId)];
} else {
$keys = array_keys($this->cache);
}
$success = true;
foreach ($keys as $key) {
if (!$this->persistCacheEntry($key)) {
$success = false;
}
}
return $success;
} | php | {
"resource": ""
} |
q244283 | QtiTimeStoragePackedFormat.packTimeLine | validation | protected function packTimeLine(&$timeLine)
{
$epoch = $this->getEpoch();
$data = [
self::STORAGE_KEY_TIMELINE_INDEX => [],
self::STORAGE_KEY_TIMELINE_TAGS => [],
self::STORAGE_KEY_TIMELINE_POINTS => [],
self::STORAGE_KEY_TIMELINE_EPOCH => $epoch,
];
// Will split tags from the list of TimePoint, and put them into a dedicated index.
// The other TimePoint info are put in a simple array with predictable order, this way: [target, type, timestamp].
// To save more space a reference value is removed from each timestamp.
$index = 0;
foreach ($timeLine->getPoints() as &$point) {
/** @var TimePoint $point */
$data[self::STORAGE_KEY_TIMELINE_POINTS][$index] = [$point->getTarget(), $point->getType(), round($point->getTimestamp() - $epoch, 6)];
foreach ($point->getTags() as &$tag) {
$data[self::STORAGE_KEY_TIMELINE_INDEX][$tag][] = $index;
}
$index++;
}
// try to reduce the size of the index by simplifying those that target all TimePoint
if ($index) {
foreach ($data[self::STORAGE_KEY_TIMELINE_INDEX] as $tag => &$list) {
if (count($list) == $index) {
unset($data[self::STORAGE_KEY_TIMELINE_INDEX][$tag]);
$data[self::STORAGE_KEY_TIMELINE_TAGS][] = $tag;
}
}
} else {
$data = [];
}
return $data;
} | php | {
"resource": ""
} |
q244284 | QtiTimeStoragePackedFormat.unpackTimeLine | validation | protected function unpackTimeLine(&$data)
{
$timeLine = new QtiTimeLine();
// the stored data can be packed or not
if (isset($data[self::STORAGE_KEY_TIMELINE_POINTS])) {
// get the reference value used to compress the timestamps
$epoch = 0;
if (isset($data[self::STORAGE_KEY_TIMELINE_EPOCH])) {
$epoch = $data[self::STORAGE_KEY_TIMELINE_EPOCH];
}
// rebuild the TimeLine from the list of stored TimePoint
$tags = $data[self::STORAGE_KEY_TIMELINE_TAGS];
foreach ($data[self::STORAGE_KEY_TIMELINE_POINTS] as &$dataPoint) {
$point = new TimePoint($tags, $dataPoint[2] + $epoch, $dataPoint[1], $dataPoint[0]);
$timeLine->add($point);
}
// reassign the tags from the stored index
$points = $timeLine->getPoints();
foreach ($data[self::STORAGE_KEY_TIMELINE_INDEX] as $tag => &$list) {
foreach ($list as $index) {
$points[$index]->addTag($tag);
}
}
} else {
$timeLine->fromArray($data);
}
return $timeLine;
} | php | {
"resource": ""
} |
q244285 | QtiTimeStoragePackedFormat.encode | validation | public function encode($data)
{
if (is_array($data)) {
$encodedData = [
self::STORAGE_KEY_FORMAT => $this->getFormat(),
self::STORAGE_KEY_VERSION => $this->getVersion(),
];
foreach ($data as $key => &$value) {
if ($value instanceof TimeLine) {
$encodedData[$key] = $this->packTimeLine($value);
} else {
$encodedData[$key] = &$value;
}
}
return json_encode($encodedData);
}
return json_encode($data);
} | php | {
"resource": ""
} |
q244286 | RecompileItemsElements.getAssessmentsFromDelivery | validation | protected function getAssessmentsFromDelivery(\core_kernel_classes_Resource $compiledDelivery)
{
/** @var UnionAssignmentService $unionAssignmentService */
$unionAssignmentService = $this->getServiceLocator()->get(UnionAssignmentService::SERVICE_ID);
$runtime = $unionAssignmentService->getRuntime($compiledDelivery);
$inputParameters = \tao_models_classes_service_ServiceCallHelper::getInputValues($runtime, []);
$testDefinition = \taoQtiTest_helpers_Utils::getTestDefinition($inputParameters['QtiTestCompilation']);
$assessmentItemRefs = $testDefinition->getComponentsByClassName('assessmentItemRef');
$this->report->add(
new Report(
Report::TYPE_INFO,
"Starting to recompile items for delivery {$compiledDelivery->getLabel()} with identifier {$compiledDelivery->getUri()}:"
)
);
$count = 0;
/** @var AssessmentItemRef $assessmentItemRef */
foreach ($assessmentItemRefs as $assessmentItemRef) {
$directoryIds = explode('|', $assessmentItemRef->getHref());
$item = $this->getResource($directoryIds[0]);
$properties = [];
foreach ($item->getRdfTriples() as $triple) {
$properties[$triple->predicate] = $triple->object;
}
if ($properties) {
$directory = \tao_models_classes_service_FileStorage::singleton()->getDirectoryById($directoryIds[2]);
$languages = $item->getUsedLanguages(
$this->getProperty(\taoItems_models_classes_ItemsService::PROPERTY_ITEM_CONTENT)
);
foreach ($languages as $lang) {
$path = $lang.DIRECTORY_SEPARATOR.QtiJsonItemCompiler::METADATA_FILE_NAME;
if (!$directory->has($path)) {
$this->writeMetadata($item, $directory, $path, $properties);
$count++;
}
}
}
}
$this->report->add(new Report(Report::TYPE_INFO, "Was updated {$count} items."));
} | php | {
"resource": ""
} |
q244287 | RunnerToolStates.saveToolStates | validation | protected function saveToolStates()
{
$toolStateParameter = 'toolStates';
if ($this->hasRequestParameter($toolStateParameter)) {
// since the parameter content is a JSON string
// we need to load it using the raw mode
$param = $this->getRawRequestParameter($toolStateParameter);
if ($param) {
$toolStates = json_decode($param, true);
if (count($toolStates) > 0) {
array_walk($toolStates, function (&$toolState) {
$toolState = json_encode($toolState);
});
$this->getRunnerService()->setToolsStates(
$this->getServiceContext(),
$toolStates
);
return true;
}
}
}
return false;
} | php | {
"resource": ""
} |
q244288 | RunnerToolStates.getToolStates | validation | protected function getToolStates()
{
$toolStates = $this->getRunnerService()->getToolsStates($this->getServiceContext());
array_walk($toolStates, function (&$toolState) {
$toolState = json_decode($toolState);
});
return $toolStates;
} | php | {
"resource": ""
} |
q244289 | QtiRunnerServiceContext.init | validation | public function init()
{
// code borrowed from the previous implementation, maybe obsolete...
/** @var SessionStateService $sessionStateService */
$sessionStateService = $this->getServiceManager()->get(SessionStateService::SERVICE_ID);
$sessionStateService->resumeSession($this->getTestSession());
$this->retrieveItemIndex();
} | php | {
"resource": ""
} |
q244290 | QtiRunnerServiceContext.initCompilationDirectory | validation | protected function initCompilationDirectory()
{
$fileStorage = \tao_models_classes_service_FileStorage::singleton();
$directoryIds = explode('|', $this->getTestCompilationUri());
$directories = array(
'private' => $fileStorage->getDirectoryById($directoryIds[0]),
'public' => $fileStorage->getDirectoryById($directoryIds[1])
);
$this->compilationDirectory = $directories;
} | php | {
"resource": ""
} |
q244291 | QtiRunnerServiceContext.initStorage | validation | protected function initStorage()
{
/** @var DeliveryServerService $deliveryServerService */
$deliveryServerService = $this->getServiceManager()->get(DeliveryServerService::SERVICE_ID);
$resultStore = $deliveryServerService->getResultStoreWrapper($this->getTestExecutionUri());
$testResource = new \core_kernel_classes_Resource($this->getTestDefinitionUri());
$sessionManager = new \taoQtiTest_helpers_SessionManager($resultStore, $testResource);
$seeker = new BinaryAssessmentTestSeeker($this->getTestDefinition());
$userUri = $this->getUserUri();
$config = \common_ext_ExtensionsManager::singleton()->getExtensionById('taoQtiTest')->getConfig('testRunner');
$storageClassName = $config['test-session-storage'];
$this->storage = new $storageClassName($sessionManager, $seeker, $userUri);
$this->sessionManager = $sessionManager;
} | php | {
"resource": ""
} |
q244292 | QtiRunnerServiceContext.retrieveItemIndex | validation | protected function retrieveItemIndex()
{
$this->itemIndex = new QtiTestCompilerIndex();
try {
$directories = $this->getCompilationDirectory();
$data = $directories['private']->read(taoQtiTest_models_classes_QtiTestService::TEST_COMPILED_INDEX);
if ($data) {
$this->itemIndex->unserialize($data);
}
} catch(\Exception $e) {
\common_Logger::d('Ignoring file not found exception for Items Index');
}
} | php | {
"resource": ""
} |
q244293 | QtiRunnerServiceContext.getItemIndexValue | validation | public function getItemIndexValue($id, $name)
{
return $this->itemIndex->getItemValue($id, \common_session_SessionManager::getSession()->getInterfaceLanguage(), $name);
} | php | {
"resource": ""
} |
q244294 | QtiRunnerServiceContext.getCatEngine | validation | public function getCatEngine(RouteItem $routeItem = null)
{
$compiledDirectory = $this->getCompilationDirectory()['private'];
$adaptiveSectionMap = $this->getServiceManager()->get(CatService::SERVICE_ID)->getAdaptiveSectionMap($compiledDirectory);
$routeItem = $routeItem ? $routeItem : $this->getTestSession()->getRoute()->current();
$sectionId = $routeItem->getAssessmentSection()->getIdentifier();
$catEngine = false;
if (isset($adaptiveSectionMap[$sectionId])) {
$catEngine = $this->getServiceManager()->get(CatService::SERVICE_ID)->getEngine($adaptiveSectionMap[$sectionId]['endpoint']);
}
return $catEngine;
} | php | {
"resource": ""
} |
q244295 | QtiRunnerServiceContext.persistSeenCatItemIds | validation | public function persistSeenCatItemIds($seenCatItemId)
{
$sessionId = $this->getTestSession()->getSessionId();
$items = $this->getServiceManager()->get(ExtendedStateService::SERVICE_ID)->getCatValue(
$sessionId,
$this->getCatSection()->getSectionId(),
'cat-seen-item-ids'
);
if (!$items) {
$items = [];
} else {
$items = json_decode($items);
}
if (!in_array($seenCatItemId, $items)) {
$items[] = $seenCatItemId;
}
$this->getServiceManager()->get(ExtendedStateService::SERVICE_ID)->setCatValue(
$sessionId,
$this->getCatSection()->getSectionId(),
'cat-seen-item-ids',
json_encode($items)
);
} | php | {
"resource": ""
} |
q244296 | QtiRunnerServiceContext.getLastCatItemOutput | validation | public function getLastCatItemOutput()
{
$sessionId = $this->getTestSession()->getSessionId();
$itemOutput = $this->getServiceManager()->get(ExtendedStateService::SERVICE_ID)->getCatValue(
$sessionId,
$this->getCatSection()->getSectionId(),
'cat-item-output'
);
$output = [];
if (!is_null($itemOutput)) {
$rawData = json_decode($itemOutput, true);
foreach ($rawData as $result) {
/** @var ItemResult $itemResult */
$itemResult = ItemResult::restore($result);
$output[$itemResult->getItemRefId()] = $itemResult;
}
}
return $output;
} | php | {
"resource": ""
} |
q244297 | QtiRunnerServiceContext.persistLastCatItemOutput | validation | public function persistLastCatItemOutput(array $lastCatItemOutput)
{
$sessionId = $this->getTestSession()->getSessionId();
$this->getServiceManager()->get(ExtendedStateService::SERVICE_ID)->setCatValue(
$sessionId,
$this->getCatSection()->getSectionId(),
'cat-item-output',
json_encode($lastCatItemOutput)
);
} | php | {
"resource": ""
} |
q244298 | QtiRunnerServiceContext.isAdaptive | validation | public function isAdaptive(AssessmentItemRef $currentAssessmentItemRef = null)
{
return $this->getServiceManager()->get(CatService::SERVICE_ID)->isAdaptive($this->getTestSession(), $currentAssessmentItemRef);
} | php | {
"resource": ""
} |
q244299 | QtiRunnerServiceContext.containsAdaptive | validation | public function containsAdaptive()
{
$adaptiveSectionMap = $this->getServiceManager()->get(CatService::SERVICE_ID)->getAdaptiveSectionMap($this->getCompilationDirectory()['private']);
return !empty($adaptiveSectionMap);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.