_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q8500 | Net_SmartIRC_irccommands.join | train | public function join($channelarray, $key = null, $priority = SMARTIRC_MEDIUM)
{
if (!is_array($channelarray)) {
$channelarray = array($channelarray);
}
$channellist = implode(',', $channelarray);
if ($key !== null) {
foreach ($channelarray as $idx => $value) {
$this->send('JOIN '.$value.' '.$key, $priority);
}
} else {
foreach ($channelarray as $idx => $value) {
$this->send('JOIN '.$value, $priority);
}
}
return $this;
} | php | {
"resource": ""
} |
q8501 | Net_SmartIRC_irccommands.part | train | public function part($channelarray, $reason = null,
$priority = SMARTIRC_MEDIUM
) {
if (!is_array($channelarray)) {
$channelarray = array($channelarray);
}
$channellist = implode(',', $channelarray);
if ($reason !== null) {
$this->send('PART '.$channellist.' :'.$reason, $priority);
} else {
$this->send('PART '.$channellist, $priority);
}
return $this;
} | php | {
"resource": ""
} |
q8502 | Net_SmartIRC_irccommands.kick | train | public function kick($channel, $nicknamearray, $reason = null,
$priority = SMARTIRC_MEDIUM
) {
if (!is_array($nicknamearray)) {
$nicknamearray = array($nicknamearray);
}
$nicknamelist = implode(',', $nicknamearray);
if ($reason !== null) {
$this->send('KICK '.$channel.' '.$nicknamelist.' :'.$reason, $priority);
} else {
$this->send('KICK '.$channel.' '.$nicknamelist, $priority);
}
return $this;
} | php | {
"resource": ""
} |
q8503 | Net_SmartIRC_irccommands.getList | train | public function getList($channelarray = null, $priority = SMARTIRC_MEDIUM)
{
if ($channelarray !== null) {
if (!is_array($channelarray)) {
$channelarray = array($channelarray);
}
$channellist = implode(',', $channelarray);
$this->send('LIST '.$channellist, $priority);
} else {
$this->send('LIST', $priority);
}
return $this;
} | php | {
"resource": ""
} |
q8504 | Net_SmartIRC_irccommands.setTopic | train | public function setTopic($channel, $newtopic, $priority = SMARTIRC_MEDIUM)
{
$this->send('TOPIC '.$channel.' :'.$newtopic, $priority);
return $this;
} | php | {
"resource": ""
} |
q8505 | Net_SmartIRC_irccommands.mode | train | public function mode($target, $newmode = null, $priority = SMARTIRC_MEDIUM)
{
if ($newmode !== null) {
$this->send('MODE '.$target.' '.$newmode, $priority);
} else {
$this->send('MODE '.$target, $priority);
}
return $this;
} | php | {
"resource": ""
} |
q8506 | Net_SmartIRC_irccommands.founder | train | public function founder($channel, $nickname, $priority = SMARTIRC_MEDIUM)
{
return $this->mode($channel, '+q '.$nickname, $priority);
} | php | {
"resource": ""
} |
q8507 | Net_SmartIRC_irccommands.defounder | train | public function defounder($channel, $nickname, $priority = SMARTIRC_MEDIUM)
{
return $this->mode($channel, '-q '.$nickname, $priority);
} | php | {
"resource": ""
} |
q8508 | Net_SmartIRC_irccommands.admin | train | public function admin($channel, $nickname, $priority = SMARTIRC_MEDIUM)
{
return $this->mode($channel, '+a '.$nickname, $priority);
} | php | {
"resource": ""
} |
q8509 | Net_SmartIRC_irccommands.deadmin | train | public function deadmin($channel, $nickname, $priority = SMARTIRC_MEDIUM)
{
return $this->mode($channel, '-a '.$nickname, $priority);
} | php | {
"resource": ""
} |
q8510 | Net_SmartIRC_irccommands.op | train | public function op($channel, $nickname, $priority = SMARTIRC_MEDIUM)
{
return $this->mode($channel, '+o '.$nickname, $priority);
} | php | {
"resource": ""
} |
q8511 | Net_SmartIRC_irccommands.deop | train | public function deop($channel, $nickname, $priority = SMARTIRC_MEDIUM)
{
return $this->mode($channel, '-o '.$nickname, $priority);
} | php | {
"resource": ""
} |
q8512 | Net_SmartIRC_irccommands.hop | train | public function hop($channel, $nickname, $priority = SMARTIRC_MEDIUM)
{
return $this->mode($channel, '+h '.$nickname, $priority);
} | php | {
"resource": ""
} |
q8513 | Net_SmartIRC_irccommands.dehop | train | public function dehop($channel, $nickname, $priority = SMARTIRC_MEDIUM)
{
return $this->mode($channel, '-h '.$nickname, $priority);
} | php | {
"resource": ""
} |
q8514 | Net_SmartIRC_irccommands.voice | train | public function voice($channel, $nickname, $priority = SMARTIRC_MEDIUM)
{
return $this->mode($channel, '+v '.$nickname, $priority);
} | php | {
"resource": ""
} |
q8515 | Net_SmartIRC_irccommands.devoice | train | public function devoice($channel, $nickname, $priority = SMARTIRC_MEDIUM)
{
return $this->mode($channel, '-v '.$nickname, $priority);
} | php | {
"resource": ""
} |
q8516 | Net_SmartIRC_irccommands.ban | train | public function ban($channel, $hostmask = null, $priority = SMARTIRC_MEDIUM)
{
if ($hostmask !== null) {
$this->mode($channel, '+b '.$hostmask, $priority);
} else {
$this->mode($channel, 'b', $priority);
}
return $this;
} | php | {
"resource": ""
} |
q8517 | Net_SmartIRC_irccommands.unban | train | public function unban($channel, $hostmask, $priority = SMARTIRC_MEDIUM)
{
return $this->mode($channel, '-b '.$hostmask, $priority);
} | php | {
"resource": ""
} |
q8518 | Net_SmartIRC_irccommands.invite | train | public function invite($nickname, $channel, $priority = SMARTIRC_MEDIUM)
{
return $this->send('INVITE '.$nickname.' '.$channel, $priority);
} | php | {
"resource": ""
} |
q8519 | Net_SmartIRC_irccommands.changeNick | train | public function changeNick($newnick, $priority = SMARTIRC_MEDIUM)
{
$this->_nick = $newnick;
return $this->send('NICK '.$newnick, $priority);
} | php | {
"resource": ""
} |
q8520 | Net_SmartIRC_irccommands.quit | train | public function quit($quitmessage = null, $priority = SMARTIRC_CRITICAL)
{
if ($quitmessage !== null) {
$this->send('QUIT :'.$quitmessage, $priority);
} else {
$this->send('QUIT', $priority);
}
return $this->disconnect(true);
} | php | {
"resource": ""
} |
q8521 | ShortcodeAttsParser.parse_atts | train | public function parse_atts( $atts, $tag ) {
$atts = \shortcode_atts(
$this->default_atts(),
$this->validated_atts( (array) $atts ),
$tag
);
return $atts;
} | php | {
"resource": ""
} |
q8522 | ShortcodeAttsParser.default_atts | train | protected function default_atts() {
$atts = array();
if ( ! $this->hasConfigKey( 'atts' ) ) {
return $atts;
}
$atts_config = $this->getConfigKey( 'atts' );
array_walk( $atts_config,
function ( $att_properties, $att_label ) use ( &$atts ) {
$atts[ $att_label ] = $att_properties['default'];
}
);
return $atts;
} | php | {
"resource": ""
} |
q8523 | ShortcodeAttsParser.validated_atts | train | protected function validated_atts( $atts ) {
if ( ! $this->hasConfigKey( 'atts' ) ) {
return $atts;
}
$atts_config = $this->getConfigKey( 'atts' );
array_walk( $atts_config,
function ( $att_properties, $att_label ) use ( &$atts ) {
if ( array_key_exists( $att_label, $atts ) ) {
$validate_function = $att_properties['validate'];
$atts[ $att_label ] = $validate_function( $atts[ $att_label ] );
}
}
);
return $atts;
} | php | {
"resource": ""
} |
q8524 | LeaseClient.LeaseGrant | train | public function LeaseGrant(LeaseGrantRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.Lease/LeaseGrant',
$argument,
['\Etcdserverpb\LeaseGrantResponse', 'decode'],
$metadata,
$options
);
} | php | {
"resource": ""
} |
q8525 | LeaseClient.LeaseRevoke | train | public function LeaseRevoke(LeaseRevokeRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.Lease/LeaseRevoke',
$argument,
['\Etcdserverpb\LeaseRevokeResponse', 'decode'],
$metadata,
$options
);
} | php | {
"resource": ""
} |
q8526 | LeaseClient.LeaseTimeToLive | train | public function LeaseTimeToLive(LeaseTimeToLiveRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.Lease/LeaseTimeToLive',
$argument,
['\Etcdserverpb\LeaseTimeToLiveResponse', 'decode'],
$metadata,
$options
);
} | php | {
"resource": ""
} |
q8527 | Calculator.isExcluded | train | public function isExcluded(Carbon $dt) {
foreach ($this->exclusions() as $exc) {
if ($dt->eq($exc)) {
return TRUE;
}
}
foreach ($this->callbacks() as $fn) {
if ($fn($dt) == TRUE) {
return TRUE;
}
}
return FALSE;
} | php | {
"resource": ""
} |
q8528 | Calculator.nbd | train | public function nbd(Carbon $dt = NULL) {
if (($dt instanceof Carbon) == FALSE) {
$dt = new Carbon();
}
if ($this->deadline()) {
if ($this->deadline()->lt($dt)) {
$dt->addDay();
}
} else {
$dt->addDay();
}
/* Time becomes irrelevant */
$dt->setTime(0,0,0);
$iters = 0;
while ($this->isExcluded($dt)) {
if ($iters == static::$N_MAX_ITER) {
throw new \RuntimeException('Maximum iterations met for next business day calculation');
}
$dt->addDay();
$iters++;
}
return $dt;
} | php | {
"resource": ""
} |
q8529 | SourceCodeInfo.addLocation | train | public function addLocation(\google\protobuf\SourceCodeInfo\Location $value)
{
if ($this->location === null) {
$this->location = new \Protobuf\MessageCollection();
}
$this->location->add($value);
} | php | {
"resource": ""
} |
q8530 | Minifier.minify | train | public function minify($content, $type, $fileName)
{
if ($type == 'css') {
$minifier = new Minify\CSS();
$minifier->add($content);
return $minifier->minify();
} elseif ($type == 'js') {
$minifier = new Minify\JS();
$minifier->add($content);
return $minifier->minify() . ';';
}
return $content;
} | php | {
"resource": ""
} |
q8531 | MelisFrontSEODispatchRouterRegularUrlListener.redirectPageSEO301 | train | public function redirectPageSEO301($e, $idpage)
{
$sm = $e->getApplication()->getServiceManager();
$router = $e->getRouter();
$uri = $router->getRequestUri();
// Check for defined SEO 301 redirection
$uri = $uri->getPath();
if (substr($uri, 0, 1) == '/')
$uri = substr($uri, 1, strlen($uri));
$melisTablePageSeo = $sm->get('MelisEngineTablePageSeo');
$datasPageSeo = $melisTablePageSeo->getEntryById($idpage);
if (!empty($datasPageSeo))
{
$datasPageSeo = $datasPageSeo->current();
if (!empty($datasPageSeo) && !empty($datasPageSeo->pseo_url_301))
{
if (substr($datasPageSeo->pseo_url_301, 0, 4) != 'http')
$newuri = '/' . $datasPageSeo->pseo_url_301;
else
$newuri = $datasPageSeo->pseo_url_301;
$newuri .= $this->getQueryParameters($e);
return $newuri;
}
}
return null;
} | php | {
"resource": ""
} |
q8532 | EntityChangedListener.preFlush | train | public function preFlush(PreFlushEventArgs $event)
{
$em = $event->getEntityManager();
$changes = $this->meta_mutation_provider->getFullChangeSet($em);
foreach ($changes as $updates) {
if (0 === count($updates)) {
continue;
}
if (false === $this->meta_annotation_provider->isTracked($em, current($updates))) {
continue;
}
foreach ($updates as $entity) {
if ($entity instanceof Proxy && !$entity->__isInitialized()) {
continue;
}
$original = $this->meta_mutation_provider->createOriginalEntity($em, $entity);
$mutated_fields = $this->meta_mutation_provider->getMutatedFields($em, $entity, $original);
if (null === $original || !empty($mutated_fields)) {
$this->logger->debug(
'Going to notify a change (preFlush) to {entity_class}, which has {mutated_fields}',
[
'entity_class' => get_class($entity),
'mutated_fields' => $mutated_fields
]
);
$em->getEventManager()->dispatchEvent(
Events::ENTITY_CHANGED,
new EntityChangedEvent($em, $entity, $original, $mutated_fields)
);
}
}
}
} | php | {
"resource": ""
} |
q8533 | UserProfileResource.handleGET | train | protected function handleGET()
{
$user = Session::user();
if (empty($user)) {
throw new UnauthorizedException('There is no valid session for the current request.');
}
$data = [
'username' => $user->username,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'name' => $user->name,
'email' => $user->email,
'phone' => $user->phone,
'security_question' => $user->security_question,
'default_app_id' => $user->default_app_id,
'oauth_provider' => (!empty($user->oauth_provider)) ? $user->oauth_provider : '',
'adldap' => (!empty($user->adldap)) ? $user->adldap : ''
];
return $data;
} | php | {
"resource": ""
} |
q8534 | UserProfileResource.handlePOST | train | protected function handlePOST()
{
if (empty($payload = $this->getPayloadData())) {
throw new BadRequestException('No data supplied for operation.');
}
$data = [
'username' => array_get($payload, 'username'),
'first_name' => array_get($payload, 'first_name'),
'last_name' => array_get($payload, 'last_name'),
'name' => array_get($payload, 'name'),
'email' => array_get($payload, 'email'),
'phone' => array_get($payload, 'phone'),
'security_question' => array_get($payload, 'security_question'),
'security_answer' => array_get($payload, 'security_answer'),
'default_app_id' => array_get($payload, 'default_app_id')
];
$data = array_filter($data, function ($value) {
return !is_null($value);
});
$user = Session::user();
if (empty($user)) {
throw new NotFoundException('No user session found.');
}
$oldToken = Session::getSessionToken();
$email = $user->email;
$user->update($data);
if (!empty($oldToken) && $email !== array_get($data, 'email', $email)) {
// Email change invalidates token. Need to create a new token.
$forever = JWTUtilities::isForever($oldToken);
Session::setUserInfoWithJWT($user, $forever);
$newToken = Session::getSessionToken();
return ['success' => true, 'session_token' => $newToken];
}
return ['success' => true];
} | php | {
"resource": ""
} |
q8535 | ServiceDescriptorProto.addMethod | train | public function addMethod(\google\protobuf\MethodDescriptorProto $value)
{
if ($this->method === null) {
$this->method = new \Protobuf\MessageCollection();
}
$this->method->add($value);
} | php | {
"resource": ""
} |
q8536 | CourseCompleted.read | train | public function read(array $opts) {
return [array_merge(parent::read($opts)[0], [
'recipe' => 'course_completed',
'user_id' => $opts['relateduser']->id,
'user_url' => $opts['relateduser']->url,
'user_name' => $opts['relateduser']->fullname,
])];
} | php | {
"resource": ""
} |
q8537 | QuestionSubmitted.expandQuestion | train | protected function expandQuestion($question, $questions) {
if ($question->qtype == 'randomsamatch') {
$subquestions = [];
foreach ($questions as $otherquestion) {
if ($otherquestion->qtype == 'shortanswer') {
foreach ($otherquestion->answers as $answer) {
if (intval($answer->fraction) === 1) {
array_push(
$subquestions,
(object) [
"id" => $answer->id,
"questiontext" => $otherquestion->questiontext,
"answertext" => $answer->answer
]
);
// Only take the first correct answer because that's what Moodle does.
break;
}
}
}
}
$question->match = (object) [
'subquestions' => $subquestions
];
}
return $question;
} | php | {
"resource": ""
} |
q8538 | QuestionSubmitted.resultFromState | train | public function resultFromState($translatorevent, $questionAttempt, $submittedState) {
$maxMark = isset($questionAttempt->maxmark) ? $questionAttempt->maxmark : 100;
$scaledScore = $submittedState->fraction;
$rawScore = $scaledScore * floatval($maxMark);
switch ($submittedState->state) {
case "todo":
$translatorevent['attempt_completed'] = false;
$translatorevent['attempt_success'] = null;
break;
case "gaveup":
$translatorevent['attempt_completed'] = false;
$translatorevent['attempt_success'] = false;
break;
case "complete":
$translatorevent['attempt_completed'] = true;
$translatorevent['attempt_success'] = null;
break;
case "gradedwrong":
$translatorevent['attempt_completed'] = true;
$translatorevent['attempt_success'] = false;
$translatorevent['attempt_score_scaled'] = $scaledScore;
$translatorevent['attempt_score_raw'] = $rawScore;
break;
case "gradedpartial":
$translatorevent['attempt_completed'] = true;
$translatorevent['attempt_success'] = false;
$translatorevent['attempt_score_scaled'] = $scaledScore;
$translatorevent['attempt_score_raw'] = $rawScore;
break;
case "gradedright":
$translatorevent['attempt_completed'] = true;
$translatorevent['attempt_success'] = true;
$translatorevent['attempt_score_scaled'] = $scaledScore;
$translatorevent['attempt_score_raw'] = $rawScore;
break;
default:
$translatorevent['attempt_completed'] = null;
$translatorevent['attempt_success'] = null;
break;
}
return $translatorevent;
} | php | {
"resource": ""
} |
q8539 | QuestionSubmitted.numericStatement | train | public function numericStatement($translatorevent, $questionAttempt, $question) {
$translatorevent['interaction_type'] = 'numeric';
$correctAnswerId = null;
foreach ($question->answers as $answer) {
if (intval($answer->fraction) === 1) {
$correctAnswerId = $answer->id;
}
}
$tolerance = 0;
$toleranceType = 2;
$answersdata = [];
if ($question->qtype == "numerical") {
$answersdata = $question->numerical->answers;
} else if (strpos($question->qtype, 'calculated') === 0) {
$answersdata = $question->calculated->answers;
}
if (!is_null($correctAnswerId) && count($answersdata) > 0) {
foreach ($answersdata as $answerdata) {
if(isset($answerdata->answer)){
if ($answerdata->answer == $correctAnswerId) {
$tolerance = floatval($answerdata->tolerance);
if (isset($answerdata->tolerancetype)) {
$toleranceType = intval($answerdata->tolerancetype);
}
}
}
}
}
$rigthtanswer = floatval($questionAttempt->rightanswer);
if ($tolerance > 0) {
$toleranceMax = $rigthtanswer + $tolerance;
$toleranceMin = $rigthtanswer - $tolerance;
switch ($toleranceType) {
case 1:
$toleranceMax = $rigthtanswer + ($rigthtanswer * $tolerance);
$toleranceMin = $rigthtanswer - ($rigthtanswer * $tolerance);
break;
case 3:
$toleranceMax = $rigthtanswer + ($rigthtanswer * $tolerance);
$toleranceMin = $rigthtanswer / (1 + $tolerance);
break;
default:
break;
}
$rigthtanswerstring = strval($toleranceMin) . '[:]' . strval($toleranceMax);
$translatorevent['interaction_correct_responses'] = [$rigthtanswerstring];
} else {
$translatorevent['interaction_correct_responses'] = [$questionAttempt->rightanswer];
}
return $translatorevent;
} | php | {
"resource": ""
} |
q8540 | QuestionSubmitted.shortanswerStatement | train | public function shortanswerStatement($translatorevent, $questionAttempt, $question) {
$translatorevent['interaction_type'] = 'fill-in';
$translatorevent['interaction_correct_responses'] = [];
foreach ($question->answers as $answer) {
if (intval($answer->fraction) === 1) {
$correctResponse;
if ($question->shortanswer->options->usecase == '1') {
$correctResponse = '{case_matters=true}'.$answer->answer;
} else {
$correctResponse = '{case_matters=false}'.$answer->answer;
}
array_push($translatorevent['interaction_correct_responses'], $correctResponse);
}
}
return $translatorevent;
} | php | {
"resource": ""
} |
q8541 | QuestionSubmitted.matchStatement | train | public function matchStatement($translatorevent, $questionAttempt, $question) {
$translatorevent['interaction_type'] = 'matching';
$targets = [];
$sources = [];
$correctResponses = [];
$responseTargetsPos = [];
$responseSourcesPos = [];
foreach ($question->match->subquestions as $subquestion) {
$target = strip_tags($subquestion->questiontext);
$source = strip_tags($subquestion->answertext);
$targetId = 'moodle_quiz_question_target_'.$subquestion->id;
$sourceId = 'moodle_quiz_question_source_'.$subquestion->id;
$targets[$targetId] = $target;
$sources[$sourceId] = $source;
array_push(
$correctResponses,
$sourceId.'[.]'.$targetId
);
// Get the positions of the target and source within the response string.
$responseTargetsPos[strpos($questionAttempt->responsesummary, $target)] = $targetId;
$responseSourcesPos[strpos($questionAttempt->responsesummary, $source)] = $sourceId;
}
// Get ordered and indexed lists of target and source.
ksort($responseTargetsPos);
$responseTargets = array_values($responseTargetsPos);
ksort($responseSourcesPos);
$responseSources = array_values($responseSourcesPos);
$translatorevent['attempt_response'] = '';
if (count($responseTargets) == count($responseSources) && count($responseTargets) > 0) {
$responses = [];
foreach ($responseTargets as $index => $targetId) {
array_push(
$responses,
$responseSources[$index].'[.]'.$targetId
);
}
$translatorevent['attempt_response'] = implode('[,]', $responses);
}
$translatorevent['interaction_target'] = $targets;
$translatorevent['interaction_source'] = $sources;
$translatorevent['interaction_correct_responses'] = [implode('[,]', $correctResponses)];
return $translatorevent;
} | php | {
"resource": ""
} |
q8542 | QuestionSubmitted.getLastState | train | private function getLastState($questionAttempt) {
// Default placeholder to -1 so that the first item we check will always be greater than the placeholder.
$sequencenumber = -1;
// Default state in case there are no steps.
$state = (object)[
"state" => "todo",
"timestamp" => null
];
// Cycle through steps to find the last one (the one with the highest sequence number).
foreach ($questionAttempt->steps as $stepId => $step) {
if ($step->sequencenumber > $sequencenumber) {
// Now this step has the highest sequence number we've seen.
$sequencenumber = $step->sequencenumber;
$state = (object)[
"state" => $step->state,
"timestamp" => $step->timecreated,
"fraction" => (is_null($step->fraction) || $step->fraction == '') ? 0 : floatval($step->fraction)
];
}
}
return $state;
} | php | {
"resource": ""
} |
q8543 | EnumOptions.addUninterpretedOption | train | public function addUninterpretedOption(\google\protobuf\UninterpretedOption $value)
{
if ($this->uninterpreted_option === null) {
$this->uninterpreted_option = new \Protobuf\MessageCollection();
}
$this->uninterpreted_option->add($value);
} | php | {
"resource": ""
} |
q8544 | ValidatorAssistant.validate | train | private function validate()
{
// Try to resolve subrules if there are any
// as a final step before running the validator.
$this->resolveSubrules();
// Apply input filters.
$filters = new Filters($this->inputs, $this->filters, $this);
$this->inputs = $filters->apply();
// Apply custom rules.
$this->customRules();
$this->validator = $this->validator->make($this->inputs, $this->rules, $this->messages);
// Apply attributes.
$this->validator->setAttributeNames($this->attributes);
// Run the 'after' method, letting the
// user execute code after validation.
if (method_exists($this, 'after')) {
$this->after($this->validator);
}
} | php | {
"resource": ""
} |
q8545 | ValidatorAssistant.scope | train | public function scope($scope)
{
$beforeMethod = 'before'.ucfirst($scope);
$afterMethod = 'after'.ucfirst($scope);
if ( method_exists($this, $beforeMethod) )
{
call_user_func([$this,$beforeMethod]);
}
$this->rules = $this->resolveScope($scope);
$this->attributes = $this->resolveAttributes($scope);
$this->messages = $this->resolveMessages($scope);
if ( method_exists($this, $afterMethod) )
{
call_user_func([$this,$afterMethod]);
}
return $this;
} | php | {
"resource": ""
} |
q8546 | ValidatorAssistant.resolveSubrules | train | private function resolveSubrules()
{
$subrules = new Subrules($this->inputs, $this->rules, $this->attributes, $this->filters, $this->messages);
$this->rules = $subrules->rules();
$this->attributes = $subrules->attributes();
$this->filters = $subrules->filters();
$this->messages = $subrules->messages();
$this->inputs = $subrules->inputs();
} | php | {
"resource": ""
} |
q8547 | ValidatorAssistant.customRules | train | private function customRules()
{
// Get the methods of the calling class.
$methods = get_class_methods(get_called_class());
// Custom rule methods begin with "custom".
$methods = array_filter($methods, function($var) {
return strpos($var, 'custom') !== false && $var !== 'customRules';
});
if (count($methods)) {
foreach ($methods as $method) {
$self = $this;
// Convert camelCase method name to snake_case
// custom rule name.
$customRule = snake_case($method);
$customRule = str_replace('custom_', '', $customRule);
// Extend the validator using the return value
// of the custom rule method.
$this->validator->extend($customRule, function($attribute, $value, $parameters) use ($self, $method) {
return $self->$method($attribute, $value, $parameters);
});
}
}
} | php | {
"resource": ""
} |
q8548 | ValidatorAssistant.append | train | public function append($rule, $value)
{
if (isset($this->rules[$rule])) {
$existing = $this->rules[$rule];
// String rules are transformed into an array,
// so they can be easily merged. Laravel's Validator
// accepts rules as arrays or strings.
if (! is_array($existing)) $existing = explode('|', $existing);
if (! is_array($value)) $value = explode('|', $value);
$this->rules[$rule] = implode('|', array_unique(array_merge($existing, $value)));
}
return $this;
} | php | {
"resource": ""
} |
q8549 | ValidatorAssistant.bind | train | public function bind()
{
if (func_num_args()) {
$bindings = new Bindings(func_get_args(), $this->rules);
$this->rules = $bindings->rules();
}
return $this;
} | php | {
"resource": ""
} |
q8550 | SuperScraper.curl_setopt | train | protected function curl_setopt($ch)
{
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
} | php | {
"resource": ""
} |
q8551 | PluginHtml.lettering | train | public function lettering($str)
{
$output = '';
$array = str_split($str);
$idx = 1;
foreach ($array as $letter) {
$output .= '<span class="char' . $idx++ . '">' . $letter . '</span>';
}
return $output;
} | php | {
"resource": ""
} |
q8552 | getid3_lib.iconv_fallback_iso88591_utf16be | train | public static function iconv_fallback_iso88591_utf16be($string, $bom=false) {
$newcharstring = '';
if ($bom) {
$newcharstring .= "\xFE\xFF";
}
for ($i = 0; $i < strlen($string); $i++) {
$newcharstring .= "\x00".$string{$i};
}
return $newcharstring;
} | php | {
"resource": ""
} |
q8553 | getid3_lib.iconv_fallback_iso88591_utf16le | train | public static function iconv_fallback_iso88591_utf16le($string, $bom=false) {
$newcharstring = '';
if ($bom) {
$newcharstring .= "\xFF\xFE";
}
for ($i = 0; $i < strlen($string); $i++) {
$newcharstring .= $string{$i}."\x00";
}
return $newcharstring;
} | php | {
"resource": ""
} |
q8554 | getid3_lib.iconv_fallback_utf8_iso88591 | train | public static function iconv_fallback_utf8_iso88591($string) {
if (function_exists('utf8_decode')) {
return utf8_decode($string);
}
// utf8_decode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
$newcharstring = '';
$offset = 0;
$stringlength = strlen($string);
while ($offset < $stringlength) {
if ((ord($string{$offset}) | 0x07) == 0xF7) {
// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
((ord($string{($offset + 1)}) & 0x3F) << 12) &
((ord($string{($offset + 2)}) & 0x3F) << 6) &
(ord($string{($offset + 3)}) & 0x3F);
$offset += 4;
} elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
// 1110bbbb 10bbbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
((ord($string{($offset + 1)}) & 0x3F) << 6) &
(ord($string{($offset + 2)}) & 0x3F);
$offset += 3;
} elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
// 110bbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
(ord($string{($offset + 1)}) & 0x3F);
$offset += 2;
} elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
// 0bbbbbbb
$charval = ord($string{$offset});
$offset += 1;
} else {
// error? throw some kind of warning here?
$charval = false;
$offset += 1;
}
if ($charval !== false) {
$newcharstring .= (($charval < 256) ? chr($charval) : '?');
}
}
return $newcharstring;
} | php | {
"resource": ""
} |
q8555 | getid3_lib.iconv_fallback_utf8_utf16be | train | public static function iconv_fallback_utf8_utf16be($string, $bom=false) {
$newcharstring = '';
if ($bom) {
$newcharstring .= "\xFE\xFF";
}
$offset = 0;
$stringlength = strlen($string);
while ($offset < $stringlength) {
if ((ord($string{$offset}) | 0x07) == 0xF7) {
// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
((ord($string{($offset + 1)}) & 0x3F) << 12) &
((ord($string{($offset + 2)}) & 0x3F) << 6) &
(ord($string{($offset + 3)}) & 0x3F);
$offset += 4;
} elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
// 1110bbbb 10bbbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
((ord($string{($offset + 1)}) & 0x3F) << 6) &
(ord($string{($offset + 2)}) & 0x3F);
$offset += 3;
} elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
// 110bbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
(ord($string{($offset + 1)}) & 0x3F);
$offset += 2;
} elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
// 0bbbbbbb
$charval = ord($string{$offset});
$offset += 1;
} else {
// error? throw some kind of warning here?
$charval = false;
$offset += 1;
}
if ($charval !== false) {
$newcharstring .= (($charval < 65536) ? self::BigEndian2String($charval, 2) : "\x00".'?');
}
}
return $newcharstring;
} | php | {
"resource": ""
} |
q8556 | getid3_lib.iconv_fallback_utf8_utf16le | train | public static function iconv_fallback_utf8_utf16le($string, $bom=false) {
$newcharstring = '';
if ($bom) {
$newcharstring .= "\xFF\xFE";
}
$offset = 0;
$stringlength = strlen($string);
while ($offset < $stringlength) {
if ((ord($string{$offset}) | 0x07) == 0xF7) {
// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
((ord($string{($offset + 1)}) & 0x3F) << 12) &
((ord($string{($offset + 2)}) & 0x3F) << 6) &
(ord($string{($offset + 3)}) & 0x3F);
$offset += 4;
} elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
// 1110bbbb 10bbbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
((ord($string{($offset + 1)}) & 0x3F) << 6) &
(ord($string{($offset + 2)}) & 0x3F);
$offset += 3;
} elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
// 110bbbbb 10bbbbbb
$charval = ((ord($string{($offset + 0)}) & 0x1F) << 6) &
(ord($string{($offset + 1)}) & 0x3F);
$offset += 2;
} elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
// 0bbbbbbb
$charval = ord($string{$offset});
$offset += 1;
} else {
// error? maybe throw some warning here?
$charval = false;
$offset += 1;
}
if ($charval !== false) {
$newcharstring .= (($charval < 65536) ? self::LittleEndian2String($charval, 2) : '?'."\x00");
}
}
return $newcharstring;
} | php | {
"resource": ""
} |
q8557 | getid3_lib.iconv_fallback_utf16le_utf8 | train | public static function iconv_fallback_utf16le_utf8($string) {
if (substr($string, 0, 2) == "\xFF\xFE") {
// strip BOM
$string = substr($string, 2);
}
$newcharstring = '';
for ($i = 0; $i < strlen($string); $i += 2) {
$charval = self::LittleEndian2Int(substr($string, $i, 2));
$newcharstring .= self::iconv_fallback_int_utf8($charval);
}
return $newcharstring;
} | php | {
"resource": ""
} |
q8558 | getid3_lib.iconv_fallback_utf16be_iso88591 | train | public static function iconv_fallback_utf16be_iso88591($string) {
if (substr($string, 0, 2) == "\xFE\xFF") {
// strip BOM
$string = substr($string, 2);
}
$newcharstring = '';
for ($i = 0; $i < strlen($string); $i += 2) {
$charval = self::BigEndian2Int(substr($string, $i, 2));
$newcharstring .= (($charval < 256) ? chr($charval) : '?');
}
return $newcharstring;
} | php | {
"resource": ""
} |
q8559 | getid3_lib.iconv_fallback_utf16le_iso88591 | train | public static function iconv_fallback_utf16le_iso88591($string) {
if (substr($string, 0, 2) == "\xFF\xFE") {
// strip BOM
$string = substr($string, 2);
}
$newcharstring = '';
for ($i = 0; $i < strlen($string); $i += 2) {
$charval = self::LittleEndian2Int(substr($string, $i, 2));
$newcharstring .= (($charval < 256) ? chr($charval) : '?');
}
return $newcharstring;
} | php | {
"resource": ""
} |
q8560 | Client.isSuccessful | train | public function isSuccessful()
{
$successful = false;
$errorCode = $this->getErrorCode();
if ($errorCode === 200 || $errorCode === 0) {
$successful = true;
}
return $successful;
} | php | {
"resource": ""
} |
q8561 | Client.initUrl | train | private function initUrl($demo)
{
$url = self::LIVE_URL;
if ($demo === true) {
$url = self::DEMO_URL;
}
$this->setUrl($url);
return $this;
} | php | {
"resource": ""
} |
q8562 | Client.initCertificate | train | private function initCertificate($providedCertificate, $pass, $rawCertificate = false)
{
$certificateContent = $providedCertificate;
if ($rawCertificate === false) {
$certificateContent = $this->readCertificateFromDisk($providedCertificate);
}
openssl_pkcs12_read($certificateContent, $certificate, $pass);
$this->setCertificate($certificate);
$this->setPrivateKeyResource(openssl_pkey_get_private($this->getCertificatePrivateKey(), $pass));
$this->setPublicCertificateData(openssl_x509_parse($this->getCertificateCert()));
return $this;
} | php | {
"resource": ""
} |
q8563 | Client.initRootCertificatePath | train | private function initRootCertificatePath($demo)
{
$rootCertificatePath = self::LIVE_ROOT_CERTIFICATE_PATH;
if ($demo === true) {
$rootCertificatePath = self::DEMO_ROOT_CERTIFICATE_PATH;
}
$this->setRootCertificatePath($rootCertificatePath);
return $this;
} | php | {
"resource": ""
} |
q8564 | Client.readCertificateFromDisk | train | private function readCertificateFromDisk($path)
{
$cert = @file_get_contents($path);
if ($cert === false) {
throw new \Exception('Can not read certificate from location: '.$path, 1);
}
return $cert;
} | php | {
"resource": ""
} |
q8565 | Client.getCertificateIssuerName | train | private function getCertificateIssuerName()
{
$publicCertData = $this->getPublicCertificateData();
$x509Issuer = $publicCertData['issuer'];
$x509IssuerC = isset($x509Issuer['C']) ? $x509Issuer['C'] : '';
$x509IssuerO = isset($x509Issuer['O']) ? $x509Issuer['O'] : '';
$x509IssuerOU = isset($x509Issuer['OU']) ? $x509Issuer['OU'] : '';
$x509IssuerName = sprintf('OU=%s,O=%s,C=%s', $x509IssuerOU, $x509IssuerO, $x509IssuerC);
return $x509IssuerName;
} | php | {
"resource": ""
} |
q8566 | Client.signXML | train | private function signXML($xmlRequest)
{
$xmlRequestDOMDoc = new DOMDocument();
$xmlRequestDOMDoc->loadXML($xmlRequest);
$canonical = $xmlRequestDOMDoc->C14N();
$digestValue = base64_encode(hash('sha1', $canonical, true));
$rootElem = $xmlRequestDOMDoc->documentElement;
/** @var \DOMElement $signatureNode Signature node */
$signatureNode = $rootElem->appendChild(new DOMElement('Signature'));
$signatureNode->setAttribute('xmlns', 'http://www.w3.org/2000/09/xmldsig#');
/** @var \DOMElement $signedInfoNode Signed info node */
$signedInfoNode = $signatureNode->appendChild(new DOMElement('SignedInfo'));
$signedInfoNode->setAttribute('xmlns', 'http://www.w3.org/2000/09/xmldsig#');
/** @var \DOMElement $canonicalMethodNode Canonicalization method node */
$canonicalMethodNode = $signedInfoNode->appendChild(new DOMElement('CanonicalizationMethod'));
$canonicalMethodNode->setAttribute('Algorithm', 'http://www.w3.org/2001/10/xml-exc-c14n#');
/** @var \DOMElement $signatureMethodNode Signature method node */
$signatureMethodNode = $signedInfoNode->appendChild(new DOMElement('SignatureMethod'));
$signatureMethodNode->setAttribute('Algorithm', 'http://www.w3.org/2000/09/xmldsig#rsa-sha1');
/** @var \DOMElement $referenceNode */
$referenceNode = $signedInfoNode->appendChild(new DOMElement('Reference'));
$referenceNode->setAttribute('URI', sprintf('#%s', $xmlRequestDOMDoc->documentElement->getAttribute('Id')));
/** @var \DOMElement $transformsNode */
$transformsNode = $referenceNode->appendChild(new DOMElement('Transforms'));
/** @var \DOMElement $transform1Node */
$transform1Node = $transformsNode->appendChild(new DOMElement('Transform'));
$transform1Node->setAttribute('Algorithm', 'http://www.w3.org/2000/09/xmldsig#enveloped-signature');
/** @var \DOMElement $transform2Node */
$transform2Node = $transformsNode->appendChild(new DOMElement('Transform'));
$transform2Node->setAttribute('Algorithm', 'http://www.w3.org/2001/10/xml-exc-c14n#');
/** @var \DOMElement $digestMethodNode */
$digestMethodNode = $referenceNode->appendChild(new DOMElement('DigestMethod'));
$digestMethodNode->setAttribute('Algorithm', 'http://www.w3.org/2000/09/xmldsig#sha1');
$referenceNode->appendChild(new DOMElement('DigestValue', $digestValue));
$signedInfoNode = $xmlRequestDOMDoc->getElementsByTagName('SignedInfo')->item(0);
$signatureNode = $xmlRequestDOMDoc->getElementsByTagName('Signature')->item(0);
$signatureValueNode = new DOMElement(
'SignatureValue',
base64_encode($this->generateSignature($signedInfoNode))
);
$signatureNode->appendChild($signatureValueNode);
$keyInfoNode = $signatureNode->appendChild(new DOMElement('KeyInfo'));
$x509DataNode = $keyInfoNode->appendChild(new DOMElement('X509Data'));
$x509CertificateNode = new DOMElement('X509Certificate', $this->getPublicCertificateString());
$x509DataNode->appendChild($x509CertificateNode);
$x509IssuerSerialNode = $x509DataNode->appendChild(new DOMElement('X509IssuerSerial'));
$x509IssuerNameNode = new DOMElement('X509IssuerName', $this->getCertificateIssuerName());
$x509IssuerSerialNode->appendChild($x509IssuerNameNode);
$x509SerialNumberNode = new DOMElement('X509SerialNumber', $this->getCertificateIssuerSerialNumber());
$x509IssuerSerialNode->appendChild($x509SerialNumberNode);
return $this->plainXML($xmlRequestDOMDoc);
} | php | {
"resource": ""
} |
q8567 | Client.plainXML | train | private function plainXML($xmlRequest)
{
$envelope = new DOMDocument();
$envelope->loadXML(
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body></soapenv:Body>
</soapenv:Envelope>'
);
$envelope->encoding = 'UTF-8';
$envelope->version = '1.0';
$xmlRequestType = $xmlRequest->documentElement->localName;
$xmlRequestTypeNode = $xmlRequest->getElementsByTagName($xmlRequestType)->item(0);
$xmlRequestTypeNode = $envelope->importNode($xmlRequestTypeNode, true);
$envelope->getElementsByTagName('Body')->item(0)->appendChild($xmlRequestTypeNode);
return $envelope->saveXML();
} | php | {
"resource": ""
} |
q8568 | Client.sendSoap | train | public function sendSoap($payload)
{
$options = [
CURLOPT_URL => $this->getUrl(),
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 5,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_CAINFO => $this->getRootCertificatePath(),
];
$curlHandle = curl_init();
curl_setopt_array($curlHandle, $options);
$this->setLastRequest($payload);
$response = curl_exec($curlHandle);
$code = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
$error = curl_error($curlHandle);
$this->setErrorCode($code);
$this->setLastResponse($response);
curl_close($curlHandle);
if ($response) {
return $this->parseResponse($response, $code);
} else {
throw new Exception($error);
}
} | php | {
"resource": ""
} |
q8569 | Client.parseResponse | train | public function parseResponse($response, $code = 4)
{
$domResponse = new DOMDocument();
$domResponse->loadXML($response);
if ($code === 200 || $code == 0) {
return $response;
} else {
$errorCode = $domResponse->getElementsByTagName('SifraGreske')->item(0);
$errorMessage = $domResponse->getElementsByTagName('PorukaGreske')->item(0);
$faultCode = $domResponse->getElementsByTagName('faultcode')->item(0);
$faultMessage = $domResponse->getElementsByTagName('faultstring')->item(0);
if ($errorCode && $errorMessage) {
throw new Exception(sprintf('[%s] %s', $errorCode->nodeValue, $errorMessage->nodeValue));
} else {
if ($faultCode && $faultMessage) {
throw new Exception(sprintf('[%s] %s', $faultCode->nodeValue, $faultMessage->nodeValue));
} else {
throw new Exception(print_r($response, true), $code);
}
}
}
} | php | {
"resource": ""
} |
q8570 | Client.sendRequest | train | public function sendRequest($xmlRequest)
{
$payload = $this->signXML($xmlRequest->toXML());
return $this->sendSoap($payload);
} | php | {
"resource": ""
} |
q8571 | AbstractDoctrineFilterType.getFullAttributeReferences | train | public function getFullAttributeReferences(
FilterInterface $filter,
DoctrineQueryHandlerInterface $queryHandler
): array {
$references = [];
foreach ($filter->getAttributes() as $attributePath) {
$references[] = $queryHandler->resolveAttributeAlias($attributePath);
}
return $references;
} | php | {
"resource": ""
} |
q8572 | AbstractStorage.fireBeforeOperation | train | protected function fireBeforeOperation($operation, OperationArguments $args)
{
$this->getEventManager()->triggerEvent(
new OperationEvent('beforeOperation', $this, $operation, $args)
);
} | php | {
"resource": ""
} |
q8573 | AbstractStorage.fireAfterOperation | train | protected function fireAfterOperation($operation, OperationArguments $args, & $returnValue)
{
$this->getEventManager()->triggerEvent(
new OperationEvent('afterOperation', $this, $operation, $args, $returnValue)
);
} | php | {
"resource": ""
} |
q8574 | AbstractStorage.fireOnOperationException | train | protected function fireOnOperationException($operation, OperationArguments $args, Exception $exception)
{
$returnValue = null;
$this->getEventManager()->triggerEvent(
new OperationEvent('onOperationException', $this, $operation, $args, $returnValue, $exception)
);
} | php | {
"resource": ""
} |
q8575 | AbstractStorage.doOperation | train | protected function doOperation($operation, OperationArguments $args)
{
try {
// Trigger 'beforeOperation' event.
$this->fireBeforeOperation($operation, $args);
// Run the internal operation.
$forwardMethod = 'forward' . ucfirst($operation);
$returnValue = call_user_func([$this, $forwardMethod], $args);
// Trigger 'afterOperation' event.
$this->fireAfterOperation($operation, $args, $returnValue);
// Return the operation result.
return $returnValue;
} catch (Exception $e) {
// Trigger 'onOperationException' event.
$this->fireOnOperationException($operation, $args, $e);
// Throw the original exception.
throw $e;
}
} | php | {
"resource": ""
} |
q8576 | AbstractStorage.addOperationListener | train | public function addOperationListener(OperationListenerInterface $listener, $priority = 0)
{
$this->getEventManager()->attach('beforeOperation', [$listener, 'beforeOperation'], $priority);
$this->getEventManager()->attach('afterOperation', [$listener, 'afterOperation'], $priority);
$this->getEventManager()->attach('onOperationException', [$listener, 'onOperationException'], $priority);
} | php | {
"resource": ""
} |
q8577 | ModelChoiceList.createIndex | train | protected function createIndex($model)
{
if ($this->identifierAsIndex) {
return current($this->getIdentifierValues($model));
}
return parent::createIndex($model);
} | php | {
"resource": ""
} |
q8578 | ModelChoiceList.createValue | train | protected function createValue($model)
{
if ($this->identifierAsIndex) {
return (string) current($this->getIdentifierValues($model));
}
return parent::createValue($model);
} | php | {
"resource": ""
} |
q8579 | ModelChoiceList.load | train | private function load()
{
if ($this->loaded) {
return;
}
$models = (array) $this->query->find();
$preferred = array();
if ($this->preferredQuery instanceof \ModelCriteria) {
$preferred = (array) $this->preferredQuery->find();
}
try {
// The second parameter $labels is ignored by ObjectChoiceList
parent::initialize($models, array(), $preferred);
$this->loaded = true;
} catch (StringCastException $e) {
throw new StringCastException(str_replace('argument $labelPath', 'option "property"', $e->getMessage()), null, $e);
}
} | php | {
"resource": ""
} |
q8580 | ModelChoiceList.getIdentifierValues | train | private function getIdentifierValues($model)
{
if (!$model instanceof $this->class) {
return array();
}
if (1 === count($this->identifier) && current($this->identifier) instanceof \ColumnMap) {
$phpName = current($this->identifier)->getPhpName();
if (method_exists($model, 'get'.$phpName)) {
return array($model->{'get'.$phpName}());
}
}
if ($model instanceof \Persistent) {
return array($model->getPrimaryKey());
}
// readonly="true" models do not implement \Persistent.
if ($model instanceof \BaseObject && method_exists($model, 'getPrimaryKey')) {
return array($model->getPrimaryKey());
}
if (!method_exists($model, 'getPrimaryKeys')) {
return array();
}
return $model->getPrimaryKeys();
} | php | {
"resource": ""
} |
q8581 | ModelChoiceList.isEqual | train | private function isEqual($choice, $givenChoice)
{
if ($choice === $givenChoice) {
return true;
}
if ($this->getIdentifierValues($choice) === $this->getIdentifierValues($givenChoice)) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q8582 | Client.addServer | train | public function addServer(string $dsn) : bool
{
try {
$context = new \ZMQContext;
$this->socket = $context->getSocket(\ZMQ::SOCKET_REQ);
$this->socket->connect($dsn);
$this->dsn = $dsn;
return true;
} catch (\ZMQException $e) {
throw new ClientException($e->getMessage());
}
} | php | {
"resource": ""
} |
q8583 | Client.doBackground | train | public function doBackground(string $jobName, string $workload) : string
{
try {
$this->socket->send(json_encode([
'action' => 'background_job',
'job' => [
'name' => $jobName,
'workload' => $workload
]
]));
$result = $this->socket->recv();
return $result;
} catch (\ZMQException $e) {
throw new ClientException($e->getMessage());
}
} | php | {
"resource": ""
} |
q8584 | Client.sendCommand | train | public function sendCommand(string $command) : string
{
try {
$this->socket->send(json_encode([
'action' => 'command',
'command' => [
'name' => $command,
]
]));
$result = $this->socket->recv();
return $result;
} catch (\ZMQException $e) {
throw new ClientException($e->getMessage());
}
} | php | {
"resource": ""
} |
q8585 | Client.close | train | public function close()
{
try {
$this->socket->disconnect($this->dsn);
} catch (\ZMQException $e) {
throw new ClientException($e->getMessage());
}
} | php | {
"resource": ""
} |
q8586 | Uuid.generateUuid | train | public function generateUuid()
{
$format = '%04x%04x-%04x-%04x-%04x-%04x%04x%04x';
return sprintf(
$format,
// 32 bits for "time_low"
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
// 16 bits for "time_mid"
mt_rand(0, 0xffff),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,
// 48 bits for "node"
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff)
);
} | php | {
"resource": ""
} |
q8587 | Net_SmartIRC.setAutoRetryMax | train | public function setAutoRetryMax($autoretrymax = null)
{
if (is_integer($autoretrymax)) {
if ($autoretrymax == 0) {
$this->setAutoRetry(false);
} else {
$this->_autoretrymax = $autoretrymax;
}
} else {
$this->_autoretrymax = self::DEF_AUTORETRY_MAX;
}
return $this->_autoretrymax;
} | php | {
"resource": ""
} |
q8588 | Net_SmartIRC.setDisconnectTime | train | public function setDisconnectTime($milliseconds = null)
{
if (is_integer($milliseconds)
&& $milliseconds >= self::DEF_DISCONNECT_TIME
) {
$this->_disconnecttime = $milliseconds;
} else {
$this->_disconnecttime = self::DEF_DISCONNECT_TIME;
}
return $this->_disconnecttime;
} | php | {
"resource": ""
} |
q8589 | Net_SmartIRC.setLogDestination | train | public function setLogDestination($type)
{
switch ($type) {
case SMARTIRC_FILE:
case SMARTIRC_STDOUT:
case SMARTIRC_SYSLOG:
case SMARTIRC_BROWSEROUT:
case SMARTIRC_NONE:
$this->_logdestination = $type;
break;
default:
$this->log(SMARTIRC_DEBUG_NOTICE,
'WARNING: unknown logdestination type ('.$type
.'), will use STDOUT instead', __FILE__, __LINE__);
$this->_logdestination = SMARTIRC_STDOUT;
}
return $this->_logdestination;
} | php | {
"resource": ""
} |
q8590 | Net_SmartIRC.setReceiveDelay | train | public function setReceiveDelay($milliseconds = null)
{
if (is_integer($milliseconds)
&& $milliseconds >= self::DEF_RECEIVE_DELAY
) {
$this->_receivedelay = $milliseconds;
} else {
$this->_receivedelay = self::DEF_RECEIVE_DELAY;
}
return $this->_receivedelay;
} | php | {
"resource": ""
} |
q8591 | Net_SmartIRC.setReconnectDelay | train | public function setReconnectDelay($milliseconds = null)
{
if (is_integer($milliseconds)) {
$this->_reconnectdelay = $milliseconds;
} else {
$this->_reconnectdelay = self::DEF_RECONNECT_DELAY;
}
return $this->_reconnectdelay;
} | php | {
"resource": ""
} |
q8592 | Net_SmartIRC.setSendDelay | train | public function setSendDelay($milliseconds = null)
{
if (is_integer($milliseconds)) {
$this->_senddelay = $milliseconds;
} else {
$this->_senddelay = self::DEF_SEND_DELAY;
}
return $this->_senddelay;
} | php | {
"resource": ""
} |
q8593 | Net_SmartIRC.setTransmitTimeout | train | public function setTransmitTimeout($seconds = null)
{
if (is_integer($seconds)) {
$this->_txtimeout = $seconds;
} else {
$this->_txtimeout = self::DEF_TX_RX_TIMEOUT;
}
return $this->_txtimeout;
} | php | {
"resource": ""
} |
q8594 | Net_SmartIRC.stopBenchmark | train | public function stopBenchmark()
{
$this->_benchmark_stoptime = microtime(true);
$this->log(SMARTIRC_DEBUG_NOTICE, 'benchmark stopped', __FILE__, __LINE__);
if ($this->_benchmark) {
$this->showBenchmark();
}
return $this;
} | php | {
"resource": ""
} |
q8595 | Net_SmartIRC.showBenchmark | train | public function showBenchmark()
{
$this->log(SMARTIRC_DEBUG_NOTICE, 'benchmark time: '
.((float)$this->_benchmark_stoptime-(float)$this->_benchmark_starttime),
__FILE__, __LINE__
);
return $this;
} | php | {
"resource": ""
} |
q8596 | Net_SmartIRC.& | train | public function &getChannel($channelname)
{
$err = null;
if (!$this->_channelsyncing) {
$this->log(SMARTIRC_DEBUG_NOTICE,
'WARNING: getChannel() is called and the required Channel '
.'Syncing is not activated!', __FILE__, __LINE__
);
return $err;
}
if (!isset($this->_channels[strtolower($channelname)])) {
$this->log(SMARTIRC_DEBUG_NOTICE,
'WARNING: getChannel() is called and the required channel '
.$channelname.' has not been joined!', __FILE__, __LINE__
);
return $err;
}
return $this->_channels[strtolower($channelname)];
} | php | {
"resource": ""
} |
q8597 | Net_SmartIRC.& | train | public function &getUser($channelname, $username)
{
if (!$this->_channelsyncing) {
$this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: getUser() is called and'
.' the required Channel Syncing is not activated!',
__FILE__, __LINE__
);
return;
}
if ($this->isJoined($channelname, $username)) {
return $this->getChannel($channelname)->users[strtolower($username)];
}
} | php | {
"resource": ""
} |
q8598 | Net_SmartIRC.connect | train | public function connect($addr, $port = 6667, $reconnecting = false)
{
ob_implicit_flush();
$this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: connecting',
__FILE__, __LINE__
);
if ($hasPort = preg_match(self::IP_PATTERN, $addr)) {
$colon = strrpos($addr, ':');
$this->_address = substr($addr, 0, $colon);
$this->_port = (int) substr($addr, $colon + 1);
} elseif ($hasPort === 0) {
$this->_address = $addr;
$this->_port = $port;
$addr .= ':' . $port;
}
$timeout = ini_get("default_socket_timeout");
$context = stream_context_create(array('socket' => array('bindto' => $this->_bindto)));
$this->log(SMARTIRC_DEBUG_SOCKET, 'DEBUG_SOCKET: binding to '.$this->_bindto,
__FILE__, __LINE__);
if ($this->_socket = stream_socket_client($addr, $errno, $errstr,
$timeout, STREAM_CLIENT_CONNECT, $context)
) {
if (!stream_set_blocking($this->_socket, 0)) {
$this->log(SMARTIRC_DEBUG_SOCKET, 'DEBUG_SOCKET: unable to unblock stream',
__FILE__, __LINE__
);
$this->throwError('unable to unblock stream');
}
$this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: connected',
__FILE__, __LINE__
);
$this->_autoretrycount = 0;
$this->_connectionerror = false;
$this->registerTimeHandler($this->_rxtimeout * 125, $this, '_pingcheck');
$this->_lasttx = $this->_lastrx = time();
$this->_updatestate();
return $this;
}
$error_msg = "couldn't connect to \"$addr\" reason: \"$errstr ($errno)\"";
$this->log(SMARTIRC_DEBUG_SOCKET, 'DEBUG_NOTICE: '.$error_msg,
__FILE__, __LINE__
);
$this->throwError($error_msg);
return ($reconnecting) ? false : $this->reconnect();
} | php | {
"resource": ""
} |
q8599 | Net_SmartIRC.disconnect | train | function disconnect($quick = false)
{
if ($this->_updatestate() != SMARTIRC_STATE_CONNECTED) {
return false;
}
if (!$quick) {
$this->send('QUIT', SMARTIRC_CRITICAL);
usleep($this->_disconnecttime*1000);
}
fclose($this->_socket);
$this->_updatestate();
$this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: disconnected',
__FILE__, __LINE__
);
if ($this->_channelsyncing) {
// let's clean our channel array
$this->_channels = array();
$this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: '
.'cleaned channel array', __FILE__, __LINE__
);
}
if ($this->_usersyncing) {
// let's clean our user array
$this->_users = array();
$this->log(SMARTIRC_DEBUG_USERSYNCING, 'DEBUG_USERSYNCING: cleaned '
.'user array', __FILE__, __LINE__
);
}
if ($this->_logdestination == SMARTIRC_FILE) {
fclose($this->_logfilefp);
$this->_logfilefp = null;
} else if ($this->_logdestination == SMARTIRC_SYSLOG) {
closelog();
}
return $this;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.