_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q7400 | Utility.getRoute | train | public function getRoute()
{
/** @var Http $req */
$req = $this->context->getRequest();
if (isset($this->map[$req->getControllerName()])) {
return $this->map[$req->getControllerName()];
}
return $this->map[Generic::CONTROLLER_KEY];
} | php | {
"resource": ""
} |
q7401 | Retriever.getPaymentMethods | train | public function getPaymentMethods()
{
$this->quote->setStoreId($this->storeManager->getStore()->getId());
$export = [];
$paymentMethods = $this->paymentModel->getAvailableMethods($this->quote);
foreach ($paymentMethods as $method) {
$export[] = [
'id' => $method->getCode(),
'title' => $method->getTitle(),
'is_active' => 1
];
}
return $export;
} | php | {
"resource": ""
} |
q7402 | Builder.buildHttpRedirect | train | public function buildHttpRedirect()
{
if (!is_null($this->http)) {
return $this->http;
}
$builder = new ShopgateBuilder($this->initConfig());
$userAgent = $this->header->getHttpUserAgent();
try {
$this->http = $builder->buildHttpRedirect($userAgent, $this->request->getParams(), $_COOKIE);
} catch (\ShopgateMerchantApiException $e) {
$this->logger->error('HTTP > oAuth access token for store not set: ' . $e->getMessage());
return null;
} catch (\Exception $e) {
$this->logger->error('HTTP > error in HTTP redirect: ' . $e->getMessage());
return null;
}
return $this->http;
} | php | {
"resource": ""
} |
q7403 | Builder.buildJsRedirect | train | public function buildJsRedirect()
{
if (!is_null($this->js)) {
return $this->js;
}
$builder = new ShopgateBuilder($this->initConfig());
try {
$this->js = $builder->buildJsRedirect($this->request->getParams(), $_COOKIE);
} catch (\ShopgateMerchantApiException $e) {
$this->logger->error('JS > oAuth access token for store not set: ' . $e->getMessage());
return null;
} catch (\Exception $e) {
$this->logger->error('JS > error in HTTP redirect: ' . $e->getMessage());
return null;
}
return $this->js;
} | php | {
"resource": ""
} |
q7404 | Pagination.prepare | train | public function prepare(OptionList $objOptions = null): OptionList
{
if (is_null($objOptions)) {
$objOptions = new OptionList;
}
// Page
if ('post' == $this->options->get('method')) {
$requestBody = $this->serverRequest->getParsedBody();
if (is_array($requestBody) && !empty($requestBody[$this->getParam()])) {
$this->page = intval($requestBody[$this->getParam()]);
} else {
$this->page = 1;
}
} else {
$queryParams = $this->serverRequest->getQueryParams();
if (is_array($queryParams) && !empty($queryParams[$this->getParam()])) {
$this->page = intval($queryParams[$this->getParam()]);
} else {
$this->page = 1;
}
}
// Nb per page
$this->nb_per_page = $this->options->is_int('nb_per_page') ? $this->options->get('nb_per_page') : 20;
// Obj _b_options
$objOptions->set('limitStart', $this->nb_per_page * ($this->page - 1));
$objOptions->set('limitEnd', $objOptions->get('limitStart') + $this->nb_per_page);
$objOptions->set('limitNb', $this->nb_per_page);
return $objOptions;
} | php | {
"resource": ""
} |
q7405 | Pagination.handle | train | public function handle($mixed): Pagination
{
if ($mixed instanceof Collection) {
$this->mixed = $mixed;
$this->nb_pages = ceil(max(count($mixed), 1) / max($this->nb_per_page, 1));
} else {
if ($mixed instanceof \Countable) {
$this->mixed = $mixed;
$this->nb_pages = ceil(max(count($mixed), 1) / max($this->nb_per_page, 1));
} else {
if (is_int($mixed)) {
$this->mixed = $mixed;
$this->nb_pages = ceil(max($mixed, 1) / max($this->nb_per_page, 1));
} else {
trigger_error('Parameter of Pagination::handle must be an Collection object or integer', E_USER_WARNING);
}
}
}
return $this;
} | php | {
"resource": ""
} |
q7406 | Pagination.canBeShowed | train | public function canBeShowed(): bool
{
return ($this->mixed instanceof Collection || $this->mixed instanceof \Countable || is_int($this->mixed));
} | php | {
"resource": ""
} |
q7407 | Pagination.getParam | train | public function getParam(): string
{
if ($this->options->is_null('param')) {
$this->options->set('param', 'page' . (1 == self::$iPagination ? '' : self::$iPagination));
}
return $this->options->get('param');
} | php | {
"resource": ""
} |
q7408 | Pagination.getHttpQueryString | train | public function getHttpQueryString(array $moreQuery = null): string
{
$queries = [];
if (!(is_null($this->page) || 1 == $this->page)) {
$queries[$this->getParam()] = $this->page;
}
if (!empty($moreQuery)) {
$queries = array_merge($queries, $moreQuery);
}
return !empty($queries) ? '?' . http_build_query($queries) : '';
} | php | {
"resource": ""
} |
q7409 | StateMachineAbstract.parseYAML | train | protected function parseYAML()
{
try {
$yaml = $this->configuration;
$yaml_fixed = [];
$yaml_fixed['class'] = $yaml['class'];
foreach ($yaml['states'] as $key => $value) {
if ($value['type'] != \Mothership\StateMachine\StatusInterface::TYPE_INITIAL && $value['type'] != \Mothership\StateMachine\StatusInterface::TYPE_EXCEPTION) {
$state = [
'name' => $key,
'type' => $value['type'],
'transitions_from' => $value['transitions_from'],
'transitions_to' => $value['transitions_to'],
];
$yaml_fixed['states'][] = $state;
} else {
$state = [
'name' => $key,
'type' => $value['type'],
];
$yaml_fixed['states'][] = $state;
}
}
$yaml_fixed['yaml'] = $this->configuration;
return $yaml_fixed;
} catch (\Symfony\Component\Yaml\Exception\ParseException $ex) {
throw $ex;
}
} | php | {
"resource": ""
} |
q7410 | StateMachineAbstract.initWorkflow | train | protected function initWorkflow()
{
$className = $this->workflowConfiguration['class']['name'];
if (!class_exists($className, true)) {
throw new StateMachineException('The class ' . $className . ' does not exist!', 100);
}
try {
$this->workflow = new $className($this->workflowConfiguration);
} catch (WorkflowException $ex) {
throw new StateMachineException('Workflow with some problems', 90, $ex);
}
} | php | {
"resource": ""
} |
q7411 | StateMachineAbstract.renderGraph | train | public function renderGraph($outputPath = './workflow.png', $stopAfterExecution = true)
{
/*
* This example is based on http://martin-thoma.com/how-to-draw-a-finite-state-machine/
* Feel free to tweak the rendering output. I have decided do use the most simple
* implementation over the fancy stuff to avoid additional complexity.
*/
$template
= '
digraph finite_state_machine {
rankdir=LR;
size="%d"
node [shape = doublecircle]; start;
node [shape = circle];
%s
}
';
$pattern = ' %s -> %s [ label = "%s" ];';
$_transitions = [];
foreach ($this->workflowConfiguration['states'] as $state) {
if (array_key_exists('transitions_from', $state)) {
$transitions_from = $state['transitions_from'];
foreach ($transitions_from as $from) {
if (is_array($from)) {
$_transitions[] = sprintf(
$pattern,
$from['status'],
$state['name'],
'<< IF '
. $this->convertToStringCondition($from['result']) . ' >>' . $state['name']
);
} else {
$_transitions[] = sprintf($pattern, $from, $state['name'], $state['name']);
}
}
} else {
if ('type' == 'exception') {
$_transitions[] = 'node [shape = doublecircle]; exception;';
}
}
}
file_put_contents('/tmp/sm.gv', sprintf($template, count($_transitions) * 2, implode("\n", $_transitions)));
shell_exec('dot -Tpng /tmp/sm.gv -o ' . $outputPath);
if ($stopAfterExecution) {
//exit;
}
} | php | {
"resource": ""
} |
q7412 | StateMachineAbstract.run | train | public function run(array $args = [], $enableLog = false)
{
try {
return $this->workflow->run($args, $enableLog);
} catch (WorkflowException $ex) {
throw new StateMachineException('Error running State Machine', 100, $ex);
}
} | php | {
"resource": ""
} |
q7413 | Generic.generate | train | public function generate($pageTitle)
{
return [
Shopgate_Helper_Redirect_TagsGenerator::SITE_PARAMETER_SITENAME => $this->getSiteName(),
Shopgate_Helper_Redirect_TagsGenerator::SITE_PARAMETER_DESKTOP_URL => $this->getShopUrl(),
Shopgate_Helper_Redirect_TagsGenerator::SITE_PARAMETER_MOBILE_WEB_URL => $this->getMobileUrl(),
Shopgate_Helper_Redirect_TagsGenerator::SITE_PARAMETER_TITLE => $pageTitle
];
} | php | {
"resource": ""
} |
q7414 | CURLFactory.getInstance | train | public static function getInstance($method, CURLConfiguration $configuration = null, $resourcePath = null) {
// Check the configuration.
if (null === $configuration) {
$configuration = new CURLConfiguration();
}
// Switch into $method.
switch ($method) {
case self::HTTP_METHOD_DELETE:
return new CURLDeleteRequest($configuration, $resourcePath);
case self::HTTP_METHOD_GET:
return new CURLGetRequest($configuration, $resourcePath);
case self::HTTP_METHOD_HEAD:
return new CURLHeadRequest($configuration, $resourcePath);
case self::HTTP_METHOD_OPTIONS:
return new CURLOptionsRequest($configuration, $resourcePath);
case self::HTTP_METHOD_PATCH:
return new CURLPatchRequest($configuration, $resourcePath);
case self::HTTP_METHOD_POST:
return new CURLPostRequest($configuration, $resourcePath);
case self::HTTP_METHOD_PUT:
return new CURLPutRequest($configuration, $resourcePath);
default:
throw new InvalidHTTPMethodException($method);
}
} | php | {
"resource": ""
} |
q7415 | ARC2.createGraph | train | public function createGraph(NamedNode $graph, array $options = [])
{
if (false === isset($this->getGraphs()[$graph->getUri()])) {
// table names
$g2t = $this->configuration['table-prefix'].'_g2t';
$id2val = $this->configuration['table-prefix'].'_id2val';
/*
* for id2val table
*/
$query = 'INSERT INTO '.$id2val.' (val) VALUES("'.$graph->getUri().'")';
$this->store->queryDB($query, $this->store->getDBCon());
$usedId = $this->store->getDBCon()->insert_id;
/*
* for g2t table
*/
$newIdg2t = 1 + $this->getRowCount($g2t);
$query = 'INSERT INTO '.$g2t.' (t, g) VALUES('.$newIdg2t.', '.$usedId.')';
$this->store->queryDB($query, $this->store->getDBCon());
$usedId = $this->store->getDBCon()->insert_id;
}
} | php | {
"resource": ""
} |
q7416 | ARC2.getRowCount | train | public function getRowCount($tableName)
{
$result = $this->store->queryDB(
'SELECT COUNT(*) as count FROM '.$tableName,
$this->store->getDBCon()
);
$row = $result->fetch_assoc();
return $row['count'];
} | php | {
"resource": ""
} |
q7417 | ARC2.openConnection | train | protected function openConnection()
{
// set standard values
$this->configuration = array_merge([
'host' => 'localhost',
'database' => '',
'username' => '',
'password' => '',
'table-prefix' => 'saft_',
], $this->configuration);
/*
* check for missing connection credentials
*/
if ('' == $this->configuration['database']) {
throw new \Exception('ARC2: Field database is not set.');
} elseif ('' == $this->configuration['username']) {
throw new \Exception('ARC2: Field username is not set.');
} elseif ('' == $this->configuration['host']) {
throw new \Exception('ARC2: Field host is not set.');
}
// init store
$this->store = \ARC2::getStore([
'db_host' => $this->configuration['host'],
'db_name' => $this->configuration['database'],
'db_user' => $this->configuration['username'],
'db_pwd' => $this->configuration['password'],
'store_name' => $this->configuration['table-prefix'],
]);
} | php | {
"resource": ""
} |
q7418 | SgProfiler.start | train | public function start($identifier = null)
{
$this->loadProfile($identifier);
$this->currentProfile->start();
return $this;
} | php | {
"resource": ""
} |
q7419 | SgProfiler.loadProfile | train | protected function loadProfile($identifier = null)
{
if (!$identifier) {
$identifier = 'generic';
}
if (isset($this->profiles[$identifier])) {
$this->currentProfile = $this->profiles[$identifier];
} else {
$this->currentProfile = new SgProfile();
$this->profiles[$identifier] = $this->currentProfile;
}
return $this->currentProfile;
} | php | {
"resource": ""
} |
q7420 | SgProfiler.debug | train | public function debug($message = "%s seconds")
{
$this->logger->debug(sprintf($message, $this->currentProfile->getDuration()));
} | php | {
"resource": ""
} |
q7421 | AbstractTextTranslator.weeks | train | public function weeks($weeks)
{
return sprintf($this->formatPattern, $weeks, $this->week_words[$this->pluralization($weeks)]);
} | php | {
"resource": ""
} |
q7422 | AbstractTextTranslator.months | train | public function months($months)
{
return sprintf($this->formatPattern, $months, $this->month_words[$this->pluralization($months)]);
} | php | {
"resource": ""
} |
q7423 | AbstractTextTranslator.years | train | public function years($years)
{
return sprintf($this->formatPattern, $years, $this->year_words[$this->pluralization($years)]);
} | php | {
"resource": ""
} |
q7424 | TimeSlot.leftJoinWithout | train | public function leftJoinWithout() {
// Sort and count the time slots.
$buffer = TimeSlotHelper::merge($this->getTimeSlots());
$number = count($buffer);
// Check the time slots count.
if (0 === $number) {
return [$this];
}
// Initialize the output.
$output = [$this];
// Handle each time slot.
for ($i = 0; $i < $number; ++$i) {
//
$j = count($output) - 1;
// Left join without.
$res = TimeSlotHelper::leftJoinWithout($output[$j], $buffer[$i]);
if (null === $res) {
continue;
}
//
$output[$j] = $res[0];
if (2 === count($res)) {
$output[] = $res[1];
}
}
// Return the output.
if (1 === count($output) && $this === $output[0]) {
return [];
}
return $output;
} | php | {
"resource": ""
} |
q7425 | TimeSlot.removeTimeSlot | train | public function removeTimeSlot(TimeSlot $timeSlot) {
for ($i = count($this->timeSlots) - 1; 0 <= $i; --$i) {
if (true !== TimeSlotHelper::equals($timeSlot, $this->timeSlots[$i])) {
continue;
}
unset($this->timeSlots[$i]);
}
return $this;
} | php | {
"resource": ""
} |
q7426 | Config.setConfigDirectory | train | private function setConfigDirectory(string $dirName): void
{
$dirName = realpath($this->getDirectory(Config::DIR_ROOT) . $dirName);
if (is_dir($dirName)) {
$this->configDirectory = $dirName;
} else {
if ($dirName !== false) {
throw new \InvalidArgumentException(sprintf('Directory "%s" does not exists', $dirName));
} else {
throw new \InvalidArgumentException(sprintf('Config directory does not exists', $dirName));
}
}
} | php | {
"resource": ""
} |
q7427 | Retriever.getCustomerGroups | train | public function getCustomerGroups()
{
$groups = [];
/** @var GroupInterface $customerGroup */
foreach ($this->customerGroupCollection->getItems() as $customerGroup) {
$group = [];
$group['id'] = $customerGroup->getId();
$group['name'] = $customerGroup->getCode();
$group['is_default'] = intval($customerGroup->getId() == GroupInterface::NOT_LOGGED_IN_ID);
$matchingTaxClasses =
$this->taxCollection->getItemsByColumnValue('class_id', $customerGroup->getTaxClassId());
if (count($matchingTaxClasses)) {
$group['customer_tax_class_key'] = array_pop($matchingTaxClasses)->getClassName();
}
$groups[] = $group;
}
return $groups;
} | php | {
"resource": ""
} |
q7428 | AbstractValidator.create_error_message | train | protected function create_error_message( $message_name, $value ) {
$message = $this->get_message_template( $message_name );
if ( ! is_scalar( $value ) ) {
$value = $this->get_value_as_string( $value );
}
// replacing the placeholder for the %value%
$message = str_replace( '%value%', $value, $message );
// replacing the possible options-placeholder on the message
foreach ( $this->options as $search => $replace ) {
$replace = $this->get_value_as_string( $replace );
$message = str_replace( '%' . $search . '%', $replace, $message );
}
return $message;
} | php | {
"resource": ""
} |
q7429 | AbstractValidator.get_value_as_string | train | protected function get_value_as_string( $value ) {
if ( is_object( $value ) && ! in_array( '__toString', get_class_methods( $value ) ) ) {
$value = get_class( $value ) . ' object';
} else if ( is_array( $value ) ) {
$value = var_export( $value, TRUE );
}
return (string) $value;
} | php | {
"resource": ""
} |
q7430 | ZypioSNMP.addOid | train | public function addOid( $oid, $type = STRING, $value= NULL, $allowed = [] ){
$this->tree[$oid] = [ 'type' => $type, 'value' => $value, 'allowed' => $allowed ];
return $this;
} | php | {
"resource": ""
} |
q7431 | Image.resize | train | public function resize($props = array(), $coords = null) {
$croppable = elgg_extract('croppable', $props, false);
$width = elgg_extract('w', $props);
$height = elgg_extract('h', $props);
if (is_array($coords) && $croppable) {
$master_width = elgg_extract('master_width', $coords, self::MASTER);
$master_height = elgg_extract('master_height', $coords, self::MASTER);
$x1 = elgg_extract('x1', $coords, 0);
$y1 = elgg_extract('y1', $coords, 0);
$x2 = elgg_extract('x2', $coords, self::MASTER);
$y2 = elgg_extract('y2', $coords, self::MASTER);
// scale to master size and then crop
$this->source = $this->source->resize($master_width, $master_height, 'inside', 'down')->crop($x1, $y1, $x2 - $x1, $y2 - $y1)->resize($width);
} else if ($croppable) {
// crop to icon width and height
$this->source = $this->source->resize($width, $height, 'outside', 'any')->crop('center', 'center', $width, $height);
} else {
$this->source = $this->source->resize($width, $height, 'inside', 'down');
}
return $this;
} | php | {
"resource": ""
} |
q7432 | Image.save | train | public function save($path, $quality = array()) {
$ext = pathinfo($path, PATHINFO_EXTENSION);
$jpeg_quality = elgg_extract('jpeg_quality', $quality);
$png_quality = elgg_extract('png_quality', $quality);
$png_filter = elgg_extract('png_filter', $quality);
switch ($ext) {
default :
$this->source->saveToFile($path, $jpeg_quality);
break;
case 'gif';
$this->source->saveToFile($path);
break;
case 'png' :
$this->source->saveToFile($path, $png_quality, $png_filter);
break;
}
return $this;
} | php | {
"resource": ""
} |
q7433 | CMySQLConnector.clearStats | train | private function clearStats()
{
$this->queries_executed = 0;
$this->queries_released = 0;
$this->queries_erroneous = 0;
$this->sentences_executed = 0;
$this->sentences_erroneous = 0;
$this->inserts_executed = 0;
$this->inserts_erroneous = 0;
$this->updates_executed = 0;
$this->updates_erroneous = 0;
$this->deletes_executed = 0;
$this->deletes_erroneous = 0;
} | php | {
"resource": ""
} |
q7434 | CMySQLConnector.enqueueStatement | train | public function enqueueStatement(CNabuDBAbstractStatement $statement)
{
if ($statement instanceof CMySQLStatement) {
$hash = $statement->getHash();
if (!is_array($this->statements) || count($this->statements) === 0) {
$this->statements = array($hash => $statement);
} else {
$this->statements[$hash] = $statement;
}
}
} | php | {
"resource": ""
} |
q7435 | CMySQLConnector.dequeueStatement | train | public function dequeueStatement(CNabuDBAbstractStatement $statement)
{
if ($statement instanceof CMySQLStatement) {
$hash = $statement->getHash();
if ($hash !== null && count($this->statements) > 0 && array_key_exists($hash, $this->statements)) {
unset($this->statements[$hash]);
}
}
} | php | {
"resource": ""
} |
q7436 | CMySQLConnector.clearLeadingAndTrailingSpaces | train | private function clearLeadingAndTrailingSpaces(string $sentence) : string
{
if ($this->trailing_optimization) {
$sentence = preg_replace('/^\\s+/', '', $sentence);
$sentence = preg_replace('/\\s+$/', '', $sentence);
$sentence = preg_replace('/\\s*\\n\\s*/', ' ', $sentence);
}
return $sentence;
} | php | {
"resource": ""
} |
q7437 | UserCredentialAuthenticationLdapTrait.initializeLdap | train | public function initializeLdap() {
//initialize from parent
$this->initialize();
//validate ldap settings
$ldapSettings = $this->_passwordAuthenticationPlatformSettings;
if(
!(array_key_exists('ldap_account_suffix', $ldapSettings))
||!(array_key_exists('ad_password', $ldapSettings))
|| !(array_key_exists('ad_username', $ldapSettings))
|| !(array_key_exists('base_dn', $ldapSettings))
|| !(array_key_exists('cn_identifier', $ldapSettings))
|| !(array_key_exists('domain_controllers', $ldapSettings))
|| !(array_key_exists('group_attribute', $ldapSettings))
|| !(array_key_exists('group_cn_identifier', $ldapSettings))
|| !(array_key_exists('ldap_server_type', $ldapSettings))
|| !(array_key_exists('network_timeout', $ldapSettings))
|| !(array_key_exists('port', $ldapSettings))
|| !(array_key_exists('recursive_groups', $ldapSettings))
|| !(array_key_exists('time_limit', $ldapSettings))
|| !(array_key_exists('use_ssl', $ldapSettings))
|| !(array_key_exists('cache_support', $ldapSettings))
|| !(array_key_exists('cache_folder', $ldapSettings))
|| !(array_key_exists('expired_password_valid', $ldapSettings))
) {
throw new UserCredentialException("The LDAP feature of the usercredential login service is not initialized with all parameters", 2000);
}
//inject settings to the ldap handler
$this->_passwordAuthenticationPlatformSettings = $ldapSettings;
$this->initializeLdapAuthenticationHandler();
} | php | {
"resource": ""
} |
q7438 | UserCredentialAuthenticationLdapTrait.initializeLdapAuthenticationHandler | train | protected function initializeLdapAuthenticationHandler() {
$ldapSettings = $this->_passwordAuthenticationPlatformSettings;
$ldapAuthenticationHandler = new MultiotpWrapper();
$ldapAuthenticationHandler->SetLdapServerPassword($this->getCurrentPassword());
$ldapAuthenticationHandler->SetLdapBindDn($this->getCurrentUsername());
$ldapAuthenticationHandler->SetLdapAccountSuffix($ldapSettings['ldap_account_suffix']);
$ldapAuthenticationHandler->SetLdapBaseDn($ldapSettings['base_dn']);
$ldapAuthenticationHandler->SetLdapCnIdentifier($ldapSettings['cn_identifier']);
$ldapAuthenticationHandler->SetLdapDomainControllers($ldapSettings['domain_controllers']);
$ldapAuthenticationHandler->SetLdapGroupAttribute($ldapSettings['group_attribute']);
$ldapAuthenticationHandler->SetLdapGroupCnIdentifier($ldapSettings['group_cn_identifier']);
$ldapAuthenticationHandler->SetLdapServerType($ldapSettings['ldap_server_type']);
$ldapAuthenticationHandler->SetLdapNetworkTimeout($ldapSettings['network_timeout']);
$ldapAuthenticationHandler->SetLdapPort($ldapSettings['port']);
$ldapAuthenticationHandler->SetLdapRecursiveGroups($ldapSettings['recursive_groups']);
$ldapAuthenticationHandler->SetLdapTimeLimit($ldapSettings['time_limit']);
$ldapAuthenticationHandler->SetLdapSsl($ldapSettings['use_ssl']);
$ldapAuthenticationHandler->SetLdapCacheOn($ldapSettings['cache_support']);
$ldapAuthenticationHandler->SetLdapCacheFolder($ldapSettings['cache_folder']);
$ldapAuthenticationHandler->SetLdapExpiredPasswordValid($ldapSettings['expired_password_valid']);
$this->ldapAuthenticationHandler = $ldapAuthenticationHandler;
} | php | {
"resource": ""
} |
q7439 | Observer.execute | train | public function execute(\Magento\Framework\Event\Observer $observer)
{
if (!$this->redirect->isAllowed()) {
$this->session->unsetScript();
return;
}
foreach ($this->getRedirects() as $redirect) {
$redirect->run();
}
} | php | {
"resource": ""
} |
q7440 | Observer.getRedirects | train | private function getRedirects()
{
$httpWithJsBackup = [
$this->httpRedirect,
$this->jsRedirect
];
return $this->redirect->isTypeJavaScript() ? [$this->jsRedirect] : $httpWithJsBackup;
} | php | {
"resource": ""
} |
q7441 | AbstractTriplePatternStore.getStatement | train | protected function getStatement(Query $queryObject)
{
$queryParts = $queryObject->getQueryParts();
$tupleInformaton = null;
$tupleType = null;
/*
* Use triple pattern
*/
if (true === isset($queryParts['triple_pattern'])) {
$tupleInformation = $queryParts['triple_pattern'];
$tupleType = 'triple';
/*
* Use quad pattern
*/
} elseif (true === isset($queryParts['quad_pattern'])) {
$tupleInformation = $queryParts['quad_pattern'];
$tupleType = 'quad';
/*
* Neither triple nor quad information
*/
} else {
throw new \Exception(
'Neither triple nor quad information available in given query object: '.$queryObject->getQuery()
);
}
if (1 > count($tupleInformation)) {
throw new \Exception('Query contains more than one triple- respectivly quad pattern.');
}
/*
* Triple
*/
if ('triple' == $tupleType) {
$subject = $this->createNodeByValueAndType($tupleInformation[0]['s'], $tupleInformation[0]['s_type']);
$predicate = $this->createNodeByValueAndType($tupleInformation[0]['p'], $tupleInformation[0]['p_type']);
$object = $this->createNodeByValueAndType($tupleInformation[0]['o'], $tupleInformation[0]['o_type']);
$graph = null;
/*
* Quad
*/
} elseif ('quad' == $tupleType) {
$subject = $this->createNodeByValueAndType($tupleInformation[0]['s'], $tupleInformation[0]['s_type']);
$predicate = $this->createNodeByValueAndType($tupleInformation[0]['p'], $tupleInformation[0]['p_type']);
$object = $this->createNodeByValueAndType($tupleInformation[0]['o'], $tupleInformation[0]['o_type']);
$graph = $this->createNodeByValueAndType($tupleInformation[0]['g'], 'uri');
}
// no else neccessary, because otherwise the upper exception would be thrown if tupleType is neither
// quad or triple.
return $this->statementFactory->createStatement($subject, $predicate, $object, $graph);
} | php | {
"resource": ""
} |
q7442 | AbstractTriplePatternStore.getStatements | train | protected function getStatements(Query $queryObject)
{
$queryParts = $queryObject->getQueryParts();
$statementArray = [];
// if only triples, but no quads
if (true === isset($queryParts['triple_pattern'])
&& false === isset($queryParts['quad_pattern'])) {
foreach ($queryParts['triple_pattern'] as $pattern) {
/**
* Create Node instances for S, P and O to build a Statement instance later on.
*/
$s = $this->createNodeByValueAndType($pattern['s'], $pattern['s_type']);
$p = $this->createNodeByValueAndType($pattern['p'], $pattern['p_type']);
$o = $this->createNodeByValueAndType($pattern['o'], $pattern['o_type']);
$g = null;
$statementArray[] = $this->statementFactory->createStatement($s, $p, $o, $g);
}
// if only quads, but not triples
} elseif (false === isset($queryParts['triple_pattern'])
&& true === isset($queryParts['quad_pattern'])) {
foreach ($queryParts['quad_pattern'] as $pattern) {
/**
* Create Node instances for S, P and O to build a Statement instance later on.
*/
$s = $this->createNodeByValueAndType($pattern['s'], $pattern['s_type']);
$p = $this->createNodeByValueAndType($pattern['p'], $pattern['p_type']);
$o = $this->createNodeByValueAndType($pattern['o'], $pattern['o_type']);
$g = $this->createNodeByValueAndType($pattern['g'], $pattern['g_type']);
$statementArray[] = $this->statementFactory->createStatement($s, $p, $o, $g);
}
// found quads and triples
} elseif (true === isset($queryParts['triple_pattern'])
&& true === isset($queryParts['quad_pattern'])) {
throw new \Exception('Query contains quads and triples. That is not supported yet.');
// neither quads nor triples
} else {
throw new \Exception('Query contains neither quads nor triples.');
}
return $this->statementIteratorFactory->createStatementIteratorFromArray($statementArray);
} | php | {
"resource": ""
} |
q7443 | ValidatorFactory.create | train | public function create( $type, array $properties = [ ] ) {
// If type is already an instance of validator, and no properties provided, we just return it as is
if ( $type instanceof ValidatorInterface && ! $properties ) {
return $type;
}
// If an instance of validator is given alongside some properties, we extract the class so a new instance
// will be created with given properties
if ( $type instanceof ValidatorInterface ) {
$type = get_class( $type );
}
// From now on, we expect a string, if not, let's just throw an exception
if ( ! is_string( $type ) ) {
throw new Exception\InvalidArgumentException(
sprintf( 'Validator identifier must be in a string, %s given.', gettype( $type ) )
);
}
// If `$type` is the fully qualified name of a validator class, just use it
if ( is_subclass_of( $type, ValidatorInterface::class, TRUE ) ) {
return new $type( $properties );
}
// If name is fine, but namespace is missing, let's just add it and instantiate
if ( is_subclass_of( __NAMESPACE__ . '\\' . $type, ValidatorInterface::class, TRUE ) ) {
$class = __NAMESPACE__ . '\\' . $type;
return new $class( $properties );
}
$type = trim( $type );
// We accept case-insensitive types, e.g. 'greater_than', 'Greater_Than', 'GREATER_THAN'
$lower_case_type = strtolower( $type );
if ( isset( self::$classes_map[ $lower_case_type ] ) ) {
$class = self::$classes_map[ $lower_case_type ];
return new $class( $properties );
}
// We also accept alternative version of identifier:
// - TitleCased: 'GreaterThan'
// - camelCased: 'greaterThan'
// - separated with any character and case insensitive: 'greater-than', 'greater~than', 'Greater Than'...
$alt_types[] = strtolower( preg_replace( [ '/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/' ], '$1_$2', $type ) );
$alt_types[] = preg_replace( '/[^a-z]+/', '_', $lower_case_type );
foreach ( $alt_types as $alt_type ) {
if ( isset( self::$classes_map[ $alt_type ] ) ) {
$class = self::$classes_map[ $alt_type ];
return new $class( $properties );
}
}
throw new Exception\InvalidArgumentException(
sprintf(
'%s is not an accepted validator identifier for %s.',
$type,
__METHOD__
)
);
} | php | {
"resource": ""
} |
q7444 | ControllerFinder.parseNamespace | train | private function parseNamespace($filePath): string
{
preg_match('/namespace(.*);/', file_get_contents($filePath), $result);
return isset($result[1]) ? $result[1] . "\\" : '';
} | php | {
"resource": ""
} |
q7445 | Integration.getServiceProvider | train | public static function getServiceProvider() {
if (is_callable('_elgg_services')) {
return _elgg_services();
}
global $CONFIG;
if (!isset($CONFIG)) {
$path = self::getRootPath() . '/engine/settings.php';
if (!is_file($path)) {
$path = self::getRootPath() . '/elgg-config/settings.php';
}
require_once $path;
}
return new \Elgg\Di\ServiceProvider(new \Elgg\Config($CONFIG));
} | php | {
"resource": ""
} |
q7446 | Integration.getElggVersion | train | public static function getElggVersion() {
if (isset(self::$version)) {
return self::$version;
}
if (is_callable('elgg_get_version')) {
return elgg_get_version(true);
} else {
$path = self::getRootPath() . '/version.php';
if (!include($path)) {
return false;
}
self::$version = $release;
return self::$version;
}
} | php | {
"resource": ""
} |
q7447 | MultiotpXmlParser.Parse | train | function Parse()
{
//Create the parser resource
$this->parser = xml_parser_create();
//Set the handlers
xml_set_object($this->parser, $this);
xml_set_element_handler($this->parser, 'StartElement', 'EndElement');
xml_set_character_data_handler($this->parser, 'CharacterData');
//Error handling
if (!xml_parse($this->parser, $this->xml))
$this->HandleError(xml_get_error_code($this->parser), xml_get_current_line_number($this->parser), xml_get_current_column_number($this->parser), xml_get_current_byte_index($this->parser));
//Free the parser
xml_parser_free($this->parser);
} | php | {
"resource": ""
} |
q7448 | MultiotpXmlParser.HandleError | train | function HandleError($code, $line, $col, $byte_index = 0)
{
$sample_size = 80;
$sample_start = $byte_index - ($sample_size / 2);
if ($sample_start < 0) {
$sample_start = 0;
}
trigger_error('XML Parsing Error at '.$line.':'.$col. (($byte_index != 0)?' (byte index: '.$byte_index.')':''). '. Error '.$code.': '.xml_error_string($code). ' check sample which starts at position '.$sample_start.': html encoded: '.htmlentities(substr($this->xml, $sample_start, $sample_size)). ' (hex: '.bin2hex(substr($this->xml, $sample_start, $sample_size)).', raw: '.(substr($this->xml, $sample_start, $sample_size)).')');
} | php | {
"resource": ""
} |
q7449 | MultiotpXmlParser.StartElement | train | function StartElement($parser, $name, $attrs = array())
{
//Make the name of the tag lower case
$name = strtolower($name);
//Check to see if tag is root-level
if (count($this->stack) == 0)
{
//If so, set the document as the current tag
$this->document = new MultiotpXMLTag($name, $attrs);
//And start out the stack with the document tag
$this->stack = array('document');
}
//If it isn't root level, use the stack to find the parent
else
{
//Get the name which points to the current direct parent, relative to $this
$parent = $this->GetStackLocation();
//Add the child
eval('$this->'.$parent.'->AddChild($name, $attrs, '.count($this->stack).', $this->cleanTagNames);');
//If the cleanTagName feature is on, replace colons and dashes with underscores
if($this->cleanTagNames)
$name = str_replace(array(':', '-'), '_', $name);
//Update the stack
eval('$this->stack[] = $name.\'[\'.(count($this->'.$parent.'->'.$name.') - 1).\']\';');
}
} | php | {
"resource": ""
} |
q7450 | MultiotpXMLTag.AddChild | train | function AddChild($name, $attrs, $parents, $cleanTagName = true)
{
//If the tag is a reserved name, output an error
if(in_array($name, array('tagChildren', 'tagAttrs', 'tagParents', 'tagData', 'tagName')))
{
trigger_error('You have used a reserved name as the name of an XML tag. Please consult the documentation (http://www.criticaldevelopment.net/xml/) and rename the tag named "'.$name.'" to something other than a reserved name.', E_USER_ERROR);
return;
}
//Create the child object itself
$child = new MultiotpXMLTag($name, $attrs, $parents);
//If the cleanTagName feature is on, replace colons and dashes with underscores
if($cleanTagName)
$name = str_replace(array(':', '-'), '_', $name);
//Toss up a notice if someone's trying to to use a colon or dash in a tag name
elseif(strstr($name, ':') || strstr($name, '-'))
trigger_error('Your tag named "'.$name.'" contains either a dash or a colon. Neither of these characters are friendly with PHP variable names, and, as such, they cannot be accessed and will cause the parser to not work. You must enable the cleanTagName feature (pass true as the second argument of the MultiotpXmlParser constructor). For more details, see http://www.criticaldevelopment.net/xml/', E_USER_ERROR);
//If there is no array already set for the tag name being added,
//create an empty array for it
if(!isset($this->$name))
$this->$name = array();
//Add the reference of it to the end of an array member named for the tag's name
$this->{$name}[] =& $child;
//Add the reference to the children array member
$this->tagChildren[] =& $child;
} | php | {
"resource": ""
} |
q7451 | MultiotpXMLTag.GetXML | train | function GetXML()
{
//Start a new line, indent by the number indicated in $this->parents, add a <, and add the name of the tag
$out = "\n".str_repeat("\t", $this->tagParents).'<'.$this->tagName;
//For each attribute, add attr="value"
foreach($this->tagAttrs as $attr => $value)
$out .= ' '.$attr.'="'.$value.'"';
//If there are no children and it contains no data, end it off with a />
if(empty($this->tagChildren) && empty($this->tagData))
$out .= " />";
//Otherwise...
else
{
//If there are children
if(!empty($this->tagChildren))
{
//Close off the start tag
$out .= '>';
//For each child, call the GetXML function (this will ensure that all children are added recursively)
foreach($this->tagChildren as $child)
{
if(is_object($child))
$out .= $child->GetXML();
}
//Add the newline and indentation to go along with the close tag
$out .= "\n".str_repeat("\t", $this->tagParents);
}
//If there is data, close off the start tag and add the data
elseif(!empty($this->tagData))
$out .= '>'.$this->tagData;
//Add the end tag
$out .= '</'.$this->tagName.'>';
}
//Return the final output
return $out;
} | php | {
"resource": ""
} |
q7452 | MultiotpXMLTag.DeleteChildren | train | function DeleteChildren()
{
//Loop through all child tags
for($x = 0; $x < count($this->tagChildren); $x ++)
{
//Do this recursively
$this->tagChildren[$x]->DeleteChildren();
//Delete the name and value
$this->tagChildren[$x] = null;
unset($this->tagChildren[$x]);
}
} | php | {
"resource": ""
} |
q7453 | Redirect.isTypeJavaScript | train | public function isTypeJavaScript()
{
$redirectType = $this->coreConfig->getConfigByPath(SgCoreInterface::PATH_REDIRECT_TYPE);
return $redirectType->getValue() === SgCoreInterface::VALUE_REDIRECT_JS;
} | php | {
"resource": ""
} |
q7454 | LocalFileController.view | train | public function view($id)
{
$file = LocalFile::getByIdentifier($id);
$response = response($file->getContents(), 200)->withHeaders([
'Content-Type' => $file->getFile()->getMimeType(),
'Cache-Control' => 'max-age=86400, public',
'Expires' => Carbon::now()->addSeconds(86400)->format('D, d M Y H:i:s \G\M\T')
]);
return $response;
} | php | {
"resource": ""
} |
q7455 | LocalFileController.download | train | public function download($id)
{
$file = LocalFile::getByIdentifier($id);
return response()->download($file->getAbsolutePath(), $file->getDownloadName());
} | php | {
"resource": ""
} |
q7456 | QueryFactoryImpl.createInstanceByQueryString | train | public function createInstanceByQueryString($query)
{
switch ($this->rdfHelpers->getQueryType($query)) {
case 'askQuery':
return new AskQueryImpl($query, $this->rdfHelpers);
case 'constructQuery':
return new ConstructQueryImpl($query, $this->rdfHelpers);
case 'describeQuery':
return new DescribeQueryImpl($query, $this->rdfHelpers);
case 'graphQuery':
return new GraphQueryImpl($query, $this->rdfHelpers);
case 'selectQuery':
return new SelectQueryImpl($query, $this->rdfHelpers);
case 'updateQuery':
return new UpdateQueryImpl($query, $this->rdfHelpers);
default:
throw new \Exception('Unknown query type: '.$query);
}
} | php | {
"resource": ""
} |
q7457 | Model.toFullArray | train | public function toFullArray(): array
{
//convert the obj to array in order to conver to json
$result = get_object_vars($this);
foreach ($result as $key => $value) {
if (preg_match('#^_#', $key) === 1) {
unset($result[$key]);
}
}
return $result;
} | php | {
"resource": ""
} |
q7458 | TwigExtension.getApp | train | public function getApp(): App
{
if (!is_null($this->getTemplateEngine()->getApp())) {
return $this->getTemplateEngine()->getApp();
} else {
throw new RuntimeException('Template engine is not initialized with application');
}
} | php | {
"resource": ""
} |
q7459 | TwigExtension.filterDateFormat | train | public function filterDateFormat($datetime, string $pattern = 'dd/MM/yyyy', string $locale = null): string
{
if (empty($locale)) {
$locale = $this->getApp()->getProfile()->getLocale();
}
return b_date_format($datetime, $pattern, $locale);
} | php | {
"resource": ""
} |
q7460 | TwigExtension.functionPath | train | public function functionPath(string $name, array $parameters = []): string
{
return $this->getApp()->getService('routing')->generate($name, $parameters);
} | php | {
"resource": ""
} |
q7461 | TwigExtension.functionPreload | train | public function functionPreload(string $link, array $parameters = []): string
{
$push = !(!empty($parameters['nopush']) && $parameters['nopush'] == true);
if (!$push || !in_array(md5($link), $this->h2pushCache)) {
$header = sprintf('Link: <%s>; rel=preload', $link);
// as
if (!empty($parameters['as'])) {
$header = sprintf('%s; as=%s', $header, $parameters['as']);
}
// type
if (!empty($parameters['type'])) {
$header = sprintf('%s; type=%s', $header, $parameters['as']);
}
// crossorigin
if (!empty($parameters['crossorigin']) && $parameters['crossorigin'] == true) {
$header .= '; crossorigin';
}
// nopush
if (!$push) {
$header .= '; nopush';
}
header($header, false);
// Cache
if ($push) {
$this->h2pushCache[] = md5($link);
setcookie(sprintf('%s[%s]', self::H2PUSH_CACHE_COOKIE, md5($link)), 1, 0, '/', '', false, true);
}
}
return $link;
} | php | {
"resource": ""
} |
q7462 | BaseAsset.run | train | private function run($type) {
//getting the defined array of assets
//this method will define in the children classes
$this->init();
//making the base path of public dir
$this->getTarget();
//duplication check
if ($type == 'del') {
return Asset::delAsset($this->name);
}
//find all of them between patterns and folders
$this->boot();
//check for those that have to copy to their cache folders
foreach ($this->loop as $kind => $contents) {
if ( ! empty($contents)) {
foreach ($contents as $index => $content) {
if ( ! $this->isPublic($this->baseDir . $content)) {
$index = $this->baseDir . $content;
$this->copy[$kind][$index] = public_path() . $this->target . $content;
} else {
$this->target = '';
}
$this->destination[$kind][] = $this->target . $content;
}
}
}
//remove the ignored items from all other kinds
if ( ! empty($this->loop['ignore'])) {
foreach ($this->loop as $kind => $contents) {
if ($kind != 'ignore' && ! empty($contents)) {
$this->copy[$kind] = array_diff($this->copy[$kind], $this->copy['ignore']);
$this->destination[$kind] = array_diff($this->destination[$kind], $this->destination['ignore']);
}
}
unset($this->copy['ignore']);
unset($this->destination['ignore']);
}
//un setting the include index from destination
if (array_key_exists('include', $this->destination)) {
unset($this->destination['include']);
}
//flatting the copy array
$copyTemp = [];
foreach ($this->copy as $kind => $contents) {
foreach ($contents as $from => $to) {
$copyTemp[$from] = $to;
}
}
$this->copy = $copyTemp;
//detect type of command and then we pass the data to the AssetHolder
if ($type == 'add') {
$result = array_merge($this->destination, [
'name' => $this->name,
'copy' => $this->copy,
'forceCopy' => $this->forceCopy,
'chmod' => $this->chmod,
'style' => $this->style,
'script' => $this->script,
'cssOption' => $this->cssOption,
'jsOption' => $this->jsOption,
]);
Asset::addAsset($result);
}
//we must destroy the previous object!
self::$instance = null;
} | php | {
"resource": ""
} |
q7463 | BaseAsset.getTarget | train | private function getTarget() {
$this->name = str_replace('Asset', '', class_basename(static::class));
$name = $this->name;
if ( ! empty($this->cacheFolder)) {
$name = $this->cacheFolder;
}
$cacheName = trim(config('asset.public_cache_folder'), '/');
$this->target = '/' . $cacheName . '/' . studly_case($name) . '/';
} | php | {
"resource": ""
} |
q7464 | Fix.getDefaultMethod | train | private function getDefaultMethod($price, $cost = null)
{
$method = $this->rateMethodFactory->create();
$method->setData('carrier', $this->getCarrierCode());
$method->setData('carrier_title', 'Shopgate');
$method->setData('method', $this->method);
$method->setData('method_title', $this->getConfigData('name'));
$method->setData('cost', $cost ? : $price);
$method->setPrice($price);
return $method;
} | php | {
"resource": ""
} |
q7465 | FitTransformer.fill | train | public function fill($image) {
$fill = $this->getConfig('fill');
$r = $fill[0];
$g = $fill[1];
$b = $fill[2];
$a = isset($fill[3]) ? $fill[3] : 127;
imagefill($image, 0, 0, imagecolorallocatealpha($image, $r, $g, $b, $a));
return $image;
} | php | {
"resource": ""
} |
q7466 | DateTimeHelper.getWeekNumberToApply | train | public static function getWeekNumberToApply(DateTime $date, DateTime $startDate, $weekCount, $weekOffset = 1) {
// Check the week arguments.
if ($weekCount <= 0 || $weekOffset <= 0 || $weekCount < $weekOffset) {
return -1;
}
// Calculate.
$result = intval($date->diff($startDate)->d / 7);
$result %= $weekCount;
$result += $weekOffset;
if ($weekCount < $result) {
$result -= $weekCount;
}
// Return.
return $result;
} | php | {
"resource": ""
} |
q7467 | DateTimeHelper.translateWeekday | train | public static function translateWeekday($date, $locale = "en") {
// Initialize.
$template = __DIR__ . "/../Resources/translations/messages.%locale%.yml";
$filename = str_replace("%locale%", $locale, $template);
// Check if the filename exists.
if (false === file_exists($filename)) {
$filename = str_replace("%locale%", "en", $template);
}
// Parse the translations.
$translations = Yaml::parse(file_get_contents($filename));
// Return the weekday part translated.
return str_ireplace(array_keys($translations["weekdays"]), array_values($translations["weekdays"]), $date);
} | php | {
"resource": ""
} |
q7468 | FilteredBacktraceReporter.getBacktrace | train | public function getBacktrace($exception = null)
{
$backtrace = parent::getBacktrace($exception);
foreach ($backtrace as $index => $backtraceCall) {
$functionName = $this->buildFunctionName($backtraceCall);
foreach ($this->filteredFunctions as $pattern) {
if (preg_match('/'.$pattern.'/', $functionName)) {
unset($backtrace[$index]);
break;
}
}
}
return array_values($backtrace);
} | php | {
"resource": ""
} |
q7469 | DateTimeAgo.get | train | public function get(DateTime $date, DateTime $reference_date = null )
{
if (is_null($reference_date)) {
$reference_date = new DateTime();
}
$diff = $reference_date->diff($date);
return $this->getText($diff, $date);
} | php | {
"resource": ""
} |
q7470 | DateTimeAgo.getText | train | public function getText(DateInterval $diff, $date)
{
if ($this->now($diff)) {
return $this->text_translator->now();
}
if ($this->minutes($diff)) {
return $this->text_translator->minutes($this->minutes($diff));
}
if ($this->hours($diff)) {
return $this->text_translator->hours($this->hours($diff));
}
if ($this->days($diff)) {
return $this->text_translator->days($this->days($diff));
}
if ($this->text_translator->supportsWeeks() && $this->weeks($diff)) {
return $this->text_translator->weeks($this->weeks($diff));
}
if ($this->text_translator->supportsMonths() && $this->months($diff)) {
return $this->text_translator->months($this->months($diff));
}
if ($this->text_translator->supportsYears() && $this->years($diff)) {
return $this->text_translator->years($this->years($diff));
}
return $date->format($this->format);
} | php | {
"resource": ""
} |
q7471 | DateTimeAgo.daily | train | public function daily($diff)
{
if (($diff->y == 0) && ($diff->m == 0) && (($diff->d == 0) || (($diff->d == 1) && ($diff->h == 0) && ($diff->i == 0)))) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q7472 | DateTimeAgo.hourly | train | public function hourly($diff)
{
if ($this->daily($diff) && ($diff->d == 0) && (($diff->h == 0) || (($diff->h == 1) && ($diff->i == 0)))) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q7473 | DateTimeAgo.days | train | public function days(DateInterval $diff)
{
if ($diff->days <= $this->max_days_count) {
return $diff->days;
}
return false;
} | php | {
"resource": ""
} |
q7474 | DateTimeAgo.weeks | train | public function weeks(DateInterval $diff)
{
if ($diff->days < 30) {
return (int) floor($diff->days / 7);
}
return false;
} | php | {
"resource": ""
} |
q7475 | DateTimeAgo.months | train | public function months(DateInterval $diff)
{
if ($diff->days >= 365) {
return FALSE;
}
$x = (int) floor($diff->days / 30.417);
if ($x === 0) {
return 1;
} else {
return $x;
}
} | php | {
"resource": ""
} |
q7476 | CookieMonster.addClassOption | train | protected function addClassOption($name, $value)
{
$value = trim($value);
if (substr($value, 0, 1) == '.' || substr($value, 0, 1) == '#') {
$value = substr($value, 1);
}
if ($value != '') {
$this->addOption('class', $name, $value);
}
} | php | {
"resource": ""
} |
q7477 | CookieMonster.addContentOption | train | protected function addContentOption($name, $value)
{
$value = trim($value);
if (!empty($value) && is_string($value)) {
$this->addOption('content', $name, $value);
}
} | php | {
"resource": ""
} |
q7478 | CookieMonster.addCookieBoolOption | train | protected function addCookieBoolOption($name, $value)
{
if ($value === true || $value === false) {
$this->addOption('cookie', $name, $value);
}
} | php | {
"resource": ""
} |
q7479 | CookieMonster.addCookieIntOption | train | protected function addCookieIntOption($name, $value)
{
$value = trim($value);
if ($value !== null && $value !== '' && is_numeric($value)) {
$this->addOption('cookie', $name, (int)$value);
}
} | php | {
"resource": ""
} |
q7480 | CookieMonster.addCookieOption | train | protected function addCookieOption($name, $value)
{
if (is_string($value)) {
$value = preg_replace("~^;? ?$name=~", '', trim($value));
if ($value !== '') {
$this->addOption('cookie', $name, $value);
}
}
} | php | {
"resource": ""
} |
q7481 | CookieMonster.addParamsOption | train | protected function addParamsOption($name, $value)
{
if (is_array($value) && count($value)) {
$this->addOption('content', $name, $value);
}
} | php | {
"resource": ""
} |
q7482 | CookieMonster.addStyle | train | protected function addStyle($what, $value)
{
if (is_array($value) && count($value)) {
$type = 'inner';
switch ($what) {
case 0:
$type = 'outer';
break;
case 2:
$type = 'button';
break;
}
foreach ($value as $name => $set) {
if (!empty($set) && is_string($set)) {
$this->{$type . 'Style'}[$name] = str_replace(';', '', trim($set));
}
}
}
} | php | {
"resource": ""
} |
q7483 | CookieMonster.checkContent | train | protected function checkContent()
{
if (is_array($this->content) && count($this->content)) {
foreach ($this->content as $name => $value) {
switch ($name) {
case 'category':
case 'mainMessage':
case 'buttonMessage':
case 'language':
$this->addContentOption($name, $value);
break;
case 'mainParams':
case 'buttonParams':
$this->addParamsOption($name, $value);
break;
}
}
}
} | php | {
"resource": ""
} |
q7484 | CookieMonster.checkCookie | train | protected function checkCookie()
{
if (is_array($this->cookie) && count($this->cookie)) {
foreach ($this->cookie as $name => $value) {
switch ($name) {
case 'domain':
case 'path':
$this->addCookieOption($name, $value);
break;
case 'max-age':
case 'expires':
$this->addCookieIntOption($name, $value);
break;
case 'secure':
$this->addCookieBoolOption($name, $value);
break;
}
}
}
} | php | {
"resource": ""
} |
q7485 | CookieMonster.initCookie | train | protected function initCookie()
{
$cookieOptions = Json::encode(
array_merge(
$this->cookieOptions,
[
'classOuter' => str_replace(' ', '.', $this->classOptions['classOuter']),
'classInner' => str_replace(' ', '.', $this->classOptions['classInner']),
'classButton' => str_replace(' ', '.', $this->classOptions['classButton']),
]
)
);
$view = $this->getView();
assets\CookieMonsterAsset::register($view);
$view->registerJs("CookieMonster.init($cookieOptions);");
} | php | {
"resource": ""
} |
q7486 | CookieMonster.prepareViewParams | train | protected function prepareViewParams()
{
$outerStyle = [];
$innerStyle = [];
$buttonStyle = [];
foreach ($this->outerStyle as $name => $value) {
$outerStyle[] = $name . ':' . $value;
}
foreach ($this->innerStyle as $name => $value) {
$innerStyle[] = $name . ':' . $value;
}
foreach ($this->buttonStyle as $name => $value) {
$buttonStyle[] = $name . ':' . $value;
}
return [
'content' => $this->contentOptions,
'outerHtmlOptions' => array_merge(
$this->outerHtml,
[
'style' => implode(';', $outerStyle),
'class' => $this->classOptions['classOuter']
]
),
'innerHtmlOptions' => array_merge(
$this->innerHtml,
[
'style' => implode(';', $innerStyle),
'class' => $this->classOptions['classInner']
]
),
'buttonHtmlOptions' => array_merge(
$this->buttonHtml,
[
'style' => implode(';', $buttonStyle),
'class' => $this->classOptions['classButton']
]
),
'params' => $this->params
];
} | php | {
"resource": ""
} |
q7487 | CookieMonster.replaceStyle | train | protected function replaceStyle($what, $value)
{
if (is_array($value) && count($value)) {
$type = 'inner';
switch ($what) {
case 0:
$type = 'outer';
break;
case 2:
$type = 'button';
break;
}
foreach ($value as $name => $set) {
if (isset($this->{$type . 'Style'}[$name])) {
if ($set === false || $set === null) {
unset($this->{$type . 'Style'}[$name]);
} else {
$this->{$type . 'Style'}[$name] = str_replace(';', '', trim($set));
}
}
}
}
} | php | {
"resource": ""
} |
q7488 | CookieMonster.setDefaults | train | protected function setDefaults()
{
if (!isset($this->contentOptions['category'])
|| (isset($this->contentOptions['category'])
&& empty($this->contentOptions['category']))) {
$this->contentOptions['category'] = 'app';
}
if (!isset($this->contentOptions['mainParams'])) {
$this->contentOptions['mainParams'] = [];
}
if (!isset($this->contentOptions['buttonParams'])) {
$this->contentOptions['buttonParams'] = [];
}
if (!isset($this->contentOptions['language'])) {
$this->contentOptions['language'] = null;
}
if (!isset($this->contentOptions['mainMessage'])) {
$this->contentOptions['mainMessage'] = 'We use cookies on our websites to help us offer you the best online experience. By continuing to use our website, you are agreeing to our use of cookies. Alternatively, you can manage them in your browser settings.';
}
if (!isset($this->contentOptions['buttonMessage'])) {
$this->contentOptions['buttonMessage'] = 'I understand';
}
if (!isset($this->cookieOptions['path'])) {
$this->cookieOptions['path'] = '/';
}
if (!isset($this->cookieOptions['expires'])) {
$this->cookieOptions['expires'] = 30;
}
if (!isset($this->cookieOptions['secure'])) {
$this->cookieOptions['secure'] = false;
}
if (!isset($this->classOptions['classOuter'])) {
$this->classOptions['classOuter'] = 'CookieMonsterBox';
}
if (!isset($this->classOptions['classInner'])) {
$this->classOptions['classInner'] = '';
}
if (!isset($this->classOptions['classButton'])) {
$this->classOptions['classButton'] = 'CookieMonsterOk';
}
} | php | {
"resource": ""
} |
q7489 | CookieMonster.setHtmlOptions | train | protected function setHtmlOptions($what, $value)
{
if (is_array($value) && count($value)) {
$type = 'inner';
switch ($what) {
case 0:
$type = 'outer';
break;
case 2:
$type = 'button';
break;
}
foreach ($value as $name => $set) {
if ($name == 'class' || $name == 'style') {
continue;
} else {
$this->{$type . 'Html'}[$name] = trim($set);
}
}
}
} | php | {
"resource": ""
} |
q7490 | CookieMonster.setMode | train | protected function setMode()
{
$this->outerStyle = [
'display' => 'none',
'z-index' => 10000,
'position' => 'fixed',
'background-color' => '#fff',
'font-size' => '12px',
'color' => '#000'
];
$this->innerStyle = ['margin' => '10px'];
$this->buttonStyle = ['margin-left' => '10px'];
switch ($this->mode) {
case 'bottom':
$this->outerStyle = array_merge(
$this->outerStyle,
[
'bottom' => 0,
'left' => 0,
'width' => '100%',
'box-shadow' => '0 -2px 2px #000',
]
);
break;
case 'box':
$this->outerStyle = array_merge(
$this->outerStyle,
[
'bottom' => '20px',
'right' => '20px',
'width' => '300px',
'box-shadow' => '-2px 2px 2px #000',
'border-radius' => '10px',
]
);
break;
case 'custom':
$this->outerStyle = [];
$this->innerStyle = [];
$this->buttonStyle = [];
break;
case 'top':
default:
$this->outerStyle = array_merge(
$this->outerStyle,
[
'top' => 0,
'left' => 0,
'width' => '100%',
'box-shadow' => '0 2px 2px #000',
]
);
}
} | php | {
"resource": ""
} |
q7491 | CookieMonster.setCookieView | train | protected function setCookieView($value)
{
$value = trim($value);
if (!empty($value)) {
$this->cookieView = $value;
}
} | php | {
"resource": ""
} |
q7492 | CMySQLDescriptor.buildFieldReplacement | train | public function buildFieldReplacement(array $field_descriptor, $alias = false)
{
if ($alias === false) {
$alias = $field_descriptor['name'];
}
switch ($field_descriptor['data_type']) {
case 'int':
$retval = "%d$alias\$d";
break;
case 'float':
case 'double':
$retval = "%F$alias\$d";
break;
case 'varchar':
case 'text':
case 'longtext':
case 'enum':
case 'set':
case 'tinytext':
$retval = "'%s$alias\$s'";
break;
default:
$retval = false;
}
return $retval;
} | php | {
"resource": ""
} |
q7493 | CMySQLDescriptor.buildFieldValue | train | public function buildFieldValue($field_descriptor, $value)
{
if ($value === null) {
$retval = 'NULL';
} elseif ($value === false) {
$retval = 'false';
} elseif ($value === true) {
$retval = 'true';
} else {
if (!is_array($value)) {
$value = array($value);
}
switch ($field_descriptor['data_type']) {
case 'int':
$retval = $this->nb_connector->buildSentence('%d', $value);
break;
case 'float':
case 'double':
$retval = $this->nb_connector->buildSentence('%F', $value);
break;
case 'varchar':
case 'text':
case 'longtext':
case 'enum':
case 'set':
case 'tinytext':
$retval = $this->nb_connector->buildSentence("'%s'", $value);
break;
case 'date':
case 'datetime':
if ($field_descriptor['name'] !== $this->storage_descriptor['name'] . '_creation_datetime') {
if ($value === null) {
$retval = 'null';
} else {
$retval = $this->nb_connector->buildSentence("'%s'", $value);
}
} else {
$retval = false;
}
break;
default:
error_log($field_descriptor['data_type']);
throw new ENabuCoreException(ENabuCoreException::ERROR_FEATURE_NOT_IMPLEMENTED);
}
}
return $retval;
} | php | {
"resource": ""
} |
q7494 | PandaSigner.signParams | train | public function signParams($method, $path, array $params = array())
{
$params = $this->completeParams($params);
// generate the signature
$params['signature'] = $this->signature($method, $path, $params);
return $params;
} | php | {
"resource": ""
} |
q7495 | PandaSigner.signature | train | public function signature($method, $path, array $params = array())
{
$params = $this->completeParams($params);
ksort($params);
if (isset($params['file'])) {
unset($params['file']);
}
$canonicalQueryString = str_replace(
array('+', '%5B', '%5D'),
array('%20', '[', ']'),
http_build_query($params, '', '&')
);
$stringToSign = sprintf(
"%s\n%s\n%s\n%s",
strtoupper($method),
$this->account->getApiHost(),
$path,
$canonicalQueryString
);
$hmac = hash_hmac('sha256', $stringToSign, $this->account->getSecretKey(), true);
return base64_encode($hmac);
} | php | {
"resource": ""
} |
q7496 | PandaSigner.getInstance | train | public static function getInstance($cloudId, Account $account)
{
$signer = new PandaSigner();
$signer->setCloudId($cloudId);
$signer->setAccount($account);
return $signer;
} | php | {
"resource": ""
} |
q7497 | BatchResult.getItems | train | public function getItems() {
$batch = $this->getBatch();
$items = array();
foreach ($batch as $b) {
$items[] = $b;
}
return $items;
} | php | {
"resource": ""
} |
q7498 | BatchResult.export | train | public function export(array $params = array()) {
$result = array(
'type' => 'list',
'count' => $this->getCount(),
'limit' => elgg_extract('limit', $this->options, elgg_get_config('default_limit')),
'offset' => elgg_extract('offset', $this->options, 0),
'items' => array(),
);
$batch = $this->getBatch();
foreach ($batch as $entity) {
$result['items'][] = hypeApps()->graph->export($entity, $params);
}
return $result;
} | php | {
"resource": ""
} |
q7499 | BatchResult.prepareBatchOptions | train | protected function prepareBatchOptions(array $options = array()) {
if (!in_array($this->getter, array(
'elgg_get_entities',
'elgg_get_entities_from_metadata',
'elgg_get_entities_from_relationship',
))) {
return $options;
}
$sort = elgg_extract('sort', $options);
unset($options['sort']);
if (!is_array($sort)) {
return $options;
}
$dbprefix = elgg_get_config('dbprefix');
$order_by = array();
foreach ($sort as $field => $direction) {
$field = sanitize_string($field);
$direction = strtoupper(sanitize_string($direction));
if (!in_array($direction, array('ASC', 'DESC'))) {
$direction = 'ASC';
}
switch ($field) {
case 'alpha' :
if (elgg_extract('types', $options) == 'user') {
$options['joins']['ue'] = "JOIN {$dbprefix}users_entity ue ON ue.guid = e.guid";
$order_by[] = "ue.name {$direction}";
} else if (elgg_extract('types', $options) == 'group') {
$options['joins']['ge'] = "JOIN {$dbprefix}groups_entity ge ON ge.guid = e.guid";
$order_by[] = "ge.name {$direction}";
} else if (elgg_extract('types', $options) == 'object') {
$options['joins']['oe'] = "JOIN {$dbprefix}objects_entity oe ON oe.guid = e.guid";
$order_by[] = "oe.title {$direction}";
}
break;
case 'type' :
case 'subtype' :
case 'guid' :
case 'owner_guid' :
case 'container_guid' :
case 'site_guid' :
case 'enabled' :
case 'time_created';
case 'time_updated' :
case 'last_action' :
case 'access_id' :
$order_by[] = "e.{$field} {$direction}";
break;
}
}
$options['order_by'] = implode(',', $order_by);
return $options;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.