_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q7300 | DiagramUML.getAttributes | train | public function getAttributes(\DOMElement $diaObject)
{
$xpath = $diaObject->getNodePath() . '/dia:attribute[@name="attributes"]/*';
$nodeList = $this->engine->query($xpath);
if ($nodeList->length > 0) {
return $nodeList;
}
return false;
} | php | {
"resource": ""
} |
q7301 | DiagramUML.getElement | train | public function getElement(\DOMElement $nodeList, $level = 0, $showPaths = false)
{
$tabs = str_repeat("\t", $level);
$output = '';
if (!$showPaths) {
$output = "";
foreach ($nodeList as $attribute) {
$output .= $tabs . $attribute->nodeName . " = " . $attribute->nodeValue . "\n";
}
$output .= $tabs . $nodeList->nodeName . " = " . $nodeList->nodeValue . "\n";
} else {
$output .= $nodeList->getNodePath() . "\n";
}
foreach ($nodeList->childNodes as $childObject) {
if ($childObject instanceof \DOMElement) {
$output .= $this->getElement($childObject, $level + 1, $showPaths);
} elseif ($showPaths) {
$output .= $childObject->getNodePath() . "\n";
}
}
return $output;
} | php | {
"resource": ""
} |
q7302 | DiagramUML.getPaths | train | public function getPaths(\DOMElement $nodeList, $level = 0)
{
$output = $nodeList->getNodePath();
foreach ($nodeList->childNodes as $childObject) {
$output .= $childObject->getNodePath() . "\n";
if ($childObject instanceof \DOMElement) {
$output .= $this->getElement($childObject, $level + 1, true);
}
}
return $output;
} | php | {
"resource": ""
} |
q7303 | DiagramUML.retriveAttributeType | train | public function retriveAttributeType(\DOMElement $element)
{
$name = $this->engine->query($element->getNodePath() . '/dia:attribute[@name="type"]/dia:string');
return $this->cleanString($name->item(0)->nodeValue);
} | php | {
"resource": ""
} |
q7304 | DiagramUML.retriveAttributeVisibility | train | public function retriveAttributeVisibility(\DOMElement $element)
{
$name = $this->engine->query($element->getNodePath() . '/dia:attribute[@name="visibility"]/dia:enum');
$propertyVisibility = $name->item(0)->attributes->getNamedItem('val')->nodeValue;
return self::$propertyVisibilityTypes[$propertyVisibility];
} | php | {
"resource": ""
} |
q7305 | DiagramUML.retriveLayerObjects | train | public function retriveLayerObjects()
{
$classes = [];
foreach ($this->engine->query('//dia:diagram/dia:layer') as $layer) {
if ($layer->nodeName == 'dia:layer') {
foreach ($layer->childNodes as $elementObject) {
if ($elementObject->nodeName == 'dia:object') {
foreach ($elementObject->childNodes as $childNodesAttributes) {
if ($childNodesAttributes->nodeName == 'dia:attribute' &&
$childNodesAttributes->attributes->getNamedItem("name")->nodeValue == 'name'
) {
$name = str_replace(['#'], [''], $childNodesAttributes->childNodes->item(1)->nodeValue);
$classes[$name] = $elementObject;
}
}
}
}
}
}
return $classes;
} | php | {
"resource": ""
} |
q7306 | AbstractCURLRequest.mergeHeaders | train | private function mergeHeaders() {
// Initialize the merged headers.
$mergedHeaders = [];
// Handle each header.
foreach (array_merge($this->getConfiguration()->getHeaders(), $this->getHeaders()) as $key => $value) {
$mergedHeaders[] = implode(": ", [$key, $value]);
}
// Return the merged headers.
return $mergedHeaders;
} | php | {
"resource": ""
} |
q7307 | AbstractCURLRequest.mergeURL | train | private function mergeURL() {
// Initialize the merged URL.
$mergedURL = [];
$mergedURL[] = $this->getConfiguration()->getHost();
if (null !== $this->getResourcePath() && "" !== $this->getResourcePath()) {
$mergedURL[] = $this->getResourcePath();
}
// Return the merged URL.
return implode("/", $mergedURL);
} | php | {
"resource": ""
} |
q7308 | AbstractCURLRequest.parseHeader | train | private function parseHeader($rawHeader) {
// Initialize the headers.
$headers = [];
$key = "";
// Handle each header.
foreach (explode("\n", $rawHeader) as $h) {
$h = explode(":", $h, 2);
if (true === isset($h[1])) {
if (false === isset($headers[$h[0]])) {
$headers[$h[0]] = trim($h[1]);
} elseif (true === is_array($headers[$h[0]])) {
$headers[$h[0]] = array_merge($headers[$h[0]], [trim($h[1])]);
} else {
$headers[$h[0]] = array_merge([$headers[$h[0]]], [trim($h[1])]);
}
$key = $h[0];
} else {
if ("\t" === substr($h[0], 0, 1)) {
$headers[$key] .= "\r\n\t" . trim($h[0]);
} elseif (!$key) {
$headers[0] = trim($h[0]);
}
trim($h[0]);
}
}
// Return the headers.
return $headers;
} | php | {
"resource": ""
} |
q7309 | FabricationEngine.registerNamespace | train | public function registerNamespace($prefix, $uri)
{
$this->initializeXPath();
$this->xpath->registerNamespace($prefix, $uri);
} | php | {
"resource": ""
} |
q7310 | FabricationEngine.getSpecification | train | public function getSpecification($element = '')
{
if (isset($element) && $element !== '') {
$spec = $this->pattern->specification[$this->getOption('doctype')][$element];
} else {
$spec = $this->pattern->specification[$this->getOption('doctype')];
}
return $spec;
} | php | {
"resource": ""
} |
q7311 | FabricationEngine.run | train | public function run($data = '', $load = 'string', $type = 'html')
{
if (!empty($data)) {
$this->$type = $type;
// Check if data is a path to a valid file then load into buffer.
if (file_exists($data)) {
$pathHash = md5($data);
$this->views[$pathHash] = $data;
}
switch ($load . '.' . $type) {
default:
return false;
// load string html
case 'string.html':
if (@$this->loadHTML($data)) {
$objectName = 'Fabrication\\Html';
$this->pattern = new $objectName($this);
$this->mapSymbols();
return true;
} else {
return false;
}
// load file html
case 'file.html':
if (@$this->loadHTMLFile($data)) {
$this->mapSymbols();
return true;
} else {
return false;
}
// load string xml
case 'string.xml':
if ($this->loadXML($data)) {
$this->mapSymbols();
return true;
} else {
return false;
}
// load file xml
case 'file.xml':
$contents = file_get_contents($data);
if (@$this->loadXML($contents)) {
$this->mapSymbols();
return true;
} else {
return false;
}
}
}
return;
} | php | {
"resource": ""
} |
q7312 | FabricationEngine.mapSymbols | train | public function mapSymbols()
{
foreach ($this->input as $key => $input) {
foreach ($this->symbols as $skey => $svalue) {
if (substr($key, 0, 1) == $svalue) {
$keyWithoutSymbol = str_replace($svalue, '', $key);
if (is_string($input)) {
$this->setElementBy($skey, $keyWithoutSymbol, $input);
}
if (is_array($input)) {
$this->setElementBy($skey, $keyWithoutSymbol, $input);
}
if (is_object($input)) {
$this->setElementBy($skey, $keyWithoutSymbol, $input);
}
}
}
}
} | php | {
"resource": ""
} |
q7313 | FabricationEngine.saveHTML | train | public function saveHTML($path = '', $trim = true)
{
if (is_string($path) && $path !== '') {
// no processing as just return xpath html result no adding doctype.
$this->output['raw'] = $this->view($path);
} else {
$this->output['raw'] = parent::saveHTML();
}
$this->outputProcess();
$raw = $this->output['raw'];
return $trim ? trim($raw) : $raw;
} | php | {
"resource": ""
} |
q7314 | FabricationEngine.saveFabric | train | public function saveFabric($type = 'html')
{
switch ($type) {
case 'html':
$this->output['raw'] = parent::saveHTML();
break;
case 'xml':
$this->output['raw'] = parent::saveXML();
break;
}
// default output process.
$this->outputProcess();
return $this->getDoctype() . trim($this->output['raw']);
} | php | {
"resource": ""
} |
q7315 | FabricationEngine.outputProcess | train | public function outputProcess()
{
// remove doctype.
$this->output['raw'] = preg_replace(
'/^<!DOCTYPE[^>]+>/U', '', $this->output['raw']
);
if ($this->outputProcess && $this->getOption('process')) {
// Remove doctype added by DOMDocument (hacky)
$this->output['raw'] = $this->getDoctype() . $this->output['raw'];
/**
* Process img, br, hr, tags, change html to xhtml.
*
* <img> <img src=""> <img src="/image.png">
* Are changed to xhtml
* <img /> <img src="" /> <img src="/image.png" />
*/
if ($this->getOption('process.body.image')) {
$this->output['raw'] = preg_replace(
'/<img(.*)>/sU', '<img\\1 />', $this->output['raw']
);
}
if ($this->getOption('process.body.br')) {
$this->output['raw'] = preg_replace(
'/<br(.*)>/sU', '<br\\1 />', $this->output['raw']
);
}
if ($this->getOption('process.body.hr')) {
$this->output['raw'] = preg_replace(
'/<hr(.*)>/sU', '<hr\\1 />', $this->output['raw']
);
}
// Trim whitespace need this to get exactly the wanted data back for test cases, mmm.
$this->output['raw'] = trim($this->output['raw']);
return $this->outputProcess;
}
return $this->outputProcess;
} | php | {
"resource": ""
} |
q7316 | FabricationEngine.dump | train | public static function dump($data, $return = false)
{
$result = '';
if (Fabrication::isCli()) {
$end = "\n";
} else {
$end = "<br />\n";
}
if (is_object($data)) {
$classname = get_class($data);
$result = str_repeat('-', 80) . $end .
"\t" . __METHOD__ . ' Type: ' . gettype($data) . "\tReturn:" . var_export($return, true) . $end .
str_repeat('-', 80) . $end .
"Object Instance: $classname: $end" .
"Object Methods $end";
$class_methods = get_class_methods($data);
if (count($class_methods) > 0) {
foreach ($class_methods as $method) {
$result.="\t" . $method . $end;
}
} else {
$result.="No methods found.$end";
}
$result.= $end;
$result.= "Object XPath:$end";
$result.= $end;
switch ($classname) {
case 'DOMAttr':
$result.= "DOMAttr XPath: {$data->getNodePath()}$end" .
$data->ownerDocument->saveXML($data);
break;
case 'DOMDocument':
$result.= "DOMDocument XPath: {$data->getNodePath()}$end" .
$data->saveXML($data);
break;
case 'DOMElement':
$result.= "DOMElement XPath: {$data->getNodePath()}$end" .
$data->ownerDocument->saveXML($data);
break;
case 'DOMNodeList':
for ($i = 0; $i < $data->length; $i++) {
$result.= "DOMNodeList Item #$i, " .
"XPath: {$data->item($i)->getNodePath()}$end" .
"{$data->item($i)->ownerDocument->saveXML($data->item($i))}$end";
}
break;
default: $result.= var_export($data, true);
}
}
if (is_array($data)) {
$result = $end .
$end .
str_repeat('-', 80) . $end .
"| DUMP Type:" . gettype($data) . "\tReturn:" . var_export($return, true) . $end .
str_repeat('-', 80) . $end .
$end;
}
if (is_string($data)) {
$result = var_export($data, true);
}
if (is_int($data)) {
$result = var_export($data, true);
}
if ($return) {
return $result . $end;
} else {
echo $result . $end;
}
} | php | {
"resource": ""
} |
q7317 | FabricationEngine.createPattern | train | public function createPattern($name = 'html', $attributes = array(), $data = array())
{
$patternName = ucfirst($name);
$objectName = 'Library\Pattern\\' . $patternName;
$pattern = new $objectName($this, $attributes, $data);
return $pattern;
} | php | {
"resource": ""
} |
q7318 | FabricationEngine.specification | train | public function specification($pattern = 'html', $value = '', $attributes = [], $contract = [])
{
if (!is_array($contract)) {
return;
}
// create the root specification element.
$this->appendChild(
$this->create($pattern, $value, $attributes, $contract)
);
return $this;
} | php | {
"resource": ""
} |
q7319 | FabricationEngine.template | train | public function template($pattern, $dataset = array(), $map = 'id')
{
if (count($dataset) == 0) {
return false;
}
try {
$template = '';
if (is_string($pattern)) {
$engine = new FabricationEngine();
$engine->setOption('doctype', 'html.5');
$engine->loadHTML($pattern);
$templateDiv = $engine->getDiv();
if ($templateDiv) {
$template = $templateDiv->item(0);
}
}
if (is_object($pattern)) {
$template = $pattern;
}
// Create an empty container, from the template node details.
if (is_object($template)) {
$container = $this->create($template->nodeName, $template->nodeValue);
foreach ($dataset as $key => $row) {
// process the template child nodes.
foreach ($template->childNodes as $child) {
if ($child->nodeName == '#text') {
continue;
}
if (is_object($child->attributes->getNamedItem($map))) {
$mappedName = $child->attributes->getNamedItem($map)->nodeName;
$mappedValue = $child->attributes->getNamedItem($map)->nodeValue;
$nodeAttributes = array();
foreach ($child->attributes as $attribute) {
$nodeAttributes[$attribute->nodeName] = $attribute->nodeValue;
}
if (in_array($mappedValue, array_keys($row))) {
// create the mapped node attribute with updated numeric key.
$nodeAttributes[$mappedName] = $mappedValue . '_' . ($key + 1);
// fabricate the new child nodes.
$node = $this->create($child->nodeName, $row[$mappedValue], $nodeAttributes
);
$container->appendChild($node);
}
}
}
}
return $container;
}
return false;
} catch (\Exception $ex) {
echo $ex->getMessage();
}
} | php | {
"resource": ""
} |
q7320 | FabricationEngine.view | train | public function view($path = '', $trim = true, $return = true)
{
if (!empty($path)) {
$results = $this->query($path);
// create an empty template object for xpath query results.
$template = new FabricationEngine();
foreach ($results as $result) {
$node = $template->importNode($result, true);
$template->appendChild($node);
}
if ($trim) {
$buffer = trim($template->saveHTML());
} else {
$buffer = $template->saveHTML();
}
} else {
if ($trim) {
$buffer = trim($this->saveHTML());
} else {
$buffer = $this->saveHTML();
}
}
if ($return) {
return $buffer;
}
echo $buffer;
} | php | {
"resource": ""
} |
q7321 | FabricationEngine.query | train | public function query($path)
{
$this->initializeXPath();
if ($path) {
return $this->xpath->query($path);
}
return false;
} | php | {
"resource": ""
} |
q7322 | FabricationEngine.output | train | public function output($key = '', $query = '', $options = array())
{
// ensure key based retrievals are returned first/fast if empty query.
if (empty($query) && isset($this->input[$key])) {
return $this->input[$key];
}
// setup standard options.
if (empty($options)) {
$options = array('return' => true, 'tags' => true, 'echo' => false);
}
// templated output patterns
$output = $this->templateTextElement($key, $query, $options);
if (array_key_exists('return', $options)) {
if ($options['return']) {
return $output;
}
} else {
return false;
}
} | php | {
"resource": ""
} |
q7323 | FabricationEngine.convert | train | public function convert($data)
{
$data = trim($data);
try {
// Buffer engine used to convert the html string into DOMElements,
$engine = new FabricationEngine;
$engine->run($data);
// Check if the body is null, so use the head if avaliable.
if ($engine->getBody()->item(0) == null) {
$node = $engine->getHead()->item(0)->childNodes->item(0);
return $this->importNode($node, true);
}
if ($engine->getBody()->item(0) !== null) {
// body first item.
$node = $engine->getBody()->item(0)->childNodes->item(0);
return $this->importNode($node, true);
}
return false;
} catch (\Exception $e) {
return('FabricationEngine :: convert : ' . $e->getMessage());
}
} | php | {
"resource": ""
} |
q7324 | FabricationEngine.htmlToElement | train | public function htmlToElement($html)
{
// Buffer engine used to convert the html string into DOMElements,
$fabrication = new FabricationEngine;
$fabrication->run($html);
// Retrive xpath element from the FabricationEngine.
$element = $this->query('//html/body')->item(0);
// Append the new DOM Element(s) to the found DOMElement.
$element->appendChild(
$this->importNode(
$fabrication->query($this->xpath . '/*')->item(0)
, true
)
);
return $element;
} | php | {
"resource": ""
} |
q7325 | FabricationEngine.setElementBy | train | public function setElementBy($element, $value, $nodeValue)
{
$xql = "//*[@$element='$value']";
if (is_object($nodeValue)) {
$result = $this->query($xql)->item(0)->appendChild($this->importNode($nodeValue, true));
} else {
$result = $this->query($xql)->item(0)->nodeValue = $nodeValue;
}
return $result;
} | php | {
"resource": ""
} |
q7326 | FabricationEngine.setHtml | train | public function setHtml($q, $value)
{
$this->getHtml($q)->item(0)->nodeValue = "$value";
return $this->getHtml($q)->item(0);
} | php | {
"resource": ""
} |
q7327 | FabricationEngine.timeTaken | train | public function timeTaken()
{
$timeStop = microtime(true);
$timeTaken = (float) substr(-($this->timeStarted - $timeStop), 0, 5);
return $timeTaken;
} | php | {
"resource": ""
} |
q7328 | CustomFields.getFields | train | public static function getFields(string $module)
{
$modules = Modules::findFirstByName($module);
if ($modules) {
return self::find([
'modules_id = ?0',
'bind' => [$modules->id],
'columns' => 'name, label, type'
]);
}
return null;
} | php | {
"resource": ""
} |
q7329 | AbstractNode.addNode | train | public function addNode(AbstractNode $node) {
$node->parent = $this;
$this->index[$node->id] = count($this->nodes);
$this->nodes[] = $node;
return $this;
} | php | {
"resource": ""
} |
q7330 | AbstractNode.getNodeAt | train | public function getNodeAt($position) {
if (0 <= $position && $position <= count($this->nodes) - 1) {
return $this->nodes[$position];
}
return null;
} | php | {
"resource": ""
} |
q7331 | AbstractNode.getNodeById | train | public function getNodeById($id, $recursively = false) {
$found = null;
if (true === array_key_exists($id, $this->index)) {
$found = $this->getNodeAt($this->index[$id]);
}
if (null === $found && true === $recursively) {
foreach ($this->nodes as $current) {
$found = $current->getNodeById($id, $recursively);
if (null !== $found) {
break;
}
}
}
return $found;
} | php | {
"resource": ""
} |
q7332 | AbstractNode.removeNode | train | public function removeNode(AbstractNode $node) {
if (true === array_key_exists($node->id, $this->index)) {
unset($this->nodes[$this->index[$node->id]]);
unset($this->index[$node->id]);
$node->parent = null;
}
return $this;
} | php | {
"resource": ""
} |
q7333 | Router.getDocBlockFactory | train | public static function getDocBlockFactory(): DocBlockFactory
{
if (is_null(self::$docBlockFactory)) {
self::$docBlockFactory = DocBlockFactory::createInstance();
}
return self::$docBlockFactory;
} | php | {
"resource": ""
} |
q7334 | Router.getHttpMethod | train | private function getHttpMethod(): string
{
if (!empty($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
$method = mb_strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
} else {
$method = mb_strtoupper($_SERVER['REQUEST_METHOD']);
}
switch ($method) {
case 'GET':
return static::HTTP_METHOD_GET;
case 'HEAD':
return static::HTTP_METHOD_HEAD;
case 'POST':
return static::HTTP_METHOD_POST;
case 'OPTIONS':
return static::HTTP_METHOD_OPTIONS;
case 'CONNECT':
return static::HTTP_METHOD_CONNECT;
case 'TRACE':
return static::HTTP_METHOD_TRACE;
case 'PUT':
return static::HTTP_METHOD_PUT;
case 'DELETE':
return static::HTTP_METHOD_DELETE;
default:
return static::HTTP_METHOD_UNKNOWN;
}
} | php | {
"resource": ""
} |
q7335 | Router.getHttpPath | train | private function getHttpPath(): ?string
{
$path = null;
if (isset($_SERVER['REQUEST_URI'])) {
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
}
return $path;
} | php | {
"resource": ""
} |
q7336 | Router.getHttpHeaders | train | protected function getHttpHeaders(string $prefix = null): array
{
$headers = [];
// Get all headers
if (function_exists('\getallheaders')) {
$headers = \getallheaders() ?: [];
} else {
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
} else {
if ($name === 'CONTENT_TYPE') {
$headers['Content-Type'] = $value;
}
}
}
}
// Headers filter
if (!empty($prefix)) {
$prefixLength = mb_strlen($prefix);
$headers =
array_filter(
$headers,
function ($key) use ($prefix, $prefixLength) {
return substr($key, 0, $prefixLength) == $prefix;
}, ARRAY_FILTER_USE_KEY);
}
return $headers;
} | php | {
"resource": ""
} |
q7337 | RdfHelpers.getNodeInSparqlFormat | train | public function getNodeInSparqlFormat(Node $node, $var = null)
{
if ($node->isConcrete()) {
return $node->toNQuads();
}
if (null !== $var) {
return '?'.$var;
} else {
return '?'.uniqid('tempVar');
}
} | php | {
"resource": ""
} |
q7338 | RdfHelpers.getQueryType | train | public function getQueryType($query)
{
/**
* First we get rid of all PREFIX information.
*/
$adaptedQuery = preg_replace('/PREFIX\s+[a-z0-9\-]+\:\s*\<[a-z0-9\:\/\.\#\-\~\_]+\>/si', '', $query);
// remove whitespace lines and trailing whitespaces
$adaptedQuery = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", '', trim($adaptedQuery));
// only lower chars
$adaptedQuery = strtolower($adaptedQuery);
/**
* After we know the type, we initiate the according class and return it.
*/
$firstPart = substr($adaptedQuery, 0, 3);
switch ($firstPart) {
// ASK
case 'ask':
return 'askQuery';
// CONSTRUCT
case 'con':
return 'constructQuery';
// DESCRIBE
case 'des':
return 'describeQuery';
/*
* If we land here, we have to use a higher range of characters
*/
default:
$firstPart = substr($adaptedQuery, 0, 6);
switch ($firstPart) {
// CLEAR GRAPH
case 'clear ':
return 'graphQuery';
// CREATE GRAPH
// CREATE SILENT GRAPH
case 'create':
return 'graphQuery';
// DELETE DATA
case 'delete':
return 'updateQuery';
// DROP GRAPH
case 'drop g':
return 'graphQuery';
// DROP SILENT GRAPH
case 'drop s':
return 'graphQuery';
// INSERT DATA
// INSERT INTO
case 'insert':
return 'updateQuery';
// SELECT
case 'select':
return 'selectQuery';
default:
// check if query is of type: WITH <http:// ... > DELETE { ... } WHERE { ... }
// TODO make it more precise
if (false !== strpos($adaptedQuery, 'with')
&& false !== strpos($adaptedQuery, 'delete')
&& false !== strpos($adaptedQuery, 'where')) {
return 'updateQuery';
// check if query is of type: WITH <http:// ... > DELETE { ... }
// TODO make it more precise
} elseif (false !== strpos($adaptedQuery, 'with')
&& false !== strpos($adaptedQuery, 'delete')) {
return 'updateQuery';
}
}
}
throw new \Exception('Unknown query type "'.$firstPart.'" for query: '.$adaptedQuery);
} | php | {
"resource": ""
} |
q7339 | ArraySerialized._afterLoad | train | public function _afterLoad()
{
$value = $this->getValue();
/** @noinspection ExceptionsAnnotatingAndHandlingInspection */
/** @noinspection PhpParamsInspection */
$this->setValue(empty($value) ? false : $this->encoder->decode($value));
parent::_afterLoad();
} | php | {
"resource": ""
} |
q7340 | ArraySerialized.removeDuplicates | train | public function removeDuplicates($values)
{
foreach ($values as $key => $option) {
$value = $this->getCmsPageValue($option);
if ($value) {
if ($this->listHasValue($value)) {
unset($values[$key]);
} else {
$this->setListValue($value);
}
}
}
return $values;
} | php | {
"resource": ""
} |
q7341 | ParserFactoryHardf.createParserFor | train | public function createParserFor($serialization)
{
if (!in_array($serialization, $this->getSupportedSerializations())) {
throw new \Exception(
'Requested serialization '.$serialization.' is not available in: '.
implode(', ', $this->getSupportedSerializations())
);
}
return new ParserHardf(
$this->nodeFactory,
$this->statementFactory,
$this->statementIteratorFactory,
$this->RdfHelpers,
$serialization
);
} | php | {
"resource": ""
} |
q7342 | Encoder.decode | train | public function decode($string)
{
if ($this->isSerialized($string)) {
return $this->unserialize($string);
}
$result = json_decode($string, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \InvalidArgumentException('Unable to unserialize value.');
}
return $result;
} | php | {
"resource": ""
} |
q7343 | Encoder.unserialize | train | private function unserialize($string)
{
if (false === $string || null === $string || '' === $string) {
throw new \InvalidArgumentException('Unable to unserialize value.');
}
set_error_handler(
function () {
restore_error_handler();
throw new \InvalidArgumentException('Unable to unserialize value, string is corrupted.');
},
E_NOTICE
);
$result = unserialize($string);
restore_error_handler();
return $result;
} | php | {
"resource": ""
} |
q7344 | BasicBacktraceReporter.getBacktrace | train | public function getBacktrace($exception = null)
{
$skipLimit = false;
if ($exception instanceof \Exception || $exception instanceof \Throwable) {
$backtrace = $exception->getTrace();
foreach ($backtrace as $index => $backtraceCall) {
unset($backtrace[$index]['args']);
}
} elseif (version_compare(PHP_VERSION, '5.4.0') >= 0) {
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $this->backtraceLimit);
$skipLimit = true;
} else {
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
}
if ($this->backtraceLimit > 0 && !$skipLimit) {
$backtrace = array_slice($backtrace, 0, $this->backtraceLimit);
}
return $backtrace;
} | php | {
"resource": ""
} |
q7345 | ArrayHelper.BEM | train | public function BEM($block = null, $element = null, $modifiers = []): array
{
if (!isset($block) || !is_string($block) || !$block) {
return [];
}
$baseClass = $element ? "{$block}__{$element}" : "{$block}";
$classes = [$baseClass];
if (isset($modifiers)) {
$modifiers = self::modifierArray($modifiers);
foreach ($modifiers as $value) {
$classes[] = "{$baseClass}--{$value}";
}
}
return $classes;
} | php | {
"resource": ""
} |
q7346 | ArrayHelper.modifierArray | train | private static function modifierArray($modifiers = []): array {
if (is_string($modifiers)) {
return [$modifiers];
}
$array = [];
if (is_array($modifiers)) {
foreach ($modifiers as $key => $value) {
if (!$value) {
continue;
}
if (is_array($value)) {
$array = array_merge($array, self::modifierArray($value));
} else if (is_string($value)) {
$array[] = $value;
} else if (is_string($key)) {
$array[] = $key;
}
}
}
return array_unique($array);
} | php | {
"resource": ""
} |
q7347 | ArrayHelper.join | train | public function join(array $array, string $separator = ','): string
{
$result = '';
foreach ($array as $item) {
if (is_array($item)) {
$result .= $this->join($item, $separator) . $separator;
} else {
$result .= $item . $separator;
}
}
$result = substr($result, 0, 0 - strlen($separator));
return $result;
} | php | {
"resource": ""
} |
q7348 | ArrayHelper.extractSubElements | train | public function extractSubElements(
array $array,
bool $preserveKeys = false
): array {
$resultArray = [];
foreach ($array as $element) {
if (is_array($element)) {
foreach ($element as $subKey => $subElement) {
if ($preserveKeys) {
$resultArray[$subKey] = $subElement;
} else {
$resultArray[] = $subElement;
}
}
} else {
$resultArray[] = $element;
}
}
return $resultArray;
} | php | {
"resource": ""
} |
q7349 | Asset.outputStyles | train | public static function outputStyles($output = '')
{
self::lookIfProcessFiles('style', 'header');
$template = self::$templates['style'];
$styles = self::$data['style']['header'];
foreach ($styles as $value) {
$output .= sprintf(
$template,
$value['url']
);
}
self::$data['style']['header'] = [];
return ! empty($output) ? $output : false;
} | php | {
"resource": ""
} |
q7350 | Asset.isAdded | train | public static function isAdded($type, $name)
{
if (isset(self::$data[$type]['header'][$name])) {
return true;
} elseif (isset(self::$data[$type]['footer'][$name])) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q7351 | Asset.unify | train | public static function unify($uniqueID, $params, $minify = false)
{
self::$id = $uniqueID;
self::$unify = $params;
self::$minify = $minify;
return true;
} | php | {
"resource": ""
} |
q7352 | Asset.remove | train | public static function remove($type, $name)
{
if (isset(self::$data[$type]['header'][$name])) {
unset(self::$data[$type]['header'][$name]);
return true;
} elseif (isset(self::$data[$type]['footer'][$name])) {
unset(self::$data[$type]['footer'][$name]);
return true;
}
return false;
} | php | {
"resource": ""
} |
q7353 | Asset.lookIfProcessFiles | train | protected static function lookIfProcessFiles($type, $place)
{
if (is_string(self::$unify) || isset(self::$unify[$type . 's'])) {
return self::unifyFiles(
self::prepareFiles($type, $place)
);
}
} | php | {
"resource": ""
} |
q7354 | Asset.prepareFiles | train | protected static function prepareFiles($type, $place)
{
self::getProcessedFiles();
$params['type'] = $type;
$params['place'] = $place;
$params['routes'] = self::getRoutesToFolder($type);
foreach (self::$data[$type][$place] as $id => $file) {
$path = self::getPathFromUrl($file['url']);
$params['urls'][$id] = $file['url'];
$params['files'][$id] = basename($file['url']);
$params['paths'][$id] = $path;
if (is_file($path) && self::isModifiedFile($path)) {
unset($params['urls'][$id]);
continue;
}
$path = $params['routes']['path'] . $params['files'][$id];
if (is_file($path)) {
if (self::isModifiedHash($file['url'], $path)) {
continue;
}
$params['paths'][$id] = $path;
} elseif (self::isExternalUrl($file['url'])) {
continue;
}
unset($params['urls'][$id]);
}
return $params;
} | php | {
"resource": ""
} |
q7355 | Asset.getRoutesToFolder | train | protected static function getRoutesToFolder($type)
{
$type = $type . 's';
$url = isset(self::$unify[$type]) ? self::$unify[$type] : self::$unify;
return ['url' => $url, 'path' => self::getPathFromUrl($url)];
} | php | {
"resource": ""
} |
q7356 | Asset.isModifiedHash | train | protected static function isModifiedHash($url, $path)
{
if (self::isExternalUrl($url)) {
if (sha1_file($url) !== sha1_file($path)) {
return self::$changes = true;
}
}
return false;
} | php | {
"resource": ""
} |
q7357 | Asset.unifyFiles | train | protected static function unifyFiles($params, $data = '')
{
$type = $params['type'];
$place = $params['place'];
$routes = $params['routes'];
$ext = ($type == 'style') ? '.css' : '.js';
$hash = sha1(implode('', $params['files']));
$minFile = $routes['path'] . $hash . $ext;
if (! is_file($minFile) || self::$changes == true) {
foreach ($params['paths'] as $id => $path) {
if (isset($params['urls'][$id])) {
$url = $params['urls'][$id];
$path = $routes['path'] . $params['files'][$id];
$data .= self::saveExternalFile($url, $path);
}
$data .= file_get_contents($path);
}
$data = (self::$minify) ? self::compressFiles($data) : $data;
self::saveFile($minFile, $data);
}
self::setProcessedFiles();
return self::setNewParams($type, $place, $hash, $routes['url'], $ext);
} | php | {
"resource": ""
} |
q7358 | Asset.saveExternalFile | train | protected static function saveExternalFile($url, $path)
{
if ($data = file_get_contents($url)) {
return (self::saveFile($path, $data)) ? $data : '';
}
return '';
} | php | {
"resource": ""
} |
q7359 | Asset.compressFiles | train | protected static function compressFiles($content)
{
$var = ["\r\n", "\r", "\n", "\t", ' ', ' ', ' '];
$content = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $content);
$content = str_replace($var, '', $content);
$content = str_replace('{ ', '{', $content);
$content = str_replace(' }', '}', $content);
$content = str_replace('; ', ';', $content);
return $content;
} | php | {
"resource": ""
} |
q7360 | Asset.setNewParams | train | protected static function setNewParams($type, $place, $hash, $url, $ext)
{
$data = [
'name' => self::$id,
'url' => $url . $hash . $ext,
'attr' => self::unifyParams($type, 'attr'),
'version' => self::unifyParams($type, 'version', '1.0.0'),
];
if ($type === 'script') {
$data['footer'] = self::unifyParams($type, 'footer', false);
}
self::$data[$type][$place] = [$data['name'] => $data];
return true;
} | php | {
"resource": ""
} |
q7361 | Asset.unifyParams | train | protected static function unifyParams($type, $field, $default = '')
{
$data = array_column(self::$data[$type], $field);
switch ($field) {
case 'attr':
case 'footer':
case 'version':
foreach ($data as $value) {
if ($data[0] !== $value) {
return $default;
}
}
return (isset($data[0]) && $data[0]) ? $data[0] : $default;
default:
$params = [];
foreach ($data as $value) {
$params = array_merge($params, $value);
}
return array_unique($params);
}
} | php | {
"resource": ""
} |
q7362 | SgCore.retrievePathScope | train | private function retrievePathScope($path, $shopNumber)
{
$shopConfigs = $this->getShopNumberCollection($shopNumber);
if (!$shopConfigs->getSize()) {
throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_UNKNOWN_SHOP_NUMBER, false, true);
}
$firstItem = $shopConfigs->getFirstItem();
/**
* todo-sg: should be improved to use a single query, e.g. (scope = x AND scope_id = x) OR (scope = ...)
*
* @var Value $shopConfig
*/
foreach ($shopConfigs as $shopConfig) {
/** @var Collection $collection */
$collection = $this
->getCollectionByPath($path)
->addFieldToFilter('scope', $shopConfig->getScope())
->addFieldToFilter('scope_id', $shopConfig->getScopeId());
if ($collection->getItems()) {
/** @var Value $propertyConfig */
$propertyConfig = $collection->setOrder('scope_id')->getFirstItem();
if ($propertyConfig->getData('value')) {
return $propertyConfig;
}
}
}
return $firstItem;
} | php | {
"resource": ""
} |
q7363 | MigrationsLocator.getMigrationsLocations | train | public function getMigrationsLocations()
{
$migrationsLocations = [];
foreach ($this->kernel->getBundles() as $bundle) {
$migrationsLocation = $this->createMigrationsLocation($bundle);
if ($this->filesystem->exists($migrationsLocation->getDirectory())) {
$migrationsLocations[] = $migrationsLocation;
}
}
return $migrationsLocations;
} | php | {
"resource": ""
} |
q7364 | MigrationsLocator.createMigrationsLocation | train | public function createMigrationsLocation(BundleInterface $bundle)
{
return new MigrationsLocation(
$bundle->getPath() . '/' . $this->relativeDirectory,
$bundle->getNamespace() . '\\' . $this->relativeNamespace
);
} | php | {
"resource": ""
} |
q7365 | Customer.setEntity | train | public function setEntity(MageQuote $quote)
{
$id = $this->sgBase->getExternalCustomerId();
$email = $this->sgBase->getMail();
try {
$customer = $id ? $this->customerHelper->getById($id) : $this->customerHelper->getByEmail($email);
} catch (NoSuchEntityException $e) {
$customer = new DataObject();
$this->log->debug('Could not load customer by id or mail.');
}
$quote->setCustomerEmail($email)
->setRemoteIp($this->sgBase->getCustomerIp());
if ($this->sgBase->isGuest()) {
$quote->setCustomerIsGuest(true);
} elseif ($customer->getId()) {
$this->session->setCustomerId($customer->getId())->setCustomerGroupId($customer->getGroupId());
$quote->setCustomer($customer)
->setCustomerIsGuest(false);
} else {
throw new \ShopgateLibraryException(
\ShopgateLibraryException::UNKNOWN_ERROR_CODE,
__('Customer with external id "%1" or email "%2" does not exist', $id, $email)->render()
);
}
} | php | {
"resource": ""
} |
q7366 | Customer.setAddress | train | public function setAddress(MageQuote $quote)
{
$billing = $this->sgBase->getInvoiceAddress();
if (!empty($billing)) {
$data = $this->sgCustomer->createAddressData($this->sgBase, $billing, $quote->getCustomerId());
$quote->getBillingAddress()
->addData($data)
->setCustomerAddressId($billing->getId())
->setCustomerId($this->sgBase->getExternalCustomerId())
->setData('should_ignore_validation', true);
}
$shipping = $this->sgBase->getDeliveryAddress();
if (!empty($shipping)) {
$data = $this->sgCustomer->createAddressData($this->sgBase, $shipping, $quote->getCustomerId());
$quote->getShippingAddress()
->addData($data)
->setCustomerAddressId($shipping->getId())
->setCustomerId($this->sgBase->getExternalCustomerId())
->setData('should_ignore_validation', true);
}
if (!$quote->getShippingAddress()->getCountryId()) {
$defaultCountryItem = $this->sgCoreConfig->getConfigByPath(Custom::XML_PATH_GENERAL_COUNTRY_DEFAULT);
$quote->getShippingAddress()->setCountryId($defaultCountryItem->getValue());
}
} | php | {
"resource": ""
} |
q7367 | Customer.resetGuest | train | public function resetGuest(MageQuote $quote)
{
if ($this->sgBase->isGuest()) {
$quote->getBillingAddress()->isObjectNew(false);
$quote->getShippingAddress()->isObjectNew(false);
}
} | php | {
"resource": ""
} |
q7368 | DiContainer.setValue | train | public function setValue($name, $value) {
if (substr($name, -1) === '_') {
throw new InvalidArgumentException('$name cannot end with "_"');
}
$this->remove($name);
$this->{$name} = $value;
return $this;
} | php | {
"resource": ""
} |
q7369 | DiContainer.setClassName | train | public function setClassName($name, $class_name, $shared = true) {
if (substr($name, -1) === '_') {
throw new InvalidArgumentException('$name cannot end with "_"');
}
$classname_pattern = self::CLASS_NAME_PATTERN_53;
if (!is_string($class_name) || !preg_match($classname_pattern, $class_name)) {
throw new InvalidArgumentException('Class names must be valid PHP class names');
}
$func = function () use ($class_name) {
return new $class_name();
};
return $this->setFactory($name, $func, $shared);
} | php | {
"resource": ""
} |
q7370 | DiContainer.remove | train | public function remove($name) {
if (substr($name, -1) === '_') {
throw new InvalidArgumentException('$name cannot end with "_"');
}
unset($this->{$name});
unset($this->factories_[$name]);
return $this;
} | php | {
"resource": ""
} |
q7371 | DiContainer.has | train | public function has($name) {
if (isset($this->factories_[$name])) {
return true;
}
if (substr($name, -1) === '_') {
return false;
}
return (bool)property_exists($this, $name);
} | php | {
"resource": ""
} |
q7372 | AbstractChartAccountsModel.addAccount | train | public function addAccount(ChartAccountsAccount $account) {
foreach ($this->accounts as $current) {
if ($current->getNumber() === $account->getNumber()) {
throw new AccountAlreadyExistsException($account);
}
}
$this->accounts[] = $account;
return $this;
} | php | {
"resource": ""
} |
q7373 | AbstractChartAccountsModel.removeAccount | train | public function removeAccount(ChartAccountsAccount $account) {
for ($i = count($this->accounts) - 1; 0 <= $i; --$i) {
if ($account->getNumber() !== $this->accounts[$i]->getNumber()) {
continue;
}
unset($this->accounts[$i]);
}
return $this;
} | php | {
"resource": ""
} |
q7374 | CmsMap.getCmsPageRenderer | train | protected function getCmsPageRenderer()
{
if (!$this->cmsPageRenderer) {
$this->cmsPageRenderer = $this->getLayout()->createBlock(
'Shopgate\Base\Block\Adminhtml\Form\Field\CmsMap',
'',
['data' => ['is_render_to_js_template' => true]]
);
}
return $this->cmsPageRenderer;
} | php | {
"resource": ""
} |
q7375 | Filer.routes | train | public static function routes(Router $router, $namespace = 'TeamTeaTime\Filer\Controllers')
{
$router->group(compact('namespace'), function ($router) {
$router->get('{id}', [
'as' => 'filer.file.view',
'uses' => 'LocalFileController@view'
]);
$router->get('{id}/download', [
'as' => 'filer.file.download',
'uses' => 'LocalFileController@download'
]);
});
} | php | {
"resource": ""
} |
q7376 | Filer.checkType | train | public static function checkType($item)
{
if (is_string($item)) {
// Item is a string; check to see if it's a URL or filepath
if (filter_var($item, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)) {
// Item is a URL
return Type::URL;
} elseif (is_file(config('filer.path.absolute') . "/{$item}")) {
// Item is a filepath
return Type::FILEPATH;
}
} elseif (is_a($item, 'SplFileInfo')) {
// Item is a file object
return Type::FILE;
}
// Throw an exception if item doesn't match any known types
throw new Exception('Unknown item type');
} | php | {
"resource": ""
} |
q7377 | Filer.getRelativeFilepath | train | public static function getRelativeFilepath($file)
{
$storageDir = self::convertSlashes(config('filer.path.absolute'));
$absolutePath = self::convertSlashes($file->getRealPath());
return dirname(str_replace($storageDir, '', $absolutePath));
} | php | {
"resource": ""
} |
q7378 | Net_SFTP._setstat | train | function _setstat($filename, $attr, $recursive)
{
if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
return false;
}
$filename = $this->_realpath($filename);
if ($filename === false) {
return false;
}
$this->_remove_from_stat_cache($filename);
if ($recursive) {
$i = 0;
$result = $this->_setstat_recursive($filename, $attr, $i);
$this->_read_put_responses($i);
return $result;
}
// SFTPv4+ has an additional byte field - type - that would need to be sent, as well. setting it to
// SSH_FILEXFER_TYPE_UNKNOWN might work. if not, we'd have to do an SSH_FXP_STAT before doing an SSH_FXP_SETSTAT.
if (!$this->_send_sftp_packet(NET_SFTP_SETSTAT, pack('Na*a*', strlen($filename), $filename, $attr))) {
return false;
}
/*
"Because some systems must use separate system calls to set various attributes, it is possible that a failure
response will be returned, but yet some of the attributes may be have been successfully modified. If possible,
servers SHOULD avoid this situation; however, clients MUST be aware that this is possible."
-- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.6
*/
$response = $this->_get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
user_error('Expected SSH_FXP_STATUS');
return false;
}
if (strlen($response) < 4) {
return false;
}
extract(unpack('Nstatus', $this->_string_shift($response, 4)));
if ($status != NET_SFTP_STATUS_OK) {
$this->_logError($response, $status);
return false;
}
return true;
} | php | {
"resource": ""
} |
q7379 | Net_SFTP.rename | train | function rename($oldname, $newname)
{
if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
return false;
}
$oldname = $this->_realpath($oldname);
$newname = $this->_realpath($newname);
if ($oldname === false || $newname === false) {
return false;
}
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3
$packet = pack('Na*Na*', strlen($oldname), $oldname, strlen($newname), $newname);
if (!$this->_send_sftp_packet(NET_SFTP_RENAME, $packet)) {
return false;
}
$response = $this->_get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
user_error('Expected SSH_FXP_STATUS');
return false;
}
// if $status isn't SSH_FX_OK it's probably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
if (strlen($response) < 4) {
return false;
}
extract(unpack('Nstatus', $this->_string_shift($response, 4)));
if ($status != NET_SFTP_STATUS_OK) {
$this->_logError($response, $status);
return false;
}
// don't move the stat cache entry over since this operation could very well change the
// atime and mtime attributes
//$this->_update_stat_cache($newname, $this->_query_stat_cache($oldname));
$this->_remove_from_stat_cache($oldname);
$this->_remove_from_stat_cache($newname);
return true;
} | php | {
"resource": ""
} |
q7380 | OrderItem.getStackQty | train | public function getStackQty()
{
$info = $this->getInternalOrderInfo();
$qty = 1;
if ($info->getStackQuantity() > 1) {
$qty = $info->getStackQuantity();
}
return $qty;
} | php | {
"resource": ""
} |
q7381 | OrderItem.setInternalOrderInfo | train | public function setInternalOrderInfo($value)
{
if ($value instanceof ItemInfo) {
$value = $value->toJson();
} elseif (is_array($value)) {
$value = \Zend_Json_Encoder::encode($value);
}
return parent::setInternalOrderInfo($value);
} | php | {
"resource": ""
} |
q7382 | OrderItem.setMagentoError | train | public function setMagentoError($errorText)
{
$code = $this->translateMagentoError($errorText);
$message = \ShopgateLibraryException::getMessageFor($code);
$this->setUnhandledError($code, $message);
return $this;
} | php | {
"resource": ""
} |
q7383 | OrderItem.getExportProductId | train | public function getExportProductId()
{
return $this->getInternalOrderInfo()->getItemType() == Grouped::TYPE_CODE
? $this->getChildId()
: $this->getParentId();
} | php | {
"resource": ""
} |
q7384 | Status.validate | train | private function validate()
{
if (!array_key_exists('type', $this->properties)) {
throw new StatusException(sprintf('Key %s in %s missing', 'type', __CLASS__), 100, null);
}
$type = $this->properties['type'];
// the type specified must be valid
if (!in_array($this->properties['type'], $this->types)) {
throw new StatusException('The type specified is invalid', 100, null);
}
switch ($type) {
case StatusInterface::TYPE_INITIAL:
case StatusInterface::TYPE_EXCEPTION:
$mandatoryKeys = ['name'];
break;
default:
$mandatoryKeys = ['name', 'transitions_from', 'transitions_to'];
break;
}
foreach ($mandatoryKeys as $key) {
if (!array_key_exists($key, $this->properties)) {
throw new StatusException(sprintf('Key %s in %s missing', $key, __CLASS__), 100, null);
}
}
if (StatusInterface::TYPE_INITIAL != $type && StatusInterface::TYPE_EXCEPTION != $type) {
$keysMustBeArray = ['transitions_from', 'transitions_to'];
foreach ($keysMustBeArray as $key) {
if (!is_array($this->properties[$key])) {
throw new StatusException(sprintf('Key %s is not an array', $key), 100, null);
}
}
}
} | php | {
"resource": ""
} |
q7385 | CollectionWorkflowAbstract.has_more | train | public function has_more()
{
if ($this->_pointer + 1 == count($this->_collection)) {
return false;
}
++$this->_pointer;
return true;
} | php | {
"resource": ""
} |
q7386 | Error.line | train | static function line($message = '', $newLine = 'after') {
if($newLine == 'before' || $newLine == 'both') {
echo PHP_EOL;
}
echo self::formatMessage("Error. $message", ['fg-red']);
if($newLine == 'after' || $newLine == 'both') {
echo PHP_EOL;
}
} | php | {
"resource": ""
} |
q7387 | Error.formatMessage | train | private static function formatMessage($message, $styles)
{
if (empty($styles) || !self::ansiColorsSupported()) {
return $message;
}
return sprintf("\x1b[%sm", implode(';', array_map('Output::getStyleCode', $styles))) . $message . "\x1b[0m";
} | php | {
"resource": ""
} |
q7388 | IconFactory.getSizes | train | public function getSizes(\ElggEntity $entity, array $icon_sizes = array()) {
$defaults = ($entity && $entity->getSubtype() == 'file') ? $this->config->getFileIconSizes() : $this->config->getGlobalIconSizes();
$sizes = array_merge($defaults, $icon_sizes);
return elgg_trigger_plugin_hook('entity:icon:sizes', $entity->getType(), array(
'entity' => $entity,
'subtype' => $entity->getSubtype(),
), $sizes);
} | php | {
"resource": ""
} |
q7389 | IconFactory.getIconDirectory | train | public function getIconDirectory(\ElggEntity $entity, $size = null, $directory = null) {
$sizes = $this->getSizes($entity);
if (isset($sizes[$size]['metadata_name'])) {
$md_name = $sizes[$size]['metadata_name'];
if ($entity->$md_name) {
$directory = '';
}
}
if ($directory === null) {
$directory = $directory ? : $entity->icon_directory;
if ($entity instanceof \ElggUser) {
$directory = 'profile';
} else if ($entity instanceof \ElggGroup) {
$directory = 'groups';
} else {
$directory = $this->config->getDefaultIconDirectory();
}
}
$directory = elgg_trigger_plugin_hook('entity:icon:directory', $entity->getType(), array(
'entity' => $entity,
'size' => $size,
), $directory);
return trim($directory, '/');
} | php | {
"resource": ""
} |
q7390 | IconFactory.getIconFilename | train | public function getIconFilename(\ElggEntity $entity, $size = '') {
$mimetype = $entity->icon_mimetype ? : $entity->mimetype;
switch ($mimetype) {
default :
$ext = 'jpg';
break;
case 'image/png' :
$ext = 'png';
break;
case 'image/gif' :
$ext = 'gif';
break;
}
$sizes = $this->getSizes($entity);
if (isset($sizes[$size]['metadata_name'])) {
$md_name = $sizes[$size]['metadata_name'];
$filename = $entity->$md_name;
}
if (!$filename) {
$filename = "{$entity->guid}{$size}.{$ext}";
}
return elgg_trigger_plugin_hook('entity:icon:directory', $entity->getType(), array(
'entity' => $entity,
'size' => $size,
), $filename);
} | php | {
"resource": ""
} |
q7391 | IconFactory.getIconFile | train | public function getIconFile(\ElggEntity $entity, $size = '') {
$dir = $this->getIconDirectory($entity, $size);
$filename = $this->getIconFilename($entity, $size);
if ($entity instanceof \ElggUser) {
$owner_guid = $entity->guid;
} else if ($entity->owner_guid) {
$owner_guid = $entity->owner_guid;
} else {
$owner_guid = elgg_get_site_entity();
}
$file = new \ElggFile();
$file->owner_guid = $owner_guid;
$file->setFilename("{$dir}/{$filename}");
$file->mimetype = $file->detectMimeType();
return $file;
} | php | {
"resource": ""
} |
q7392 | IconFactory.getURL | train | public function getURL(\ElggEntity $entity, $size = '') {
$icon = $this->getIconFile($entity, $size);
if (!$icon->exists()) {
return;
}
$key = get_site_secret();
$guid = $entity->guid;
$path = $icon->getFilename();
$hmac = hash_hmac('sha256', $guid . $path, $key);
$query = serialize(array(
'uid' => $guid,
'd' => ($entity instanceof \ElggUser) ? $entity->guid : $entity->owner_guid, // guid of the dir owner
'dts' => ($entity instanceof \ElggUser) ? $entity->time_created : $entity->getOwnerEntity()->time_created,
'path' => $path,
'ts' => $entity->icontime,
'mac' => $hmac,
));
$url = elgg_http_add_url_query_elements('mod/hypeApps/servers/icon.php', array(
'q' => base64_encode($query),
));
return elgg_normalize_url($url);
} | php | {
"resource": ""
} |
q7393 | IconFactory.outputRawIcon | train | public function outputRawIcon($entity_guid, $size = null) {
if (headers_sent()) {
exit;
}
$ha = access_get_show_hidden_status();
access_show_hidden_entities(true);
$entity = get_entity($entity_guid);
if (!$entity) {
exit;
}
$size = strtolower($size ? : 'medium');
$filename = "icons/" . $entity->guid . $size . ".jpg";
$etag = md5($entity->icontime . $size);
$filehandler = new \ElggFile();
$filehandler->owner_guid = $entity->owner_guid;
$filehandler->setFilename($filename);
if ($filehandler->exists()) {
$filehandler->open('read');
$contents = $filehandler->grabFile();
$filehandler->close();
} else {
forward('', '404');
}
$mimetype = ($entity->mimetype) ? $entity->mimetype : 'image/jpeg';
access_show_hidden_entities($ha);
header("Content-type: $mimetype");
header("Etag: $etag");
header('Expires: ' . date('r', time() + 864000));
header("Pragma: public");
header("Cache-Control: public");
header("Content-Length: " . strlen($contents));
echo $contents;
exit;
} | php | {
"resource": ""
} |
q7394 | Configuration.getMigrationsToExecute | train | public function getMigrationsToExecute($direction, $to)
{
if ($direction === Version::DIRECTION_DOWN) {
$this->throwMethodIsNotAllowedException('Migration down is not allowed.');
}
$migrationVersionsToExecute = [];
$allMigrationVersions = $this->getMigrations();
$migratedVersions = $this->getMigratedVersions();
foreach ($allMigrationVersions as $version) {
if ($to < $version->getVersion()) {
$this->throwMethodIsNotAllowedException('Partial migration up in not allowed.');
}
if ($this->shouldExecuteMigration($version, $migratedVersions)) {
$migrationVersionsToExecute[$version->getVersion()] = $version;
}
}
return $migrationVersionsToExecute;
} | php | {
"resource": ""
} |
q7395 | GCode.drawCircle | train | public function drawCircle($x, $y, $z, $radius, $motion = 'G2', $plane = 'G17')
{
if ($plane == 'G17') {
$of = $x - $radius;
$this->setCode("(circle)");
$this->setCode("G0 X{$of} Y{$y}");
$this->setCode("G1 Z{$z} (axis spindle start point)");
// TODO Tool size ...
// TODO Cutting spindle movement ...
$this->setCode("{$plane} {$motion} X{$of} Y{$y} I{$radius} J0.00 Z{$z}");
$this->setCode("G0 Z{$this->spindleAxisStartPosition} (axis spindle start position)");
$this->setCode("(/circle)\n");
}
if ($plane == 'G18') {
// G18 is disabled
return;
}
if ($plane == 'G19') {
// G19 is disabled
return;
}
return $this;
} | php | {
"resource": ""
} |
q7396 | GCode.drawBox | train | public function drawBox($x1, $y1, $z1, $x2, $y2, $z2)
{
$this->setCode("(box)");
$this->setCode("G0 X{$x1} Y{$y1} Z{$this->spindleAxisStartPosition} (move to spindle axis start position)");
$this->setCode("G1 Z{$z1}");
$this->setCode("G1 X{$x1} Y{$y1} Z{$z1}");
$this->setCode("G1 Y{$y2}");
$this->setCode("G1 X{$x2}");
$this->setCode("G1 Y{$y1}");
$this->setCode("G1 X{$x1}");
$this->setCode("G0 Z{$z2}");
$this->setCode("(/box)\n");
return $this;
} | php | {
"resource": ""
} |
q7397 | GCode.drawLine | train | public function drawLine($xStart, $yStart, $zStart, $xEnd, $yEnd, $zEnd)
{
$this->setCode("(line)");
$this->setCode("G0 X{$xStart} Y{$yStart} Z{$this->spindleAxisStartPosition}");
$this->setCode("G1 Z{$zStart}");
// testing tool setup tool metric M8 diameter 4mm
$this->setCode("T1 M08");
$this->setCode("G41 D4");
$this->setCode("G1 X{$xStart} Y{$yStart} Z{$zStart}");
$this->setCode("G1 X{$xEnd} Y{$yEnd} Z{$zEnd}");
$this->setCode("G0 Z{$this->spindleAxisStartPosition}");
$this->setCode("G0 X{$xStart} Y{$yStart}");
$this->setCode("(/line)\n");
return $this;
} | php | {
"resource": ""
} |
q7398 | GCode.drawCubicSpline | train | public function drawCubicSpline($xStart, $yStart, $xFromEnd, $yFromEnd, $xEnd, $yEnd)
{
$this->setCode("(cubic spline)");
$this->setCode("G0 X{$xStart} Y{$yStart} Z{$this->spindleAxisStartPosition}");
// $this->setCode("G1 Z{$zStart}");
// G5 Cubic spline
$this->setCode("G5 I{$xStart} J{$yStart} P{$xFromEnd} Q-{$yFromEnd} X{$xEnd} Y{$yEnd}");
$this->setCode("G0 Z{$this->spindleAxisStartPosition}");
$this->setCode("G0 X{$xStart} Y{$yStart}");
$this->setCode("(/cubic spline)");
return $this;
} | php | {
"resource": ""
} |
q7399 | Handler.createMessageCallback | train | protected function createMessageCallback(Recipient $user, $subject = null, $callback = null)
{
return function (Message $message) use ($user, $subject, $callback) {
// Set the recipient detail.
$message->to($user->getRecipientEmail(), $user->getRecipientName());
// Only append the subject if it was provided.
! empty($subject) && $message->subject($subject);
// Run any callback if provided.
\is_callable($callback) && $callback(...func_get_args());
};
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.