repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
CatsSystem/swoole-etcd | etcd/MaintenanceClient.php | MaintenanceClient.Status | public function Status(StatusRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.Maintenance/Status',
$argument,
['\Etcdserverpb\StatusResponse', 'decode'],
$metadata, $options);
} | php | public function Status(StatusRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.Maintenance/Status',
$argument,
['\Etcdserverpb\StatusResponse', 'decode'],
$metadata, $options);
} | [
"public",
"function",
"Status",
"(",
"StatusRequest",
"$",
"argument",
",",
"$",
"metadata",
"=",
"[",
"]",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"_simpleRequest",
"(",
"'/etcdserverpb.Maintenance/Status'",
",",
"$",
"a... | Status gets the status of the member.
@param StatusRequest $argument input argument
@param array $metadata metadata
@param array $options call options
@return UnaryCall | [
"Status",
"gets",
"the",
"status",
"of",
"the",
"member",
"."
] | 9fe824bbcc39a1cc1609b22ffa030287e7e8912d | https://github.com/CatsSystem/swoole-etcd/blob/9fe824bbcc39a1cc1609b22ffa030287e7e8912d/etcd/MaintenanceClient.php#L54-L61 | train |
CatsSystem/swoole-etcd | etcd/MaintenanceClient.php | MaintenanceClient.Defragment | public function Defragment(DefragmentRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.Maintenance/Defragment',
$argument,
['\Etcdserverpb\DefragmentResponse', 'decode'],
$metadata, $options);
} | php | public function Defragment(DefragmentRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.Maintenance/Defragment',
$argument,
['\Etcdserverpb\DefragmentResponse', 'decode'],
$metadata, $options);
} | [
"public",
"function",
"Defragment",
"(",
"DefragmentRequest",
"$",
"argument",
",",
"$",
"metadata",
"=",
"[",
"]",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"_simpleRequest",
"(",
"'/etcdserverpb.Maintenance/Defragment'",
",",... | Defragment defragments a member's backend database to recover storage space.
@param DefragmentRequest $argument input argument
@param array $metadata metadata
@param array $options call options
@return UnaryCall | [
"Defragment",
"defragments",
"a",
"member",
"s",
"backend",
"database",
"to",
"recover",
"storage",
"space",
"."
] | 9fe824bbcc39a1cc1609b22ffa030287e7e8912d | https://github.com/CatsSystem/swoole-etcd/blob/9fe824bbcc39a1cc1609b22ffa030287e7e8912d/etcd/MaintenanceClient.php#L70-L77 | train |
CatsSystem/swoole-etcd | etcd/MaintenanceClient.php | MaintenanceClient.Hash | public function Hash(HashRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.Maintenance/Hash',
$argument,
['\Etcdserverpb\HashResponse', 'decode'],
$metadata, $options);
} | php | public function Hash(HashRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.Maintenance/Hash',
$argument,
['\Etcdserverpb\HashResponse', 'decode'],
$metadata, $options);
} | [
"public",
"function",
"Hash",
"(",
"HashRequest",
"$",
"argument",
",",
"$",
"metadata",
"=",
"[",
"]",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"_simpleRequest",
"(",
"'/etcdserverpb.Maintenance/Hash'",
",",
"$",
"argumen... | Hash returns the hash of the local KV state for consistency checking purpose.
This is designed for testing; do not use this in production when there
are ongoing transactions.
@param HashRequest $argument input argument
@param array $metadata metadata
@param array $options call options
@return UnaryCall | [
"Hash",
"returns",
"the",
"hash",
"of",
"the",
"local",
"KV",
"state",
"for",
"consistency",
"checking",
"purpose",
".",
"This",
"is",
"designed",
"for",
"testing",
";",
"do",
"not",
"use",
"this",
"in",
"production",
"when",
"there",
"are",
"ongoing",
"tr... | 9fe824bbcc39a1cc1609b22ffa030287e7e8912d | https://github.com/CatsSystem/swoole-etcd/blob/9fe824bbcc39a1cc1609b22ffa030287e7e8912d/etcd/MaintenanceClient.php#L88-L95 | train |
CatsSystem/swoole-etcd | etcd/MaintenanceClient.php | MaintenanceClient.Snapshot | public function Snapshot(SnapshotRequest $argument,
$metadata = [], $options = [])
{
return $this->_serverStreamRequest('/etcdserverpb.Maintenance/Snapshot',
$argument,
['\Etcdserverpb\SnapshotResponse', 'decode'],
$metadata, $options);
} | php | public function Snapshot(SnapshotRequest $argument,
$metadata = [], $options = [])
{
return $this->_serverStreamRequest('/etcdserverpb.Maintenance/Snapshot',
$argument,
['\Etcdserverpb\SnapshotResponse', 'decode'],
$metadata, $options);
} | [
"public",
"function",
"Snapshot",
"(",
"SnapshotRequest",
"$",
"argument",
",",
"$",
"metadata",
"=",
"[",
"]",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"_serverStreamRequest",
"(",
"'/etcdserverpb.Maintenance/Snapshot'",
",",... | Snapshot sends a snapshot of the entire backend from a member over a stream to a client.
@param SnapshotRequest $argument input argument
@param array $metadata metadata
@param array $options call options
@return ServerStreamingCall | [
"Snapshot",
"sends",
"a",
"snapshot",
"of",
"the",
"entire",
"backend",
"from",
"a",
"member",
"over",
"a",
"stream",
"to",
"a",
"client",
"."
] | 9fe824bbcc39a1cc1609b22ffa030287e7e8912d | https://github.com/CatsSystem/swoole-etcd/blob/9fe824bbcc39a1cc1609b22ffa030287e7e8912d/etcd/MaintenanceClient.php#L104-L111 | train |
orchestral/installer | src/InstallerServiceProvider.php | InstallerServiceProvider.registerRedirection | protected function registerRedirection(): void
{
if (! empty($this->redirectAfterInstalled) && \is_string($this->redirectAfterInstalled)) {
Installation::$redirectAfterInstalled = $this->redirectAfterInstalled;
}
} | php | protected function registerRedirection(): void
{
if (! empty($this->redirectAfterInstalled) && \is_string($this->redirectAfterInstalled)) {
Installation::$redirectAfterInstalled = $this->redirectAfterInstalled;
}
} | [
"protected",
"function",
"registerRedirection",
"(",
")",
":",
"void",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"redirectAfterInstalled",
")",
"&&",
"\\",
"is_string",
"(",
"$",
"this",
"->",
"redirectAfterInstalled",
")",
")",
"{",
"Installatio... | Register redirection services.
@return void | [
"Register",
"redirection",
"services",
"."
] | f49e251916567ce461b2dc47017fc8d8959ae6cc | https://github.com/orchestral/installer/blob/f49e251916567ce461b2dc47017fc8d8959ae6cc/src/InstallerServiceProvider.php#L52-L57 | train |
orchestral/installer | src/InstallerServiceProvider.php | InstallerServiceProvider.addDefaultSpecifications | protected function addDefaultSpecifications(RequirementContract $requirement)
{
return $requirement->add(new Specifications\WritableStorage($this->app))
->add(new Specifications\WritableBootstrapCache($this->app))
->add(new Specifications\WritableAsset($this->app))
->add(new Specifications\DatabaseConnection($this->app))
->add(new Specifications\Authentication($this->app));
} | php | protected function addDefaultSpecifications(RequirementContract $requirement)
{
return $requirement->add(new Specifications\WritableStorage($this->app))
->add(new Specifications\WritableBootstrapCache($this->app))
->add(new Specifications\WritableAsset($this->app))
->add(new Specifications\DatabaseConnection($this->app))
->add(new Specifications\Authentication($this->app));
} | [
"protected",
"function",
"addDefaultSpecifications",
"(",
"RequirementContract",
"$",
"requirement",
")",
"{",
"return",
"$",
"requirement",
"->",
"add",
"(",
"new",
"Specifications",
"\\",
"WritableStorage",
"(",
"$",
"this",
"->",
"app",
")",
")",
"->",
"add",... | Add default specifications.
@param \Orchestra\Contracts\Installation\Requirement $requirement
@return \Orchestra\Contracts\Installation\Requirement | [
"Add",
"default",
"specifications",
"."
] | f49e251916567ce461b2dc47017fc8d8959ae6cc | https://github.com/orchestral/installer/blob/f49e251916567ce461b2dc47017fc8d8959ae6cc/src/InstallerServiceProvider.php#L66-L73 | train |
globalis-ms/puppet-skilled-framework | src/Auth/Authentication.php | Authentication.retrieveResetToken | public function retrieveResetToken($token)
{
return $this->queryBuilder->from($this->getTokenTable())
->where('token', $token)
->first();
} | php | public function retrieveResetToken($token)
{
return $this->queryBuilder->from($this->getTokenTable())
->where('token', $token)
->first();
} | [
"public",
"function",
"retrieveResetToken",
"(",
"$",
"token",
")",
"{",
"return",
"$",
"this",
"->",
"queryBuilder",
"->",
"from",
"(",
"$",
"this",
"->",
"getTokenTable",
"(",
")",
")",
"->",
"where",
"(",
"'token'",
",",
"$",
"token",
")",
"->",
"fi... | Retrieve a reset token
@param string $token
@return null|stdClass Token | [
"Retrieve",
"a",
"reset",
"token"
] | 4bb9ff30a32210f54add1f0e53d4769d26eb3c29 | https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/Auth/Authentication.php#L164-L169 | train |
globalis-ms/puppet-skilled-framework | src/Auth/Authentication.php | Authentication.deleteToken | public function deleteToken($token)
{
return $this->queryBuilder->from($this->getTokenTable())
->where('token', $token)
->delete();
} | php | public function deleteToken($token)
{
return $this->queryBuilder->from($this->getTokenTable())
->where('token', $token)
->delete();
} | [
"public",
"function",
"deleteToken",
"(",
"$",
"token",
")",
"{",
"return",
"$",
"this",
"->",
"queryBuilder",
"->",
"from",
"(",
"$",
"this",
"->",
"getTokenTable",
"(",
")",
")",
"->",
"where",
"(",
"'token'",
",",
"$",
"token",
")",
"->",
"delete",
... | Delete a reset token
@param string $token
@return boolean | [
"Delete",
"a",
"reset",
"token"
] | 4bb9ff30a32210f54add1f0e53d4769d26eb3c29 | https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/Auth/Authentication.php#L177-L182 | train |
globalis-ms/puppet-skilled-framework | src/Auth/Authentication.php | Authentication.registerToken | public function registerToken(\Globalis\PuppetSkilled\Database\Magic\Model $user)
{
$this->queryBuilder->from($this->getTokenTable())
->insert([
'user_id' => $user->getKey(),
'token' => ($token = $this->generateResetToken()),
'created_at' => new Carbon(),
]);
return $token;
} | php | public function registerToken(\Globalis\PuppetSkilled\Database\Magic\Model $user)
{
$this->queryBuilder->from($this->getTokenTable())
->insert([
'user_id' => $user->getKey(),
'token' => ($token = $this->generateResetToken()),
'created_at' => new Carbon(),
]);
return $token;
} | [
"public",
"function",
"registerToken",
"(",
"\\",
"Globalis",
"\\",
"PuppetSkilled",
"\\",
"Database",
"\\",
"Magic",
"\\",
"Model",
"$",
"user",
")",
"{",
"$",
"this",
"->",
"queryBuilder",
"->",
"from",
"(",
"$",
"this",
"->",
"getTokenTable",
"(",
")",
... | Create a reset token
@param \App\Model\User $user
@return string | [
"Create",
"a",
"reset",
"token"
] | 4bb9ff30a32210f54add1f0e53d4769d26eb3c29 | https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/Auth/Authentication.php#L190-L199 | train |
arkphp/database | src/Connection.php | Connection.getConfig | public function getConfig($key = null, $default = null)
{
$name = $this->current ?: 'default';
$configs = $this->configs[$name];
if ($key === null) {
return $configs;
}
return isset($configs[$key]) ? $configs[$key] : $default;
} | php | public function getConfig($key = null, $default = null)
{
$name = $this->current ?: 'default';
$configs = $this->configs[$name];
if ($key === null) {
return $configs;
}
return isset($configs[$key]) ? $configs[$key] : $default;
} | [
"public",
"function",
"getConfig",
"(",
"$",
"key",
"=",
"null",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"current",
"?",
":",
"'default'",
";",
"$",
"configs",
"=",
"$",
"this",
"->",
"configs",
"[",
"$",
... | Get current connection config by key
@param string $key Config key
@param mixed $default
@return mixed | [
"Get",
"current",
"connection",
"config",
"by",
"key"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/Connection.php#L54-L64 | train |
arkphp/database | src/Connection.php | Connection.getOption | public function getOption($key = null, $default = null)
{
$name = $this->current ?: 'default';
$options = isset($this->configs[$name]['options']) ? $this->configs[$name]['options'] : [];
if ($key === null) {
return $options;
}
return isset($options[$key]) ? $options[$key] : $default;
} | php | public function getOption($key = null, $default = null)
{
$name = $this->current ?: 'default';
$options = isset($this->configs[$name]['options']) ? $this->configs[$name]['options'] : [];
if ($key === null) {
return $options;
}
return isset($options[$key]) ? $options[$key] : $default;
} | [
"public",
"function",
"getOption",
"(",
"$",
"key",
"=",
"null",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"current",
"?",
":",
"'default'",
";",
"$",
"options",
"=",
"isset",
"(",
"$",
"this",
"->",
"configs"... | Get current connection option by key
@param string $key
@param mixed $default
@return mixed | [
"Get",
"current",
"connection",
"option",
"by",
"key"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/Connection.php#L72-L82 | train |
arkphp/database | src/Connection.php | Connection.addConnection | public function addConnection($name, $dsn, $username = null, $password = null, $options = [])
{
//default driver options
static $defaultOptions = array(
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
//PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
);
if (isset($options['prefix'])) {
$prefix = $options['prefix'];
unset($options['prefix']);
} else {
$prefix = '';
}
$this->configs[$name] = [
'dsn' => $dsn,
'username' => $username,
'password' => $password,
'prefix' => $prefix,
'options' => $options + $defaultOptions,
];
return $this;
} | php | public function addConnection($name, $dsn, $username = null, $password = null, $options = [])
{
//default driver options
static $defaultOptions = array(
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
//PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
);
if (isset($options['prefix'])) {
$prefix = $options['prefix'];
unset($options['prefix']);
} else {
$prefix = '';
}
$this->configs[$name] = [
'dsn' => $dsn,
'username' => $username,
'password' => $password,
'prefix' => $prefix,
'options' => $options + $defaultOptions,
];
return $this;
} | [
"public",
"function",
"addConnection",
"(",
"$",
"name",
",",
"$",
"dsn",
",",
"$",
"username",
"=",
"null",
",",
"$",
"password",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"//default driver options",
"static",
"$",
"defaultOptions",
"="... | Add a new connection configuration
@param string $name
@param string $dsn
@param string $username
@param string $password
@param array $options
@return \Ark\Database\Connection | [
"Add",
"a",
"new",
"connection",
"configuration"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/Connection.php#L159-L181 | train |
arkphp/database | src/Connection.php | Connection.quoteIdentifier | public function quoteIdentifier($name)
{
$quote = null;
switch ($this->getAttribute(\PDO::ATTR_DRIVER_NAME)) {
case 'pgsql':
case 'sqlsrv':
case 'dblib':
case 'mssql':
case 'sybase':
$quote = '"';
break;
case 'mysql':
case 'sqlite':
case 'sqlite2':
default:
$quote = '`';
}
$parts = explode('.', $name);
foreach ($parts as $k => $part) {
if ($part !== '*') {
$parts[$k] = $quote . $part . $quote;
}
}
return implode('.', $parts);
} | php | public function quoteIdentifier($name)
{
$quote = null;
switch ($this->getAttribute(\PDO::ATTR_DRIVER_NAME)) {
case 'pgsql':
case 'sqlsrv':
case 'dblib':
case 'mssql':
case 'sybase':
$quote = '"';
break;
case 'mysql':
case 'sqlite':
case 'sqlite2':
default:
$quote = '`';
}
$parts = explode('.', $name);
foreach ($parts as $k => $part) {
if ($part !== '*') {
$parts[$k] = $quote . $part . $quote;
}
}
return implode('.', $parts);
} | [
"public",
"function",
"quoteIdentifier",
"(",
"$",
"name",
")",
"{",
"$",
"quote",
"=",
"null",
";",
"switch",
"(",
"$",
"this",
"->",
"getAttribute",
"(",
"\\",
"PDO",
"::",
"ATTR_DRIVER_NAME",
")",
")",
"{",
"case",
"'pgsql'",
":",
"case",
"'sqlsrv'",
... | Quote table or column
@param string $name
@return string | [
"Quote",
"table",
"or",
"column"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/Connection.php#L334-L360 | train |
clue/reactphp-quassel | src/Client.php | Client.writeClientInit | public function writeClientInit($compression = false, $ssl = false)
{
// MMM dd yyyy HH:mm:ss
$date = date('M d Y H:i:s');
$data = array(
'MsgType' => 'ClientInit',
'ClientDate' => $date,
'ClientVersion' => 'clue/quassel-react alpha'
);
if ($this->protocol->isLegacy()) {
$data += array(
'ProtocolVersion' => 10,
'UseCompression' => (bool)$compression,
'UseSsl' => (bool)$ssl
);
}
return $this->write($data);
} | php | public function writeClientInit($compression = false, $ssl = false)
{
// MMM dd yyyy HH:mm:ss
$date = date('M d Y H:i:s');
$data = array(
'MsgType' => 'ClientInit',
'ClientDate' => $date,
'ClientVersion' => 'clue/quassel-react alpha'
);
if ($this->protocol->isLegacy()) {
$data += array(
'ProtocolVersion' => 10,
'UseCompression' => (bool)$compression,
'UseSsl' => (bool)$ssl
);
}
return $this->write($data);
} | [
"public",
"function",
"writeClientInit",
"(",
"$",
"compression",
"=",
"false",
",",
"$",
"ssl",
"=",
"false",
")",
"{",
"// MMM dd yyyy HH:mm:ss",
"$",
"date",
"=",
"date",
"(",
"'M d Y H:i:s'",
")",
";",
"$",
"data",
"=",
"array",
"(",
"'MsgType'",
"=>",... | send client init info
expect either of ClientInitAck or ClientInitReject["Error"] in response
ClientInitAck["Configured"] === true means you should continue with
writeClientInit() next
ClientInitAck["Configured"] === false means you should continue with
writeCoreSetupData() next
@param boolean $compression (only for legacy protocol)
@param boolean $ssl (only for legacy protocol)
@return boolean | [
"send",
"client",
"init",
"info"
] | 379d63fdfc068d3571985a2afeea50c248ad3014 | https://github.com/clue/reactphp-quassel/blob/379d63fdfc068d3571985a2afeea50c248ad3014/src/Client.php#L62-L82 | train |
clue/reactphp-quassel | src/Client.php | Client.writeCoreSetupData | public function writeCoreSetupData($user, $password, $backend = 'SQLite', $properties = array())
{
return $this->write(array(
'MsgType' => 'CoreSetupData',
'SetupData' => array(
'AdminUser' => (string)$user,
'AdminPasswd' => (string)$password,
'Backend' => (string)$backend,
'ConnectionProperties' => $properties
)
));
} | php | public function writeCoreSetupData($user, $password, $backend = 'SQLite', $properties = array())
{
return $this->write(array(
'MsgType' => 'CoreSetupData',
'SetupData' => array(
'AdminUser' => (string)$user,
'AdminPasswd' => (string)$password,
'Backend' => (string)$backend,
'ConnectionProperties' => $properties
)
));
} | [
"public",
"function",
"writeCoreSetupData",
"(",
"$",
"user",
",",
"$",
"password",
",",
"$",
"backend",
"=",
"'SQLite'",
",",
"$",
"properties",
"=",
"array",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"write",
"(",
"array",
"(",
"'MsgType'",
"=... | send setup data
expect either of CoreSetupAck or CoreSetupReject["Error"] in response
Possible values for the $backend and $properties parameters are reported
as part of the ClientInitAck["StorageBackends"] list of maps.
At the time of writing this, the only supported backends are the default
"SQLite" which requires no additional configuration and the significantly
faster "PostgreSQL" which accepts a map with your database credentials.
@param string $user admin user name
@param string $password admin password
@param string $backend One of the available "DisplayName" values from ClientInitAck["StorageBackends"]
@param array $properties (optional) map with keys from "SetupKeys" from ClientInitAck["StorageBackends"], where missing keys default to those from the "SetupDefaults"
@return boolean | [
"send",
"setup",
"data"
] | 379d63fdfc068d3571985a2afeea50c248ad3014 | https://github.com/clue/reactphp-quassel/blob/379d63fdfc068d3571985a2afeea50c248ad3014/src/Client.php#L120-L131 | train |
clue/reactphp-quassel | src/Client.php | Client.writeHeartBeatRequest | public function writeHeartBeatRequest(\DateTime $dt = null)
{
if ($dt === null) {
$dt = \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)));
}
return $this->write(array(
Protocol::REQUEST_HEARTBEAT,
$dt
));
} | php | public function writeHeartBeatRequest(\DateTime $dt = null)
{
if ($dt === null) {
$dt = \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)));
}
return $this->write(array(
Protocol::REQUEST_HEARTBEAT,
$dt
));
} | [
"public",
"function",
"writeHeartBeatRequest",
"(",
"\\",
"DateTime",
"$",
"dt",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"dt",
"===",
"null",
")",
"{",
"$",
"dt",
"=",
"\\",
"DateTime",
"::",
"createFromFormat",
"(",
"'U.u'",
",",
"sprintf",
"(",
"'%.6F... | Sends a heartbeat request
Expect the Quassel IRC core to respond with a heartbeat reply with the
same Datetime object with millisecond precision.
Giving a DateTime object is optional because the most common use case is
to send the current timestamp. It is recommended to not give one so the
appropriate timestamp is sent automatically. Otherwise, you should make
sure to use a DateTime object with appropriate precision.
Note that the Quassel protocol limits the DateTime accuracy to
millisecond precision and incoming DateTime objects will always be
expressed in the current default timezone. Also note that the legacy
protocol only transports number of milliseconds since midnight, so this
is not suited a transport arbitrary timestamps.
@param null|\DateTime $dt (optional) DateTime object with millisecond precision or null=current timestamp
@return bool | [
"Sends",
"a",
"heartbeat",
"request"
] | 379d63fdfc068d3571985a2afeea50c248ad3014 | https://github.com/clue/reactphp-quassel/blob/379d63fdfc068d3571985a2afeea50c248ad3014/src/Client.php#L162-L172 | train |
clue/reactphp-quassel | src/Client.php | Client.writeBufferRequestBacklogAll | public function writeBufferRequestBacklogAll($messageIdFirst, $messageIdLast, $maxAmount, $additional)
{
return $this->write(array(
Protocol::REQUEST_SYNC,
"BacklogManager",
"",
"requestBacklogAll",
new QVariant((int)$messageIdFirst, 'MsgId'),
new QVariant((int)$messageIdLast, 'MsgId'),
(int)$maxAmount,
(int)$additional
));
} | php | public function writeBufferRequestBacklogAll($messageIdFirst, $messageIdLast, $maxAmount, $additional)
{
return $this->write(array(
Protocol::REQUEST_SYNC,
"BacklogManager",
"",
"requestBacklogAll",
new QVariant((int)$messageIdFirst, 'MsgId'),
new QVariant((int)$messageIdLast, 'MsgId'),
(int)$maxAmount,
(int)$additional
));
} | [
"public",
"function",
"writeBufferRequestBacklogAll",
"(",
"$",
"messageIdFirst",
",",
"$",
"messageIdLast",
",",
"$",
"maxAmount",
",",
"$",
"additional",
")",
"{",
"return",
"$",
"this",
"->",
"write",
"(",
"array",
"(",
"Protocol",
"::",
"REQUEST_SYNC",
","... | Sends a backlog request for all messages in all channels
@param int $messageIdFirst
@param int $messageIdLast
@param int $maxAmount
@param int $additional
@return bool
@see self::writeBufferRequestBacklog() for parameter description | [
"Sends",
"a",
"backlog",
"request",
"for",
"all",
"messages",
"in",
"all",
"channels"
] | 379d63fdfc068d3571985a2afeea50c248ad3014 | https://github.com/clue/reactphp-quassel/blob/379d63fdfc068d3571985a2afeea50c248ad3014/src/Client.php#L280-L292 | train |
clue/reactphp-quassel | src/Client.php | Client.write | public function write($data)
{
return $this->stream->write(
$this->splitter->writePacket(
$this->protocol->serializeVariantPacket($data)
)
);
} | php | public function write($data)
{
return $this->stream->write(
$this->splitter->writePacket(
$this->protocol->serializeVariantPacket($data)
)
);
} | [
"public",
"function",
"write",
"(",
"$",
"data",
")",
"{",
"return",
"$",
"this",
"->",
"stream",
"->",
"write",
"(",
"$",
"this",
"->",
"splitter",
"->",
"writePacket",
"(",
"$",
"this",
"->",
"protocol",
"->",
"serializeVariantPacket",
"(",
"$",
"data"... | writes the given data array to the underlying connection
This is a low level method that should only be used if you know what
you're doing. Also check the other write*() methods instead.
@param array $data
@return boolean returns boolean false if buffer is full and writing should be throttled | [
"writes",
"the",
"given",
"data",
"array",
"to",
"the",
"underlying",
"connection"
] | 379d63fdfc068d3571985a2afeea50c248ad3014 | https://github.com/clue/reactphp-quassel/blob/379d63fdfc068d3571985a2afeea50c248ad3014/src/Client.php#L415-L422 | train |
maximebf/CacheCache | src/CacheCache/Pipeline.php | Pipeline.execute | public function execute()
{
$groups = array();
$results = array();
$currentOperation = null;
$currentGroup = array();
foreach ($this->commands as $command) {
if ($currentOperation !== $command[0]) {
$groups[] = array($currentOperation, $currentGroup);
$currentOperation = $command[0];
$currentGroup = array();
}
if ($currentOperation === 'get') {
$currentGroup[] = $command[1];
} else {
$currentGroup[$command[1]] = $command[2];
}
}
$groups[] = array($currentOperation, $currentGroup);
array_shift($groups);
foreach ($groups as $group) {
list($op, $args) = $group;
if ($op === 'set') {
$result = $this->backend->setMulti($args, $this->ttl);
$results = array_merge($results, array_fill(0, count($args), $result));
} else {
$results = array_merge($results, $this->backend->getMulti($args));
}
}
$this->commands = array();
return $results;
} | php | public function execute()
{
$groups = array();
$results = array();
$currentOperation = null;
$currentGroup = array();
foreach ($this->commands as $command) {
if ($currentOperation !== $command[0]) {
$groups[] = array($currentOperation, $currentGroup);
$currentOperation = $command[0];
$currentGroup = array();
}
if ($currentOperation === 'get') {
$currentGroup[] = $command[1];
} else {
$currentGroup[$command[1]] = $command[2];
}
}
$groups[] = array($currentOperation, $currentGroup);
array_shift($groups);
foreach ($groups as $group) {
list($op, $args) = $group;
if ($op === 'set') {
$result = $this->backend->setMulti($args, $this->ttl);
$results = array_merge($results, array_fill(0, count($args), $result));
} else {
$results = array_merge($results, $this->backend->getMulti($args));
}
}
$this->commands = array();
return $results;
} | [
"public",
"function",
"execute",
"(",
")",
"{",
"$",
"groups",
"=",
"array",
"(",
")",
";",
"$",
"results",
"=",
"array",
"(",
")",
";",
"$",
"currentOperation",
"=",
"null",
";",
"$",
"currentGroup",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$... | Executes the pipeline and returns results of individual commands
as an array.
@return array | [
"Executes",
"the",
"pipeline",
"and",
"returns",
"results",
"of",
"individual",
"commands",
"as",
"an",
"array",
"."
] | eb64a3748aad4ddaf236ef4738a83267576a0f97 | https://github.com/maximebf/CacheCache/blob/eb64a3748aad4ddaf236ef4738a83267576a0f97/src/CacheCache/Pipeline.php#L88-L122 | train |
nanbando/core | src/Bundle/Command/ReconfigureCommand.php | ReconfigureCommand.rebuild | protected function rebuild(InputInterface $input, OutputInterface $output)
{
$puli = new Puli(Path::join([getcwd(), NANBANDO_DIR]));
$puli->start();
/** @var EmbeddedComposerInterface $embeddedComposer */
$embeddedComposer = $this->getApplication()->getEmbeddedComposer();
$packageManager = $puli->getPackageManager();
$io = new ConsoleIO($input, $output, $this->getApplication()->getHelperSet());
$composer = $embeddedComposer->createComposer($io);
$installationManager = $composer->getInstallationManager();
$rootPackage = $composer->getPackage();
$repository = $composer->getRepositoryManager()->getLocalRepository();
$packages = [];
foreach ($repository->getPackages() as $package) {
$packages[$package->getName()] = $package;
}
foreach ($rootPackage->getRequires() as $require) {
if (!array_key_exists($require->getTarget(), $packages)) {
continue;
}
$packageManager->installPackage(
Path::normalize($installationManager->getInstallPath($packages[$require->getTarget()])),
$require->getTarget(),
'nanbando'
);
}
$filesystem = new Filesystem();
$filesystem->remove(Path::join([getcwd(), NANBANDO_DIR, '.puli']));
$discoveryManager = $puli->getDiscoveryManager();
if (!$discoveryManager->hasRootTypeDescriptor('nanbando/bundle')) {
$discoveryManager->addRootTypeDescriptor(new BindingTypeDescriptor(new BindingType('nanbando/bundle')), 0);
}
$discoveryManager->clearDiscovery();
$discoveryManager->buildDiscovery();
$filesystem = new Filesystem();
$filesystem->remove(Path::join([getcwd(), NANBANDO_DIR, 'app', 'cache']));
} | php | protected function rebuild(InputInterface $input, OutputInterface $output)
{
$puli = new Puli(Path::join([getcwd(), NANBANDO_DIR]));
$puli->start();
/** @var EmbeddedComposerInterface $embeddedComposer */
$embeddedComposer = $this->getApplication()->getEmbeddedComposer();
$packageManager = $puli->getPackageManager();
$io = new ConsoleIO($input, $output, $this->getApplication()->getHelperSet());
$composer = $embeddedComposer->createComposer($io);
$installationManager = $composer->getInstallationManager();
$rootPackage = $composer->getPackage();
$repository = $composer->getRepositoryManager()->getLocalRepository();
$packages = [];
foreach ($repository->getPackages() as $package) {
$packages[$package->getName()] = $package;
}
foreach ($rootPackage->getRequires() as $require) {
if (!array_key_exists($require->getTarget(), $packages)) {
continue;
}
$packageManager->installPackage(
Path::normalize($installationManager->getInstallPath($packages[$require->getTarget()])),
$require->getTarget(),
'nanbando'
);
}
$filesystem = new Filesystem();
$filesystem->remove(Path::join([getcwd(), NANBANDO_DIR, '.puli']));
$discoveryManager = $puli->getDiscoveryManager();
if (!$discoveryManager->hasRootTypeDescriptor('nanbando/bundle')) {
$discoveryManager->addRootTypeDescriptor(new BindingTypeDescriptor(new BindingType('nanbando/bundle')), 0);
}
$discoveryManager->clearDiscovery();
$discoveryManager->buildDiscovery();
$filesystem = new Filesystem();
$filesystem->remove(Path::join([getcwd(), NANBANDO_DIR, 'app', 'cache']));
} | [
"protected",
"function",
"rebuild",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"puli",
"=",
"new",
"Puli",
"(",
"Path",
"::",
"join",
"(",
"[",
"getcwd",
"(",
")",
",",
"NANBANDO_DIR",
"]",
")",
")",
";",... | Rebuild the puli dependencies for symfony container. | [
"Rebuild",
"the",
"puli",
"dependencies",
"for",
"symfony",
"container",
"."
] | 790f5c6339753bffafb50a846ccb6bab81f26877 | https://github.com/nanbando/core/blob/790f5c6339753bffafb50a846ccb6bab81f26877/src/Bundle/Command/ReconfigureCommand.php#L104-L149 | train |
undera/pwe | PWE/Modules/SimpleWiki/GoogleCodeWikiSyntax/ExtLipsum.php | ExtLipsum._getParagraph | private function _getParagraph($first = false)
{
$words = $this->_dictionary;
shuffle($words);
if ($first) {
$pre = array('lorem', 'ipsum');
$words = array_merge($pre, $words);
}
$nbrWordsPerParagraph = $this->_nbrWordsPerParagraph + mt_rand(-20, 20);
$nbrWordsPerSentence = $this->_nbrWordsPerSentence + mt_rand(-8, 8);
$words = array_slice($words, 0, $nbrWordsPerParagraph);
$sentences = array_chunk($words, $nbrWordsPerSentence);
$result = array();
foreach ($sentences as &$sentence) {
$this->_punctuate($sentence);
$result[] = ucfirst(implode(' ', $sentence));
}
return ('<p>' . implode(' ', $result) . '</p>');
} | php | private function _getParagraph($first = false)
{
$words = $this->_dictionary;
shuffle($words);
if ($first) {
$pre = array('lorem', 'ipsum');
$words = array_merge($pre, $words);
}
$nbrWordsPerParagraph = $this->_nbrWordsPerParagraph + mt_rand(-20, 20);
$nbrWordsPerSentence = $this->_nbrWordsPerSentence + mt_rand(-8, 8);
$words = array_slice($words, 0, $nbrWordsPerParagraph);
$sentences = array_chunk($words, $nbrWordsPerSentence);
$result = array();
foreach ($sentences as &$sentence) {
$this->_punctuate($sentence);
$result[] = ucfirst(implode(' ', $sentence));
}
return ('<p>' . implode(' ', $result) . '</p>');
} | [
"private",
"function",
"_getParagraph",
"(",
"$",
"first",
"=",
"false",
")",
"{",
"$",
"words",
"=",
"$",
"this",
"->",
"_dictionary",
";",
"shuffle",
"(",
"$",
"words",
")",
";",
"if",
"(",
"$",
"first",
")",
"{",
"$",
"pre",
"=",
"array",
"(",
... | Returns a paragraph.
@param bool $first Is it the first paragraph?
@return string The HTML result. | [
"Returns",
"a",
"paragraph",
"."
] | 4795f3a9755657c2a8be8ef3236992580b7954b3 | https://github.com/undera/pwe/blob/4795f3a9755657c2a8be8ef3236992580b7954b3/PWE/Modules/SimpleWiki/GoogleCodeWikiSyntax/ExtLipsum.php#L87-L105 | train |
undera/pwe | PWE/Modules/SimpleWiki/GoogleCodeWikiSyntax/ExtLipsum.php | ExtLipsum._numberOfCommas | private function _numberOfCommas($len)
{
$avg = (float)log($len, 6);
$stdDev = (float)($avg / 6.000);
return ((int)round($this->_gauss($avg, $stdDev)));
} | php | private function _numberOfCommas($len)
{
$avg = (float)log($len, 6);
$stdDev = (float)($avg / 6.000);
return ((int)round($this->_gauss($avg, $stdDev)));
} | [
"private",
"function",
"_numberOfCommas",
"(",
"$",
"len",
")",
"{",
"$",
"avg",
"=",
"(",
"float",
")",
"log",
"(",
"$",
"len",
",",
"6",
")",
";",
"$",
"stdDev",
"=",
"(",
"float",
")",
"(",
"$",
"avg",
"/",
"6.000",
")",
";",
"return",
"(",
... | Determines the number of commas for a sentence of the given length.
Average and standard deviation are determined superficially.
@param int $len Length of text.
@return int Number of commas to insert. | [
"Determines",
"the",
"number",
"of",
"commas",
"for",
"a",
"sentence",
"of",
"the",
"given",
"length",
".",
"Average",
"and",
"standard",
"deviation",
"are",
"determined",
"superficially",
"."
] | 4795f3a9755657c2a8be8ef3236992580b7954b3 | https://github.com/undera/pwe/blob/4795f3a9755657c2a8be8ef3236992580b7954b3/PWE/Modules/SimpleWiki/GoogleCodeWikiSyntax/ExtLipsum.php#L133-L138 | train |
raftalks/Form | src/Raftalks/Form/Html/HtmlMaker.php | HtmlMaker.get | public function get($name)
{
if(isset($this->global_vars[$name]))
{
return $this->global_vars[$name];
}
return null;
} | php | public function get($name)
{
if(isset($this->global_vars[$name]))
{
return $this->global_vars[$name];
}
return null;
} | [
"public",
"function",
"get",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"global_vars",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"global_vars",
"[",
"$",
"name",
"]",
";",
"}",
"return",
"null... | get data from roots scope from any where within a Form closure | [
"get",
"data",
"from",
"roots",
"scope",
"from",
"any",
"where",
"within",
"a",
"Form",
"closure"
] | e6d116263e0ef46eb46a4741df99fd4f1414e6ad | https://github.com/raftalks/Form/blob/e6d116263e0ef46eb46a4741df99fd4f1414e6ad/src/Raftalks/Form/Html/HtmlMaker.php#L77-L85 | train |
canax/textfilter | src/TextFilter/Filter/Frontmatter.php | Frontmatter.parseLines | public function parseLines()
{
$text = [];
while (($line = $this->nextLine()) !== false) {
$line = rtrim($line);
// Skip empty lines
if ($line == "") {
$text[] = null;
continue;
}
// Look at start of line to detect valid blocktypes
$blockTypes = [];
$marker = $line[0];
if (isset($this->blockTypes[$marker])) {
foreach ($this->blockTypes[$marker] as $blockType) {
$blockTypes[] = $blockType;
}
}
// Check if line is matching a detected blocktype
foreach ($blockTypes as $blockType) {
if ($this->{"block".$blockType}($line)) {
continue;
}
}
}
$text = implode("\n", $this->lines);
return [
"text" => $text,
"frontmatter" => $this->frontmatter,
];
} | php | public function parseLines()
{
$text = [];
while (($line = $this->nextLine()) !== false) {
$line = rtrim($line);
// Skip empty lines
if ($line == "") {
$text[] = null;
continue;
}
// Look at start of line to detect valid blocktypes
$blockTypes = [];
$marker = $line[0];
if (isset($this->blockTypes[$marker])) {
foreach ($this->blockTypes[$marker] as $blockType) {
$blockTypes[] = $blockType;
}
}
// Check if line is matching a detected blocktype
foreach ($blockTypes as $blockType) {
if ($this->{"block".$blockType}($line)) {
continue;
}
}
}
$text = implode("\n", $this->lines);
return [
"text" => $text,
"frontmatter" => $this->frontmatter,
];
} | [
"public",
"function",
"parseLines",
"(",
")",
"{",
"$",
"text",
"=",
"[",
"]",
";",
"while",
"(",
"(",
"$",
"line",
"=",
"$",
"this",
"->",
"nextLine",
"(",
")",
")",
"!==",
"false",
")",
"{",
"$",
"line",
"=",
"rtrim",
"(",
"$",
"line",
")",
... | Parse each line and look into it to see whats need to be done.
@return array with the resulting text and optional additional items. | [
"Parse",
"each",
"line",
"and",
"look",
"into",
"it",
"to",
"see",
"whats",
"need",
"to",
"be",
"done",
"."
] | a90177cd404b093541222fd0d6cf71907ac2ce25 | https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/Filter/Frontmatter.php#L126-L162 | train |
canax/textfilter | src/TextFilter/Filter/Frontmatter.php | Frontmatter.currentLine | public function currentLine()
{
return isset($this->lines[$this->lineNumber - 1])
? $this->lines[$this->lineNumber - 1]
: false;
} | php | public function currentLine()
{
return isset($this->lines[$this->lineNumber - 1])
? $this->lines[$this->lineNumber - 1]
: false;
} | [
"public",
"function",
"currentLine",
"(",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"lines",
"[",
"$",
"this",
"->",
"lineNumber",
"-",
"1",
"]",
")",
"?",
"$",
"this",
"->",
"lines",
"[",
"$",
"this",
"->",
"lineNumber",
"-",
"1",
"]",
... | Get current line to parse.
@return string|boolean containing text for current row or false when
reached EOF. | [
"Get",
"current",
"line",
"to",
"parse",
"."
] | a90177cd404b093541222fd0d6cf71907ac2ce25 | https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/Filter/Frontmatter.php#L172-L177 | train |
canax/textfilter | src/TextFilter/Filter/Frontmatter.php | Frontmatter.blockInclude | protected function blockInclude($line)
{
if ($this->config["include"]
&& preg_match("/^#include[ \t]([\w.]+)$/", $line, $matches)
) {
$file = $this->config["include_base"]."/".$matches[1];
if (!is_readable($file)) {
throw new Exception("Could not find include file: '$file'");
}
$include = file_get_contents($file);
$include = str_replace(array("\r\n", "\r"), "\n", $include);
$include = explode("\n", $include);
array_splice(
$this->lines,
$this->lineNumber - 1,
1,
$include
);
$this->lineNumber--;
return true;
}
} | php | protected function blockInclude($line)
{
if ($this->config["include"]
&& preg_match("/^#include[ \t]([\w.]+)$/", $line, $matches)
) {
$file = $this->config["include_base"]."/".$matches[1];
if (!is_readable($file)) {
throw new Exception("Could not find include file: '$file'");
}
$include = file_get_contents($file);
$include = str_replace(array("\r\n", "\r"), "\n", $include);
$include = explode("\n", $include);
array_splice(
$this->lines,
$this->lineNumber - 1,
1,
$include
);
$this->lineNumber--;
return true;
}
} | [
"protected",
"function",
"blockInclude",
"(",
"$",
"line",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"config",
"[",
"\"include\"",
"]",
"&&",
"preg_match",
"(",
"\"/^#include[ \\t]([\\w.]+)$/\"",
",",
"$",
"line",
",",
"$",
"matches",
")",
")",
"{",
"$",
"... | Detect and include external file, add it to lines array and parse it.
@param string $line to begin parsing.
@return boolean|void true when block is found and parsed, else void. | [
"Detect",
"and",
"include",
"external",
"file",
"add",
"it",
"to",
"lines",
"array",
"and",
"parse",
"it",
"."
] | a90177cd404b093541222fd0d6cf71907ac2ce25 | https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/Filter/Frontmatter.php#L202-L226 | train |
canax/textfilter | src/TextFilter/Filter/Frontmatter.php | Frontmatter.blockYamlFrontmatter | protected function blockYamlFrontmatter($line)
{
if ($this->config["frontmatter_yaml"]
&& strlen($line) === 3
&& $line[2] === "-"
&& $line[1] === "-"
) {
$startLineNumber = $this->lineNumber;
// Detect end of block and move it to frontmatter
while (($line = $this->nextLine()) !== false) {
$line = rtrim($line);
// Block ends with --- or ...
if (strlen($line) === 3
&& (
($line[2] === "-" && $line[1] === "-" && $line[0] === "-") ||
($line[2] === "." && $line[1] === "." && $line[0] === ".")
)
) {
$linesRemoved = $this->lineNumber + 1 - $startLineNumber;
$this->linesRemoved += $linesRemoved;
$frontmatter = array_splice(
$this->lines,
$startLineNumber - 1,
$linesRemoved
);
unset($frontmatter[$linesRemoved - 1]);
unset($frontmatter[0]);
$this->addYamlFrontmatter($frontmatter);
$this->lineNumber = $startLineNumber - 1;
return true;
}
}
if ($this->currentLine() === false) {
throw new Exception("Start of YAML detected at line: $startLineNumber but no end of block detected.");
}
}
} | php | protected function blockYamlFrontmatter($line)
{
if ($this->config["frontmatter_yaml"]
&& strlen($line) === 3
&& $line[2] === "-"
&& $line[1] === "-"
) {
$startLineNumber = $this->lineNumber;
// Detect end of block and move it to frontmatter
while (($line = $this->nextLine()) !== false) {
$line = rtrim($line);
// Block ends with --- or ...
if (strlen($line) === 3
&& (
($line[2] === "-" && $line[1] === "-" && $line[0] === "-") ||
($line[2] === "." && $line[1] === "." && $line[0] === ".")
)
) {
$linesRemoved = $this->lineNumber + 1 - $startLineNumber;
$this->linesRemoved += $linesRemoved;
$frontmatter = array_splice(
$this->lines,
$startLineNumber - 1,
$linesRemoved
);
unset($frontmatter[$linesRemoved - 1]);
unset($frontmatter[0]);
$this->addYamlFrontmatter($frontmatter);
$this->lineNumber = $startLineNumber - 1;
return true;
}
}
if ($this->currentLine() === false) {
throw new Exception("Start of YAML detected at line: $startLineNumber but no end of block detected.");
}
}
} | [
"protected",
"function",
"blockYamlFrontmatter",
"(",
"$",
"line",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"config",
"[",
"\"frontmatter_yaml\"",
"]",
"&&",
"strlen",
"(",
"$",
"line",
")",
"===",
"3",
"&&",
"$",
"line",
"[",
"2",
"]",
"===",
"\"-\"",
... | Detect and extract block with YAML frontmatter from the lines array.
@param string $line to begin parsing.
@return boolean|void true when block is found and parsed, else void.
@SuppressWarnings(PHPMD.CyclomaticComplexity) | [
"Detect",
"and",
"extract",
"block",
"with",
"YAML",
"frontmatter",
"from",
"the",
"lines",
"array",
"."
] | a90177cd404b093541222fd0d6cf71907ac2ce25 | https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/Filter/Frontmatter.php#L239-L280 | train |
canax/textfilter | src/TextFilter/Filter/Frontmatter.php | Frontmatter.addYamlFrontmatter | protected function addYamlFrontmatter($lines)
{
$text = implode("\n", $lines);
$parsed = $this->parseYaml($text);
if (!is_array($parsed)) {
$parsed = [$parsed];
}
$this->frontmatter = array_merge($this->frontmatter, $parsed);
} | php | protected function addYamlFrontmatter($lines)
{
$text = implode("\n", $lines);
$parsed = $this->parseYaml($text);
if (!is_array($parsed)) {
$parsed = [$parsed];
}
$this->frontmatter = array_merge($this->frontmatter, $parsed);
} | [
"protected",
"function",
"addYamlFrontmatter",
"(",
"$",
"lines",
")",
"{",
"$",
"text",
"=",
"implode",
"(",
"\"\\n\"",
",",
"$",
"lines",
")",
";",
"$",
"parsed",
"=",
"$",
"this",
"->",
"parseYaml",
"(",
"$",
"text",
")",
";",
"if",
"(",
"!",
"i... | Extract YAML frontmatter from text and merge into existing frontmatter.
@param array $lines the YAML to parsed.
@return void. | [
"Extract",
"YAML",
"frontmatter",
"from",
"text",
"and",
"merge",
"into",
"existing",
"frontmatter",
"."
] | a90177cd404b093541222fd0d6cf71907ac2ce25 | https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/Filter/Frontmatter.php#L291-L301 | train |
canax/textfilter | src/TextFilter/Filter/Frontmatter.php | Frontmatter.parseYaml | protected function parseYaml($text)
{
if ($this->config["yaml_parser_pecl"]
&& function_exists("yaml_parse")
) {
// PECL php5-yaml extension
$parsed = yaml_parse($text);
if ($parsed === false) {
throw new Exception("Failed parsing YAML frontmatter using PECL.");
}
return $parsed;
}
if ($this->config["yaml_parser_symfony"]
&& method_exists("Symfony\Component\Yaml\Yaml", "parse")
) {
// symfony/yaml
$parsed = Yaml::parse($text);
return $parsed;
}
if ($this->config["yaml_parser_spyc"]
&& function_exists("spyc_load")
) {
// mustangostang/spyc
$parsed = spyc_load($text);
return $parsed;
}
throw new Exception("Could not find support for YAML.");
} | php | protected function parseYaml($text)
{
if ($this->config["yaml_parser_pecl"]
&& function_exists("yaml_parse")
) {
// PECL php5-yaml extension
$parsed = yaml_parse($text);
if ($parsed === false) {
throw new Exception("Failed parsing YAML frontmatter using PECL.");
}
return $parsed;
}
if ($this->config["yaml_parser_symfony"]
&& method_exists("Symfony\Component\Yaml\Yaml", "parse")
) {
// symfony/yaml
$parsed = Yaml::parse($text);
return $parsed;
}
if ($this->config["yaml_parser_spyc"]
&& function_exists("spyc_load")
) {
// mustangostang/spyc
$parsed = spyc_load($text);
return $parsed;
}
throw new Exception("Could not find support for YAML.");
} | [
"protected",
"function",
"parseYaml",
"(",
"$",
"text",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"config",
"[",
"\"yaml_parser_pecl\"",
"]",
"&&",
"function_exists",
"(",
"\"yaml_parse\"",
")",
")",
"{",
"// PECL php5-yaml extension",
"$",
"parsed",
"=",
"yaml_... | Parse YAML front matter from text, use one of several available
implementations of a YAML parser.
@param string $text the YAML to parsed.
@return void.
@throws Exception when parsing frontmatter fails of is not installed. | [
"Parse",
"YAML",
"front",
"matter",
"from",
"text",
"use",
"one",
"of",
"several",
"available",
"implementations",
"of",
"a",
"YAML",
"parser",
"."
] | a90177cd404b093541222fd0d6cf71907ac2ce25 | https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/Filter/Frontmatter.php#L315-L346 | train |
canax/textfilter | src/TextFilter/Filter/Frontmatter.php | Frontmatter.addJsonFrontmatter | protected function addJsonFrontmatter($lines)
{
if (!function_exists("json_decode")) {
throw new Exception("Missing JSON support, perhaps install JSON module with PHP.");
}
$text = implode("\n", $lines);
$parsed = json_decode($text."\n", true);
if (is_null($parsed)) {
throw new Exception("Failed parsing JSON frontmatter.");
}
if (!is_array($parsed)) {
$parsed = [$parsed];
}
$this->frontmatter = array_merge($this->frontmatter, $parsed);
} | php | protected function addJsonFrontmatter($lines)
{
if (!function_exists("json_decode")) {
throw new Exception("Missing JSON support, perhaps install JSON module with PHP.");
}
$text = implode("\n", $lines);
$parsed = json_decode($text."\n", true);
if (is_null($parsed)) {
throw new Exception("Failed parsing JSON frontmatter.");
}
if (!is_array($parsed)) {
$parsed = [$parsed];
}
$this->frontmatter = array_merge($this->frontmatter, $parsed);
} | [
"protected",
"function",
"addJsonFrontmatter",
"(",
"$",
"lines",
")",
"{",
"if",
"(",
"!",
"function_exists",
"(",
"\"json_decode\"",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Missing JSON support, perhaps install JSON module with PHP.\"",
")",
";",
"}",
... | Extract JSON frontmatter from text and merge into existing frontmatter.
@param array $lines the JSON to parsed.
@return void. | [
"Extract",
"JSON",
"frontmatter",
"from",
"text",
"and",
"merge",
"into",
"existing",
"frontmatter",
"."
] | a90177cd404b093541222fd0d6cf71907ac2ce25 | https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/Filter/Frontmatter.php#L409-L427 | train |
protobuf-php/google-protobuf-proto | src/google/protobuf/DescriptorProto.php | DescriptorProto.addField | public function addField(\google\protobuf\FieldDescriptorProto $value)
{
if ($this->field === null) {
$this->field = new \Protobuf\MessageCollection();
}
$this->field->add($value);
} | php | public function addField(\google\protobuf\FieldDescriptorProto $value)
{
if ($this->field === null) {
$this->field = new \Protobuf\MessageCollection();
}
$this->field->add($value);
} | [
"public",
"function",
"addField",
"(",
"\\",
"google",
"\\",
"protobuf",
"\\",
"FieldDescriptorProto",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"field",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"field",
"=",
"new",
"\\",
"Protobuf",
"\\... | Add a new element to 'field'
@param \google\protobuf\FieldDescriptorProto $value | [
"Add",
"a",
"new",
"element",
"to",
"field"
] | da1827b4a23fccd4eb998a8d4bcd972f2330bc29 | https://github.com/protobuf-php/google-protobuf-proto/blob/da1827b4a23fccd4eb998a8d4bcd972f2330bc29/src/google/protobuf/DescriptorProto.php#L162-L169 | train |
protobuf-php/google-protobuf-proto | src/google/protobuf/DescriptorProto.php | DescriptorProto.addNestedType | public function addNestedType(\google\protobuf\DescriptorProto $value)
{
if ($this->nested_type === null) {
$this->nested_type = new \Protobuf\MessageCollection();
}
$this->nested_type->add($value);
} | php | public function addNestedType(\google\protobuf\DescriptorProto $value)
{
if ($this->nested_type === null) {
$this->nested_type = new \Protobuf\MessageCollection();
}
$this->nested_type->add($value);
} | [
"public",
"function",
"addNestedType",
"(",
"\\",
"google",
"\\",
"protobuf",
"\\",
"DescriptorProto",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"nested_type",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"nested_type",
"=",
"new",
"\\",
"Prot... | Add a new element to 'nested_type'
@param \google\protobuf\DescriptorProto $value | [
"Add",
"a",
"new",
"element",
"to",
"nested_type"
] | da1827b4a23fccd4eb998a8d4bcd972f2330bc29 | https://github.com/protobuf-php/google-protobuf-proto/blob/da1827b4a23fccd4eb998a8d4bcd972f2330bc29/src/google/protobuf/DescriptorProto.php#L250-L257 | train |
protobuf-php/google-protobuf-proto | src/google/protobuf/DescriptorProto.php | DescriptorProto.addExtensionRange | public function addExtensionRange(\google\protobuf\DescriptorProto\ExtensionRange $value)
{
if ($this->extension_range === null) {
$this->extension_range = new \Protobuf\MessageCollection();
}
$this->extension_range->add($value);
} | php | public function addExtensionRange(\google\protobuf\DescriptorProto\ExtensionRange $value)
{
if ($this->extension_range === null) {
$this->extension_range = new \Protobuf\MessageCollection();
}
$this->extension_range->add($value);
} | [
"public",
"function",
"addExtensionRange",
"(",
"\\",
"google",
"\\",
"protobuf",
"\\",
"DescriptorProto",
"\\",
"ExtensionRange",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"extension_range",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"extension... | Add a new element to 'extension_range'
@param \google\protobuf\DescriptorProto\ExtensionRange $value | [
"Add",
"a",
"new",
"element",
"to",
"extension_range"
] | da1827b4a23fccd4eb998a8d4bcd972f2330bc29 | https://github.com/protobuf-php/google-protobuf-proto/blob/da1827b4a23fccd4eb998a8d4bcd972f2330bc29/src/google/protobuf/DescriptorProto.php#L338-L345 | train |
protobuf-php/google-protobuf-proto | src/google/protobuf/DescriptorProto.php | DescriptorProto.addOneofDecl | public function addOneofDecl(\google\protobuf\OneofDescriptorProto $value)
{
if ($this->oneof_decl === null) {
$this->oneof_decl = new \Protobuf\MessageCollection();
}
$this->oneof_decl->add($value);
} | php | public function addOneofDecl(\google\protobuf\OneofDescriptorProto $value)
{
if ($this->oneof_decl === null) {
$this->oneof_decl = new \Protobuf\MessageCollection();
}
$this->oneof_decl->add($value);
} | [
"public",
"function",
"addOneofDecl",
"(",
"\\",
"google",
"\\",
"protobuf",
"\\",
"OneofDescriptorProto",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"oneof_decl",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"oneof_decl",
"=",
"new",
"\\",
"Pr... | Add a new element to 'oneof_decl'
@param \google\protobuf\OneofDescriptorProto $value | [
"Add",
"a",
"new",
"element",
"to",
"oneof_decl"
] | da1827b4a23fccd4eb998a8d4bcd972f2330bc29 | https://github.com/protobuf-php/google-protobuf-proto/blob/da1827b4a23fccd4eb998a8d4bcd972f2330bc29/src/google/protobuf/DescriptorProto.php#L382-L389 | train |
protobuf-php/google-protobuf-proto | src/google/protobuf/DescriptorProto.php | DescriptorProto.addReservedRange | public function addReservedRange(\google\protobuf\DescriptorProto\ReservedRange $value)
{
if ($this->reserved_range === null) {
$this->reserved_range = new \Protobuf\MessageCollection();
}
$this->reserved_range->add($value);
} | php | public function addReservedRange(\google\protobuf\DescriptorProto\ReservedRange $value)
{
if ($this->reserved_range === null) {
$this->reserved_range = new \Protobuf\MessageCollection();
}
$this->reserved_range->add($value);
} | [
"public",
"function",
"addReservedRange",
"(",
"\\",
"google",
"\\",
"protobuf",
"\\",
"DescriptorProto",
"\\",
"ReservedRange",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"reserved_range",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"reserved_ran... | Add a new element to 'reserved_range'
@param \google\protobuf\DescriptorProto\ReservedRange $value | [
"Add",
"a",
"new",
"element",
"to",
"reserved_range"
] | da1827b4a23fccd4eb998a8d4bcd972f2330bc29 | https://github.com/protobuf-php/google-protobuf-proto/blob/da1827b4a23fccd4eb998a8d4bcd972f2330bc29/src/google/protobuf/DescriptorProto.php#L456-L463 | train |
protobuf-php/google-protobuf-proto | src/google/protobuf/DescriptorProto.php | DescriptorProto.addReservedName | public function addReservedName($value)
{
if ($this->reserved_name === null) {
$this->reserved_name = new \Protobuf\ScalarCollection();
}
$this->reserved_name->add($value);
} | php | public function addReservedName($value)
{
if ($this->reserved_name === null) {
$this->reserved_name = new \Protobuf\ScalarCollection();
}
$this->reserved_name->add($value);
} | [
"public",
"function",
"addReservedName",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"reserved_name",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"reserved_name",
"=",
"new",
"\\",
"Protobuf",
"\\",
"ScalarCollection",
"(",
")",
";",
"}",
... | Add a new element to 'reserved_name'
@param string $value | [
"Add",
"a",
"new",
"element",
"to",
"reserved_name"
] | da1827b4a23fccd4eb998a8d4bcd972f2330bc29 | https://github.com/protobuf-php/google-protobuf-proto/blob/da1827b4a23fccd4eb998a8d4bcd972f2330bc29/src/google/protobuf/DescriptorProto.php#L500-L507 | train |
jbouzekri/FileUploaderBundle | Controller/CropController.php | CropController.filterAction | public function filterAction(Request $request, $endpoint)
{
$form = $this->createForm(CropType::class);
$form->handleRequest($request);
// Form invalid. Exit.
if (!$form->isValid()) {
return $this->createErrorResponse(
$this->get('translator')->trans('Invalid crop parameters')
);
}
// Else process crop
try {
return new JsonResponse(
$this->get('jb_fileuploader.croper')->crop($endpoint, $form->getData())
);
} catch (\Exception $e) {
return $this->createErrorResponse($e->getMessage());
}
} | php | public function filterAction(Request $request, $endpoint)
{
$form = $this->createForm(CropType::class);
$form->handleRequest($request);
// Form invalid. Exit.
if (!$form->isValid()) {
return $this->createErrorResponse(
$this->get('translator')->trans('Invalid crop parameters')
);
}
// Else process crop
try {
return new JsonResponse(
$this->get('jb_fileuploader.croper')->crop($endpoint, $form->getData())
);
} catch (\Exception $e) {
return $this->createErrorResponse($e->getMessage());
}
} | [
"public",
"function",
"filterAction",
"(",
"Request",
"$",
"request",
",",
"$",
"endpoint",
")",
"{",
"$",
"form",
"=",
"$",
"this",
"->",
"createForm",
"(",
"CropType",
"::",
"class",
")",
";",
"$",
"form",
"->",
"handleRequest",
"(",
"$",
"request",
... | Filter for croping
@param Request $request
@param string $endpoint
@return JsonResponse | [
"Filter",
"for",
"croping"
] | 592e7ed827eaa4e7f8f6f52947ca5e5a86835f6c | https://github.com/jbouzekri/FileUploaderBundle/blob/592e7ed827eaa4e7f8f6f52947ca5e5a86835f6c/Controller/CropController.php#L33-L54 | train |
nanbando/core | src/Core/Storage/LocalStorage.php | LocalStorage.parseDateFromFilename | protected function parseDateFromFilename($filename)
{
if ($date = \DateTime::createFromFormat(self::FILE_NAME_PATTERN, explode('_', $filename)[0])) {
return $date;
}
/**
* @deprecated handle BC break of PR #62. will be remove in 1.0-RC1.
*/
return \DateTime::createFromFormat('H-i-s-Y-m-d', explode('_', $filename)[0]);
} | php | protected function parseDateFromFilename($filename)
{
if ($date = \DateTime::createFromFormat(self::FILE_NAME_PATTERN, explode('_', $filename)[0])) {
return $date;
}
/**
* @deprecated handle BC break of PR #62. will be remove in 1.0-RC1.
*/
return \DateTime::createFromFormat('H-i-s-Y-m-d', explode('_', $filename)[0]);
} | [
"protected",
"function",
"parseDateFromFilename",
"(",
"$",
"filename",
")",
"{",
"if",
"(",
"$",
"date",
"=",
"\\",
"DateTime",
"::",
"createFromFormat",
"(",
"self",
"::",
"FILE_NAME_PATTERN",
",",
"explode",
"(",
"'_'",
",",
"$",
"filename",
")",
"[",
"... | Parse date from given filename.
@param string $filename
@return \DateTime
@deprecated This function contains deprecated parts | [
"Parse",
"date",
"from",
"given",
"filename",
"."
] | 790f5c6339753bffafb50a846ccb6bab81f26877 | https://github.com/nanbando/core/blob/790f5c6339753bffafb50a846ccb6bab81f26877/src/Core/Storage/LocalStorage.php#L266-L276 | train |
arkphp/database | src/QueryBuilder.php | QueryBuilder.prepare | public function prepare()
{
if (null === $this->statement) {
$this->statement = $this->db->prepare($this->getSql());
}
return $this;
} | php | public function prepare()
{
if (null === $this->statement) {
$this->statement = $this->db->prepare($this->getSql());
}
return $this;
} | [
"public",
"function",
"prepare",
"(",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"statement",
")",
"{",
"$",
"this",
"->",
"statement",
"=",
"$",
"this",
"->",
"db",
"->",
"prepare",
"(",
"$",
"this",
"->",
"getSql",
"(",
")",
")",
";... | Prepare PDO statement
@return \Ark\Database\QueryBuilder | [
"Prepare",
"PDO",
"statement"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/QueryBuilder.php#L70-L77 | train |
arkphp/database | src/QueryBuilder.php | QueryBuilder.groupBy | public function groupBy($fields)
{
if (!is_array($fields)) {
$fields = $this->splitParts($fields);
}
foreach ($fields as $k => $field) {
$fields[$k] = $this->db->quoteColumn($field);
}
$this->query['group'] = implode(',', $fields);
return $this;
} | php | public function groupBy($fields)
{
if (!is_array($fields)) {
$fields = $this->splitParts($fields);
}
foreach ($fields as $k => $field) {
$fields[$k] = $this->db->quoteColumn($field);
}
$this->query['group'] = implode(',', $fields);
return $this;
} | [
"public",
"function",
"groupBy",
"(",
"$",
"fields",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"fields",
")",
")",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"splitParts",
"(",
"$",
"fields",
")",
";",
"}",
"foreach",
"(",
"$",
"fields",
"... | GROUP BY statement
@param string|array $fields
@return \Ark\Database\QueryBuilder | [
"GROUP",
"BY",
"statement"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/QueryBuilder.php#L433-L446 | train |
arkphp/database | src/QueryBuilder.php | QueryBuilder.buildQuery | public function buildQuery($query = null)
{
if (null === $query) {
$query = $this->query;
}
$sql = "SELECT ";
if (isset($query['distinct']) && $query['distinct']) {
$sql .= 'DISTINCT ';
}
$sql .= isset($query['select']) ? $query['select'] : '*';
if (!isset($query['from'])) {
return false;
}
$sql .= "\nFROM " . $query['from'];
if (isset($query['join'])) {
$sql .= "\n" . (is_array($query['join']) ? implode("\n", $query['join']) : $query['join']);
}
if (isset($query['where']) && $query['where'] !== '') {
$sql .= "\nWHERE " . $query['where'];
}
if (isset($query['group'])) {
$sql .= "\nGROUP BY " . $query['group'];
if (isset($query['having'])) {
$sql .= "\nHAVING " . $query['having'];
}
}
if (isset($query['order'])) {
$sql .= "\n ORDER BY " . $query['order'];
}
$limit = isset($query['limit']) ? $query['limit'] : 0;
$offset = isset($query['offset']) ? $query['offset'] : 0;
$sql = $this->db->buildLimitOffset($sql, $limit, $offset);
if (isset($query['union'])) {
$sql .= "\n" . (is_array($query['union']) ? implode("\n", $query['union']) : $query['union']);
}
return $sql;
} | php | public function buildQuery($query = null)
{
if (null === $query) {
$query = $this->query;
}
$sql = "SELECT ";
if (isset($query['distinct']) && $query['distinct']) {
$sql .= 'DISTINCT ';
}
$sql .= isset($query['select']) ? $query['select'] : '*';
if (!isset($query['from'])) {
return false;
}
$sql .= "\nFROM " . $query['from'];
if (isset($query['join'])) {
$sql .= "\n" . (is_array($query['join']) ? implode("\n", $query['join']) : $query['join']);
}
if (isset($query['where']) && $query['where'] !== '') {
$sql .= "\nWHERE " . $query['where'];
}
if (isset($query['group'])) {
$sql .= "\nGROUP BY " . $query['group'];
if (isset($query['having'])) {
$sql .= "\nHAVING " . $query['having'];
}
}
if (isset($query['order'])) {
$sql .= "\n ORDER BY " . $query['order'];
}
$limit = isset($query['limit']) ? $query['limit'] : 0;
$offset = isset($query['offset']) ? $query['offset'] : 0;
$sql = $this->db->buildLimitOffset($sql, $limit, $offset);
if (isset($query['union'])) {
$sql .= "\n" . (is_array($query['union']) ? implode("\n", $query['union']) : $query['union']);
}
return $sql;
} | [
"public",
"function",
"buildQuery",
"(",
"$",
"query",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"query",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"query",
";",
"}",
"$",
"sql",
"=",
"\"SELECT \"",
";",
"if",
"(",
"isset",
"(",... | Build query SQL
@param array $query use $this->query if not specified
@return string | [
"Build",
"query",
"SQL"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/QueryBuilder.php#L486-L527 | train |
arkphp/database | src/QueryBuilder.php | QueryBuilder.setSql | public function setSql($sql)
{
if ('' !== $prefix = $this->db->getPrefix()) {
$sql = preg_replace('#{{(.*?)}}#', $prefix . '\1', $sql);
}
$this->sql = $sql;
return $this;
} | php | public function setSql($sql)
{
if ('' !== $prefix = $this->db->getPrefix()) {
$sql = preg_replace('#{{(.*?)}}#', $prefix . '\1', $sql);
}
$this->sql = $sql;
return $this;
} | [
"public",
"function",
"setSql",
"(",
"$",
"sql",
")",
"{",
"if",
"(",
"''",
"!==",
"$",
"prefix",
"=",
"$",
"this",
"->",
"db",
"->",
"getPrefix",
"(",
")",
")",
"{",
"$",
"sql",
"=",
"preg_replace",
"(",
"'#{{(.*?)}}#'",
",",
"$",
"prefix",
".",
... | Set SQL for this command
@param string $sql
@return \Ark\Database\QueryBuilder | [
"Set",
"SQL",
"for",
"this",
"command"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/QueryBuilder.php#L535-L543 | train |
arkphp/database | src/QueryBuilder.php | QueryBuilder.getSql | public function getSql()
{
if (null === $this->sql) {
if (!empty($this->query)) {
$this->setSql($this->buildQuery());
} else {
return false;
}
}
return $this->sql;
} | php | public function getSql()
{
if (null === $this->sql) {
if (!empty($this->query)) {
$this->setSql($this->buildQuery());
} else {
return false;
}
}
return $this->sql;
} | [
"public",
"function",
"getSql",
"(",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"sql",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"query",
")",
")",
"{",
"$",
"this",
"->",
"setSql",
"(",
"$",
"this",
"->",
"buildQue... | Get SQL for this command
@return string | [
"Get",
"SQL",
"for",
"this",
"command"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/QueryBuilder.php#L550-L561 | train |
arkphp/database | src/QueryBuilder.php | QueryBuilder.beginQuery | protected function beginQuery()
{
$autoSlave = $this->db->isAutoSlave();
if ($autoSlave) {
$this->db->switchConnection('slave');
}
$reconnect = $this->db->getOption('reconnect');
$reconnectRetries = $this->db->getOption('reconnect_retries', 3);
$reconnectDelayMS = $this->db->getOption('reconnect_delay_ms', 1000);
while (true) {
$e = null;
$errorCode = null;
$errorInfo = null;
$result = null;
$isReconnectError = false;
try {
$this->prepare();
$result = $this->statement->execute($this->params ? $this->params : $this->positionParams);
} catch (\Exception $e) {
}
if ($result === false || !$e) {
$errorCode = $this->statement->errorCode();
$errorInfo = $this->statement->errorInfo();
}
$isReconnectError = Util::checkReconnectError($errorCode, $errorInfo, $e);
// reconnect
if ($reconnect && $isReconnectError && $reconnectRetries > 0) {
$reconnectRetries--;
$this->statement = null;
$this->db->close();
$reconnectDelayMS && usleep($reconnectDelayMS * 1000);
continue;
}
break;
}
if ($autoSlave) {
$this->db->switchConnection();
}
if ($e) {
$this->db->logError(sprintf('Statement exception error #%s: %s', $e->getCode(), $e->getMessage()));
throw $e;
}
if ($result === false) {
$errorMsg = sprintf('Statement execute error #%s: %s', $errorInfo[0], $errorInfo[2]);
$this->db->logError($errorMsg);
throw new Exception($errorMsg);
}
} | php | protected function beginQuery()
{
$autoSlave = $this->db->isAutoSlave();
if ($autoSlave) {
$this->db->switchConnection('slave');
}
$reconnect = $this->db->getOption('reconnect');
$reconnectRetries = $this->db->getOption('reconnect_retries', 3);
$reconnectDelayMS = $this->db->getOption('reconnect_delay_ms', 1000);
while (true) {
$e = null;
$errorCode = null;
$errorInfo = null;
$result = null;
$isReconnectError = false;
try {
$this->prepare();
$result = $this->statement->execute($this->params ? $this->params : $this->positionParams);
} catch (\Exception $e) {
}
if ($result === false || !$e) {
$errorCode = $this->statement->errorCode();
$errorInfo = $this->statement->errorInfo();
}
$isReconnectError = Util::checkReconnectError($errorCode, $errorInfo, $e);
// reconnect
if ($reconnect && $isReconnectError && $reconnectRetries > 0) {
$reconnectRetries--;
$this->statement = null;
$this->db->close();
$reconnectDelayMS && usleep($reconnectDelayMS * 1000);
continue;
}
break;
}
if ($autoSlave) {
$this->db->switchConnection();
}
if ($e) {
$this->db->logError(sprintf('Statement exception error #%s: %s', $e->getCode(), $e->getMessage()));
throw $e;
}
if ($result === false) {
$errorMsg = sprintf('Statement execute error #%s: %s', $errorInfo[0], $errorInfo[2]);
$this->db->logError($errorMsg);
throw new Exception($errorMsg);
}
} | [
"protected",
"function",
"beginQuery",
"(",
")",
"{",
"$",
"autoSlave",
"=",
"$",
"this",
"->",
"db",
"->",
"isAutoSlave",
"(",
")",
";",
"if",
"(",
"$",
"autoSlave",
")",
"{",
"$",
"this",
"->",
"db",
"->",
"switchConnection",
"(",
"'slave'",
")",
"... | Prepare statement before query | [
"Prepare",
"statement",
"before",
"query"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/QueryBuilder.php#L566-L623 | train |
arkphp/database | src/QueryBuilder.php | QueryBuilder.queryAll | public function queryAll($params = array())
{
$this->mergeParams($params);
$this->beginQuery();
$rst = $this->statement->fetchAll(\PDO::FETCH_ASSOC);
$this->statement->closeCursor();
return $rst;
} | php | public function queryAll($params = array())
{
$this->mergeParams($params);
$this->beginQuery();
$rst = $this->statement->fetchAll(\PDO::FETCH_ASSOC);
$this->statement->closeCursor();
return $rst;
} | [
"public",
"function",
"queryAll",
"(",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"mergeParams",
"(",
"$",
"params",
")",
";",
"$",
"this",
"->",
"beginQuery",
"(",
")",
";",
"$",
"rst",
"=",
"$",
"this",
"->",
"statement",... | Get query result as array
@param array $params
@return array | [
"Get",
"query",
"result",
"as",
"array"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/QueryBuilder.php#L645-L652 | train |
arkphp/database | src/QueryBuilder.php | QueryBuilder.queryRow | public function queryRow($params = array())
{
$this->mergeParams($params);
$this->beginQuery();
$rst = $this->statement->fetch(\PDO::FETCH_ASSOC);
$this->statement->closeCursor();
return $rst;
} | php | public function queryRow($params = array())
{
$this->mergeParams($params);
$this->beginQuery();
$rst = $this->statement->fetch(\PDO::FETCH_ASSOC);
$this->statement->closeCursor();
return $rst;
} | [
"public",
"function",
"queryRow",
"(",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"mergeParams",
"(",
"$",
"params",
")",
";",
"$",
"this",
"->",
"beginQuery",
"(",
")",
";",
"$",
"rst",
"=",
"$",
"this",
"->",
"statement",... | Get first row of result
@param array $params
@return array | [
"Get",
"first",
"row",
"of",
"result"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/QueryBuilder.php#L660-L667 | train |
arkphp/database | src/QueryBuilder.php | QueryBuilder.queryColumn | public function queryColumn($params = array())
{
$this->mergeParams($params);
$this->beginQuery();
$rst = $this->statement->fetchAll(\PDO::FETCH_COLUMN);
$this->statement->closeCursor();
return $rst;
} | php | public function queryColumn($params = array())
{
$this->mergeParams($params);
$this->beginQuery();
$rst = $this->statement->fetchAll(\PDO::FETCH_COLUMN);
$this->statement->closeCursor();
return $rst;
} | [
"public",
"function",
"queryColumn",
"(",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"mergeParams",
"(",
"$",
"params",
")",
";",
"$",
"this",
"->",
"beginQuery",
"(",
")",
";",
"$",
"rst",
"=",
"$",
"this",
"->",
"statemen... | Get first column of result set
@param array $params
@return array | [
"Get",
"first",
"column",
"of",
"result",
"set"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/QueryBuilder.php#L675-L682 | train |
arkphp/database | src/QueryBuilder.php | QueryBuilder.queryValue | public function queryValue($params = array())
{
$this->mergeParams($params);
$this->beginQuery();
$rst = $this->statement->fetchColumn();
$this->statement->closeCursor();
return $rst;
} | php | public function queryValue($params = array())
{
$this->mergeParams($params);
$this->beginQuery();
$rst = $this->statement->fetchColumn();
$this->statement->closeCursor();
return $rst;
} | [
"public",
"function",
"queryValue",
"(",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"mergeParams",
"(",
"$",
"params",
")",
";",
"$",
"this",
"->",
"beginQuery",
"(",
")",
";",
"$",
"rst",
"=",
"$",
"this",
"->",
"statement... | Get first column of first row of result set
@param array $params
@return string | [
"Get",
"first",
"column",
"of",
"first",
"row",
"of",
"result",
"set"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/QueryBuilder.php#L690-L698 | train |
arkphp/database | src/QueryBuilder.php | QueryBuilder.execute | public function execute($params = array())
{
$this->mergeParams($params);
$reconnect = $this->db->getOption('reconnect');
$reconnectRetries = $this->db->getOption('reconnect_retries', 3);
$reconnectDelayMS = $this->db->getOption('reconnect_delay_ms', 1000);
while (true) {
$e = null;
$errorCode = null;
$errorInfo = null;
$result = null;
$isReconnectError = false;
try {
$this->prepare();
foreach ($this->positionParams as $index => $value) {
$this->statement->bindValue($index + 1, $value);
}
$result = $this->statement->execute($this->params?:null);
} catch (\Exception $e) {
}
if ($result === false || !$e) {
$errorCode = $this->statement->errorCode();
$errorInfo = $this->statement->errorInfo();
}
$isReconnectError = Util::checkReconnectError($errorCode, $errorInfo, $e);
// reconnect
if ($reconnect && $isReconnectError && $reconnectRetries > 0) {
$reconnectRetries--;
$this->statement = null;
$this->db->close();
$reconnectDelayMS && usleep($reconnectDelayMS * 1000);
continue;
}
break;
}
if ($e) {
$this->db->logError(sprintf('Statement exception error #%s: %s', $e->getCode(), $e->getMessage()));
throw $e;
}
if ($result === false) {
$this->db->logError(sprintf('Statement execute error #%s: %s', $errorInfo[0], $errorInfo[2]));
return false;
}
return $this->statement->rowCount();
} | php | public function execute($params = array())
{
$this->mergeParams($params);
$reconnect = $this->db->getOption('reconnect');
$reconnectRetries = $this->db->getOption('reconnect_retries', 3);
$reconnectDelayMS = $this->db->getOption('reconnect_delay_ms', 1000);
while (true) {
$e = null;
$errorCode = null;
$errorInfo = null;
$result = null;
$isReconnectError = false;
try {
$this->prepare();
foreach ($this->positionParams as $index => $value) {
$this->statement->bindValue($index + 1, $value);
}
$result = $this->statement->execute($this->params?:null);
} catch (\Exception $e) {
}
if ($result === false || !$e) {
$errorCode = $this->statement->errorCode();
$errorInfo = $this->statement->errorInfo();
}
$isReconnectError = Util::checkReconnectError($errorCode, $errorInfo, $e);
// reconnect
if ($reconnect && $isReconnectError && $reconnectRetries > 0) {
$reconnectRetries--;
$this->statement = null;
$this->db->close();
$reconnectDelayMS && usleep($reconnectDelayMS * 1000);
continue;
}
break;
}
if ($e) {
$this->db->logError(sprintf('Statement exception error #%s: %s', $e->getCode(), $e->getMessage()));
throw $e;
}
if ($result === false) {
$this->db->logError(sprintf('Statement execute error #%s: %s', $errorInfo[0], $errorInfo[2]));
return false;
}
return $this->statement->rowCount();
} | [
"public",
"function",
"execute",
"(",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"mergeParams",
"(",
"$",
"params",
")",
";",
"$",
"reconnect",
"=",
"$",
"this",
"->",
"db",
"->",
"getOption",
"(",
"'reconnect'",
")",
";",
... | Execute statement and return rows affected
@param array $params
@return int|boolean | [
"Execute",
"statement",
"and",
"return",
"rows",
"affected"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/QueryBuilder.php#L706-L761 | train |
maximebf/CacheCache | src/CacheCache/Cache.php | Cache.computeTTL | public function computeTTL($ttl = null)
{
$ttl = $ttl ?: $this->defaultTTL;
if ($ttl === null) {
return null;
}
return $ttl + rand(0, $this->ttlVariation);
} | php | public function computeTTL($ttl = null)
{
$ttl = $ttl ?: $this->defaultTTL;
if ($ttl === null) {
return null;
}
return $ttl + rand(0, $this->ttlVariation);
} | [
"public",
"function",
"computeTTL",
"(",
"$",
"ttl",
"=",
"null",
")",
"{",
"$",
"ttl",
"=",
"$",
"ttl",
"?",
":",
"$",
"this",
"->",
"defaultTTL",
";",
"if",
"(",
"$",
"ttl",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
... | Computes the final TTL taking into account the default ttl
and the ttl variation
@param int $ttl
@return int | [
"Computes",
"the",
"final",
"TTL",
"taking",
"into",
"account",
"the",
"default",
"ttl",
"and",
"the",
"ttl",
"variation"
] | eb64a3748aad4ddaf236ef4738a83267576a0f97 | https://github.com/maximebf/CacheCache/blob/eb64a3748aad4ddaf236ef4738a83267576a0f97/src/CacheCache/Cache.php#L135-L142 | train |
maximebf/CacheCache | src/CacheCache/Cache.php | Cache.capturePage | public function capturePage($id = null, $ttl = null, $exit = true)
{
if ($id === null) {
$id = md5(serialize($_SERVER['REQUEST_URI']) . serialize($_REQUEST));
}
if ($this->start($id)) {
if ($exit) {
exit;
}
return true;
}
$self = $this;
register_shutdown_function(function() use ($self, $ttl) { $self->end($ttl); });
return false;
} | php | public function capturePage($id = null, $ttl = null, $exit = true)
{
if ($id === null) {
$id = md5(serialize($_SERVER['REQUEST_URI']) . serialize($_REQUEST));
}
if ($this->start($id)) {
if ($exit) {
exit;
}
return true;
}
$self = $this;
register_shutdown_function(function() use ($self, $ttl) { $self->end($ttl); });
return false;
} | [
"public",
"function",
"capturePage",
"(",
"$",
"id",
"=",
"null",
",",
"$",
"ttl",
"=",
"null",
",",
"$",
"exit",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"id",
"===",
"null",
")",
"{",
"$",
"id",
"=",
"md5",
"(",
"serialize",
"(",
"$",
"_SERVER"... | Captures the whole output of the script until it ends.
If no $id is specified, it will be computed from a combination
of the $_SERVER['REQUEST_URI'] and the $_REQUEST variables.
If $id is found, the script will exit unless $exit is set to false.
@param string $id
@param int $ttl
@param bool $exit
@return bool | [
"Captures",
"the",
"whole",
"output",
"of",
"the",
"script",
"until",
"it",
"ends",
"."
] | eb64a3748aad4ddaf236ef4738a83267576a0f97 | https://github.com/maximebf/CacheCache/blob/eb64a3748aad4ddaf236ef4738a83267576a0f97/src/CacheCache/Cache.php#L433-L448 | train |
maximebf/CacheCache | src/CacheCache/Cache.php | Cache.pipeline | public function pipeline($callback = null)
{
$pipe = $this->createPipeline();
if ($callback === null) {
return $pipe;
}
call_user_func($callback, $pipe);
return $pipe->execute();
} | php | public function pipeline($callback = null)
{
$pipe = $this->createPipeline();
if ($callback === null) {
return $pipe;
}
call_user_func($callback, $pipe);
return $pipe->execute();
} | [
"public",
"function",
"pipeline",
"(",
"$",
"callback",
"=",
"null",
")",
"{",
"$",
"pipe",
"=",
"$",
"this",
"->",
"createPipeline",
"(",
")",
";",
"if",
"(",
"$",
"callback",
"===",
"null",
")",
"{",
"return",
"$",
"pipe",
";",
"}",
"call_user_func... | Creates a pipeline, executes the callback which should use
the provided pipeline object as its only argument without
executing it. The pipeline will the be executed and its
results will be returned.
If no callback is specified, the pipeline object will be
returned without being executed.
<code>
$results = $cache->pipeline(function($pipe) {
$pipe->set('id1', 'value1');
$pipe->set('id2', 'value2');
})
</code>
@param callback $callback
@return mixed | [
"Creates",
"a",
"pipeline",
"executes",
"the",
"callback",
"which",
"should",
"use",
"the",
"provided",
"pipeline",
"object",
"as",
"its",
"only",
"argument",
"without",
"executing",
"it",
".",
"The",
"pipeline",
"will",
"the",
"be",
"executed",
"and",
"its",
... | eb64a3748aad4ddaf236ef4738a83267576a0f97 | https://github.com/maximebf/CacheCache/blob/eb64a3748aad4ddaf236ef4738a83267576a0f97/src/CacheCache/Cache.php#L533-L541 | train |
excelwebzone/EWZSearchBundle | src/Lucene/Field.php | Field.unIndexed | public static function unIndexed($name, $value, $encoding = 'UTF-8')
{
return new self($name, $value, $encoding, true, false, false);
} | php | public static function unIndexed($name, $value, $encoding = 'UTF-8')
{
return new self($name, $value, $encoding, true, false, false);
} | [
"public",
"static",
"function",
"unIndexed",
"(",
"$",
"name",
",",
"$",
"value",
",",
"$",
"encoding",
"=",
"'UTF-8'",
")",
"{",
"return",
"new",
"self",
"(",
"$",
"name",
",",
"$",
"value",
",",
"$",
"encoding",
",",
"true",
",",
"false",
",",
"f... | Constructs a String-valued Field that is not tokenized nor indexed,
but is stored in the index, for return with hits.
@param string $name
@param string $value
@param string $encoding
@return \Zend\Search\Lucene\Document\Field | [
"Constructs",
"a",
"String",
"-",
"valued",
"Field",
"that",
"is",
"not",
"tokenized",
"nor",
"indexed",
"but",
"is",
"stored",
"in",
"the",
"index",
"for",
"return",
"with",
"hits",
"."
] | f1cdb2317c9fc31606d82d1cdee9654af936aff3 | https://github.com/excelwebzone/EWZSearchBundle/blob/f1cdb2317c9fc31606d82d1cdee9654af936aff3/src/Lucene/Field.php#L34-L37 | train |
jbouzekri/FileUploaderBundle | Service/Validator/AbstractImageValidator.php | AbstractImageValidator.validateConfig | protected function validateConfig($key, array $configuration, $isFloat = false)
{
if (!$isFloat && !ctype_digit((string) $configuration[$key])) {
throw new ValidationException(sprintf('"%s" is not a valid %s configuration', $configuration[$key], $key));
}
if ($isFloat && !is_numeric((string) $configuration[$key])) {
throw new ValidationException(sprintf('"%s" is not a valid %s configuration', $configuration[$key], $key));
}
return true;
} | php | protected function validateConfig($key, array $configuration, $isFloat = false)
{
if (!$isFloat && !ctype_digit((string) $configuration[$key])) {
throw new ValidationException(sprintf('"%s" is not a valid %s configuration', $configuration[$key], $key));
}
if ($isFloat && !is_numeric((string) $configuration[$key])) {
throw new ValidationException(sprintf('"%s" is not a valid %s configuration', $configuration[$key], $key));
}
return true;
} | [
"protected",
"function",
"validateConfig",
"(",
"$",
"key",
",",
"array",
"$",
"configuration",
",",
"$",
"isFloat",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"isFloat",
"&&",
"!",
"ctype_digit",
"(",
"(",
"string",
")",
"$",
"configuration",
"[",
"... | Validate configuration value
@param string $key
@param array $configuration
@param bool $isFloat
@return bool
@throws ValidationException | [
"Validate",
"configuration",
"value"
] | 592e7ed827eaa4e7f8f6f52947ca5e5a86835f6c | https://github.com/jbouzekri/FileUploaderBundle/blob/592e7ed827eaa4e7f8f6f52947ca5e5a86835f6c/Service/Validator/AbstractImageValidator.php#L126-L137 | train |
et-nik/gameap-daemon-client | src/GdaemonFiles.php | GdaemonFiles.metadata | public function metadata($path)
{
$writeBinn= new BinnList;
$writeBinn->addUint8(self::FSERV_FILEINFO);
$writeBinn->addStr($path);
$read = $this->writeAndReadSocket($writeBinn->serialize());
$readBinn = new BinnList;
$readBinn->binnOpen($read);
$results = $readBinn->unserialize();
if ($results[0] != self::FSERV_STATUS_OK) {
throw new RuntimeException('GDaemon metadata error:' . isset($results[1]) ? $results[1] : 'Unknown');
}
$fileInfo = $results[2];
return [
'name' => basename($fileInfo[0]),
'size' => $fileInfo[1],
'type' => ($fileInfo[2] == 1) ? 'dir' : 'file',
'mtime' => $fileInfo[3],
'atime' => $fileInfo[4],
'ctime' => $fileInfo[5],
'permissions' => $fileInfo[6],
'mimetype' => $fileInfo[7],
];
} | php | public function metadata($path)
{
$writeBinn= new BinnList;
$writeBinn->addUint8(self::FSERV_FILEINFO);
$writeBinn->addStr($path);
$read = $this->writeAndReadSocket($writeBinn->serialize());
$readBinn = new BinnList;
$readBinn->binnOpen($read);
$results = $readBinn->unserialize();
if ($results[0] != self::FSERV_STATUS_OK) {
throw new RuntimeException('GDaemon metadata error:' . isset($results[1]) ? $results[1] : 'Unknown');
}
$fileInfo = $results[2];
return [
'name' => basename($fileInfo[0]),
'size' => $fileInfo[1],
'type' => ($fileInfo[2] == 1) ? 'dir' : 'file',
'mtime' => $fileInfo[3],
'atime' => $fileInfo[4],
'ctime' => $fileInfo[5],
'permissions' => $fileInfo[6],
'mimetype' => $fileInfo[7],
];
} | [
"public",
"function",
"metadata",
"(",
"$",
"path",
")",
"{",
"$",
"writeBinn",
"=",
"new",
"BinnList",
";",
"$",
"writeBinn",
"->",
"addUint8",
"(",
"self",
"::",
"FSERV_FILEINFO",
")",
";",
"$",
"writeBinn",
"->",
"addStr",
"(",
"$",
"path",
")",
";"... | Get file metadata
@param string $path
@return array | [
"Get",
"file",
"metadata"
] | d054cbeb7ca7d6e06fb617608e282d7d0c6ae609 | https://github.com/et-nik/gameap-daemon-client/blob/d054cbeb7ca7d6e06fb617608e282d7d0c6ae609/src/GdaemonFiles.php#L395-L425 | train |
et-nik/gameap-daemon-client | src/GdaemonFiles.php | GdaemonFiles.chmod | public function chmod($mode, $path)
{
$writeBinn = new BinnList;
$writeBinn->addUint8(self::FSERV_CHMOD);
$writeBinn->addStr($path);
$writeBinn->addUint16($mode);
$read = $this->writeAndReadSocket($writeBinn->serialize());
$readBinn = new BinnList;
$readBinn->binnOpen($read);
$results = $readBinn->unserialize();
if ($results[0] != self::FSERV_STATUS_OK) {
throw new RuntimeException('Couldn\'t chmod: ' . isset($results[1]) ? $results[1] : 'Unknown');
}
return true;
} | php | public function chmod($mode, $path)
{
$writeBinn = new BinnList;
$writeBinn->addUint8(self::FSERV_CHMOD);
$writeBinn->addStr($path);
$writeBinn->addUint16($mode);
$read = $this->writeAndReadSocket($writeBinn->serialize());
$readBinn = new BinnList;
$readBinn->binnOpen($read);
$results = $readBinn->unserialize();
if ($results[0] != self::FSERV_STATUS_OK) {
throw new RuntimeException('Couldn\'t chmod: ' . isset($results[1]) ? $results[1] : 'Unknown');
}
return true;
} | [
"public",
"function",
"chmod",
"(",
"$",
"mode",
",",
"$",
"path",
")",
"{",
"$",
"writeBinn",
"=",
"new",
"BinnList",
";",
"$",
"writeBinn",
"->",
"addUint8",
"(",
"self",
"::",
"FSERV_CHMOD",
")",
";",
"$",
"writeBinn",
"->",
"addStr",
"(",
"$",
"p... | Change file mode
@param integer $mode
@param string $path
@return bool | [
"Change",
"file",
"mode"
] | d054cbeb7ca7d6e06fb617608e282d7d0c6ae609 | https://github.com/et-nik/gameap-daemon-client/blob/d054cbeb7ca7d6e06fb617608e282d7d0c6ae609/src/GdaemonFiles.php#L434-L453 | train |
nanbando/core | src/Core/Storage/Zipper.php | Zipper.zip | public function zip($directory, $fileName)
{
$path = sprintf('%s/%s/%s.zip', $this->localDirectory, $this->name, $fileName);
$this->filesystem->mkdir(dirname($path));
// FIXME find better place for this message
$this->output->writeln(PHP_EOL . 'Creating zip file (it may take a few minutes) ...');
$zip = $this->openZip($path);
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory));
foreach ($files as $filePath => $file) {
$relative = Path::makeRelative($filePath, $directory);
if (is_dir($filePath)) {
$zip->addEmptyDir($relative);
continue;
}
$zip->addFile($filePath, $relative);
}
$zip->close();
return $path;
} | php | public function zip($directory, $fileName)
{
$path = sprintf('%s/%s/%s.zip', $this->localDirectory, $this->name, $fileName);
$this->filesystem->mkdir(dirname($path));
// FIXME find better place for this message
$this->output->writeln(PHP_EOL . 'Creating zip file (it may take a few minutes) ...');
$zip = $this->openZip($path);
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory));
foreach ($files as $filePath => $file) {
$relative = Path::makeRelative($filePath, $directory);
if (is_dir($filePath)) {
$zip->addEmptyDir($relative);
continue;
}
$zip->addFile($filePath, $relative);
}
$zip->close();
return $path;
} | [
"public",
"function",
"zip",
"(",
"$",
"directory",
",",
"$",
"fileName",
")",
"{",
"$",
"path",
"=",
"sprintf",
"(",
"'%s/%s/%s.zip'",
",",
"$",
"this",
"->",
"localDirectory",
",",
"$",
"this",
"->",
"name",
",",
"$",
"fileName",
")",
";",
"$",
"th... | Creates a new zip from the given directory.
@param string $directory
@param string $fileName
@return string
@throws IOException | [
"Creates",
"a",
"new",
"zip",
"from",
"the",
"given",
"directory",
"."
] | 790f5c6339753bffafb50a846ccb6bab81f26877 | https://github.com/nanbando/core/blob/790f5c6339753bffafb50a846ccb6bab81f26877/src/Core/Storage/Zipper.php#L59-L84 | train |
nanbando/core | src/Core/Storage/Zipper.php | Zipper.openZip | private function openZip($path)
{
$zip = new \ZipArchive();
if (!$zip->open($path, \ZipArchive::CREATE)) {
throw new IOException('Cannot create zip file');
}
return $zip;
} | php | private function openZip($path)
{
$zip = new \ZipArchive();
if (!$zip->open($path, \ZipArchive::CREATE)) {
throw new IOException('Cannot create zip file');
}
return $zip;
} | [
"private",
"function",
"openZip",
"(",
"$",
"path",
")",
"{",
"$",
"zip",
"=",
"new",
"\\",
"ZipArchive",
"(",
")",
";",
"if",
"(",
"!",
"$",
"zip",
"->",
"open",
"(",
"$",
"path",
",",
"\\",
"ZipArchive",
"::",
"CREATE",
")",
")",
"{",
"throw",
... | Open zip from given path.
@param string $path
@return \ZipArchive | [
"Open",
"zip",
"from",
"given",
"path",
"."
] | 790f5c6339753bffafb50a846ccb6bab81f26877 | https://github.com/nanbando/core/blob/790f5c6339753bffafb50a846ccb6bab81f26877/src/Core/Storage/Zipper.php#L93-L101 | train |
dreamfactorysoftware/df-system | src/Resources/App.php | App.deleteHostedAppStorage | protected static function deleteHostedAppStorage($id, $storageServiceId, $storageFolder)
{
$app = AppModel::whereId($id)->first();
if (empty($app) && !empty($storageServiceId) && !empty($storageFolder)) {
/** @type FileServiceInterface $storageService */
$storageService = ServiceManager::getServiceById($storageServiceId);
if ($storageService->folderExists($storageFolder)) {
$storageService->deleteFolder($storageFolder, true);
}
}
} | php | protected static function deleteHostedAppStorage($id, $storageServiceId, $storageFolder)
{
$app = AppModel::whereId($id)->first();
if (empty($app) && !empty($storageServiceId) && !empty($storageFolder)) {
/** @type FileServiceInterface $storageService */
$storageService = ServiceManager::getServiceById($storageServiceId);
if ($storageService->folderExists($storageFolder)) {
$storageService->deleteFolder($storageFolder, true);
}
}
} | [
"protected",
"static",
"function",
"deleteHostedAppStorage",
"(",
"$",
"id",
",",
"$",
"storageServiceId",
",",
"$",
"storageFolder",
")",
"{",
"$",
"app",
"=",
"AppModel",
"::",
"whereId",
"(",
"$",
"id",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
... | Deletes hosted app files from storage.
@param $id
@param $storageServiceId
@param $storageFolder
@throws \DreamFactory\Core\Exceptions\NotFoundException | [
"Deletes",
"hosted",
"app",
"files",
"from",
"storage",
"."
] | 18f91d7630d3cdaef85611c5b668c0521130593e | https://github.com/dreamfactorysoftware/df-system/blob/18f91d7630d3cdaef85611c5b668c0521130593e/src/Resources/App.php#L174-L186 | train |
nanbando/core | src/Core/Plugin/DirectoryPlugin.php | DirectoryPlugin.getHash | private function getHash($stream, $algorithm = 'sha256')
{
$hash = hash_init($algorithm);
hash_update_stream($hash, $stream);
return hash_final($hash);
} | php | private function getHash($stream, $algorithm = 'sha256')
{
$hash = hash_init($algorithm);
hash_update_stream($hash, $stream);
return hash_final($hash);
} | [
"private",
"function",
"getHash",
"(",
"$",
"stream",
",",
"$",
"algorithm",
"=",
"'sha256'",
")",
"{",
"$",
"hash",
"=",
"hash_init",
"(",
"$",
"algorithm",
")",
";",
"hash_update_stream",
"(",
"$",
"hash",
",",
"$",
"stream",
")",
";",
"return",
"has... | Returns hash for resource.
@param resource $stream
@param string $algorithm
@return string | [
"Returns",
"hash",
"for",
"resource",
"."
] | 790f5c6339753bffafb50a846ccb6bab81f26877 | https://github.com/nanbando/core/blob/790f5c6339753bffafb50a846ccb6bab81f26877/src/Core/Plugin/DirectoryPlugin.php#L151-L157 | train |
arkphp/database | src/Model.php | Model.getRaw | public function getRaw($key = null){
if(null === $key){
return $this->_data;
}
else{
return isset($this->_data[$key])?$this->_data[$key]:null;
}
} | php | public function getRaw($key = null){
if(null === $key){
return $this->_data;
}
else{
return isset($this->_data[$key])?$this->_data[$key]:null;
}
} | [
"public",
"function",
"getRaw",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"key",
")",
"{",
"return",
"$",
"this",
"->",
"_data",
";",
"}",
"else",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"_data",
"[",
"$",
"... | Get raw data
@param string $key
@return mixed | [
"Get",
"raw",
"data"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/Model.php#L180-L187 | train |
arkphp/database | src/Model.php | Model.getWithRelation | public function getWithRelation($name){
$relations = $this->getRelations();
if(isset($relations[$name])){
$relation = $relations[$name];
if($relation['relation'] === 'OTO'){
return $this->getOneToOne($relation['target'], isset($relation['key'])?$relation['key']:null, isset($relation['target_key'])?$relation['target_key']:null);
}
elseif($relation['relation'] == 'OTM'){
return $this->getOneToMany($relation['target'], isset($relation['key'])?$relation['key']:null, isset($relation['target_key'])?$relation['target_key']:null);
}
elseif($relation['relation'] == 'MTO'){
return $this->getManyToOne($relation['target'], isset($relation['key'])?$relation['key']:null, isset($relation['target_key'])?$relation['target_key']:null);
}
elseif($relation['relation'] == 'MTM'){
return $this->getManyToMany($relation['target'], $relation['through'], isset($relation['key'])?$relation['key']:null, isset($relation['target_key'])?$relation['target_key']:null);
}
else{
throw new Exception('Invalid relation "'.$relation['relation'].'"');
}
}
else{
return false;
}
} | php | public function getWithRelation($name){
$relations = $this->getRelations();
if(isset($relations[$name])){
$relation = $relations[$name];
if($relation['relation'] === 'OTO'){
return $this->getOneToOne($relation['target'], isset($relation['key'])?$relation['key']:null, isset($relation['target_key'])?$relation['target_key']:null);
}
elseif($relation['relation'] == 'OTM'){
return $this->getOneToMany($relation['target'], isset($relation['key'])?$relation['key']:null, isset($relation['target_key'])?$relation['target_key']:null);
}
elseif($relation['relation'] == 'MTO'){
return $this->getManyToOne($relation['target'], isset($relation['key'])?$relation['key']:null, isset($relation['target_key'])?$relation['target_key']:null);
}
elseif($relation['relation'] == 'MTM'){
return $this->getManyToMany($relation['target'], $relation['through'], isset($relation['key'])?$relation['key']:null, isset($relation['target_key'])?$relation['target_key']:null);
}
else{
throw new Exception('Invalid relation "'.$relation['relation'].'"');
}
}
else{
return false;
}
} | [
"public",
"function",
"getWithRelation",
"(",
"$",
"name",
")",
"{",
"$",
"relations",
"=",
"$",
"this",
"->",
"getRelations",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"relations",
"[",
"$",
"name",
"]",
")",
")",
"{",
"$",
"relation",
"=",
"$"... | Get a field with relation
@param string $name
@return mixed | [
"Get",
"a",
"field",
"with",
"relation"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/Model.php#L230-L253 | train |
arkphp/database | src/Model.php | Model.getManyToMany | public function getManyToMany($target, $through, $key = null, $target_key = null){
$factory = $this->_db->factory($target);
if(null === $key){
$key = $this->getPK();
}
if(null === $target_key){
$target_key = $factory->getPK();
}
$through = $this->parseThrough($through);
if(!$through[1]){
$through[1] = $key;
}
if(!$through[2]){
$through[2] = $target_key;
}
$rows = $this->_db->builder()
->select('t.*')
->from($factory->getTable().' t')
->leftJoin($through[0].' m', 'm.'.$through[2].'=t.'.$target_key)
->where('m.'.$through[1].'=:value', array(
':value' => $this->get($key)
))
->queryAll();
if(false === $rows){
return false;
}
return $factory->mapModels($rows);
} | php | public function getManyToMany($target, $through, $key = null, $target_key = null){
$factory = $this->_db->factory($target);
if(null === $key){
$key = $this->getPK();
}
if(null === $target_key){
$target_key = $factory->getPK();
}
$through = $this->parseThrough($through);
if(!$through[1]){
$through[1] = $key;
}
if(!$through[2]){
$through[2] = $target_key;
}
$rows = $this->_db->builder()
->select('t.*')
->from($factory->getTable().' t')
->leftJoin($through[0].' m', 'm.'.$through[2].'=t.'.$target_key)
->where('m.'.$through[1].'=:value', array(
':value' => $this->get($key)
))
->queryAll();
if(false === $rows){
return false;
}
return $factory->mapModels($rows);
} | [
"public",
"function",
"getManyToMany",
"(",
"$",
"target",
",",
"$",
"through",
",",
"$",
"key",
"=",
"null",
",",
"$",
"target_key",
"=",
"null",
")",
"{",
"$",
"factory",
"=",
"$",
"this",
"->",
"_db",
"->",
"factory",
"(",
"$",
"target",
")",
";... | Many to many
@param string $target
@param string $through
@param string $key
@param string $target_key
@return array | [
"Many",
"to",
"many"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/Model.php#L324-L356 | train |
arkphp/database | src/Model.php | Model.save | public function save(){
if($this->beforeSave()){
if($this->isNew()){
$data = $this->_dirty;
//insert
if(false !== $rst = $this->_db->builder()->insert($this->getTable(), $data))
{
if(is_string($this->getPK()) && $id = $this->_db->lastInsertId()){
$data[$this->getPK()] = $id;
}
$this->_data = $data;
$this->_dirty = array();
$this->_isNew = false;
$this->afterSave();
return $rst;
}
}
else{
if($this->isDirty()){
//update
$pkConditions = $this->buildPKConditions();
if(false !== $rst = $this->_db->builder()->update($this->getTable(), $this->_dirty, $pkConditions[0], $pkConditions[1])){
$this->_data = array_merge($this->_data, $this->_dirty);
$this->_dirty = array();
$this->afterSave();
return $rst;
}
}
}
}
return false;
} | php | public function save(){
if($this->beforeSave()){
if($this->isNew()){
$data = $this->_dirty;
//insert
if(false !== $rst = $this->_db->builder()->insert($this->getTable(), $data))
{
if(is_string($this->getPK()) && $id = $this->_db->lastInsertId()){
$data[$this->getPK()] = $id;
}
$this->_data = $data;
$this->_dirty = array();
$this->_isNew = false;
$this->afterSave();
return $rst;
}
}
else{
if($this->isDirty()){
//update
$pkConditions = $this->buildPKConditions();
if(false !== $rst = $this->_db->builder()->update($this->getTable(), $this->_dirty, $pkConditions[0], $pkConditions[1])){
$this->_data = array_merge($this->_data, $this->_dirty);
$this->_dirty = array();
$this->afterSave();
return $rst;
}
}
}
}
return false;
} | [
"public",
"function",
"save",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"beforeSave",
"(",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isNew",
"(",
")",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"_dirty",
";",
"//insert",
"if",
"(",
... | Save modified data to db
@return int|boolean | [
"Save",
"modified",
"data",
"to",
"db"
] | 5b332d0b0b683bb4211fa12687e7c89a3ab158df | https://github.com/arkphp/database/blob/5b332d0b0b683bb4211fa12687e7c89a3ab158df/src/Model.php#L422-L455 | train |
canax/textfilter | src/TextFilter/TTextUtilities.php | TTextUtilities.createToc | public function createToc($text, $start = 2, $stop = 4)
{
$level = "$start-$stop";
$pattern = "#<(h[$level])([^>]*)>(.*)</h[$level]>#";
preg_match_all($pattern, $text, $matches, PREG_SET_ORDER);
$toc = [];
foreach ($matches as $val) {
preg_match("#id=['\"]([^>\"']+)#", $val[2], $id);
$id = isset($id[1]) ? $id[1] : null;
$toc[] = [
"level" => isset($val[1])
? $val[1]
: null,
"title" => isset($val[3])
? ltrim(strip_tags($val[3]), "#")
: null,
"id" => $id,
];
}
return $toc;
} | php | public function createToc($text, $start = 2, $stop = 4)
{
$level = "$start-$stop";
$pattern = "#<(h[$level])([^>]*)>(.*)</h[$level]>#";
preg_match_all($pattern, $text, $matches, PREG_SET_ORDER);
$toc = [];
foreach ($matches as $val) {
preg_match("#id=['\"]([^>\"']+)#", $val[2], $id);
$id = isset($id[1]) ? $id[1] : null;
$toc[] = [
"level" => isset($val[1])
? $val[1]
: null,
"title" => isset($val[3])
? ltrim(strip_tags($val[3]), "#")
: null,
"id" => $id,
];
}
return $toc;
} | [
"public",
"function",
"createToc",
"(",
"$",
"text",
",",
"$",
"start",
"=",
"2",
",",
"$",
"stop",
"=",
"4",
")",
"{",
"$",
"level",
"=",
"\"$start-$stop\"",
";",
"$",
"pattern",
"=",
"\"#<(h[$level])([^>]*)>(.*)</h[$level]>#\"",
";",
"preg_match_all",
"(",... | Create a TOC of HTML headings from and to a certain level.
@param string $text with content
@param integer $start level of headings to use for toc.
@param integer $stop level of headings to use for toc.
@return array with entries to generate a TOC. | [
"Create",
"a",
"TOC",
"of",
"HTML",
"headings",
"from",
"and",
"to",
"a",
"certain",
"level",
"."
] | a90177cd404b093541222fd0d6cf71907ac2ce25 | https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TTextUtilities.php#L103-L125 | train |
canax/textfilter | src/TextFilter/TTextUtilities.php | TTextUtilities.addBaseurlToRelativeLinks | public function addBaseurlToRelativeLinks($text, $baseurl, $callback)
{
$pattern = "#<a(.+?)href=\"([^\"]*)\"([.^>]*)>#";
return preg_replace_callback(
$pattern,
function ($matches) use ($baseurl, $callback) {
$url = $callback($matches[2], $baseurl);
return "<a${matches[1]}href=\"$url\"${matches[3]}>";
},
$text
);
} | php | public function addBaseurlToRelativeLinks($text, $baseurl, $callback)
{
$pattern = "#<a(.+?)href=\"([^\"]*)\"([.^>]*)>#";
return preg_replace_callback(
$pattern,
function ($matches) use ($baseurl, $callback) {
$url = $callback($matches[2], $baseurl);
return "<a${matches[1]}href=\"$url\"${matches[3]}>";
},
$text
);
} | [
"public",
"function",
"addBaseurlToRelativeLinks",
"(",
"$",
"text",
",",
"$",
"baseurl",
",",
"$",
"callback",
")",
"{",
"$",
"pattern",
"=",
"\"#<a(.+?)href=\\\"([^\\\"]*)\\\"([.^>]*)>#\"",
";",
"return",
"preg_replace_callback",
"(",
"$",
"pattern",
",",
"functio... | Add baseurl to all relative links.
@param string $text with content.
@param string $baseurl as string to prepend relative link.
@param callable $callback Use to create url from route.
@return string with modified text. | [
"Add",
"baseurl",
"to",
"all",
"relative",
"links",
"."
] | a90177cd404b093541222fd0d6cf71907ac2ce25 | https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TTextUtilities.php#L161-L173 | train |
canax/textfilter | src/TextFilter/TTextUtilities.php | TTextUtilities.addBaseurlToImageSource | public function addBaseurlToImageSource($text, $baseurl, $callback)
{
$pattern = "#<img(.+?)src=\"([^\"]*)\"(.*?)>#";
return preg_replace_callback(
$pattern,
function ($matches) use ($baseurl, $callback) {
$url = $callback($matches[2], $baseurl);
return "<img${matches[1]}src=\"$url\"${matches[3]}>";
},
$text
);
} | php | public function addBaseurlToImageSource($text, $baseurl, $callback)
{
$pattern = "#<img(.+?)src=\"([^\"]*)\"(.*?)>#";
return preg_replace_callback(
$pattern,
function ($matches) use ($baseurl, $callback) {
$url = $callback($matches[2], $baseurl);
return "<img${matches[1]}src=\"$url\"${matches[3]}>";
},
$text
);
} | [
"public",
"function",
"addBaseurlToImageSource",
"(",
"$",
"text",
",",
"$",
"baseurl",
",",
"$",
"callback",
")",
"{",
"$",
"pattern",
"=",
"\"#<img(.+?)src=\\\"([^\\\"]*)\\\"(.*?)>#\"",
";",
"return",
"preg_replace_callback",
"(",
"$",
"pattern",
",",
"function",
... | Add baseurl to all relative links in image source.
@param string $text with content.
@param string $baseurl as string to prepend relative link.
@param callable $callback Use to create url from route.
@return string with modified text. | [
"Add",
"baseurl",
"to",
"all",
"relative",
"links",
"in",
"image",
"source",
"."
] | a90177cd404b093541222fd0d6cf71907ac2ce25 | https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TTextUtilities.php#L186-L198 | train |
canax/textfilter | src/TextFilter/TTextUtilities.php | TTextUtilities.addRevisionHistory | public function addRevisionHistory($text, $revision, $start, $end, $class, $source = null)
{
$text = $text . $start;
$text .= "<ul class=\"$class\">\n";
foreach ($revision as $date => $info) {
$text .= "<li>$date: $info</li>\n";
}
$text .= "</ul>\n";
if ($source) {
$text .= "<p><a class=\"$class\" href=\"$source\">"
. t("Document source")
. "</a>.</p>\n";
}
$text .= $end;
return $text;
} | php | public function addRevisionHistory($text, $revision, $start, $end, $class, $source = null)
{
$text = $text . $start;
$text .= "<ul class=\"$class\">\n";
foreach ($revision as $date => $info) {
$text .= "<li>$date: $info</li>\n";
}
$text .= "</ul>\n";
if ($source) {
$text .= "<p><a class=\"$class\" href=\"$source\">"
. t("Document source")
. "</a>.</p>\n";
}
$text .= $end;
return $text;
} | [
"public",
"function",
"addRevisionHistory",
"(",
"$",
"text",
",",
"$",
"revision",
",",
"$",
"start",
",",
"$",
"end",
",",
"$",
"class",
",",
"$",
"source",
"=",
"null",
")",
"{",
"$",
"text",
"=",
"$",
"text",
".",
"$",
"start",
";",
"$",
"tex... | Generate revision history and add to the end of content.
@param string $text with content.
@param array $revision with all revisions.
@param string $start start wrap with this.
@param string $end end wrap with this.
@param string $class to add to ul element.
@param string $source optional url to document source.
@return string with text and optionally added revision history. | [
"Generate",
"revision",
"history",
"and",
"add",
"to",
"the",
"end",
"of",
"content",
"."
] | a90177cd404b093541222fd0d6cf71907ac2ce25 | https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TTextUtilities.php#L214-L235 | train |
protobuf-php/google-protobuf-proto | src/google/protobuf/compiler/CodeGeneratorRequest.php | CodeGeneratorRequest.addFileToGenerate | public function addFileToGenerate($value)
{
if ($this->file_to_generate === null) {
$this->file_to_generate = new \Protobuf\ScalarCollection();
}
$this->file_to_generate->add($value);
} | php | public function addFileToGenerate($value)
{
if ($this->file_to_generate === null) {
$this->file_to_generate = new \Protobuf\ScalarCollection();
}
$this->file_to_generate->add($value);
} | [
"public",
"function",
"addFileToGenerate",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"file_to_generate",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"file_to_generate",
"=",
"new",
"\\",
"Protobuf",
"\\",
"ScalarCollection",
"(",
")",
";",... | Add a new element to 'file_to_generate'
@param string $value | [
"Add",
"a",
"new",
"element",
"to",
"file_to_generate"
] | da1827b4a23fccd4eb998a8d4bcd972f2330bc29 | https://github.com/protobuf-php/google-protobuf-proto/blob/da1827b4a23fccd4eb998a8d4bcd972f2330bc29/src/google/protobuf/compiler/CodeGeneratorRequest.php#L83-L90 | train |
protobuf-php/google-protobuf-proto | src/google/protobuf/compiler/CodeGeneratorRequest.php | CodeGeneratorRequest.addProtoFile | public function addProtoFile(\google\protobuf\FileDescriptorProto $value)
{
if ($this->proto_file === null) {
$this->proto_file = new \Protobuf\MessageCollection();
}
$this->proto_file->add($value);
} | php | public function addProtoFile(\google\protobuf\FileDescriptorProto $value)
{
if ($this->proto_file === null) {
$this->proto_file = new \Protobuf\MessageCollection();
}
$this->proto_file->add($value);
} | [
"public",
"function",
"addProtoFile",
"(",
"\\",
"google",
"\\",
"protobuf",
"\\",
"FileDescriptorProto",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"proto_file",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"proto_file",
"=",
"new",
"\\",
"Pro... | Add a new element to 'proto_file'
@param \google\protobuf\FileDescriptorProto $value | [
"Add",
"a",
"new",
"element",
"to",
"proto_file"
] | da1827b4a23fccd4eb998a8d4bcd972f2330bc29 | https://github.com/protobuf-php/google-protobuf-proto/blob/da1827b4a23fccd4eb998a8d4bcd972f2330bc29/src/google/protobuf/compiler/CodeGeneratorRequest.php#L157-L164 | train |
dreamfactorysoftware/df-system | src/Resources/UserPasswordResource.php | UserPasswordResource.handlePOST | protected function handlePOST()
{
$oldPassword = $this->getPayloadData('old_password');
$newPassword = $this->getPayloadData('new_password');
$login = $this->request->getParameterAsBool('login');
if (!empty($oldPassword) && Session::isAuthenticated()) {
$user = Session::user();
return static::changePassword($user, $oldPassword, $newPassword, $login);
}
$email = $this->getPayloadData('email');
$username = $this->getPayloadData('username');
$code = $this->getPayloadData('code');
$answer = $this->getPayloadData('security_answer');
$loginAttribute = strtolower(config('df.login_attribute', 'email'));
if ($this->request->getParameterAsBool('reset')) {
if ($loginAttribute === 'username') {
return $this->passwordResetWithUsername($username);
}
return $this->passwordReset($email);
}
if (!empty($code)) {
if ($loginAttribute === 'username') {
return static::changePasswordByCodeWithUsername($username, $code, $newPassword, $login);
}
return static::changePasswordByCode($email, $code, $newPassword, $login);
}
if (!empty($answer)) {
if ($loginAttribute === 'username') {
return static::changePasswordBySecurityAnswerWithUsername($username, $answer, $newPassword, $login);
}
return static::changePasswordBySecurityAnswer($email, $answer, $newPassword, $login);
}
throw new BadRequestException('Not enough information provided to change password.');
} | php | protected function handlePOST()
{
$oldPassword = $this->getPayloadData('old_password');
$newPassword = $this->getPayloadData('new_password');
$login = $this->request->getParameterAsBool('login');
if (!empty($oldPassword) && Session::isAuthenticated()) {
$user = Session::user();
return static::changePassword($user, $oldPassword, $newPassword, $login);
}
$email = $this->getPayloadData('email');
$username = $this->getPayloadData('username');
$code = $this->getPayloadData('code');
$answer = $this->getPayloadData('security_answer');
$loginAttribute = strtolower(config('df.login_attribute', 'email'));
if ($this->request->getParameterAsBool('reset')) {
if ($loginAttribute === 'username') {
return $this->passwordResetWithUsername($username);
}
return $this->passwordReset($email);
}
if (!empty($code)) {
if ($loginAttribute === 'username') {
return static::changePasswordByCodeWithUsername($username, $code, $newPassword, $login);
}
return static::changePasswordByCode($email, $code, $newPassword, $login);
}
if (!empty($answer)) {
if ($loginAttribute === 'username') {
return static::changePasswordBySecurityAnswerWithUsername($username, $answer, $newPassword, $login);
}
return static::changePasswordBySecurityAnswer($email, $answer, $newPassword, $login);
}
throw new BadRequestException('Not enough information provided to change password.');
} | [
"protected",
"function",
"handlePOST",
"(",
")",
"{",
"$",
"oldPassword",
"=",
"$",
"this",
"->",
"getPayloadData",
"(",
"'old_password'",
")",
";",
"$",
"newPassword",
"=",
"$",
"this",
"->",
"getPayloadData",
"(",
"'new_password'",
")",
";",
"$",
"login",
... | Resets user password.
@return array|bool
@throws BadRequestException
@throws \Exception | [
"Resets",
"user",
"password",
"."
] | 18f91d7630d3cdaef85611c5b668c0521130593e | https://github.com/dreamfactorysoftware/df-system/blob/18f91d7630d3cdaef85611c5b668c0521130593e/src/Resources/UserPasswordResource.php#L51-L94 | train |
dreamfactorysoftware/df-system | src/Resources/UserPasswordResource.php | UserPasswordResource.changePasswordByCode | public static function changePasswordByCode($email, $code, $newPassword, $login = true)
{
if (empty($email)) {
throw new BadRequestException("Missing required email for password reset confirmation.");
}
if (empty($newPassword)) {
throw new BadRequestException("Missing new password for reset.");
}
if (empty($code) || 'y' == $code) {
throw new BadRequestException("Invalid confirmation code.");
}
/** @var User $user */
$user = User::whereEmail($email)->whereConfirmCode($code)->first();
if (null === $user) {
// bad code
throw new NotFoundException("The supplied email and/or confirmation code were not found in the system.");
} elseif ($user->isConfirmationExpired()) {
throw new BadRequestException("Confirmation code expired.");
}
static::isAllowed($user);
try {
$user->confirm_code = 'y';
$user->password = $newPassword;
$user->save();
} catch (\Exception $ex) {
throw new InternalServerErrorException("Error processing password reset.\n{$ex->getMessage()}");
}
if ($login) {
static::userLogin($email, $newPassword);
return ['success' => true, 'session_token' => Session::getSessionToken()];
}
return ['success' => true];
} | php | public static function changePasswordByCode($email, $code, $newPassword, $login = true)
{
if (empty($email)) {
throw new BadRequestException("Missing required email for password reset confirmation.");
}
if (empty($newPassword)) {
throw new BadRequestException("Missing new password for reset.");
}
if (empty($code) || 'y' == $code) {
throw new BadRequestException("Invalid confirmation code.");
}
/** @var User $user */
$user = User::whereEmail($email)->whereConfirmCode($code)->first();
if (null === $user) {
// bad code
throw new NotFoundException("The supplied email and/or confirmation code were not found in the system.");
} elseif ($user->isConfirmationExpired()) {
throw new BadRequestException("Confirmation code expired.");
}
static::isAllowed($user);
try {
$user->confirm_code = 'y';
$user->password = $newPassword;
$user->save();
} catch (\Exception $ex) {
throw new InternalServerErrorException("Error processing password reset.\n{$ex->getMessage()}");
}
if ($login) {
static::userLogin($email, $newPassword);
return ['success' => true, 'session_token' => Session::getSessionToken()];
}
return ['success' => true];
} | [
"public",
"static",
"function",
"changePasswordByCode",
"(",
"$",
"email",
",",
"$",
"code",
",",
"$",
"newPassword",
",",
"$",
"login",
"=",
"true",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"email",
")",
")",
"{",
"throw",
"new",
"BadRequestException",
... | Changes password by confirmation code.
@param $email
@param $code
@param $newPassword
@param bool $login
@return array
@throws BadRequestException
@throws InternalServerErrorException
@throws NotFoundException | [
"Changes",
"password",
"by",
"confirmation",
"code",
"."
] | 18f91d7630d3cdaef85611c5b668c0521130593e | https://github.com/dreamfactorysoftware/df-system/blob/18f91d7630d3cdaef85611c5b668c0521130593e/src/Resources/UserPasswordResource.php#L275-L316 | train |
dreamfactorysoftware/df-system | src/Resources/UserPasswordResource.php | UserPasswordResource.changePasswordBySecurityAnswer | protected static function changePasswordBySecurityAnswer($email, $answer, $newPassword, $login = true)
{
if (empty($email)) {
throw new BadRequestException("Missing required email for password reset confirmation.");
}
if (empty($newPassword)) {
throw new BadRequestException("Missing new password for reset.");
}
if (empty($answer)) {
throw new BadRequestException("Missing security answer.");
}
/** @var User $user */
$user = User::whereEmail($email)->first();
if (null === $user) {
// bad code
throw new NotFoundException("The supplied email and confirmation code were not found in the system.");
}
static::isAllowed($user);
try {
// validate answer
$isValid = \Hash::check($answer, $user->security_answer);
} catch (\Exception $ex) {
throw new InternalServerErrorException("Error validating security answer.\n{$ex->getMessage()}");
}
if (!$isValid) {
throw new BadRequestException("The answer supplied does not match.");
}
try {
$user->password = $newPassword;
$user->save();
} catch (\Exception $ex) {
throw new InternalServerErrorException("Error processing password change.\n{$ex->getMessage()}");
}
if ($login) {
static::userLogin($email, $newPassword);
return ['success' => true, 'session_token' => Session::getSessionToken()];
}
return ['success' => true];
} | php | protected static function changePasswordBySecurityAnswer($email, $answer, $newPassword, $login = true)
{
if (empty($email)) {
throw new BadRequestException("Missing required email for password reset confirmation.");
}
if (empty($newPassword)) {
throw new BadRequestException("Missing new password for reset.");
}
if (empty($answer)) {
throw new BadRequestException("Missing security answer.");
}
/** @var User $user */
$user = User::whereEmail($email)->first();
if (null === $user) {
// bad code
throw new NotFoundException("The supplied email and confirmation code were not found in the system.");
}
static::isAllowed($user);
try {
// validate answer
$isValid = \Hash::check($answer, $user->security_answer);
} catch (\Exception $ex) {
throw new InternalServerErrorException("Error validating security answer.\n{$ex->getMessage()}");
}
if (!$isValid) {
throw new BadRequestException("The answer supplied does not match.");
}
try {
$user->password = $newPassword;
$user->save();
} catch (\Exception $ex) {
throw new InternalServerErrorException("Error processing password change.\n{$ex->getMessage()}");
}
if ($login) {
static::userLogin($email, $newPassword);
return ['success' => true, 'session_token' => Session::getSessionToken()];
}
return ['success' => true];
} | [
"protected",
"static",
"function",
"changePasswordBySecurityAnswer",
"(",
"$",
"email",
",",
"$",
"answer",
",",
"$",
"newPassword",
",",
"$",
"login",
"=",
"true",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"email",
")",
")",
"{",
"throw",
"new",
"BadReque... | Changes password by security answer.
@param $email
@param $answer
@param $newPassword
@param bool $login
@return array
@throws BadRequestException
@throws InternalServerErrorException
@throws NotFoundException | [
"Changes",
"password",
"by",
"security",
"answer",
"."
] | 18f91d7630d3cdaef85611c5b668c0521130593e | https://github.com/dreamfactorysoftware/df-system/blob/18f91d7630d3cdaef85611c5b668c0521130593e/src/Resources/UserPasswordResource.php#L331-L380 | train |
dreamfactorysoftware/df-system | src/Resources/UserPasswordResource.php | UserPasswordResource.sendPasswordResetEmail | protected function sendPasswordResetEmail(User $user)
{
$email = $user->email;
/** @var \DreamFactory\Core\User\Services\User $parent */
$parent = $this->getService();
if (!empty($parent->passwordEmailServiceId)) {
try {
/** @var EmailServiceInterface $emailService */
$emailService = ServiceManager::getServiceById($parent->passwordEmailServiceId);
if (empty($emailService)) {
throw new ServiceUnavailableException("Bad email service identifier.");
}
$data = [];
if (!empty($parent->passwordEmailTemplateId)) {
// find template in system db
$template = EmailTemplate::whereId($parent->passwordEmailTemplateId)->first();
if (empty($template)) {
throw new NotFoundException("Email Template id '{$parent->passwordEmailTemplateId}' not found");
}
$data = $template->toArray();
}
if (empty($data) || !is_array($data)) {
throw new ServiceUnavailableException("No data found in default email template for password reset.");
}
$data['to'] = $email;
$data['content_header'] = 'Password Reset';
$data['first_name'] = $user->first_name;
$data['last_name'] = $user->last_name;
$data['name'] = $user->name;
$data['phone'] = $user->phone;
$data['email'] = $user->email;
$data['link'] = url(\Config::get('df.confirm_reset_url')) .
'?code=' . $user->confirm_code .
'&email=' . $email .
'&username=' . $user->username .
'&admin=' . $user->is_sys_admin;
$data['confirm_code'] = $user->confirm_code;
$bodyHtml = array_get($data, 'body_html');
$bodyText = array_get($data, 'body_text');
if (empty($bodyText) && !empty($bodyHtml)) {
$bodyText = strip_tags($bodyHtml);
$bodyText = preg_replace('/ +/', ' ', $bodyText);
}
$emailService->sendEmail($data, $bodyText, $bodyHtml);
return true;
} catch (\Exception $ex) {
throw new InternalServerErrorException("Error processing password reset.\n{$ex->getMessage()}");
}
}
return false;
} | php | protected function sendPasswordResetEmail(User $user)
{
$email = $user->email;
/** @var \DreamFactory\Core\User\Services\User $parent */
$parent = $this->getService();
if (!empty($parent->passwordEmailServiceId)) {
try {
/** @var EmailServiceInterface $emailService */
$emailService = ServiceManager::getServiceById($parent->passwordEmailServiceId);
if (empty($emailService)) {
throw new ServiceUnavailableException("Bad email service identifier.");
}
$data = [];
if (!empty($parent->passwordEmailTemplateId)) {
// find template in system db
$template = EmailTemplate::whereId($parent->passwordEmailTemplateId)->first();
if (empty($template)) {
throw new NotFoundException("Email Template id '{$parent->passwordEmailTemplateId}' not found");
}
$data = $template->toArray();
}
if (empty($data) || !is_array($data)) {
throw new ServiceUnavailableException("No data found in default email template for password reset.");
}
$data['to'] = $email;
$data['content_header'] = 'Password Reset';
$data['first_name'] = $user->first_name;
$data['last_name'] = $user->last_name;
$data['name'] = $user->name;
$data['phone'] = $user->phone;
$data['email'] = $user->email;
$data['link'] = url(\Config::get('df.confirm_reset_url')) .
'?code=' . $user->confirm_code .
'&email=' . $email .
'&username=' . $user->username .
'&admin=' . $user->is_sys_admin;
$data['confirm_code'] = $user->confirm_code;
$bodyHtml = array_get($data, 'body_html');
$bodyText = array_get($data, 'body_text');
if (empty($bodyText) && !empty($bodyHtml)) {
$bodyText = strip_tags($bodyHtml);
$bodyText = preg_replace('/ +/', ' ', $bodyText);
}
$emailService->sendEmail($data, $bodyText, $bodyHtml);
return true;
} catch (\Exception $ex) {
throw new InternalServerErrorException("Error processing password reset.\n{$ex->getMessage()}");
}
}
return false;
} | [
"protected",
"function",
"sendPasswordResetEmail",
"(",
"User",
"$",
"user",
")",
"{",
"$",
"email",
"=",
"$",
"user",
"->",
"email",
";",
"/** @var \\DreamFactory\\Core\\User\\Services\\User $parent */",
"$",
"parent",
"=",
"$",
"this",
"->",
"getService",
"(",
"... | Sends the user an email with password reset link.
@param User $user
@return bool
@throws InternalServerErrorException | [
"Sends",
"the",
"user",
"an",
"email",
"with",
"password",
"reset",
"link",
"."
] | 18f91d7630d3cdaef85611c5b668c0521130593e | https://github.com/dreamfactorysoftware/df-system/blob/18f91d7630d3cdaef85611c5b668c0521130593e/src/Resources/UserPasswordResource.php#L411-L473 | train |
graze/console-diff-renderer | src/Terminal/ANSI.php | ANSI.filter | public function filter($string, $replacement = '')
{
if ($replacement !== '') {
return preg_replace_callback(static::REGEX_ANSI, function ($matches) use ($replacement) {
return str_repeat($replacement, mb_strlen($matches[0]));
}, $string);
}
return preg_replace(static::REGEX_ANSI, $replacement, $string);
} | php | public function filter($string, $replacement = '')
{
if ($replacement !== '') {
return preg_replace_callback(static::REGEX_ANSI, function ($matches) use ($replacement) {
return str_repeat($replacement, mb_strlen($matches[0]));
}, $string);
}
return preg_replace(static::REGEX_ANSI, $replacement, $string);
} | [
"public",
"function",
"filter",
"(",
"$",
"string",
",",
"$",
"replacement",
"=",
"''",
")",
"{",
"if",
"(",
"$",
"replacement",
"!==",
"''",
")",
"{",
"return",
"preg_replace_callback",
"(",
"static",
"::",
"REGEX_ANSI",
",",
"function",
"(",
"$",
"matc... | Filter takes a string with Cursor movements and filters them out
@param string $string
@param string $replacement Optional character or string to replace specific codes with
@return string | [
"Filter",
"takes",
"a",
"string",
"with",
"Cursor",
"movements",
"and",
"filters",
"them",
"out"
] | aafdaf504a96e6889f284bb15c75330318318df1 | https://github.com/graze/console-diff-renderer/blob/aafdaf504a96e6889f284bb15c75330318318df1/src/Terminal/ANSI.php#L231-L239 | train |
graze/console-diff-renderer | src/Terminal/ANSI.php | ANSI.getCurrentFormatting | public function getCurrentFormatting($string)
{
$stack = [];
foreach ($this->getStyleStack($string) as $style) {
if (preg_match(static::REGEX_FIRST_KEY, $style, $matches)) {
$key = $matches[0];
// if this is a valid setting style, add it to the stack
if (array_key_exists($key, $this->formats)) {
$stack[] = ['key' => $key, 'style' => $style];
} else {
// otherwise remove all elements that this turns off from the current stack
if ($key === static::STYLE_RESET) {
$stack = [];
} else {
$stack = array_filter($stack, function ($item) use ($key) {
return !in_array($key, $this->formats[$item['key']]);
});
}
}
}
}
if (count($stack) === 0) {
return '';
}
$items = array_map(function ($item) {
return $item['style'];
}, $stack);
return sprintf(static::ESCAPE . '[%sm', implode(';', $items));
} | php | public function getCurrentFormatting($string)
{
$stack = [];
foreach ($this->getStyleStack($string) as $style) {
if (preg_match(static::REGEX_FIRST_KEY, $style, $matches)) {
$key = $matches[0];
// if this is a valid setting style, add it to the stack
if (array_key_exists($key, $this->formats)) {
$stack[] = ['key' => $key, 'style' => $style];
} else {
// otherwise remove all elements that this turns off from the current stack
if ($key === static::STYLE_RESET) {
$stack = [];
} else {
$stack = array_filter($stack, function ($item) use ($key) {
return !in_array($key, $this->formats[$item['key']]);
});
}
}
}
}
if (count($stack) === 0) {
return '';
}
$items = array_map(function ($item) {
return $item['style'];
}, $stack);
return sprintf(static::ESCAPE . '[%sm', implode(';', $items));
} | [
"public",
"function",
"getCurrentFormatting",
"(",
"$",
"string",
")",
"{",
"$",
"stack",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getStyleStack",
"(",
"$",
"string",
")",
"as",
"$",
"style",
")",
"{",
"if",
"(",
"preg_match",
"(",
"st... | Gets the styling that would be active at the end of this string
@param string $string
@return string | [
"Gets",
"the",
"styling",
"that",
"would",
"be",
"active",
"at",
"the",
"end",
"of",
"this",
"string"
] | aafdaf504a96e6889f284bb15c75330318318df1 | https://github.com/graze/console-diff-renderer/blob/aafdaf504a96e6889f284bb15c75330318318df1/src/Terminal/ANSI.php#L248-L279 | train |
graze/console-diff-renderer | src/Terminal/ANSI.php | ANSI.getStyleStack | private function getStyleStack($string)
{
if (preg_match_all(static::REGEX_FORMAT, $string, $matches)) {
foreach ($matches[1] as $grouping) {
if (preg_match_all(static::REGEX_STYLE_ITEM, $grouping, $styles)) {
foreach ($styles[0] as $style) {
yield $style;
}
} else {
yield static::STYLE_RESET;
}
}
}
return;
} | php | private function getStyleStack($string)
{
if (preg_match_all(static::REGEX_FORMAT, $string, $matches)) {
foreach ($matches[1] as $grouping) {
if (preg_match_all(static::REGEX_STYLE_ITEM, $grouping, $styles)) {
foreach ($styles[0] as $style) {
yield $style;
}
} else {
yield static::STYLE_RESET;
}
}
}
return;
} | [
"private",
"function",
"getStyleStack",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"preg_match_all",
"(",
"static",
"::",
"REGEX_FORMAT",
",",
"$",
"string",
",",
"$",
"matches",
")",
")",
"{",
"foreach",
"(",
"$",
"matches",
"[",
"1",
"]",
"as",
"$",
... | Get all the styles in order that should be applied at the end
@param string $string
@return \Generator|void Iterator of numbers representing styles | [
"Get",
"all",
"the",
"styles",
"in",
"order",
"that",
"should",
"be",
"applied",
"at",
"the",
"end"
] | aafdaf504a96e6889f284bb15c75330318318df1 | https://github.com/graze/console-diff-renderer/blob/aafdaf504a96e6889f284bb15c75330318318df1/src/Terminal/ANSI.php#L288-L302 | train |
jbouzekri/FileUploaderBundle | Service/FileHistoryManager.php | FileHistoryManager.getAuthUserId | protected function getAuthUserId()
{
$token = $this->tokenStorage->getToken();
if (null === $token) {
return;
}
$user = $token->getUser();
if (!is_object($user)) {
return;
}
return $user->getId();
} | php | protected function getAuthUserId()
{
$token = $this->tokenStorage->getToken();
if (null === $token) {
return;
}
$user = $token->getUser();
if (!is_object($user)) {
return;
}
return $user->getId();
} | [
"protected",
"function",
"getAuthUserId",
"(",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"tokenStorage",
"->",
"getToken",
"(",
")",
";",
"if",
"(",
"null",
"===",
"$",
"token",
")",
"{",
"return",
";",
"}",
"$",
"user",
"=",
"$",
"token",
"-... | Get authenticated user id
@return int | [
"Get",
"authenticated",
"user",
"id"
] | 592e7ed827eaa4e7f8f6f52947ca5e5a86835f6c | https://github.com/jbouzekri/FileUploaderBundle/blob/592e7ed827eaa4e7f8f6f52947ca5e5a86835f6c/Service/FileHistoryManager.php#L122-L135 | train |
remorhaz/php-unilex | src/Parser/LL1/Lookup/Set.php | Set.addToken | public function addToken(int $symbolId, int ...$tokenIdList): void
{
if (empty($tokenIdList)) {
return;
}
if (!isset($this->tokenMap[$symbolId])) {
$this->tokenMap[$symbolId] = $tokenIdList;
$this->increaseChangeCount(count($tokenIdList));
return;
}
$newTokenIdList = array_diff($tokenIdList, $this->tokenMap[$symbolId]);
if (empty($newTokenIdList)) {
return;
}
$this->tokenMap[$symbolId] = array_merge($this->tokenMap[$symbolId], $newTokenIdList);
$this->increaseChangeCount(count($newTokenIdList));
} | php | public function addToken(int $symbolId, int ...$tokenIdList): void
{
if (empty($tokenIdList)) {
return;
}
if (!isset($this->tokenMap[$symbolId])) {
$this->tokenMap[$symbolId] = $tokenIdList;
$this->increaseChangeCount(count($tokenIdList));
return;
}
$newTokenIdList = array_diff($tokenIdList, $this->tokenMap[$symbolId]);
if (empty($newTokenIdList)) {
return;
}
$this->tokenMap[$symbolId] = array_merge($this->tokenMap[$symbolId], $newTokenIdList);
$this->increaseChangeCount(count($newTokenIdList));
} | [
"public",
"function",
"addToken",
"(",
"int",
"$",
"symbolId",
",",
"int",
"...",
"$",
"tokenIdList",
")",
":",
"void",
"{",
"if",
"(",
"empty",
"(",
"$",
"tokenIdList",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
... | Adds list of tokens to the set.
@param int $symbolId
@param int ...$tokenIdList | [
"Adds",
"list",
"of",
"tokens",
"to",
"the",
"set",
"."
] | acac7aa1f774e03d965d4291466ee45f141fdd20 | https://github.com/remorhaz/php-unilex/blob/acac7aa1f774e03d965d4291466ee45f141fdd20/src/Parser/LL1/Lookup/Set.php#L26-L42 | train |
remorhaz/php-unilex | src/Parser/LL1/Lookup/Set.php | Set.mergeTokens | public function mergeTokens(int $targetSymbolId, int $sourceSymbolId): void
{
$this->addToken($targetSymbolId, ...$this->getTokens($sourceSymbolId));
} | php | public function mergeTokens(int $targetSymbolId, int $sourceSymbolId): void
{
$this->addToken($targetSymbolId, ...$this->getTokens($sourceSymbolId));
} | [
"public",
"function",
"mergeTokens",
"(",
"int",
"$",
"targetSymbolId",
",",
"int",
"$",
"sourceSymbolId",
")",
":",
"void",
"{",
"$",
"this",
"->",
"addToken",
"(",
"$",
"targetSymbolId",
",",
"...",
"$",
"this",
"->",
"getTokens",
"(",
"$",
"sourceSymbol... | Merges token sets.
@param int $targetSymbolId
@param int $sourceSymbolId | [
"Merges",
"token",
"sets",
"."
] | acac7aa1f774e03d965d4291466ee45f141fdd20 | https://github.com/remorhaz/php-unilex/blob/acac7aa1f774e03d965d4291466ee45f141fdd20/src/Parser/LL1/Lookup/Set.php#L78-L81 | train |
techdivision/import-product-media | src/Observers/ProductMediaObserver.php | ProductMediaObserver.processImages | protected function processImages()
{
// load the store view code
$storeViewCode = $this->getValue(ColumnKeys::STORE_VIEW_CODE);
$attributeSetCode = $this->getValue(ColumnKeys::ATTRIBUTE_SET_CODE);
// load the parent SKU from the row
$parentSku = $this->getValue(ColumnKeys::SKU);
// iterate over the available image fields
foreach ($this->getImageTypes() as $imageColumnName => $labelColumnName) {
// query whether or not, we've a base image
if ($image = $this->getValue($imageColumnName)) {
// initialize the label text
$labelText = $this->getDefaultImageLabel();
// query whether or not a custom label text has been passed
if ($this->hasValue($labelColumnName)) {
$labelText = $this->getValue($labelColumnName);
}
// prepare the new base image
$artefact = $this->newArtefact(
array(
ColumnKeys::STORE_VIEW_CODE => $storeViewCode,
ColumnKeys::ATTRIBUTE_SET_CODE => $attributeSetCode,
ColumnKeys::IMAGE_PARENT_SKU => $parentSku,
ColumnKeys::IMAGE_PATH => $image,
ColumnKeys::IMAGE_PATH_NEW => $image,
ColumnKeys::IMAGE_LABEL => $labelText
),
array(
ColumnKeys::STORE_VIEW_CODE => ColumnKeys::STORE_VIEW_CODE,
ColumnKeys::ATTRIBUTE_SET_CODE => ColumnKeys::ATTRIBUTE_SET_CODE,
ColumnKeys::IMAGE_PARENT_SKU => ColumnKeys::SKU,
ColumnKeys::IMAGE_PATH => $imageColumnName,
ColumnKeys::IMAGE_PATH_NEW => $imageColumnName,
ColumnKeys::IMAGE_LABEL => $labelColumnName
)
);
// append the base image to the artefacts
$this->artefacts[] = $artefact;
}
}
} | php | protected function processImages()
{
// load the store view code
$storeViewCode = $this->getValue(ColumnKeys::STORE_VIEW_CODE);
$attributeSetCode = $this->getValue(ColumnKeys::ATTRIBUTE_SET_CODE);
// load the parent SKU from the row
$parentSku = $this->getValue(ColumnKeys::SKU);
// iterate over the available image fields
foreach ($this->getImageTypes() as $imageColumnName => $labelColumnName) {
// query whether or not, we've a base image
if ($image = $this->getValue($imageColumnName)) {
// initialize the label text
$labelText = $this->getDefaultImageLabel();
// query whether or not a custom label text has been passed
if ($this->hasValue($labelColumnName)) {
$labelText = $this->getValue($labelColumnName);
}
// prepare the new base image
$artefact = $this->newArtefact(
array(
ColumnKeys::STORE_VIEW_CODE => $storeViewCode,
ColumnKeys::ATTRIBUTE_SET_CODE => $attributeSetCode,
ColumnKeys::IMAGE_PARENT_SKU => $parentSku,
ColumnKeys::IMAGE_PATH => $image,
ColumnKeys::IMAGE_PATH_NEW => $image,
ColumnKeys::IMAGE_LABEL => $labelText
),
array(
ColumnKeys::STORE_VIEW_CODE => ColumnKeys::STORE_VIEW_CODE,
ColumnKeys::ATTRIBUTE_SET_CODE => ColumnKeys::ATTRIBUTE_SET_CODE,
ColumnKeys::IMAGE_PARENT_SKU => ColumnKeys::SKU,
ColumnKeys::IMAGE_PATH => $imageColumnName,
ColumnKeys::IMAGE_PATH_NEW => $imageColumnName,
ColumnKeys::IMAGE_LABEL => $labelColumnName
)
);
// append the base image to the artefacts
$this->artefacts[] = $artefact;
}
}
} | [
"protected",
"function",
"processImages",
"(",
")",
"{",
"// load the store view code",
"$",
"storeViewCode",
"=",
"$",
"this",
"->",
"getValue",
"(",
"ColumnKeys",
"::",
"STORE_VIEW_CODE",
")",
";",
"$",
"attributeSetCode",
"=",
"$",
"this",
"->",
"getValue",
"... | Parses the column and exports the image data to a separate file.
@return void | [
"Parses",
"the",
"column",
"and",
"exports",
"the",
"image",
"data",
"to",
"a",
"separate",
"file",
"."
] | 124f4ed08d96f61fdb1eeb5aafde1c5afbd93a06 | https://github.com/techdivision/import-product-media/blob/124f4ed08d96f61fdb1eeb5aafde1c5afbd93a06/src/Observers/ProductMediaObserver.php#L83-L129 | train |
techdivision/import-product-media | src/Observers/ProductMediaObserver.php | ProductMediaObserver.processAdditionalImages | protected function processAdditionalImages()
{
// load the store view code
$storeViewCode = $this->getValue(ColumnKeys::STORE_VIEW_CODE);
$attributeSetCode = $this->getValue(ColumnKeys::ATTRIBUTE_SET_CODE);
// load the parent SKU from the row
$parentSku = $this->getValue(ColumnKeys::SKU);
// query whether or not, we've additional images
if ($additionalImages = $this->getValue(ColumnKeys::ADDITIONAL_IMAGES, null, array($this, 'explode'))) {
// expand the additional image labels, if available
$additionalImageLabels = $this->getValue(ColumnKeys::ADDITIONAL_IMAGE_LABELS, array(), array($this, 'explode'));
// initialize the images with the found values
foreach ($additionalImages as $key => $additionalImage) {
// prepare the additional image
$artefact = $this->newArtefact(
array(
ColumnKeys::STORE_VIEW_CODE => $storeViewCode,
ColumnKeys::ATTRIBUTE_SET_CODE => $attributeSetCode,
ColumnKeys::IMAGE_PARENT_SKU => $parentSku,
ColumnKeys::IMAGE_PATH => $additionalImage,
ColumnKeys::IMAGE_PATH_NEW => $additionalImage,
ColumnKeys::IMAGE_LABEL => isset($additionalImageLabels[$key]) ?
$additionalImageLabels[$key] :
$this->getDefaultImageLabel()
),
array(
ColumnKeys::STORE_VIEW_CODE => ColumnKeys::STORE_VIEW_CODE,
ColumnKeys::ATTRIBUTE_SET_CODE => ColumnKeys::ATTRIBUTE_SET_CODE,
ColumnKeys::IMAGE_PARENT_SKU => ColumnKeys::SKU,
ColumnKeys::IMAGE_PATH => ColumnKeys::ADDITIONAL_IMAGES,
ColumnKeys::IMAGE_PATH_NEW => ColumnKeys::ADDITIONAL_IMAGES,
ColumnKeys::IMAGE_LABEL => ColumnKeys::ADDITIONAL_IMAGE_LABELS
)
);
// append the additional image to the artefacts
$this->artefacts[] = $artefact;
}
}
} | php | protected function processAdditionalImages()
{
// load the store view code
$storeViewCode = $this->getValue(ColumnKeys::STORE_VIEW_CODE);
$attributeSetCode = $this->getValue(ColumnKeys::ATTRIBUTE_SET_CODE);
// load the parent SKU from the row
$parentSku = $this->getValue(ColumnKeys::SKU);
// query whether or not, we've additional images
if ($additionalImages = $this->getValue(ColumnKeys::ADDITIONAL_IMAGES, null, array($this, 'explode'))) {
// expand the additional image labels, if available
$additionalImageLabels = $this->getValue(ColumnKeys::ADDITIONAL_IMAGE_LABELS, array(), array($this, 'explode'));
// initialize the images with the found values
foreach ($additionalImages as $key => $additionalImage) {
// prepare the additional image
$artefact = $this->newArtefact(
array(
ColumnKeys::STORE_VIEW_CODE => $storeViewCode,
ColumnKeys::ATTRIBUTE_SET_CODE => $attributeSetCode,
ColumnKeys::IMAGE_PARENT_SKU => $parentSku,
ColumnKeys::IMAGE_PATH => $additionalImage,
ColumnKeys::IMAGE_PATH_NEW => $additionalImage,
ColumnKeys::IMAGE_LABEL => isset($additionalImageLabels[$key]) ?
$additionalImageLabels[$key] :
$this->getDefaultImageLabel()
),
array(
ColumnKeys::STORE_VIEW_CODE => ColumnKeys::STORE_VIEW_CODE,
ColumnKeys::ATTRIBUTE_SET_CODE => ColumnKeys::ATTRIBUTE_SET_CODE,
ColumnKeys::IMAGE_PARENT_SKU => ColumnKeys::SKU,
ColumnKeys::IMAGE_PATH => ColumnKeys::ADDITIONAL_IMAGES,
ColumnKeys::IMAGE_PATH_NEW => ColumnKeys::ADDITIONAL_IMAGES,
ColumnKeys::IMAGE_LABEL => ColumnKeys::ADDITIONAL_IMAGE_LABELS
)
);
// append the additional image to the artefacts
$this->artefacts[] = $artefact;
}
}
} | [
"protected",
"function",
"processAdditionalImages",
"(",
")",
"{",
"// load the store view code",
"$",
"storeViewCode",
"=",
"$",
"this",
"->",
"getValue",
"(",
"ColumnKeys",
"::",
"STORE_VIEW_CODE",
")",
";",
"$",
"attributeSetCode",
"=",
"$",
"this",
"->",
"getV... | Parses the column and exports the additional image data to a separate file.
@return void | [
"Parses",
"the",
"column",
"and",
"exports",
"the",
"additional",
"image",
"data",
"to",
"a",
"separate",
"file",
"."
] | 124f4ed08d96f61fdb1eeb5aafde1c5afbd93a06 | https://github.com/techdivision/import-product-media/blob/124f4ed08d96f61fdb1eeb5aafde1c5afbd93a06/src/Observers/ProductMediaObserver.php#L136-L179 | train |
melisplatform/melis-front | src/Controller/Plugin/MelisFrontDragDropZonePlugin.php | MelisFrontDragDropZonePlugin.back | public function back()
{
$viewModel = new ViewModel();
$viewModel->setTemplate('MelisFront/dragdropzone/meliscontainer');
$viewModel->pluginFrontConfig = $this->pluginFrontConfig;
$viewModel->dragdropzoneId = $this->pluginFrontConfig['id'];
$viewModel->configPluginKey = $this->configPluginKey;
$viewModel->pluginName = $this->pluginName;
$viewModel->pluginXmlDbKey = $this->pluginXmlDbKey;
$pageId = (!empty($this->pluginFrontConfig['pageId'])) ? $this->pluginFrontConfig['pageId'] : 0;
$siteModule = getenv('MELIS_MODULE');
$melisPage = $this->getServiceLocator()->get('MelisEnginePage');
$datasPage = $melisPage->getDatasPage($pageId, 'saved');
if($datasPage)
{
$datasTemplate = $datasPage->getMelisTemplate();
if(!empty($datasTemplate))
{
$siteModule = $datasTemplate->tpl_zf2_website_folder;
}
}
$viewModel->siteModule = $siteModule;
return $viewModel;
} | php | public function back()
{
$viewModel = new ViewModel();
$viewModel->setTemplate('MelisFront/dragdropzone/meliscontainer');
$viewModel->pluginFrontConfig = $this->pluginFrontConfig;
$viewModel->dragdropzoneId = $this->pluginFrontConfig['id'];
$viewModel->configPluginKey = $this->configPluginKey;
$viewModel->pluginName = $this->pluginName;
$viewModel->pluginXmlDbKey = $this->pluginXmlDbKey;
$pageId = (!empty($this->pluginFrontConfig['pageId'])) ? $this->pluginFrontConfig['pageId'] : 0;
$siteModule = getenv('MELIS_MODULE');
$melisPage = $this->getServiceLocator()->get('MelisEnginePage');
$datasPage = $melisPage->getDatasPage($pageId, 'saved');
if($datasPage)
{
$datasTemplate = $datasPage->getMelisTemplate();
if(!empty($datasTemplate))
{
$siteModule = $datasTemplate->tpl_zf2_website_folder;
}
}
$viewModel->siteModule = $siteModule;
return $viewModel;
} | [
"public",
"function",
"back",
"(",
")",
"{",
"$",
"viewModel",
"=",
"new",
"ViewModel",
"(",
")",
";",
"$",
"viewModel",
"->",
"setTemplate",
"(",
"'MelisFront/dragdropzone/meliscontainer'",
")",
";",
"$",
"viewModel",
"->",
"pluginFrontConfig",
"=",
"$",
"thi... | Redefining the back function as the display of tags is specific with TinyMce | [
"Redefining",
"the",
"back",
"function",
"as",
"the",
"display",
"of",
"tags",
"is",
"specific",
"with",
"TinyMce"
] | 5e03e32687970bb2201e4205612d5539500dc514 | https://github.com/melisplatform/melis-front/blob/5e03e32687970bb2201e4205612d5539500dc514/src/Controller/Plugin/MelisFrontDragDropZonePlugin.php#L146-L175 | train |
LearningLocker/Moodle-xAPI-Translator | src/Events/FeedbackSubmitted.php | FeedbackSubmitted.parseFeedback | public function parseFeedback($opts){
$parsedQuestions = [];
$scoreMax = 0;
$scoreRaw = 0;
foreach ($opts['questions'] as $item => $question) {
// Find the response to the current question
$currentResponse = null;
foreach ($opts['attempt']->responses as $responseId => $response) {
if (!empty($response->item) && $response->item == $item) {
$currentResponse = $response;
}
}
if (is_null($currentResponse)) {
// Perhaps a label or the learner did not answer this question - don't add to the array.
break;
}
// Parse the current question
$parsedQuestion = (object)[
'question' => $question,
'options' => $this->parseQuestionPresentation($question->presentation, $question->typ),
'score' => (object) [
'max' => 0,
'raw' => 0
],
'response' => null
];
$parsedQuestion->response = $currentResponse->id;
// Add scores and response
foreach ($parsedQuestion->options as $optionIndex => $option) {
if (isset($option->value) && $option->value > $parsedQuestion->score->max) {
$parsedQuestion->score->max = $option->value;
}
// Find the option the learner selected
if ($optionIndex == $currentResponse->id){
if (isset($option->value)) {
$parsedQuestion->score->raw = $option->value;
}
}
}
$scoreMax += $parsedQuestion->score->max;
$scoreRaw += $parsedQuestion->score->raw;
if ($parsedQuestion->score->max == 0) {
$parsedQuestion->score->max = null;
$parsedQuestion->score->raw = null;
}
else {
$parsedQuestion->score->min = 0;
$parsedQuestion->score->scaled = $parsedQuestion->score->raw / $parsedQuestion->score->max;
}
array_push(
$parsedQuestions,
$parsedQuestion
);
}
$scoreMin = null;
$scoreScaled = null;
if ($scoreMax == 0){
$scoreMax = null;
$scoreRaw = null;
}
else {
$scoreScaled = $scoreRaw / $scoreMax;
$scoreMin = 0;
}
return (object)[
'questions' => $parsedQuestions,
'score' => (object) [
'max' => $scoreMax,
'raw' => $scoreRaw,
'min' => $scoreMin,
'scaled' => $scoreScaled
]
];
} | php | public function parseFeedback($opts){
$parsedQuestions = [];
$scoreMax = 0;
$scoreRaw = 0;
foreach ($opts['questions'] as $item => $question) {
// Find the response to the current question
$currentResponse = null;
foreach ($opts['attempt']->responses as $responseId => $response) {
if (!empty($response->item) && $response->item == $item) {
$currentResponse = $response;
}
}
if (is_null($currentResponse)) {
// Perhaps a label or the learner did not answer this question - don't add to the array.
break;
}
// Parse the current question
$parsedQuestion = (object)[
'question' => $question,
'options' => $this->parseQuestionPresentation($question->presentation, $question->typ),
'score' => (object) [
'max' => 0,
'raw' => 0
],
'response' => null
];
$parsedQuestion->response = $currentResponse->id;
// Add scores and response
foreach ($parsedQuestion->options as $optionIndex => $option) {
if (isset($option->value) && $option->value > $parsedQuestion->score->max) {
$parsedQuestion->score->max = $option->value;
}
// Find the option the learner selected
if ($optionIndex == $currentResponse->id){
if (isset($option->value)) {
$parsedQuestion->score->raw = $option->value;
}
}
}
$scoreMax += $parsedQuestion->score->max;
$scoreRaw += $parsedQuestion->score->raw;
if ($parsedQuestion->score->max == 0) {
$parsedQuestion->score->max = null;
$parsedQuestion->score->raw = null;
}
else {
$parsedQuestion->score->min = 0;
$parsedQuestion->score->scaled = $parsedQuestion->score->raw / $parsedQuestion->score->max;
}
array_push(
$parsedQuestions,
$parsedQuestion
);
}
$scoreMin = null;
$scoreScaled = null;
if ($scoreMax == 0){
$scoreMax = null;
$scoreRaw = null;
}
else {
$scoreScaled = $scoreRaw / $scoreMax;
$scoreMin = 0;
}
return (object)[
'questions' => $parsedQuestions,
'score' => (object) [
'max' => $scoreMax,
'raw' => $scoreRaw,
'min' => $scoreMin,
'scaled' => $scoreScaled
]
];
} | [
"public",
"function",
"parseFeedback",
"(",
"$",
"opts",
")",
"{",
"$",
"parsedQuestions",
"=",
"[",
"]",
";",
"$",
"scoreMax",
"=",
"0",
";",
"$",
"scoreRaw",
"=",
"0",
";",
"foreach",
"(",
"$",
"opts",
"[",
"'questions'",
"]",
"as",
"$",
"item",
... | Converts a outputs feedback question and result data in a more manageable format
@param [Array => Mixed] $opts
@return [PHPObj => Mixed] | [
"Converts",
"a",
"outputs",
"feedback",
"question",
"and",
"result",
"data",
"in",
"a",
"more",
"manageable",
"format"
] | 5d196b5059f0f5dcdd98f784ad814a39cd5d736c | https://github.com/LearningLocker/Moodle-xAPI-Translator/blob/5d196b5059f0f5dcdd98f784ad814a39cd5d736c/src/Events/FeedbackSubmitted.php#L37-L121 | train |
LearningLocker/Moodle-xAPI-Translator | src/Events/FeedbackSubmitted.php | FeedbackSubmitted.parseQuestionPresentation | protected function parseQuestionPresentation ($presentation, $type){
// Text areas don't have options or scores
if ($type == 'textarea') {
return [];
}
// Strip out the junk.
$presentation = str_replace('r>>>>>', '', $presentation);
$presentation = trim(preg_replace('/\s+/', ' ', $presentation));
$presentation = strip_tags($presentation);
$options = explode('|', $presentation);
$return = [(object)[
'description' => 'Not selected'
]];
foreach ($options as $index => $option) {
switch ($type) {
case 'multichoice':
array_push($return, (object)[
'description' => $option
]);
break;
case 'multichoicerated':
$optionArr = explode('#### ', $option);
array_push($return, (object)[
'description' => $optionArr[1],
'value' => $optionArr[0]
]);
break;
default:
// Unsupported type.
return [];
break;
}
}
return $return;
} | php | protected function parseQuestionPresentation ($presentation, $type){
// Text areas don't have options or scores
if ($type == 'textarea') {
return [];
}
// Strip out the junk.
$presentation = str_replace('r>>>>>', '', $presentation);
$presentation = trim(preg_replace('/\s+/', ' ', $presentation));
$presentation = strip_tags($presentation);
$options = explode('|', $presentation);
$return = [(object)[
'description' => 'Not selected'
]];
foreach ($options as $index => $option) {
switch ($type) {
case 'multichoice':
array_push($return, (object)[
'description' => $option
]);
break;
case 'multichoicerated':
$optionArr = explode('#### ', $option);
array_push($return, (object)[
'description' => $optionArr[1],
'value' => $optionArr[0]
]);
break;
default:
// Unsupported type.
return [];
break;
}
}
return $return;
} | [
"protected",
"function",
"parseQuestionPresentation",
"(",
"$",
"presentation",
",",
"$",
"type",
")",
"{",
"// Text areas don't have options or scores",
"if",
"(",
"$",
"type",
"==",
"'textarea'",
")",
"{",
"return",
"[",
"]",
";",
"}",
"// Strip out the junk.",
... | Converts a feedback item "presentation" string into an array
@param [String => Mixed] $presentation
@param [String => Mixed] $type
@return [Array => Mixed] | [
"Converts",
"a",
"feedback",
"item",
"presentation",
"string",
"into",
"an",
"array"
] | 5d196b5059f0f5dcdd98f784ad814a39cd5d736c | https://github.com/LearningLocker/Moodle-xAPI-Translator/blob/5d196b5059f0f5dcdd98f784ad814a39cd5d736c/src/Events/FeedbackSubmitted.php#L129-L168 | train |
protobuf-php/google-protobuf-proto | src/google/protobuf/FieldDescriptorProto.php | FieldDescriptorProto.setLabel | public function setLabel(\google\protobuf\FieldDescriptorProto\Label $value = null)
{
$this->label = $value;
} | php | public function setLabel(\google\protobuf\FieldDescriptorProto\Label $value = null)
{
$this->label = $value;
} | [
"public",
"function",
"setLabel",
"(",
"\\",
"google",
"\\",
"protobuf",
"\\",
"FieldDescriptorProto",
"\\",
"Label",
"$",
"value",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"label",
"=",
"$",
"value",
";",
"}"
] | Set 'label' value
@param \google\protobuf\FieldDescriptorProto\Label $value | [
"Set",
"label",
"value"
] | da1827b4a23fccd4eb998a8d4bcd972f2330bc29 | https://github.com/protobuf-php/google-protobuf-proto/blob/da1827b4a23fccd4eb998a8d4bcd972f2330bc29/src/google/protobuf/FieldDescriptorProto.php#L182-L185 | train |
protobuf-php/google-protobuf-proto | src/google/protobuf/FieldDescriptorProto.php | FieldDescriptorProto.setType | public function setType(\google\protobuf\FieldDescriptorProto\Type $value = null)
{
$this->type = $value;
} | php | public function setType(\google\protobuf\FieldDescriptorProto\Type $value = null)
{
$this->type = $value;
} | [
"public",
"function",
"setType",
"(",
"\\",
"google",
"\\",
"protobuf",
"\\",
"FieldDescriptorProto",
"\\",
"Type",
"$",
"value",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"type",
"=",
"$",
"value",
";",
"}"
] | Set 'type' value
@param \google\protobuf\FieldDescriptorProto\Type $value | [
"Set",
"type",
"value"
] | da1827b4a23fccd4eb998a8d4bcd972f2330bc29 | https://github.com/protobuf-php/google-protobuf-proto/blob/da1827b4a23fccd4eb998a8d4bcd972f2330bc29/src/google/protobuf/FieldDescriptorProto.php#L212-L215 | train |
globalis-ms/puppet-skilled-framework | src/Core/Application.php | Application.get | public function get($name)
{
if (isset($this->container['CI']->{$name})) {
return $this->container['CI']->{$name};
}
return $this->container[$name];
} | php | public function get($name)
{
if (isset($this->container['CI']->{$name})) {
return $this->container['CI']->{$name};
}
return $this->container[$name];
} | [
"public",
"function",
"get",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"container",
"[",
"'CI'",
"]",
"->",
"{",
"$",
"name",
"}",
")",
")",
"{",
"return",
"$",
"this",
"->",
"container",
"[",
"'CI'",
"]",
"->",
"{... | Access to CI data or container data
@param string $name
@return void | [
"Access",
"to",
"CI",
"data",
"or",
"container",
"data"
] | 4bb9ff30a32210f54add1f0e53d4769d26eb3c29 | https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/Core/Application.php#L65-L71 | train |
techdivision/import-product-media | src/Observers/MediaGalleryValueUpdateObserver.php | MediaGalleryValueUpdateObserver.initializeProductMediaGalleryValue | protected function initializeProductMediaGalleryValue(array $attr)
{
// load the value/store/parent ID
$valueId = $attr[MemberNames::VALUE_ID];
$storeId = $attr[MemberNames::STORE_ID];
$entityId = $attr[MemberNames::ENTITY_ID];
// query whether the product media gallery value already exists or not
if ($entity = $this->loadProductMediaGalleryValue($valueId, $storeId, $entityId)) {
return $this->mergeEntity($entity, $attr);
}
// simply return the attributes
return $attr;
} | php | protected function initializeProductMediaGalleryValue(array $attr)
{
// load the value/store/parent ID
$valueId = $attr[MemberNames::VALUE_ID];
$storeId = $attr[MemberNames::STORE_ID];
$entityId = $attr[MemberNames::ENTITY_ID];
// query whether the product media gallery value already exists or not
if ($entity = $this->loadProductMediaGalleryValue($valueId, $storeId, $entityId)) {
return $this->mergeEntity($entity, $attr);
}
// simply return the attributes
return $attr;
} | [
"protected",
"function",
"initializeProductMediaGalleryValue",
"(",
"array",
"$",
"attr",
")",
"{",
"// load the value/store/parent ID",
"$",
"valueId",
"=",
"$",
"attr",
"[",
"MemberNames",
"::",
"VALUE_ID",
"]",
";",
"$",
"storeId",
"=",
"$",
"attr",
"[",
"Mem... | Initialize the product media gallery value with the passed attributes and returns an instance.
@param array $attr The product media gallery value attributes
@return array The initialized product media gallery value | [
"Initialize",
"the",
"product",
"media",
"gallery",
"value",
"with",
"the",
"passed",
"attributes",
"and",
"returns",
"an",
"instance",
"."
] | 124f4ed08d96f61fdb1eeb5aafde1c5afbd93a06 | https://github.com/techdivision/import-product-media/blob/124f4ed08d96f61fdb1eeb5aafde1c5afbd93a06/src/Observers/MediaGalleryValueUpdateObserver.php#L44-L59 | train |
dreamfactorysoftware/df-system | src/Components/SystemResourceType.php | SystemResourceType.toArray | public function toArray()
{
return [
'name' => $this->name,
'label' => $this->label,
'description' => $this->description,
'class_name' => $this->className,
'singleton' => $this->singleton,
'read_only' => $this->readOnly,
'subscription_required' => $this->subscriptionRequired,
];
} | php | public function toArray()
{
return [
'name' => $this->name,
'label' => $this->label,
'description' => $this->description,
'class_name' => $this->className,
'singleton' => $this->singleton,
'read_only' => $this->readOnly,
'subscription_required' => $this->subscriptionRequired,
];
} | [
"public",
"function",
"toArray",
"(",
")",
"{",
"return",
"[",
"'name'",
"=>",
"$",
"this",
"->",
"name",
",",
"'label'",
"=>",
"$",
"this",
"->",
"label",
",",
"'description'",
"=>",
"$",
"this",
"->",
"description",
",",
"'class_name'",
"=>",
"$",
"t... | The configuration handler interface for this system resource type
@return array | null | [
"The",
"configuration",
"handler",
"interface",
"for",
"this",
"system",
"resource",
"type"
] | 18f91d7630d3cdaef85611c5b668c0521130593e | https://github.com/dreamfactorysoftware/df-system/blob/18f91d7630d3cdaef85611c5b668c0521130593e/src/Components/SystemResourceType.php#L125-L136 | train |
eclogue/courser | src/Context.php | Context.add | public function add(Route $route, array $params = [])
{
$callback = $route->getCallable();
if (empty($callback)) {
return;
}
$this->routes[] = $route->getRoute();
$paramNames = $route->getParamNames();
foreach ($paramNames as $name) {
if (isset($params[$name])) {
$this->setParam($name, $params[$name]);
}
}
if (is_array($callback)) {
$this->callable = array_merge($this->callable, $callback);
} elseif (!in_array($callback, $this->callable)) {
$this->callable[] = $callback;
}
} | php | public function add(Route $route, array $params = [])
{
$callback = $route->getCallable();
if (empty($callback)) {
return;
}
$this->routes[] = $route->getRoute();
$paramNames = $route->getParamNames();
foreach ($paramNames as $name) {
if (isset($params[$name])) {
$this->setParam($name, $params[$name]);
}
}
if (is_array($callback)) {
$this->callable = array_merge($this->callable, $callback);
} elseif (!in_array($callback, $this->callable)) {
$this->callable[] = $callback;
}
} | [
"public",
"function",
"add",
"(",
"Route",
"$",
"route",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"callback",
"=",
"$",
"route",
"->",
"getCallable",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"callback",
")",
")",
"{",
"retur... | add request handle
@param Route $route
@param array $params
@return void | [
"add",
"request",
"handle"
] | d1d1d460b3bea4f991b1c18ff0069ee197bbb833 | https://github.com/eclogue/courser/blob/d1d1d460b3bea4f991b1c18ff0069ee197bbb833/src/Context.php#L103-L123 | train |
eclogue/courser | src/Context.php | Context.transducer | public function transducer(RequestInterface $request)
{
$response = null;
if (count($this->middleware)) {
$md = array_pop($this->middleware);
$next = function (RequestInterface $request) {
return $this->transducer($request);
};
if (is_callable($md)) {
$response = $md($request, $next);
} elseif (is_array($md)) {
list($class, $action) = $md;
$instance = is_object($class) ? $class : new $class();
$response = $instance->$action($request, $next);
}
if ($response instanceof Generator) {
$response = Poroutine::resolve($response);
}
}
return $response ?? new Response();
} | php | public function transducer(RequestInterface $request)
{
$response = null;
if (count($this->middleware)) {
$md = array_pop($this->middleware);
$next = function (RequestInterface $request) {
return $this->transducer($request);
};
if (is_callable($md)) {
$response = $md($request, $next);
} elseif (is_array($md)) {
list($class, $action) = $md;
$instance = is_object($class) ? $class : new $class();
$response = $instance->$action($request, $next);
}
if ($response instanceof Generator) {
$response = Poroutine::resolve($response);
}
}
return $response ?? new Response();
} | [
"public",
"function",
"transducer",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"$",
"response",
"=",
"null",
";",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"middleware",
")",
")",
"{",
"$",
"md",
"=",
"array_pop",
"(",
"$",
"this",
"->",
"m... | Iterative process the request
@param mixed $request
@return mixed|Response | [
"Iterative",
"process",
"the",
"request"
] | d1d1d460b3bea4f991b1c18ff0069ee197bbb833 | https://github.com/eclogue/courser/blob/d1d1d460b3bea4f991b1c18ff0069ee197bbb833/src/Context.php#L200-L223 | train |
protobuf-php/google-protobuf-proto | src/google/protobuf/php/Extension.php | Extension.registerAllExtensions | public static function registerAllExtensions(\Protobuf\Extension\ExtensionRegistry $registry)
{
$registry->add(self::package());
$registry->add(self::genericServices());
} | php | public static function registerAllExtensions(\Protobuf\Extension\ExtensionRegistry $registry)
{
$registry->add(self::package());
$registry->add(self::genericServices());
} | [
"public",
"static",
"function",
"registerAllExtensions",
"(",
"\\",
"Protobuf",
"\\",
"Extension",
"\\",
"ExtensionRegistry",
"$",
"registry",
")",
"{",
"$",
"registry",
"->",
"add",
"(",
"self",
"::",
"package",
"(",
")",
")",
";",
"$",
"registry",
"->",
... | Register all extensions
@param \Protobuf\Extension\ExtensionRegistry | [
"Register",
"all",
"extensions"
] | da1827b4a23fccd4eb998a8d4bcd972f2330bc29 | https://github.com/protobuf-php/google-protobuf-proto/blob/da1827b4a23fccd4eb998a8d4bcd972f2330bc29/src/google/protobuf/php/Extension.php#L36-L40 | train |
hostnet/entity-tracker-component | src/Provider/EntityMutationMetadataProvider.php | EntityMutationMetadataProvider.addToChangeSet | private function addToChangeSet(
EntityManagerInterface $em,
ClassMetadata $metadata,
$entity,
array &$change_set
) {
if (!isset($change_set[$metadata->rootEntityName])) {
$change_set[$metadata->rootEntityName] = [];
}
if (!in_array($entity, $change_set[$metadata->rootEntityName], true)) {
$change_set[$metadata->rootEntityName][] = $entity;
// recursively find all changes
$this->appendAssociations($em, $metadata, $entity, $change_set);
}
} | php | private function addToChangeSet(
EntityManagerInterface $em,
ClassMetadata $metadata,
$entity,
array &$change_set
) {
if (!isset($change_set[$metadata->rootEntityName])) {
$change_set[$metadata->rootEntityName] = [];
}
if (!in_array($entity, $change_set[$metadata->rootEntityName], true)) {
$change_set[$metadata->rootEntityName][] = $entity;
// recursively find all changes
$this->appendAssociations($em, $metadata, $entity, $change_set);
}
} | [
"private",
"function",
"addToChangeSet",
"(",
"EntityManagerInterface",
"$",
"em",
",",
"ClassMetadata",
"$",
"metadata",
",",
"$",
"entity",
",",
"array",
"&",
"$",
"change_set",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"change_set",
"[",
"$",
"metada... | Add an entity to the change set. This also adds any elements to the
change set that are in the associations.
@param EntityManagerInterface $em
@param ClassMetadata $metadata
@param mixed $entity
@param array $change_set | [
"Add",
"an",
"entity",
"to",
"the",
"change",
"set",
".",
"This",
"also",
"adds",
"any",
"elements",
"to",
"the",
"change",
"set",
"that",
"are",
"in",
"the",
"associations",
"."
] | 08601d9db4faf7804f9097460e2149da3aa4fda3 | https://github.com/hostnet/entity-tracker-component/blob/08601d9db4faf7804f9097460e2149da3aa4fda3/src/Provider/EntityMutationMetadataProvider.php#L221-L237 | train |
TypiCMS/Galleries | src/Http/Controllers/PublicController.php | PublicController.show | public function show($slug)
{
$model = $this->repository->bySlug($slug, ['translations', 'files', 'files.translations']);
return view('galleries::public.show')
->with(compact('model'));
} | php | public function show($slug)
{
$model = $this->repository->bySlug($slug, ['translations', 'files', 'files.translations']);
return view('galleries::public.show')
->with(compact('model'));
} | [
"public",
"function",
"show",
"(",
"$",
"slug",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"repository",
"->",
"bySlug",
"(",
"$",
"slug",
",",
"[",
"'translations'",
",",
"'files'",
",",
"'files.translations'",
"]",
")",
";",
"return",
"view",
"(... | Show gallery.
@return \Illuminate\View\View | [
"Show",
"gallery",
"."
] | 3160eb90ea5ca08439818b3eb23b0ea080eb3c10 | https://github.com/TypiCMS/Galleries/blob/3160eb90ea5ca08439818b3eb23b0ea080eb3c10/src/Http/Controllers/PublicController.php#L39-L45 | train |
symfony/propel1-bridge | DataCollector/PropelDataCollector.php | PropelDataCollector.getTime | public function getTime()
{
$time = 0;
foreach ($this->data['queries'] as $query) {
$time += (float) $query['time'];
}
return $time;
} | php | public function getTime()
{
$time = 0;
foreach ($this->data['queries'] as $query) {
$time += (float) $query['time'];
}
return $time;
} | [
"public",
"function",
"getTime",
"(",
")",
"{",
"$",
"time",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"data",
"[",
"'queries'",
"]",
"as",
"$",
"query",
")",
"{",
"$",
"time",
"+=",
"(",
"float",
")",
"$",
"query",
"[",
"'time'",
"]",
... | Returns the total time spent on running all queries.
@return float | [
"Returns",
"the",
"total",
"time",
"spent",
"on",
"running",
"all",
"queries",
"."
] | fcf35dfbbeedcf24b2dc1b41d8e4dd0edc6ed84b | https://github.com/symfony/propel1-bridge/blob/fcf35dfbbeedcf24b2dc1b41d8e4dd0edc6ed84b/DataCollector/PropelDataCollector.php#L98-L106 | train |
symfony/propel1-bridge | DataCollector/PropelDataCollector.php | PropelDataCollector.buildQueries | private function buildQueries()
{
$queries = array();
$outerGlue = $this->propelConfiguration->getParameter('debugpdo.logging.outerglue', ' | ');
$innerGlue = $this->propelConfiguration->getParameter('debugpdo.logging.innerglue', ': ');
foreach ($this->logger->getQueries() as $q) {
$parts = explode($outerGlue, $q, 4);
$times = explode($innerGlue, $parts[0]);
$con = explode($innerGlue, $parts[2]);
$memories = explode($innerGlue, $parts[1]);
$sql = trim($parts[3]);
$con = trim($con[1]);
$time = trim($times[1]);
$memory = trim($memories[1]);
$queries[] = array('connection' => $con, 'sql' => $sql, 'time' => $time, 'memory' => $memory);
}
return $queries;
} | php | private function buildQueries()
{
$queries = array();
$outerGlue = $this->propelConfiguration->getParameter('debugpdo.logging.outerglue', ' | ');
$innerGlue = $this->propelConfiguration->getParameter('debugpdo.logging.innerglue', ': ');
foreach ($this->logger->getQueries() as $q) {
$parts = explode($outerGlue, $q, 4);
$times = explode($innerGlue, $parts[0]);
$con = explode($innerGlue, $parts[2]);
$memories = explode($innerGlue, $parts[1]);
$sql = trim($parts[3]);
$con = trim($con[1]);
$time = trim($times[1]);
$memory = trim($memories[1]);
$queries[] = array('connection' => $con, 'sql' => $sql, 'time' => $time, 'memory' => $memory);
}
return $queries;
} | [
"private",
"function",
"buildQueries",
"(",
")",
"{",
"$",
"queries",
"=",
"array",
"(",
")",
";",
"$",
"outerGlue",
"=",
"$",
"this",
"->",
"propelConfiguration",
"->",
"getParameter",
"(",
"'debugpdo.logging.outerglue'",
",",
"' | '",
")",
";",
"$",
"inner... | Computes the stats of all executed SQL queries.
@return array | [
"Computes",
"the",
"stats",
"of",
"all",
"executed",
"SQL",
"queries",
"."
] | fcf35dfbbeedcf24b2dc1b41d8e4dd0edc6ed84b | https://github.com/symfony/propel1-bridge/blob/fcf35dfbbeedcf24b2dc1b41d8e4dd0edc6ed84b/DataCollector/PropelDataCollector.php#L113-L136 | train |
nanbando/core | src/Core/EventListener/EnvironmentListener.php | EnvironmentListener.onRestoreStarted | public function onRestoreStarted(RestoreEvent $event)
{
$database = $event->getDatabase();
if ($database->getWithDefault('state', BackupStatus::STATE_SUCCESS) === BackupStatus::STATE_FAILED) {
$this->output->writeln(' <info>Bypassed</info>');
$event->stopPropagation();
}
} | php | public function onRestoreStarted(RestoreEvent $event)
{
$database = $event->getDatabase();
if ($database->getWithDefault('state', BackupStatus::STATE_SUCCESS) === BackupStatus::STATE_FAILED) {
$this->output->writeln(' <info>Bypassed</info>');
$event->stopPropagation();
}
} | [
"public",
"function",
"onRestoreStarted",
"(",
"RestoreEvent",
"$",
"event",
")",
"{",
"$",
"database",
"=",
"$",
"event",
"->",
"getDatabase",
"(",
")",
";",
"if",
"(",
"$",
"database",
"->",
"getWithDefault",
"(",
"'state'",
",",
"BackupStatus",
"::",
"S... | Bypasses failed backup in restore process.
@param RestoreEvent $event | [
"Bypasses",
"failed",
"backup",
"in",
"restore",
"process",
"."
] | 790f5c6339753bffafb50a846ccb6bab81f26877 | https://github.com/nanbando/core/blob/790f5c6339753bffafb50a846ccb6bab81f26877/src/Core/EventListener/EnvironmentListener.php#L71-L79 | train |
patrickbrouwers/Laravel-Doctrine | src/Extensions/ExtensionManager.php | ExtensionManager.bootGedmoExtensions | public function bootGedmoExtensions($namespaces = ['App'], $all = true)
{
if ($all) {
DoctrineExtensions::registerMappingIntoDriverChainORM(
$this->chain,
$this->reader
);
} else {
DoctrineExtensions::registerAbstractMappingIntoDriverChainORM(
$this->chain,
$this->reader
);
}
$driver = $this->metadata->getMetadataDriverImpl();
foreach ($namespaces as $namespace) {
$this->chain->addDriver($driver, $namespace);
}
$this->metadata->setMetadataDriverImpl($this->chain);
$this->dispatcher->fire('doctrine.driver-chain::booted', [
$driver,
$this->chain
]);
} | php | public function bootGedmoExtensions($namespaces = ['App'], $all = true)
{
if ($all) {
DoctrineExtensions::registerMappingIntoDriverChainORM(
$this->chain,
$this->reader
);
} else {
DoctrineExtensions::registerAbstractMappingIntoDriverChainORM(
$this->chain,
$this->reader
);
}
$driver = $this->metadata->getMetadataDriverImpl();
foreach ($namespaces as $namespace) {
$this->chain->addDriver($driver, $namespace);
}
$this->metadata->setMetadataDriverImpl($this->chain);
$this->dispatcher->fire('doctrine.driver-chain::booted', [
$driver,
$this->chain
]);
} | [
"public",
"function",
"bootGedmoExtensions",
"(",
"$",
"namespaces",
"=",
"[",
"'App'",
"]",
",",
"$",
"all",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"all",
")",
"{",
"DoctrineExtensions",
"::",
"registerMappingIntoDriverChainORM",
"(",
"$",
"this",
"->",
"... | Enable Gedmo Doctrine Extensions
@param array $namespaces
@param bool $all | [
"Enable",
"Gedmo",
"Doctrine",
"Extensions"
] | 94471346af6b121000256b303e585e977cc416cd | https://github.com/patrickbrouwers/Laravel-Doctrine/blob/94471346af6b121000256b303e585e977cc416cd/src/Extensions/ExtensionManager.php#L139-L163 | train |
protobuf-php/google-protobuf-proto | src/google/protobuf/FieldOptions.php | FieldOptions.setCtype | public function setCtype(\google\protobuf\FieldOptions\CType $value = null)
{
$this->ctype = $value;
} | php | public function setCtype(\google\protobuf\FieldOptions\CType $value = null)
{
$this->ctype = $value;
} | [
"public",
"function",
"setCtype",
"(",
"\\",
"google",
"\\",
"protobuf",
"\\",
"FieldOptions",
"\\",
"CType",
"$",
"value",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"ctype",
"=",
"$",
"value",
";",
"}"
] | Set 'ctype' value
@param \google\protobuf\FieldOptions\CType $value | [
"Set",
"ctype",
"value"
] | da1827b4a23fccd4eb998a8d4bcd972f2330bc29 | https://github.com/protobuf-php/google-protobuf-proto/blob/da1827b4a23fccd4eb998a8d4bcd972f2330bc29/src/google/protobuf/FieldOptions.php#L115-L118 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.