_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q257500
Rediska_Key.setBit
test
public function setBit($offset, $bit) { return $this->_getRediskaOn()->setBit($this->getName(), $offset, $bit); }
php
{ "resource": "" }
q257501
Rediska_Key.getOrSetValue
test
public function getOrSetValue($object = null, $expire = null, $expireIsTimestamp = false) { return new Rediska_Key_GetOrSetValue($this, $object, $expire, $expireIsTimestamp); }
php
{ "resource": "" }
q257502
UserController.followersAction
test
public function followersAction() { $userId = $this->_getParam('userId'); $user = new User($userId); $this->view->user = $user->getValue(); $followers = new Followers($userId); $this->view->users = User::getMultiple($followers->toArray()); $this->_setUsersIFollow(); }
php
{ "resource": "" }
q257503
UserController.followingAction
test
public function followingAction() { $userId = $this->_getParam('userId'); $following = new Following($userId); $this->view->users = User::getMultiple($following->toArray()); $this->_setUsersIFollow(); }
php
{ "resource": "" }
q257504
UserController.followAction
test
public function followAction() { $auth = Zend_Auth::getInstance(); if (!$auth->hasIdentity()) { throw new Zend_Auth_Exception("You're not authorized to see this page"); } $userId = $this->_getParam('userId'); $follower = $auth->getStorage()->read(); if ($userId != $follower['id']) { $followers = new Followers($userId); $followers[] = $follower['id']; $following = new Following($follower['id']); $following[] = $userId; } $this->_redirect('/user/followers/userId/' . $userId); }
php
{ "resource": "" }
q257505
Rediska_Key_Abstract.moveToDb
test
public function moveToDb($dbIndex) { $result = $this->_getRediskaOn()->moveToDb($this->getName(), $dbIndex); if (!is_null($this->getExpire()) && $result) { $this->expire($this->getExpire(), $this->isExpireTimestamp()); } return $result; }
php
{ "resource": "" }
q257506
Rediska_Key_Abstract.setExpire
test
public function setExpire($secondsOrTimestamp, $isTimestamp = false) { if ($secondsOrTimestamp !== null) { trigger_error('Expire option is deprecated, because expire behaviour was changed in Redis 2.2. Use expire method instead.', E_USER_WARNING); } $this->_options['expire'] = $secondsOrTimestamp; $this->_options['expireIsTimestamp'] = $isTimestamp; return $this; }
php
{ "resource": "" }
q257507
Rediska_Key_Abstract._getRediskaOn
test
protected function _getRediskaOn() { $rediska = $this->getRediska(); if (!is_null($this->getServerAlias())) { $rediska = $rediska->on($this->getServerAlias()); } return $rediska; }
php
{ "resource": "" }
q257508
Rediska_Profiler_Stream.setMode
test
public function setMode($mode) { if (is_resource($this->_stream) && $this->_mode != $mode) { $meta = stream_get_meta_data($this->_stream); $this->setStream($meta['uri']); } $this->_mode = $mode; return $this; }
php
{ "resource": "" }
q257509
Rediska_Manager.add
test
public static function add($rediska) { if ($rediska instanceof Rediska) { if (!self::has($rediska->getName())) { foreach(self::$_instances as $name => $instance) { if ($instance === $rediska && $name != $rediska->getName()) { unset(self::$_instances[$name]); break; } } } $name = $rediska->getName(); } else if (is_array($rediska)) { if (isset($rediska['name'])) { $name = $rediska['name']; } else { $name = Rediska::DEFAULT_NAME; } } else { throw new Rediska_Exception('Rediska must be a instance or options'); } if (self::has($name)) { $result = false; } else { $result = true; } self::$_instances[$name] = $rediska; return $result; }
php
{ "resource": "" }
q257510
Rediska_Manager.getAll
test
public static function getAll() { foreach(self::$_instances as $name => $instanceOrOptions) { self::_instanceFromOptions($name); } return self::$_instances; }
php
{ "resource": "" }
q257511
Rediska_Manager._instanceFromOptions
test
protected static function _instanceFromOptions($name) { if (!is_object(self::$_instances[$name])) { $options = self::$_instances[$name]; self::$_instances[$name] = new Rediska($options); } }
php
{ "resource": "" }
q257512
Ratelimit.increment
test
public function increment($subject) { $bucket = $this->_getBucketName(); $transaction = $this->_getTransaction(); $this->_setMultiIncrementTransactionPart($transaction, $subject, $bucket); $transaction->execute(); }
php
{ "resource": "" }
q257513
Ratelimit.reset
test
public function reset($subject) { $keyName = $this->_getKeyName($subject); return (bool) $this->_rediska->delete($keyName); }
php
{ "resource": "" }
q257514
Ratelimit._getBucketName
test
protected function _getBucketName($time = null) { $time = $time ? : time(); return (int) floor(($time % $this->_bucketSpan) / $this->_bucketInterval); }
php
{ "resource": "" }
q257515
Ratelimit._setMultiIncrementTransactionPart
test
protected function _setMultiIncrementTransactionPart(Rediska_Transaction $transaction, $subject, $bucket) { $keyName = $this->_getKeyName($subject); $transaction->incrementinhash($keyName, $bucket, 1) ->deletefromhash($keyName, ($bucket + 1) % $this->_bucketCount) ->deletefromhash($keyName, ($bucket + 2) % $this->_bucketCount) ->expire($keyName, $this->_subjectExpire); }
php
{ "resource": "" }
q257516
Ratelimit._setMulitExecGetCountPart
test
protected function _setMulitExecGetCountPart(Rediska_Transaction $transaction, $subject, $bucket, $count) { $keyName = $this->_getKeyName($subject); // Get the counts from the previous `$count` buckets $transaction->getfromhash($keyName, $bucket); for ($i = $count; $i > 0; $i--) { $transaction->getfromhash($keyName, (--$bucket + $this->_bucketCount) % $this->_bucketCount); } return $transaction; }
php
{ "resource": "" }
q257517
Rediska_Connection_Socket._createSocketConnection
test
protected function _createSocketConnection() { $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); socket_set_option($socket, SOL_SOCKET, TCP_NODELAY, 1); @socket_set_nonblock($socket); $result = @socket_connect($socket, $this->getHost(), $this->getPort()); if ($result === false) { $errorCode = socket_last_error($socket); if ($errorCode !== SOCKET_EINPROGRESS) { return null; } }else{ //@socket_set_block($socket); return $socket; } /* Do whatever we want while the connect is taking place. */ $result = @socket_select($r = array($socket), $w = array($socket), $e = array($socket), $this->getTimeout()); if ($result === 0 || $result === false) { return null; } if (!(($r && count($r)) || ($w && count($w))) || @socket_get_option($socket, SOL_SOCKET, SO_ERROR) != 0) { return null; } //@socket_set_block($socket); return $socket; }
php
{ "resource": "" }
q257518
Rediska_Connection_Socket._getReadBuffer
test
protected function _getReadBuffer() { if ($this->_readBuffer === null) { $this->_readBuffer = new Rediska_Connection_Socket_ReadBuffer($this); } return $this->_readBuffer; }
php
{ "resource": "" }
q257519
Rediska_Connection.read
test
public function read($length) { if (!$this->isConnected()) { throw new Rediska_Connection_Exception("Can't read without connection to Redis server. Do connect or write first."); } if ($length > 0) { $data = $this->_readAndThrowException($length); } else { $data = null; } if ($length !== -1) { $this->_readAndThrowException(2); } return $data; }
php
{ "resource": "" }
q257520
Rediska_Connection.readLine
test
public function readLine() { if (!$this->isConnected()) { throw new Rediska_Connection_Exception("Can't read without connection to Redis server. Do connect or write first."); } $reply = @fgets($this->_socket); if ($reply === false || $reply === '') { $metaData = stream_get_meta_data($this->_socket); if ($metaData['timed_out']) { throw new Rediska_Connection_TimeoutException("Connection read timed out."); } if ($this->_options['blockingMode'] && !$metaData['eof']) { $this->disconnect(); throw new Rediska_Connection_Exception("Can't read from socket."); } $reply = null; } else { $reply = trim($reply); } return $reply; }
php
{ "resource": "" }
q257521
Rediska_Connection.setReadTimeout
test
public function setReadTimeout($timeout) { $this->_options['readTimeout'] = $timeout; if ($this->isConnected()) { $seconds = floor($this->_options['readTimeout']); $microseconds = ($this->_options['readTimeout'] - $seconds) * 1000000; stream_set_timeout($this->_socket, $seconds, $microseconds); } return $this; }
php
{ "resource": "" }
q257522
Rediska_Connection.getStreamContext
test
public function getStreamContext() { if ($this->_options['streamContext'] !== null) { if (is_resource($this->_options['streamContext'])) { return $this->_options['streamContext']; } if (is_array($this->_options['streamContext'])) { return stream_context_create($this->_options['streamContext']); } } return null; }
php
{ "resource": "" }
q257523
Rediska_Connection._readAndThrowException
test
protected function _readAndThrowException($length) { $data = @stream_get_contents($this->_socket, $length); $info = stream_get_meta_data($this->_socket); if ($info['timed_out']) { throw new Rediska_Connection_TimeoutException("Connection read timed out."); } if ($data === false) { $this->disconnect(); throw new Rediska_Connection_Exception("Can't read from socket."); } return $data; }
php
{ "resource": "" }
q257524
WpNonce.validate
test
public function validate(NonceContextInterface $context = null) { $context or $context = new RequestGlobalsContext(); $value = $context->offsetExists($this->action) ? $context[$this->action] : ''; if (!$value || !is_string($value)) { return false; } $lifeFilter = $this->lifeFilter(); add_filter('nonce_life', $lifeFilter); $valid = wp_verify_nonce($value, $this->hashedAction()); remove_filter('nonce_life', $lifeFilter); return (bool)$valid; }
php
{ "resource": "" }
q257525
PeclAmqpDriver.declareAndBindQueue
test
public function declareAndBindQueue($exchange, $queueName, $routingKey = '') { $this->declareSimpleQueue($queueName); $this->bindQueue($exchange, $queueName, $routingKey); }
php
{ "resource": "" }
q257526
PeclAmqpDriver.ack
test
public function ack(Message $message) { $queue = $this->getQueue($message->getQueue()); $queue->ack($message->getDeliveryTag()); }
php
{ "resource": "" }
q257527
PeclAmqpDriver.nack
test
public function nack(Message $message, $requeue = true) { $queue = $this->getQueue($message->getQueue()); $queue->nack($message->getDeliveryTag(), $requeue ? AMQP_REQUEUE : AMQP_NOPARAM); }
php
{ "resource": "" }
q257528
PeclAmqpDriver.getMessageProperties
test
private static function getMessageProperties(Message $message) { $properties = [ self::DELIVERY_MODE => 2, self::CONTENT_TYPE => 'text/plain', self::APPLICATION_HEADERS => $message->getHeaders() ]; if ($message->getCorrelationId() !== null) { $properties[self::CORRELATION_ID] = $message->getCorrelationId(); } if ($message->getReplyTo() !== null) { $properties[self::REPLY_TO] = $message->getReplyTo(); } return $properties; }
php
{ "resource": "" }
q257529
QueueHandlingDaemon.start
test
public function start() { $this->eventEmitter->emit(new DaemonStarted()); $this->logger->info('Starting daemon...'); $options = $this->handler->options(new ConsumeOptions()); $this->driver->consume( $this->queueName, function (Message $message) { $this->eventEmitter->emit(new MessageReceived()); $this->monitor->monitor($this, $message); $result = $this->handler->handle($message); $this->eventEmitter->emit(new MessageConsumed()); pcntl_signal_dispatch(); return $result; }, $options->getTimeout(), $options->isAutoAck() ); $this->stop(); }
php
{ "resource": "" }
q257530
QueueHandlingDaemon.stop
test
public function stop() { $this->logger->info('Closing daemon...'); $this->driver->close(); $this->eventEmitter->emit(new DaemonStopped()); }
php
{ "resource": "" }
q257531
TimeoutException.build
test
public static function build(\Exception $e, $timeout) { return new self( sprintf('The connection timed out after %d sec while awaiting incoming data', $timeout), $e->getCode(), $e ); }
php
{ "resource": "" }
q257532
HandlerBuilder.build
test
public function build(QueueConsumer $consumer) { Assertion::notNull($this->sync, 'You must specify if the handler must be sync or async'); // Sync $handler = $this->sync ? new SyncConsumerHandler($consumer, $this->driver) : new AsyncConsumerHandler($consumer); $handler->setLogger($this->logger); // Ack $handler = $this->autoAck ? $handler : new AckHandler($handler, $this->driver, $this->requeueOnFailure); // Stop / Continue $handler = $this->stopOnFailure ? new StopOnExceptionHandler($handler) : new ContinueOnExceptionHandler($handler); $handler->setLogger($this->logger); return $handler; }
php
{ "resource": "" }
q257533
SyncConsumerHandler.handleSyncMessage
test
private function handleSyncMessage(Message $message, $returnValue) { self::checkMessageIsSync($message); $this->logger->debug( 'Send return value back!', [ 'returnValue' => $returnValue, 'correlationId' => $message->getCorrelationId(), 'replyTo' => $message->getReplyTo() ] ); $this->driver->publish( '', new Message( $returnValue, $message->getReplyTo(), $message->getHeaders(), $message->getCorrelationId() ) ); }
php
{ "resource": "" }
q257534
DriverFactory.getDriver
test
public static function getDriver($connection) { if (is_array($connection) && isset($connection['host'], $connection['port'], $connection['user'], $connection['pwd']) ) { $connection = self::getConnectionFromArray($connection); } if ($connection instanceof AbstractConnection) { return new PhpAmqpLibDriver($connection); } if ($connection instanceof \AMQPConnection) { return new PeclAmqpDriver($connection); } throw new \InvalidArgumentException('You provided an unsupported connection'); }
php
{ "resource": "" }
q257535
PhpAmqpLibDriver.nack
test
public function nack(Message $message, $requeue = true) { $this->getChannel()->basic_reject($message->getDeliveryTag(), $requeue); }
php
{ "resource": "" }
q257536
PhpAmqpLibDriver.close
test
public function close() { $this->stop = true; $this->getChannel()->close(); $this->connection->close(); }
php
{ "resource": "" }
q257537
SerializingConsumer.consume
test
public function consume($message, array $headers = []) { return $this->serializer->serialize( $this->consumer->consume( $this->serializer->deserialize($message), $headers ) ); }
php
{ "resource": "" }
q257538
DataTablesEditorCommand.replaceModel
test
protected function replaceModel(&$stub) { $model = explode('\\', $this->getModel()); $model = array_pop($model); $stub = str_replace('ModelName', $model, $stub); return $stub; }
php
{ "resource": "" }
q257539
DataTablesEditorCommand.qualifyClass
test
protected function qualifyClass($name) { $rootNamespace = $this->laravel->getNamespace(); if (Str::startsWith($name, $rootNamespace)) { return $name; } if (Str::contains($name, '/')) { $name = str_replace('/', '\\', $name); } if (! Str::contains(Str::lower($name), 'datatable')) { $name .= $this->type; } return $this->getDefaultNamespace(trim($rootNamespace, '\\')) . '\\' . $name; }
php
{ "resource": "" }
q257540
DataTablesEditor.process
test
public function process(Request $request) { $action = $request->get('action'); if (! in_array($action, $this->actions)) { throw new DataTablesEditorException('Requested action not supported!'); } return $this->{$action}($request); }
php
{ "resource": "" }
q257541
DataTablesEditor.create
test
public function create(Request $request) { $instance = $this->resolveModel(); $connection = $instance->getConnection(); $affected = []; $errors = []; $connection->beginTransaction(); foreach ($request->get('data') as $data) { $validator = $this->getValidationFactory()->make($data, $this->createRules(), $this->createMessages(), $this->attributes()); if ($validator->fails()) { foreach ($this->formatErrors($validator) as $error) { $errors[] = $error; } continue; } if (method_exists($this, 'creating')) { $data = $this->creating($instance, $data); } if (method_exists($this, 'saving')) { $data = $this->saving($instance, $data); } $model = $instance->newQuery()->create($data); $model->setAttribute('DT_RowId', $model->getKey()); if (method_exists($this, 'created')) { $this->created($model, $data); } if (method_exists($this, 'saved')) { $this->saved($model, $data); } $affected[] = $model; } if (! $errors) { $connection->commit(); } else { $connection->rollBack(); } return $this->toJson($affected, $errors); }
php
{ "resource": "" }
q257542
DataTablesEditor.toJson
test
protected function toJson(array $data, array $errors = []) { $response = ['data' => $data]; if ($errors) { $response['fieldErrors'] = $errors; } return new JsonResponse($response, 200); }
php
{ "resource": "" }
q257543
DataTablesEditor.edit
test
public function edit(Request $request) { $instance = $this->resolveModel(); $connection = $instance->getConnection(); $affected = []; $errors = []; $connection->beginTransaction(); foreach ($request->get('data') as $key => $data) { $model = $instance->newQuery()->find($key); $validator = $this->getValidationFactory()->make($data, $this->editRules($model), $this->editMessages(), $this->attributes()); if ($validator->fails()) { foreach ($this->formatErrors($validator) as $error) { $errors[] = $error; } continue; } if (method_exists($this, 'updating')) { $data = $this->updating($model, $data); } if (method_exists($this, 'saving')) { $data = $this->saving($model, $data); } $model->update($data); if (method_exists($this, 'updated')) { $this->updated($model, $data); } if (method_exists($this, 'saved')) { $this->saved($model, $data); } $model->setAttribute('DT_RowId', $model->getKey()); $affected[] = $model; } if (! $errors) { $connection->commit(); } else { $connection->rollBack(); } return $this->toJson($affected, $errors); }
php
{ "resource": "" }
q257544
DataTablesEditor.remove
test
public function remove(Request $request) { $instance = $this->resolveModel(); $connection = $instance->getConnection(); $affected = []; $errors = []; $connection->beginTransaction(); foreach ($request->get('data') as $key => $data) { $model = $instance->newQuery()->find($key); $validator = $this->getValidationFactory() ->make($data, $this->removeRules($model), $this->removeMessages(), $this->attributes()); if ($validator->fails()) { foreach ($this->formatErrors($validator) as $error) { $errors[] = $error['status']; } continue; } try { if (method_exists($this, 'deleting')) { $this->deleting($model, $data); } $model->delete(); if (method_exists($this, 'deleted')) { $this->deleted($model, $data); } } catch (QueryException $exception) { $error = config('app.debug') ? $exception->errorInfo[2] : $this->removeExceptionMessage($exception, $model); $errors[] = $error; } $affected[] = $model; } if (! $errors) { $connection->commit(); } else { $connection->rollBack(); } $response = ['data' => $affected]; if ($errors) { $response['error'] = implode("\n", $errors); } return new JsonResponse($response, 200); }
php
{ "resource": "" }
q257545
BlacklistVoter.voteOnAttribute
test
protected function voteOnAttribute($attribute, $subject, TokenInterface $token) { /** @var $subject Query */ return $this->isLoggedInUser($token) || !$this->inList($subject->getName()); }
php
{ "resource": "" }
q257546
HtmlReport.render
test
public function render(DocumentInterface $document, $parameters = []) { $html = $this->twig->render($this->template, [ 'doc' => $document, 'params' => $parameters, ]); return $html; }
php
{ "resource": "" }
q257547
ByteBuffer.getString
test
public function getString() { $zeroByteIndex = strpos($this->byteArray, "\0", $this->position); if($zeroByteIndex === false) { return ''; } else { $dataString = $this->get($zeroByteIndex - $this->position); $this->position ++; return $dataString; } }
php
{ "resource": "" }
q257548
GameAchievement.getGlobalPercentages
test
public static function getGlobalPercentages($appId) { $params = ['gameid' => $appId]; $data = WebApi::getJSONObject('ISteamUserStats', 'GetGlobalAchievementPercentagesForApp', 2, $params); $percentages = []; foreach($data->achievementpercentages->achievements as $achievementData) { $percentages[$achievementData->name] = (float) $achievementData->percent; } return $percentages; }
php
{ "resource": "" }
q257549
SteamSocket.close
test
public function close() { if(!empty($this->socket) && $this->socket->isOpen()) { $this->socket->close(); } }
php
{ "resource": "" }
q257550
SteamSocket.receivePacket
test
public function receivePacket($bufferLength = 0) { if(!$this->socket->select(self::$timeout)) { throw new TimeoutException(); } if($bufferLength == 0) { $this->buffer->clear(); } else { $this->buffer = ByteBuffer::allocate($bufferLength); } try { $data = $this->socket->recv($this->buffer->remaining()); $this->buffer->put($data); } catch (ConnectionResetException $e) { $this->socket->close(); throw $e; } $bytesRead = $this->buffer->position(); $this->buffer->rewind(); $this->buffer->limit($bytesRead); return $bytesRead; }
php
{ "resource": "" }
q257551
SteamSocket.send
test
public function send(SteamPacket $dataPacket) { $this->logger->debug("Sending packet of type \"" . get_class($dataPacket) . "\"..."); $this->socket->send($dataPacket->__toString()); }
php
{ "resource": "" }
q257552
MasterServerSocket.getReply
test
public function getReply() { $this->receivePacket(1500); if($this->buffer->getLong() != -1) { throw new PacketFormatException("Master query response has wrong packet header."); } $packet = SteamPacketFactory::getPacketFromData($this->buffer->get()); $this->logger->debug("Received reply of type \"" . get_class($packet) . "\""); return $packet; }
php
{ "resource": "" }
q257553
GoldSrcSocket.rconExec
test
public function rconExec($password, $command) { if($this->rconChallenge == -1 || $this->isHLTV) { $this->rconGetChallenge(); } $this->rconSend("rcon {$this->rconChallenge} $password $command"); if($this->isHLTV) { try { $response = $this->getReply()->getResponse(); } catch(\SteamCondenser\Exceptions\TimeoutException $e) { $response = ''; } } else { $response = $this->getReply()->getResponse(); } if(trim($response) == 'Bad rcon_password.') { throw new \SteamCondenser\Exceptions\RCONNoAuthException(); } elseif(trim($response) == 'You have been banned from this server.') { throw new \SteamCondenser\Exceptions\RCONBanException(); } $this->rconSend("rcon {$this->rconChallenge} $password"); do { $responsePart = $this->getReply()->getResponse(); $response .= $responsePart; } while(strlen($responsePart) > 0); return $response; }
php
{ "resource": "" }
q257554
GoldSrcSocket.rconGetChallenge
test
public function rconGetChallenge() { $this->rconSend('challenge rcon'); $response = trim($this->getReply()->getResponse()); if($response == 'You have been banned from this server.') { throw new RCONBanException(); } $this->rconChallenge = floatval(substr($response, 14)); }
php
{ "resource": "" }
q257555
GoldSrcSocket.rconSend
test
public function rconSend($command) { $this->send(new \SteamCondenser\Servers\Packets\RCON\RCONGoldSrcRequest($command)); }
php
{ "resource": "" }
q257556
TCPSocket.connect
test
public function connect($ipAddress, $portNumber, $timeout) { $this->ipAddress = $ipAddress; $this->portNumber = $portNumber; if($this->socketsEnabled) { if (!$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) { throw new SocketException(socket_last_error($this->socket)); } socket_set_nonblock($this->socket); socket_connect($this->socket, $ipAddress, $portNumber); $write = [$this->socket]; $read = $except = null; $sec = floor($timeout / 1000); $usec = $timeout % 1000; if(!socket_select($read, $write, $except, $sec, $usec)) { $errorCode = socket_last_error($this->socket); } else { $errorCode = socket_get_option($this->socket, SOL_SOCKET, SO_ERROR); } if ($errorCode) { throw new SocketException($errorCode); } socket_set_block($this->socket); } else { if (!$this->socket = fsockopen("tcp://$ipAddress", $portNumber, $socketErrno, $socketErrstr, $timeout / 1000)) { throw new SocketException($socketErrstr); } stream_set_blocking($this->socket, true); } }
php
{ "resource": "" }
q257557
MasterServer.getServers
test
public function getServers($regionCode = MasterServer::REGION_ALL , $filter = '', $force = false) { $failCount = 0; $finished = false; $portNumber = 0; $hostName = '0.0.0.0'; $serverArray = []; while(true) { $failCount = 0; try { do { $this->socket->send(new A2MGETSERVERSBATCH2Packet($regionCode, "$hostName:$portNumber", $filter)); try { $serverStringArray = $this->socket->getReply()->getServers(); foreach($serverStringArray as $serverString) { $serverString = explode(':', $serverString); $hostName = $serverString[0]; $portNumber = $serverString[1]; if($hostName != '0.0.0.0' && $portNumber != 0) { $serverArray[] = [$hostName, $portNumber]; } else { $finished = true; } } $failCount = 0; } catch(TimeoutException $e) { $failCount ++; if($failCount == self::$retries) { throw $e; } $this->logger->info("Request to master server {$this->ipAddress} timed out, retrying..."); } } while(!$finished); break; } catch(TimeoutException $e) { if ($this->rotateIp()) { if ($force) { break; } throw $e; } $this->logger->info("Request to master server failed, retrying {$this->ipAddress}..."); } } return array_unique($serverArray, SORT_REGULAR); }
php
{ "resource": "" }
q257558
GameItemSchema.internalFetch
test
public function internalFetch() { $params = ['language' => $this->language]; $data = WebApi::getJSONData("IEconItems_{$this->appId}", 'GetSchema', 1, $params); $this->attributes = []; foreach ($data->attributes as $attribute) { $this->attributes[$attribute->defindex] = $attribute; $this->attributes[$attribute->name] = $attribute; } $this->effects = []; foreach ($data->attribute_controlled_attached_particles as $effect) { $this->effects[$effect->id] = $effect; } $this->items = []; $this->itemNames = []; foreach ($data->items as $item) { $this->items[$item->defindex] = $item; $this->itemNames[$item->name] = $item->defindex; } if (!empty($data->levels)) { $this->itemLevels = []; foreach ($data->item_levels as $itemLevelType) { $itemLevels = []; foreach ($itemLevelType->levels as $itemLevel) { $itemLevels[$itemLevel->level] = $itemLevel->name; } $this->itemLevels[$itemLevelType->name] = $itemLevels; } } $this->itemSets = []; foreach ($data->item_sets as $itemSet) { $this->itemSets[$itemSet->item_set] = $itemSet; } $this->origins = []; foreach ($data->originNames as $origin) { $this->origins[$origin->origin] = $origin->name; } $this->qualities = []; $index = -1; foreach ($data->qualities as $key => $value) { $index ++; if (property_exists($data->qualityNames, $key)) { $qualityName = $data->qualityNames->$key; } if (empty($qualityName)) { $qualityName = ucwords($key); } $this->qualities[$index] = $qualityName; } }
php
{ "resource": "" }
q257559
SteamId.convertCommunityIdToSteamId
test
public static function convertCommunityIdToSteamId($communityId) { $steamId1 = bcmod($communityId, 2); $steamId2 = bcsub($communityId, 76561197960265728); if ($steamId2 <= 0) { throw new SteamCondenserException("SteamID $communityId is too small."); } $steamId2 = ($steamId2 - $steamId1) / 2; return "STEAM_0:$steamId1:$steamId2"; }
php
{ "resource": "" }
q257560
SteamId.convertSteamIdToCommunityId
test
public static function convertSteamIdToCommunityId($steamId) { if($steamId == 'STEAM_ID_LAN' || $steamId == 'BOT') { throw new SteamCondenserException("Cannot convert SteamID \"$steamId\" to a community ID."); } if (preg_match('/^STEAM_[0-1]:[0-1]:[0-9]+$/', $steamId)) { $steamId = explode(':', substr($steamId, 8)); return bcadd($steamId[0] + $steamId[1] * 2, 76561197960265728); } elseif (preg_match('/^\[U:[0-1]:[0-9]+\]$/', $steamId)) { $steamId = explode(':', substr($steamId, 3, strlen($steamId) - 1)); return bcadd($steamId[0] + $steamId[1], 76561197960265727); } else { throw new SteamCondenserException("SteamID \"$steamId\" doesn't have the correct format."); } }
php
{ "resource": "" }
q257561
SteamId.resolveVanityUrl
test
public static function resolveVanityUrl($vanityUrl) { $params = ['vanityurl' => $vanityUrl]; $result = WebApi::getJSONObject('ISteamUser', 'ResolveVanityURL', 1, $params); $result = $result->response; if ($result->success != 1) { return null; } return $result->steamid; }
php
{ "resource": "" }
q257562
SteamId.fetchFriends
test
public function fetchFriends() { $friendsData = $this->getData($this->getBaseUrl() . '/friends?xml=1'); $this->friends = []; foreach($friendsData->friends->friend as $friend) { $this->friends[] = self::create((string) $friend, false); } return $this->friends; }
php
{ "resource": "" }
q257563
SteamId.fetchGames
test
public function fetchGames() { $params = [ 'steamid' => $this->getSteamId64(), 'include_appinfo' => 1, 'include_played_free_games' => 1 ]; $gamesData = WebApi::getJSONObject('IPlayerService', 'GetOwnedGames', 1, $params); foreach ($gamesData->response->games as $gameData) { $game = SteamGame::create($gameData); $this->games[$game->getAppId()] = $game; if (property_exists($gameData, 'playtime_2weeks')) { $recent = $gameData->playtime_2weeks; } else { $recent = 0; } $total = $gameData->playtime_forever; $this->playtimes[$game->getAppId()] = [$recent, $total]; } return $this->games; }
php
{ "resource": "" }
q257564
SteamId.fetchGroups
test
public function fetchGroups() { $params = ['steamid' => $this->getSteamId64()]; $result = WebApi::getJSONObject('ISteamUser', 'GetUserGroupList', 1, $params); $this->groups = []; foreach ($result->response->groups as $groupData) { $this->groups[] = SteamGroup::create($groupData->gid, false); } return $this->groups; }
php
{ "resource": "" }
q257565
SteamId.getSteamId64
test
public function getSteamId64() { if (empty($this->steamId64)) { $this->steamId64 = self::resolveVanityUrl($this->customUrl); } return $this->steamId64; }
php
{ "resource": "" }
q257566
SteamId.getRecentPlaytime
test
public function getRecentPlaytime($appId) { if (empty($this->playtimes)) { $this->fetchGames(); } return $this->playtimes[$appId][0]; }
php
{ "resource": "" }
q257567
SteamId.getTotalPlaytime
test
public function getTotalPlaytime($appId) { if (empty($this->playtimes)) { $this->fetchGames(); } return $this->playtimes[$appId][1]; }
php
{ "resource": "" }
q257568
SteamId.internalFetch
test
protected function internalFetch() { $profile = $this->getData($this->getBaseUrl() . '?xml=1'); if(!empty($profile->error)) { throw new SteamCondenserException((string) $profile->error); } if(!empty($profile->privacyMessage)) { throw new SteamCondenserException((string) $profile->privacyMessage); } $this->nickname = htmlspecialchars_decode((string) $profile->steamID); $this->steamId64 = (string) $profile->steamID64; $this->limited = (bool)(int) $profile->isLimitedAccount; $this->tradeBanState = (string) $profile->tradeBanState; $this->vacBanned = (bool)(int) $profile->vacBanned; $this->imageUrl = substr((string) $profile->avatarIcon, 0, -4); $this->onlineState = (string) $profile->onlineState; $this->privacyState = (string) $profile->privacyState; $this->stateMessage = (string) $profile->stateMessage; $this->visibilityState = (int) $profile->visibilityState; if($this->isPublic()) { $this->customUrl = strtolower((string) $profile->customURL); $this->hoursPlayed = (float) $profile->hoursPlayed2Wk; $this->location = (string) $profile->location; $this->memberSince = (string) $profile->memberSince; $this->realName = htmlspecialchars_decode((string) $profile->realname); $this->summary = htmlspecialchars_decode((string) $profile->summary); } }
php
{ "resource": "" }
q257569
Server.rotateIp
test
public function rotateIp() { if(sizeof($this->ipAddresses) == 1) { return true; } $this->ipIndex = ($this->ipIndex + 1) % sizeof($this->ipAddresses); $this->ipAddress = $this->ipAddresses[$this->ipIndex]; $this->initSocket(); return $this->ipIndex == 0; }
php
{ "resource": "" }
q257570
SourceServer.initSocket
test
public function initSocket() { $this->rconSocket = new Sockets\RCONSocket($this->ipAddress, $this->port); $this->socket = new Sockets\SourceSocket($this->ipAddress, $this->port); }
php
{ "resource": "" }
q257571
SourceServer.rconAuth
test
public function rconAuth($password) { $this->rconRequestId = $this->generateRconRequestId(); $this->rconSocket->send(new Packets\RCON\RCONAuthRequest($this->rconRequestId, $password)); $reply = $this->rconSocket->getReply(); if ($reply == null) { throw new RCONBanException(); } $reply = $this->rconSocket->getReply(); $this->rconAuthenticated = $reply->getRequestId() == $this->rconRequestId; return $this->rconAuthenticated; }
php
{ "resource": "" }
q257572
UDPSocket.connect
test
public function connect($ipAddress, $portNumber, $timeout) { $this->ipAddress = $ipAddress; $this->portNumber = $portNumber; if($this->socketsEnabled) { if(!$this->socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) { throw new SocketException(socket_last_error($this->socket)); } if(!socket_connect($this->socket, $ipAddress, $portNumber)) { throw new SocketException(socket_last_error($this->socket)); } socket_set_block($this->socket); } else { if(!$this->socket = fsockopen("udp://$ipAddress", $portNumber, $socketErrno, $socketErrstr)) { throw new SocketException($socketErrstr); } stream_set_blocking($this->socket, true); } }
php
{ "resource": "" }
q257573
Cacheable.create
test
public static function create() { $args = func_get_args(); $className = empty(self::$className) ? get_class() : self::$className; $class = new \ReflectionClass($className); $constructor = $class->getConstructor(); $arity = $constructor->getNumberOfParameters(); if (sizeof($args) < $arity) { array_fill(0, $arity, null); } $bypassCache = (sizeof($args) > $arity + 1) ? array_pop($args) : false; $fetch = (sizeof($args) > $arity) ? array_pop($args) : true; $object = $class->newInstanceWithoutConstructor(); $constructor->setAccessible(true); $constructor->invokeArgs($object, $args); $cachedObject = $object->cachedInstance(); if ($cachedObject != null && !$bypassCache) { $object = $cachedObject; } if ($fetch && ($bypassCache || !$object->isFetched())) { $object->fetch(); $object->cache(); } return $object; }
php
{ "resource": "" }
q257574
Cacheable.cachedInstance
test
protected function cachedInstance() { $findInstance = function($id, $cache) use (&$findInstance) { self::selectIds($id, $ids); if (array_key_exists($id, $cache)) { return (empty($ids)) ? $cache[$id] : $findInstance($id, $cache[$id]); } return null; }; foreach ($this->cacheIds() as $id) { $instance = $findInstance($id, self::$cache); if ($instance != null) { return $instance; } } return null; }
php
{ "resource": "" }
q257575
Cacheable.isCached
test
public static function isCached($id) { $findId = function($id, $cache) use (&$findId) { self::selectIds($id, $ids); if (array_key_exists($id, $cache)) { return (is_array($ids)) ? $findId($id, $cache[$id]) : true; } return false; }; return $findId($id, self::$cache); }
php
{ "resource": "" }
q257576
Cacheable.cache
test
protected function cache() { $cacheInstance = function($id, &$cache) use (&$cacheInstance) { self::selectIds($id, $ids); if (empty($ids)) { $cache[$id] = $this; } else { $cacheInstance($ids, $cache[$id]); } }; foreach ($this->cacheIds() as $cacheId) { $cacheInstance($cacheId, self::$cache); } }
php
{ "resource": "" }
q257577
Cacheable.cacheIds
test
protected function cacheIds() { $values = function($id) use (&$values) { return is_array($id) ? array_map($values, $id) : $this->{$id}; }; return array_map($values, self::$cacheIds); }
php
{ "resource": "" }
q257578
GoldSrcServer.initSocket
test
public function initSocket() { $this->socket = new Sockets\GoldSrcSocket($this->ipAddress, $this->port, $this->isHLTV); }
php
{ "resource": "" }
q257579
GoldSrcServer.rconAuth
test
public function rconAuth($password) { $this->rconPassword = $password; try { $this->rconAuthenticated = true; $this->rconExec(''); } catch (RCONNoAuthException $e) { $this->rconAuthenticated = false; $this->rconPassword = null; } return $this->rconAuthenticated; }
php
{ "resource": "" }
q257580
Socket.close
test
public function close() { if(!empty($this->socket)) { if($this->socketsEnabled) { socket_close($this->socket); } else { fclose($this->socket); } $this->socket = null; } }
php
{ "resource": "" }
q257581
Socket.recv
test
public function recv($length = 128) { if($this->socketsEnabled) { $data = socket_read($this->socket, $length); if ($data === false) { $errorCode = socket_last_error($this->socket); if (defined('SOCKET_ECONNRESET') && $errorCode == SOCKET_ECONNRESET) { throw new ConnectionResetException(); } throw new SocketException($errorCode); } } else { $data = fread($this->socket, $length); if ($data === false) { throw new SocketException('Could not read from socket.'); } } return $data; }
php
{ "resource": "" }
q257582
Socket.select
test
public function select($timeout = 0) { $read = [$this->socket]; $write = null; $except = null; $sec = floor($timeout / 1000); $usec = $timeout % 1000; if($this->socketsEnabled) { $select = socket_select($read, $write, $except, $sec, $usec); } else { $select = stream_select($read, $write, $except, $sec, $usec); } return $select > 0; }
php
{ "resource": "" }
q257583
Socket.send
test
public function send($data) { if($this->socketsEnabled) { $sendResult = socket_send($this->socket, $data, strlen($data), 0); if ($sendResult === false) { throw new SocketException(socket_last_error($this->socket)); } } else { $sendResult = fwrite($this->socket, $data, strlen($data)); if ($sendResult === false) { throw new SocketException('Could not send data.'); } } }
php
{ "resource": "" }
q257584
AppNews.getNewsForApp
test
public static function getNewsForApp($appId, $count = 5, $maxLength = null) { $params = ['appid' => $appId, 'count' => $count, 'maxlength' => $maxLength]; $data = WebApi::getJSONObject('ISteamNews', 'GetNewsForApp', 2, $params); $newsItems = []; foreach($data->appnews->newsitems as $newsData) { $newsItems[] = new AppNews($appId, $newsData); } return $newsItems; }
php
{ "resource": "" }
q257585
TF2Item.getClassesEquipped
test
public function getClassesEquipped() { $classesEquipped = []; foreach($this->equipped as $classId => $equipped) { if($equipped) { $classesEquipped[] = $classId; } } return $classesEquipped; }
php
{ "resource": "" }
q257586
SteamGroup.getMemberCount
test
public function getMemberCount() { if(empty($this->memberCount)) { $totalPages = $this->fetchPage(1); if($totalPages == 1) { $this->fetchTime = time(); } } return $this->memberCount; }
php
{ "resource": "" }
q257587
SteamGroup.getMembers
test
public function getMembers() { if(sizeof($this->members) != $this->memberCount) { $this->fetch(); } return $this->members; }
php
{ "resource": "" }
q257588
SteamGroup.fetchPage
test
private function fetchPage($page) { $url = "{$this->getBaseUrl()}/memberslistxml?p=$page"; $memberData = $this->getData($url); if($page == 1) { preg_match('/\/([0-9a-f]+)\.jpg$/', (string) $memberData->groupDetails->avatarIcon, $matches); $this->avatarHash = $matches[1]; $this->customUrl = (string) $memberData->groupDetails->groupURL; $this->groupId64 = (string) $memberData->groupID64; $this->name = (string) $memberData->groupDetails->groupName; $this->headline = (string) $memberData->groupDetails->headline; $this->summary = (string) $memberData->groupDetails->summary; } $this->memberCount = (int) $memberData->memberCount; $totalPages = (int) $memberData->totalPages; foreach($memberData->members->steamID64 as $member) { array_push($this->members, SteamId::create((string) $member, false)); } return $totalPages; }
php
{ "resource": "" }
q257589
SteamGroup.internalFetch
test
protected function internalFetch() { if(empty($this->memberCount) || sizeof($this->members) == $this->memberCount) { $page = 0; } else { $page = 1; } do { $totalPages = $this->fetchPage(++$page); } while($page < $totalPages); $this->fetchTime = time(); }
php
{ "resource": "" }
q257590
GameInventory.getItemSchema
test
public function getItemSchema() { if ($this->itemSchema == null) { $this->itemSchema = GameItemSchema::create($this->appId, self::$schemaLanguage); } return $this->itemSchema; }
php
{ "resource": "" }
q257591
GameInventory.internalFetch
test
protected function internalFetch() { $params = ['SteamID' => $this->steamId64]; $result = WebApi::getJSONData("IEconItems_{$this->getAppId()}", 'GetPlayerItems', 1, $params); $this->items = []; $this->preliminaryItems = []; foreach ($result->items as $itemData) { if ($itemData != null) { $inventoryClass = get_called_class(); $itemClass = $inventoryClass::ITEM_CLASS; $item = new $itemClass($this, $itemData); if ($item->isPreliminary()) { $this->preliminaryItems[] = $item; } else { $this->items[$item->getBackpackPosition() - 1] = $item; } } } }
php
{ "resource": "" }
q257592
Portal2Item.getBotsEquipped
test
public function getBotsEquipped() { $botsEquipped = []; foreach($this->equipped as $botId => $equipped) { if($equipped) { $botsEquipped[] = $botId; } } return $botsEquipped; }
php
{ "resource": "" }
q257593
TF2GoldenWrench.getGoldenWrenches
test
public static function getGoldenWrenches() { if(self::$goldenWrenches == null) { self::$goldenWrenches = []; $data = WebApi::getJSONObject('ITFItems_440', 'GetGoldenWrenches', 2); foreach($data->results->wrenches as $wrenchData) { self::$goldenWrenches[] = new TF2GoldenWrench($wrenchData); } } return self::$goldenWrenches; }
php
{ "resource": "" }
q257594
WebApi.setApiKey
test
public static function setApiKey($apiKey) { if($apiKey != null && !preg_match('/^[0-9A-F]{32}$/', $apiKey)) { throw new WebApiException(WebApiException::INVALID_KEY); } self::$apiKey = $apiKey; }
php
{ "resource": "" }
q257595
WebApi.request
test
protected function request($url) { $this->logger->debug("Querying Steam Web API: " . str_replace(self::$apiKey, 'SECRET', $url)); $data = file_get_contents($url); if(empty($data)) { preg_match('/^.* (\d{3}) (.*)$/', $http_response_header[0], $http_status); if($http_status[1] == 401) { throw new WebApiException(WebApiException::UNAUTHORIZED); } throw new WebApiException(WebApiException::HTTP_ERROR, $http_status[1], $http_status[2]); } return $data; }
php
{ "resource": "" }
q257596
RCONSocket.send
test
public function send(SteamPacket $dataPacket) { if(empty($this->socket) || !$this->socket->isOpen()) { $this->socket = new TCPSocket(); $this->socket->connect($this->ipAddress, $this->portNumber, SteamSocket::$timeout); } parent::send($dataPacket); }
php
{ "resource": "" }
q257597
GameServer.getPlayers
test
public function getPlayers($rconPassword = null) { if($this->playerHash == null) { $this->updatePlayers($rconPassword); } return $this->playerHash; }
php
{ "resource": "" }
q257598
GameServer.handleResponseForRequest
test
protected function handleResponseForRequest($requestType, $repeatOnFailure = true) { switch($requestType) { case self::REQUEST_CHALLENGE: $expectedResponse = '\SteamCondenser\Servers\Packets\S2CCHALLENGEPacket'; $requestPacket = new A2SPLAYERPacket(); break; case self::REQUEST_INFO: $expectedResponse = '\SteamCondenser\Servers\Packets\S2AINFOBasePacket'; $requestPacket = new A2SINFOPacket(); break; case self::REQUEST_PLAYER: $expectedResponse = '\SteamCondenser\Servers\Packets\S2APLAYERPacket'; $requestPacket = new A2SPLAYERPacket($this->challengeNumber); break; case self::REQUEST_RULES: $expectedResponse = '\SteamCondenser\Servers\Packets\S2ARULESPacket'; $requestPacket = new A2SRULESPacket($this->challengeNumber); break; default: throw new SteamCondenserException('Called with wrong request type.'); } $this->socket->send($requestPacket); $responsePacket = $this->socket->getReply(); if($responsePacket instanceof S2AINFOBasePacket) { $this->infoHash = $responsePacket->getInfo(); } elseif($responsePacket instanceof S2APLAYERPacket) { $this->playerHash = $responsePacket->getPlayerHash(); } elseif($responsePacket instanceof S2ARULESPacket) { $this->rulesHash = $responsePacket->getRulesArray(); } elseif($responsePacket instanceof S2CCHALLENGEPacket) { $this->challengeNumber = $responsePacket->getChallengeNumber(); } else { throw new SteamCondenserException('Response of type ' . get_class($responsePacket) . ' cannot be handled by this method.'); } if(!($responsePacket instanceof $expectedResponse)) { $this->logger->info("Expected {$expectedResponse}, got " . get_class($responsePacket) . '.'); if($repeatOnFailure) { $this->handleResponseForRequest($requestType, false); } } }
php
{ "resource": "" }
q257599
GameServer.updatePing
test
public function updatePing() { $this->socket->send(new A2SINFOPacket()); $startTime = microtime(true); $this->socket->getReply(); $endTime = microtime(true); $this->ping = intval(round(($endTime - $startTime) * 1000)); return $this->ping; }
php
{ "resource": "" }