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
laravel-admin-extensions/helpers
src/Scaffold/ModelCreator.php
ModelCreator.replacePrimaryKey
protected function replacePrimaryKey(&$stub, $keyName) { $modelKey = $keyName == 'id' ? '' : "protected \$primaryKey = '$keyName';\n"; $stub = str_replace('DummyModelKey', $modelKey, $stub); return $this; }
php
protected function replacePrimaryKey(&$stub, $keyName) { $modelKey = $keyName == 'id' ? '' : "protected \$primaryKey = '$keyName';\n"; $stub = str_replace('DummyModelKey', $modelKey, $stub); return $this; }
[ "protected", "function", "replacePrimaryKey", "(", "&", "$", "stub", ",", "$", "keyName", ")", "{", "$", "modelKey", "=", "$", "keyName", "==", "'id'", "?", "''", ":", "\"protected \\$primaryKey = '$keyName';\\n\"", ";", "$", "stub", "=", "str_replace", "(", ...
Replace primarykey dummy. @param string $stub @param string $keyName @return $this
[ "Replace", "primarykey", "dummy", "." ]
67b2573029f90ca1873e1598a2d46ae8d9acca66
https://github.com/laravel-admin-extensions/helpers/blob/67b2573029f90ca1873e1598a2d46ae8d9acca66/src/Scaffold/ModelCreator.php#L172-L179
train
laravel-admin-extensions/helpers
src/Scaffold/ModelCreator.php
ModelCreator.replaceTable
protected function replaceTable(&$stub, $name) { $class = str_replace($this->getNamespace($name).'\\', '', $name); $table = Str::plural(strtolower($class)) !== $this->tableName ? "protected \$table = '$this->tableName';\n" : ''; $stub = str_replace('DummyModelTable', $table, $stub); return $this; }
php
protected function replaceTable(&$stub, $name) { $class = str_replace($this->getNamespace($name).'\\', '', $name); $table = Str::plural(strtolower($class)) !== $this->tableName ? "protected \$table = '$this->tableName';\n" : ''; $stub = str_replace('DummyModelTable', $table, $stub); return $this; }
[ "protected", "function", "replaceTable", "(", "&", "$", "stub", ",", "$", "name", ")", "{", "$", "class", "=", "str_replace", "(", "$", "this", "->", "getNamespace", "(", "$", "name", ")", ".", "'\\\\'", ",", "''", ",", "$", "name", ")", ";", "$", ...
Replace Table name dummy. @param string $stub @param string $name @return $this
[ "Replace", "Table", "name", "dummy", "." ]
67b2573029f90ca1873e1598a2d46ae8d9acca66
https://github.com/laravel-admin-extensions/helpers/blob/67b2573029f90ca1873e1598a2d46ae8d9acca66/src/Scaffold/ModelCreator.php#L189-L198
train
laravel-admin-extensions/helpers
src/Scaffold/ModelCreator.php
ModelCreator.replaceTimestamp
protected function replaceTimestamp(&$stub, $timestamps) { $useTimestamps = $timestamps ? '' : "public \$timestamps = false;\n"; $stub = str_replace('DummyTimestamp', $useTimestamps, $stub); return $this; }
php
protected function replaceTimestamp(&$stub, $timestamps) { $useTimestamps = $timestamps ? '' : "public \$timestamps = false;\n"; $stub = str_replace('DummyTimestamp', $useTimestamps, $stub); return $this; }
[ "protected", "function", "replaceTimestamp", "(", "&", "$", "stub", ",", "$", "timestamps", ")", "{", "$", "useTimestamps", "=", "$", "timestamps", "?", "''", ":", "\"public \\$timestamps = false;\\n\"", ";", "$", "stub", "=", "str_replace", "(", "'DummyTimestam...
Replace timestamps dummy. @param string $stub @param bool $timestamps @return $this
[ "Replace", "timestamps", "dummy", "." ]
67b2573029f90ca1873e1598a2d46ae8d9acca66
https://github.com/laravel-admin-extensions/helpers/blob/67b2573029f90ca1873e1598a2d46ae8d9acca66/src/Scaffold/ModelCreator.php#L208-L215
train
laravel-zero/framework
src/Components/AbstractInstaller.php
AbstractInstaller.require
protected function require(string $package): InstallerContract { $this->task( 'Require package via composer', function () use ($package) { return $this->composer->require($package); } ); return $this; }
php
protected function require(string $package): InstallerContract { $this->task( 'Require package via composer', function () use ($package) { return $this->composer->require($package); } ); return $this; }
[ "protected", "function", "require", "(", "string", "$", "package", ")", ":", "InstallerContract", "{", "$", "this", "->", "task", "(", "'Require package via composer'", ",", "function", "(", ")", "use", "(", "$", "package", ")", "{", "return", "$", "this", ...
Requires the provided package. @param string $package @return \LaravelZero\Framework\Contracts\Commands\Component\InstallerContract
[ "Requires", "the", "provided", "package", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Components/AbstractInstaller.php#L67-L77
train
laravel-zero/framework
src/Providers/Composer/Composer.php
Composer.run
private function run(string $cmd, string $cwd = null): bool { $process = new Process($cmd, $cwd); $process->setTimeout(300); if ($process->isTty()) { $process->setTty(true); } try { $output = $this->app->make(OutputInterface::class); } catch (Throwable $e) { $output = null; } if ($output) { $output->write("\n"); $process->run( function ($type, $line) use ($output) { $output->write($line); } ); } else { $process->run(); } return $process->isSuccessful(); }
php
private function run(string $cmd, string $cwd = null): bool { $process = new Process($cmd, $cwd); $process->setTimeout(300); if ($process->isTty()) { $process->setTty(true); } try { $output = $this->app->make(OutputInterface::class); } catch (Throwable $e) { $output = null; } if ($output) { $output->write("\n"); $process->run( function ($type, $line) use ($output) { $output->write($line); } ); } else { $process->run(); } return $process->isSuccessful(); }
[ "private", "function", "run", "(", "string", "$", "cmd", ",", "string", "$", "cwd", "=", "null", ")", ":", "bool", "{", "$", "process", "=", "new", "Process", "(", "$", "cmd", ",", "$", "cwd", ")", ";", "$", "process", "->", "setTimeout", "(", "3...
Runs the provided command on the provided folder.
[ "Runs", "the", "provided", "command", "on", "the", "provided", "folder", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Providers/Composer/Composer.php#L91-L119
train
laravel-zero/framework
src/Providers/CommandRecorder/CommandRecorderRepository.php
CommandRecorderRepository.create
public function create(string $command, array $arguments = [], string $mode = self::MODE_DEFAULT): void { $this->storage[] = [ 'command' => $command, 'arguments' => $arguments, 'mode' => $mode, ]; }
php
public function create(string $command, array $arguments = [], string $mode = self::MODE_DEFAULT): void { $this->storage[] = [ 'command' => $command, 'arguments' => $arguments, 'mode' => $mode, ]; }
[ "public", "function", "create", "(", "string", "$", "command", ",", "array", "$", "arguments", "=", "[", "]", ",", "string", "$", "mode", "=", "self", "::", "MODE_DEFAULT", ")", ":", "void", "{", "$", "this", "->", "storage", "[", "]", "=", "[", "'...
Create a new entry of a called command in the storage. @param string $command @param array $arguments @param string $mode
[ "Create", "a", "new", "entry", "of", "a", "called", "command", "in", "the", "storage", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Providers/CommandRecorder/CommandRecorderRepository.php#L54-L61
train
laravel-zero/framework
src/Providers/CommandRecorder/CommandRecorderRepository.php
CommandRecorderRepository.exists
public function exists(string $command, array $arguments = []): bool { return $this->storage->contains(function ($value) use ($command, $arguments) { return $value['command'] === $command && $value['arguments'] === $arguments; }); }
php
public function exists(string $command, array $arguments = []): bool { return $this->storage->contains(function ($value) use ($command, $arguments) { return $value['command'] === $command && $value['arguments'] === $arguments; }); }
[ "public", "function", "exists", "(", "string", "$", "command", ",", "array", "$", "arguments", "=", "[", "]", ")", ":", "bool", "{", "return", "$", "this", "->", "storage", "->", "contains", "(", "function", "(", "$", "value", ")", "use", "(", "$", ...
Determine if the given command exists with the given arguments. @param string $command @param array $arguments
[ "Determine", "if", "the", "given", "command", "exists", "with", "the", "given", "arguments", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Providers/CommandRecorder/CommandRecorderRepository.php#L69-L74
train
laravel-zero/framework
src/Application.php
Application.buildsPath
public function buildsPath(string $path = ''): string { return $this->basePath('builds'.($path ? DIRECTORY_SEPARATOR.$path : $path)); }
php
public function buildsPath(string $path = ''): string { return $this->basePath('builds'.($path ? DIRECTORY_SEPARATOR.$path : $path)); }
[ "public", "function", "buildsPath", "(", "string", "$", "path", "=", "''", ")", ":", "string", "{", "return", "$", "this", "->", "basePath", "(", "'builds'", ".", "(", "$", "path", "?", "DIRECTORY_SEPARATOR", ".", "$", "path", ":", "$", "path", ")", ...
Get the builds path. With, optionally, a path to append to the base path.
[ "Get", "the", "builds", "path", ".", "With", "optionally", "a", "path", "to", "append", "to", "the", "base", "path", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Application.php#L30-L33
train
laravel-zero/framework
src/Commands/BuildCommand.php
BuildCommand.build
private function build(string $name): BuildCommand { /* * We prepare the application for a build, moving it to production. Then, * after compile all the code to a single file, we move the built file * to the builds folder with the correct permissions. */ $this->prepare() ->compile($name) ->clear(); $this->output->writeln( sprintf(' Compiled successfully: <fg=green>%s</>', $this->app->buildsPath($name)) ); return $this; }
php
private function build(string $name): BuildCommand { /* * We prepare the application for a build, moving it to production. Then, * after compile all the code to a single file, we move the built file * to the builds folder with the correct permissions. */ $this->prepare() ->compile($name) ->clear(); $this->output->writeln( sprintf(' Compiled successfully: <fg=green>%s</>', $this->app->buildsPath($name)) ); return $this; }
[ "private", "function", "build", "(", "string", "$", "name", ")", ":", "BuildCommand", "{", "/*\n * We prepare the application for a build, moving it to production. Then,\n * after compile all the code to a single file, we move the built file\n * to the builds folder wit...
Builds the application into a single file.
[ "Builds", "the", "application", "into", "a", "single", "file", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Commands/BuildCommand.php#L78-L94
train
laravel-zero/framework
src/Commands/BuildCommand.php
BuildCommand.getTimeout
private function getTimeout(): ?float { if (! is_numeric($this->option('timeout'))) { throw new \InvalidArgumentException('The timeout value must be a number.'); } $timeout = (float) $this->option('timeout'); return $timeout > 0 ? $timeout : null; }
php
private function getTimeout(): ?float { if (! is_numeric($this->option('timeout'))) { throw new \InvalidArgumentException('The timeout value must be a number.'); } $timeout = (float) $this->option('timeout'); return $timeout > 0 ? $timeout : null; }
[ "private", "function", "getTimeout", "(", ")", ":", "?", "float", "{", "if", "(", "!", "is_numeric", "(", "$", "this", "->", "option", "(", "'timeout'", ")", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The timeout value must be a ...
Returns a valid timeout value. Non positive values are converted to null, meaning no timeout. @return float|null @throws \InvalidArgumentException
[ "Returns", "a", "valid", "timeout", "value", ".", "Non", "positive", "values", "are", "converted", "to", "null", "meaning", "no", "timeout", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Commands/BuildCommand.php#L197-L206
train
laravel-zero/framework
src/Components/Updater/GithubStrategy.php
GithubStrategy.getDownloadUrl
protected function getDownloadUrl(array $package): string { $downloadUrl = parent::getDownloadUrl($package); $downloadUrl = str_replace('releases/download', 'raw', $downloadUrl); return $downloadUrl.'/builds/'.basename(Phar::running()); }
php
protected function getDownloadUrl(array $package): string { $downloadUrl = parent::getDownloadUrl($package); $downloadUrl = str_replace('releases/download', 'raw', $downloadUrl); return $downloadUrl.'/builds/'.basename(Phar::running()); }
[ "protected", "function", "getDownloadUrl", "(", "array", "$", "package", ")", ":", "string", "{", "$", "downloadUrl", "=", "parent", "::", "getDownloadUrl", "(", "$", "package", ")", ";", "$", "downloadUrl", "=", "str_replace", "(", "'releases/download'", ",",...
Returns the Download Url. @param array $package @return string
[ "Returns", "the", "Download", "Url", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Components/Updater/GithubStrategy.php#L19-L26
train
laravel-zero/framework
src/Commands/RenameCommand.php
RenameCommand.rename
private function rename(): RenameCommand { $name = $this->asksForApplicationName(); if (File::exists($this->app->basePath($name))) { $this->app->abort(403, 'Folder or file already exists.'); } else { $this->renameBinary($name) ->updateComposer($name); } return $this; }
php
private function rename(): RenameCommand { $name = $this->asksForApplicationName(); if (File::exists($this->app->basePath($name))) { $this->app->abort(403, 'Folder or file already exists.'); } else { $this->renameBinary($name) ->updateComposer($name); } return $this; }
[ "private", "function", "rename", "(", ")", ":", "RenameCommand", "{", "$", "name", "=", "$", "this", "->", "asksForApplicationName", "(", ")", ";", "if", "(", "File", "::", "exists", "(", "$", "this", "->", "app", "->", "basePath", "(", "$", "name", ...
Updates the binary name and the application name on the composer.json.
[ "Updates", "the", "binary", "name", "and", "the", "application", "name", "on", "the", "composer", ".", "json", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Commands/RenameCommand.php#L46-L58
train
laravel-zero/framework
src/Commands/RenameCommand.php
RenameCommand.asksForApplicationName
private function asksForApplicationName(): string { if (empty($name = $this->input->getArgument('name'))) { $name = $this->ask('What is your application name?'); } if (empty($name)) { $name = trim(basename($this->app->basePath())); } return Str::lower($name); }
php
private function asksForApplicationName(): string { if (empty($name = $this->input->getArgument('name'))) { $name = $this->ask('What is your application name?'); } if (empty($name)) { $name = trim(basename($this->app->basePath())); } return Str::lower($name); }
[ "private", "function", "asksForApplicationName", "(", ")", ":", "string", "{", "if", "(", "empty", "(", "$", "name", "=", "$", "this", "->", "input", "->", "getArgument", "(", "'name'", ")", ")", ")", "{", "$", "name", "=", "$", "this", "->", "ask", ...
Asks for the application name. If there is no interaction, we take the folder basename.
[ "Asks", "for", "the", "application", "name", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Commands/RenameCommand.php#L65-L76
train
laravel-zero/framework
src/Commands/RenameCommand.php
RenameCommand.updateComposer
private function updateComposer(string $name): RenameCommand { $this->task( 'Updating config/app.php "name" property', function () use ($name) { $neededLine = "'name' => '".Str::ucfirst($this->getCurrentBinaryName())."'"; if (! Str::contains($contents = $this->getConfig(), $neededLine)) { return false; } File::put( $this->app->configPath('app.php'), Str::replaceFirst( $neededLine, "'name' => '".Str::ucfirst($name)."'", $contents ) ); } ); $this->task( 'Updating composer "bin"', function () use ($name) { $neededLine = '"bin": ["'.$this->getCurrentBinaryName().'"]'; if (! Str::contains($contents = $this->getComposer(), $neededLine)) { return false; } File::put( $this->app->basePath('composer.json'), Str::replaceFirst( $neededLine, '"bin": ["'.$name.'"]', $contents ) ); } ); return $this; }
php
private function updateComposer(string $name): RenameCommand { $this->task( 'Updating config/app.php "name" property', function () use ($name) { $neededLine = "'name' => '".Str::ucfirst($this->getCurrentBinaryName())."'"; if (! Str::contains($contents = $this->getConfig(), $neededLine)) { return false; } File::put( $this->app->configPath('app.php'), Str::replaceFirst( $neededLine, "'name' => '".Str::ucfirst($name)."'", $contents ) ); } ); $this->task( 'Updating composer "bin"', function () use ($name) { $neededLine = '"bin": ["'.$this->getCurrentBinaryName().'"]'; if (! Str::contains($contents = $this->getComposer(), $neededLine)) { return false; } File::put( $this->app->basePath('composer.json'), Str::replaceFirst( $neededLine, '"bin": ["'.$name.'"]', $contents ) ); } ); return $this; }
[ "private", "function", "updateComposer", "(", "string", "$", "name", ")", ":", "RenameCommand", "{", "$", "this", "->", "task", "(", "'Updating config/app.php \"name\" property'", ",", "function", "(", ")", "use", "(", "$", "name", ")", "{", "$", "neededLine",...
Update composer json with related information.
[ "Update", "composer", "json", "with", "related", "information", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Commands/RenameCommand.php#L81-L123
train
laravel-zero/framework
src/Commands/RenameCommand.php
RenameCommand.renameBinary
private function renameBinary(string $name): RenameCommand { $this->task( sprintf('Renaming application to "%s"', $name), function () use ($name) { return File::move($this->app->basePath($this->getCurrentBinaryName()), $this->app->basePath($name)); } ); return $this; }
php
private function renameBinary(string $name): RenameCommand { $this->task( sprintf('Renaming application to "%s"', $name), function () use ($name) { return File::move($this->app->basePath($this->getCurrentBinaryName()), $this->app->basePath($name)); } ); return $this; }
[ "private", "function", "renameBinary", "(", "string", "$", "name", ")", ":", "RenameCommand", "{", "$", "this", "->", "task", "(", "sprintf", "(", "'Renaming application to \"%s\"'", ",", "$", "name", ")", ",", "function", "(", ")", "use", "(", "$", "name"...
Renames the application binary.
[ "Renames", "the", "application", "binary", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Commands/RenameCommand.php#L128-L138
train
laravel-zero/framework
src/Commands/RenameCommand.php
RenameCommand.getComposer
private function getComposer(): string { $filePath = $this->app->basePath('composer.json'); if (! File::exists($filePath)) { $this->app->abort(400, 'The file composer.json not found'); } return File::get($filePath); }
php
private function getComposer(): string { $filePath = $this->app->basePath('composer.json'); if (! File::exists($filePath)) { $this->app->abort(400, 'The file composer.json not found'); } return File::get($filePath); }
[ "private", "function", "getComposer", "(", ")", ":", "string", "{", "$", "filePath", "=", "$", "this", "->", "app", "->", "basePath", "(", "'composer.json'", ")", ";", "if", "(", "!", "File", "::", "exists", "(", "$", "filePath", ")", ")", "{", "$", ...
Returns the composer.json file contents.
[ "Returns", "the", "composer", ".", "json", "file", "contents", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Commands/RenameCommand.php#L153-L162
train
laravel-zero/framework
src/Commands/RenameCommand.php
RenameCommand.getConfig
private function getConfig(): string { $filePath = $this->app->configPath('app.php'); if (! File::exists($filePath)) { $this->app->abort(400, 'The file config/app.php not found'); } return File::get($filePath); }
php
private function getConfig(): string { $filePath = $this->app->configPath('app.php'); if (! File::exists($filePath)) { $this->app->abort(400, 'The file config/app.php not found'); } return File::get($filePath); }
[ "private", "function", "getConfig", "(", ")", ":", "string", "{", "$", "filePath", "=", "$", "this", "->", "app", "->", "configPath", "(", "'app.php'", ")", ";", "if", "(", "!", "File", "::", "exists", "(", "$", "filePath", ")", ")", "{", "$", "thi...
Returns the config file contents.
[ "Returns", "the", "config", "file", "contents", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Commands/RenameCommand.php#L167-L176
train
laravel-zero/framework
src/Components/Database/Provider.php
Provider.registerDatabaseService
protected function registerDatabaseService(): void { $this->app->alias('db', \Illuminate\Database\ConnectionResolverInterface::class); $this->app->register(\Illuminate\Database\DatabaseServiceProvider::class); if (File::exists($this->app->databasePath('seeds'))) { collect(File::files($this->app->databasePath('seeds')))->each( function ($file) { File::requireOnce($file); } ); } }
php
protected function registerDatabaseService(): void { $this->app->alias('db', \Illuminate\Database\ConnectionResolverInterface::class); $this->app->register(\Illuminate\Database\DatabaseServiceProvider::class); if (File::exists($this->app->databasePath('seeds'))) { collect(File::files($this->app->databasePath('seeds')))->each( function ($file) { File::requireOnce($file); } ); } }
[ "protected", "function", "registerDatabaseService", "(", ")", ":", "void", "{", "$", "this", "->", "app", "->", "alias", "(", "'db'", ",", "\\", "Illuminate", "\\", "Database", "\\", "ConnectionResolverInterface", "::", "class", ")", ";", "$", "this", "->", ...
Registers the database service. Makes this Capsule Instance available globally via static methods.
[ "Registers", "the", "database", "service", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Components/Database/Provider.php#L85-L97
train
laravel-zero/framework
src/Components/Database/Provider.php
Provider.registerMigrationService
protected function registerMigrationService(): void { $config = $this->app['config']; $config->set('database.migrations', $config->get('database.migrations') ?: 'migrations'); $this->app->register(\Illuminate\Database\MigrationServiceProvider::class); $this->app->alias( 'migration.repository', \Illuminate\Database\Migrations\MigrationRepositoryInterface::class ); $this->app->singleton( 'migrator', function ($app) { $repository = $app['migration.repository']; return new Migrator($repository, $app['db'], $app['files']); } ); $this->app->alias( 'migrator', \Illuminate\Database\Migrations\Migrator::class ); }
php
protected function registerMigrationService(): void { $config = $this->app['config']; $config->set('database.migrations', $config->get('database.migrations') ?: 'migrations'); $this->app->register(\Illuminate\Database\MigrationServiceProvider::class); $this->app->alias( 'migration.repository', \Illuminate\Database\Migrations\MigrationRepositoryInterface::class ); $this->app->singleton( 'migrator', function ($app) { $repository = $app['migration.repository']; return new Migrator($repository, $app['db'], $app['files']); } ); $this->app->alias( 'migrator', \Illuminate\Database\Migrations\Migrator::class ); }
[ "protected", "function", "registerMigrationService", "(", ")", ":", "void", "{", "$", "config", "=", "$", "this", "->", "app", "[", "'config'", "]", ";", "$", "config", "->", "set", "(", "'database.migrations'", ",", "$", "config", "->", "get", "(", "'da...
Registers the migration service.
[ "Registers", "the", "migration", "service", "." ]
9854a8a69809ce011386a58455bc48f76d57681d
https://github.com/laravel-zero/framework/blob/9854a8a69809ce011386a58455bc48f76d57681d/src/Components/Database/Provider.php#L102-L126
train
spatie/nova-tags-field
src/TagsFieldServiceProvider.php
TagsFieldServiceProvider.routes
protected function routes() { if ($this->app->routesAreCached()) { return; } Route::middleware(['nova', 'api', Authorize::class]) ->prefix('nova-vendor/spatie/nova-tags-field') ->group(__DIR__.'/../routes/api.php'); }
php
protected function routes() { if ($this->app->routesAreCached()) { return; } Route::middleware(['nova', 'api', Authorize::class]) ->prefix('nova-vendor/spatie/nova-tags-field') ->group(__DIR__.'/../routes/api.php'); }
[ "protected", "function", "routes", "(", ")", "{", "if", "(", "$", "this", "->", "app", "->", "routesAreCached", "(", ")", ")", "{", "return", ";", "}", "Route", "::", "middleware", "(", "[", "'nova'", ",", "'api'", ",", "Authorize", "::", "class", "]...
Register the field's routes. @return void
[ "Register", "the", "field", "s", "routes", "." ]
c7200839ae08084d1e88460aaca01f84e4af7175
https://github.com/spatie/nova-tags-field/blob/c7200839ae08084d1e88460aaca01f84e4af7175/src/TagsFieldServiceProvider.php#L35-L44
train
microweber/screen
src/Capture.php
Capture.includeJs
public function includeJs($script) { if ($script instanceof Url) { $this->includedJsScripts[] = $script; } else { $this->includedJsSnippets[] = $script; } return $this; }
php
public function includeJs($script) { if ($script instanceof Url) { $this->includedJsScripts[] = $script; } else { $this->includedJsSnippets[] = $script; } return $this; }
[ "public", "function", "includeJs", "(", "$", "script", ")", "{", "if", "(", "$", "script", "instanceof", "Url", ")", "{", "$", "this", "->", "includedJsScripts", "[", "]", "=", "$", "script", ";", "}", "else", "{", "$", "this", "->", "includedJsSnippet...
Adds a JS script or snippet to the screen shot script @param string|URL $script Script to include @return Capture
[ "Adds", "a", "JS", "script", "or", "snippet", "to", "the", "screen", "shot", "script" ]
aa3340654eb200fd97d01aebd1580e61cba5ce51
https://github.com/microweber/screen/blob/aa3340654eb200fd97d01aebd1580e61cba5ce51/src/Capture.php#L585-L594
train
microweber/screen
src/CookieJar.php
CookieJar.load
public function load($file){ $realPath = realpath($file); if (!$realPath || !file_exists($realPath)) { throw new FileNotFoundException($realPath); } $this->cookies = file_get_contents($realPath); }
php
public function load($file){ $realPath = realpath($file); if (!$realPath || !file_exists($realPath)) { throw new FileNotFoundException($realPath); } $this->cookies = file_get_contents($realPath); }
[ "public", "function", "load", "(", "$", "file", ")", "{", "$", "realPath", "=", "realpath", "(", "$", "file", ")", ";", "if", "(", "!", "$", "realPath", "||", "!", "file_exists", "(", "$", "realPath", ")", ")", "{", "throw", "new", "FileNotFoundExcep...
Load cookies from file @param string $file Path to file
[ "Load", "cookies", "from", "file" ]
aa3340654eb200fd97d01aebd1580e61cba5ce51
https://github.com/microweber/screen/blob/aa3340654eb200fd97d01aebd1580e61cba5ce51/src/CookieJar.php#L27-L35
train
microweber/screen
src/Location/Location.php
Location.setLocation
public function setLocation($locationPath) { $locationPath = realpath($locationPath); if (!$locationPath || !is_dir($locationPath)) { throw new \Exception("The directory '$locationPath' does not exist."); } $this->location = $locationPath . DIRECTORY_SEPARATOR; }
php
public function setLocation($locationPath) { $locationPath = realpath($locationPath); if (!$locationPath || !is_dir($locationPath)) { throw new \Exception("The directory '$locationPath' does not exist."); } $this->location = $locationPath . DIRECTORY_SEPARATOR; }
[ "public", "function", "setLocation", "(", "$", "locationPath", ")", "{", "$", "locationPath", "=", "realpath", "(", "$", "locationPath", ")", ";", "if", "(", "!", "$", "locationPath", "||", "!", "is_dir", "(", "$", "locationPath", ")", ")", "{", "throw",...
Sets the files location @param string $path Path to store the files @throws \Exception If the location does not exist @return void
[ "Sets", "the", "files", "location" ]
aa3340654eb200fd97d01aebd1580e61cba5ce51
https://github.com/microweber/screen/blob/aa3340654eb200fd97d01aebd1580e61cba5ce51/src/Location/Location.php#L31-L39
train
microweber/screen
src/Image/Types.php
Types.getClass
public static function getClass($type) { if (!static::isAvailable($type)) { throw new \Exception( "Invalid image format '{$type}'. " . "Allowed formats are: " . implode(', ', static::available()) ); } $className = static::$typesMap[strtolower($type)]; return new $className(); }
php
public static function getClass($type) { if (!static::isAvailable($type)) { throw new \Exception( "Invalid image format '{$type}'. " . "Allowed formats are: " . implode(', ', static::available()) ); } $className = static::$typesMap[strtolower($type)]; return new $className(); }
[ "public", "static", "function", "getClass", "(", "$", "type", ")", "{", "if", "(", "!", "static", "::", "isAvailable", "(", "$", "type", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Invalid image format '{$type}'. \"", ".", "\"Allowed formats are:...
Returns an instance of the requested image type @param string $type Image type @return Type @throws \Exception
[ "Returns", "an", "instance", "of", "the", "requested", "image", "type" ]
aa3340654eb200fd97d01aebd1580e61cba5ce51
https://github.com/microweber/screen/blob/aa3340654eb200fd97d01aebd1580e61cba5ce51/src/Image/Types.php#L48-L60
train
microweber/screen
src/Location/Jobs.php
Jobs.clean
public function clean() { $jobFiles = glob($this->getLocation() . '*.js'); foreach ($jobFiles as $file) { unlink($file); } }
php
public function clean() { $jobFiles = glob($this->getLocation() . '*.js'); foreach ($jobFiles as $file) { unlink($file); } }
[ "public", "function", "clean", "(", ")", "{", "$", "jobFiles", "=", "glob", "(", "$", "this", "->", "getLocation", "(", ")", ".", "'*.js'", ")", ";", "foreach", "(", "$", "jobFiles", "as", "$", "file", ")", "{", "unlink", "(", "$", "file", ")", "...
Deletes all the job files
[ "Deletes", "all", "the", "job", "files" ]
aa3340654eb200fd97d01aebd1580e61cba5ce51
https://github.com/microweber/screen/blob/aa3340654eb200fd97d01aebd1580e61cba5ce51/src/Location/Jobs.php#L30-L36
train
EasyCorp/easy-deploy-bundle
src/Configuration/CustomConfiguration.php
CustomConfiguration.server
public function server(string $sshDsn, array $roles = [Server::ROLE_APP], array $properties = []): self { parent::server($sshDsn, $roles, $properties); return $this; }
php
public function server(string $sshDsn, array $roles = [Server::ROLE_APP], array $properties = []): self { parent::server($sshDsn, $roles, $properties); return $this; }
[ "public", "function", "server", "(", "string", "$", "sshDsn", ",", "array", "$", "roles", "=", "[", "Server", "::", "ROLE_APP", "]", ",", "array", "$", "properties", "=", "[", "]", ")", ":", "self", "{", "parent", "::", "server", "(", "$", "sshDsn", ...
if the parent method is used directly
[ "if", "the", "parent", "method", "is", "used", "directly" ]
f6c45c2c874ba85e0ec584a8942fd796f956a0aa
https://github.com/EasyCorp/easy-deploy-bundle/blob/f6c45c2c874ba85e0ec584a8942fd796f956a0aa/src/Configuration/CustomConfiguration.php#L24-L29
train
EasyCorp/easy-deploy-bundle
src/Configuration/DefaultConfiguration.php
DefaultConfiguration.resetOpCacheFor
public function resetOpCacheFor(string $homepageUrl): self { if (!Str::startsWith($homepageUrl, 'http')) { throw new InvalidConfigurationException(sprintf('The value of %s option must be the valid URL of your homepage (it must start with http:// or https://).', Option::resetOpCacheFor)); } $this->resetOpCacheFor = rtrim($homepageUrl, '/'); return $this; }
php
public function resetOpCacheFor(string $homepageUrl): self { if (!Str::startsWith($homepageUrl, 'http')) { throw new InvalidConfigurationException(sprintf('The value of %s option must be the valid URL of your homepage (it must start with http:// or https://).', Option::resetOpCacheFor)); } $this->resetOpCacheFor = rtrim($homepageUrl, '/'); return $this; }
[ "public", "function", "resetOpCacheFor", "(", "string", "$", "homepageUrl", ")", ":", "self", "{", "if", "(", "!", "Str", "::", "startsWith", "(", "$", "homepageUrl", ",", "'http'", ")", ")", "{", "throw", "new", "InvalidConfigurationException", "(", "sprint...
be deleted from the terminal and deployer must make a HTTP request to a real website URL
[ "be", "deleted", "from", "the", "terminal", "and", "deployer", "must", "make", "a", "HTTP", "request", "to", "a", "real", "website", "URL" ]
f6c45c2c874ba85e0ec584a8942fd796f956a0aa
https://github.com/EasyCorp/easy-deploy-bundle/blob/f6c45c2c874ba85e0ec584a8942fd796f956a0aa/src/Configuration/DefaultConfiguration.php#L351-L360
train
EasyCorp/easy-deploy-bundle
src/Deployer/AbstractDeployer.php
AbstractDeployer.safeDelete
final protected function safeDelete(Server $server, array $absolutePaths): void { $deployDir = $server->get(Property::deploy_dir); $pathsToDelete = []; foreach ($absolutePaths as $path) { if (Str::startsWith($path, $deployDir)) { $pathsToDelete[] = $path; } else { $this->log(sprintf('Skipping the unsafe deletion of "%s" because it\'s not relative to the project directory.', $path)); } } if (empty($pathsToDelete)) { $this->log('There are no paths to delete.'); } $this->runOnServer(sprintf('rm -rf %s', implode(' ', $pathsToDelete)), $server); }
php
final protected function safeDelete(Server $server, array $absolutePaths): void { $deployDir = $server->get(Property::deploy_dir); $pathsToDelete = []; foreach ($absolutePaths as $path) { if (Str::startsWith($path, $deployDir)) { $pathsToDelete[] = $path; } else { $this->log(sprintf('Skipping the unsafe deletion of "%s" because it\'s not relative to the project directory.', $path)); } } if (empty($pathsToDelete)) { $this->log('There are no paths to delete.'); } $this->runOnServer(sprintf('rm -rf %s', implode(' ', $pathsToDelete)), $server); }
[ "final", "protected", "function", "safeDelete", "(", "Server", "$", "server", ",", "array", "$", "absolutePaths", ")", ":", "void", "{", "$", "deployDir", "=", "$", "server", "->", "get", "(", "Property", "::", "deploy_dir", ")", ";", "$", "pathsToDelete",...
related to removing the wrong file or directory on the server.
[ "related", "to", "removing", "the", "wrong", "file", "or", "directory", "on", "the", "server", "." ]
f6c45c2c874ba85e0ec584a8942fd796f956a0aa
https://github.com/EasyCorp/easy-deploy-bundle/blob/f6c45c2c874ba85e0ec584a8942fd796f956a0aa/src/Deployer/AbstractDeployer.php#L192-L209
train
jwilsson/spotify-web-api-php
src/Session.php
Session.refreshAccessToken
public function refreshAccessToken($refreshToken) { $payload = base64_encode($this->getClientId() . ':' . $this->getClientSecret()); $parameters = [ 'grant_type' => 'refresh_token', 'refresh_token' => $refreshToken, ]; $headers = [ 'Authorization' => 'Basic ' . $payload, ]; $response = $this->request->account('POST', '/api/token', $parameters, $headers); $response = $response['body']; if (isset($response->access_token)) { $this->accessToken = $response->access_token; $this->expirationTime = time() + $response->expires_in; $this->scope = isset($response->scope) ? $response->scope : $this->scope; if (isset($response->refresh_token)) { $this->refreshToken = $response->refresh_token; } elseif (empty($this->refreshToken)) { $this->refreshToken = $refreshToken; } return true; } return false; }
php
public function refreshAccessToken($refreshToken) { $payload = base64_encode($this->getClientId() . ':' . $this->getClientSecret()); $parameters = [ 'grant_type' => 'refresh_token', 'refresh_token' => $refreshToken, ]; $headers = [ 'Authorization' => 'Basic ' . $payload, ]; $response = $this->request->account('POST', '/api/token', $parameters, $headers); $response = $response['body']; if (isset($response->access_token)) { $this->accessToken = $response->access_token; $this->expirationTime = time() + $response->expires_in; $this->scope = isset($response->scope) ? $response->scope : $this->scope; if (isset($response->refresh_token)) { $this->refreshToken = $response->refresh_token; } elseif (empty($this->refreshToken)) { $this->refreshToken = $refreshToken; } return true; } return false; }
[ "public", "function", "refreshAccessToken", "(", "$", "refreshToken", ")", "{", "$", "payload", "=", "base64_encode", "(", "$", "this", "->", "getClientId", "(", ")", ".", "':'", ".", "$", "this", "->", "getClientSecret", "(", ")", ")", ";", "$", "parame...
Refresh an access token. @param string $refreshToken The refresh token to use. @return bool Whether the access token was successfully refreshed.
[ "Refresh", "an", "access", "token", "." ]
4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7
https://github.com/jwilsson/spotify-web-api-php/blob/4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7/src/Session.php#L136-L167
train
jwilsson/spotify-web-api-php
src/Session.php
Session.requestCredentialsToken
public function requestCredentialsToken() { $payload = base64_encode($this->getClientId() . ':' . $this->getClientSecret()); $parameters = [ 'grant_type' => 'client_credentials', ]; $headers = [ 'Authorization' => 'Basic ' . $payload, ]; $response = $this->request->account('POST', '/api/token', $parameters, $headers); $response = $response['body']; if (isset($response->access_token)) { $this->accessToken = $response->access_token; $this->expirationTime = time() + $response->expires_in; $this->scope = isset($response->scope) ? $response->scope : $this->scope; return true; } return false; }
php
public function requestCredentialsToken() { $payload = base64_encode($this->getClientId() . ':' . $this->getClientSecret()); $parameters = [ 'grant_type' => 'client_credentials', ]; $headers = [ 'Authorization' => 'Basic ' . $payload, ]; $response = $this->request->account('POST', '/api/token', $parameters, $headers); $response = $response['body']; if (isset($response->access_token)) { $this->accessToken = $response->access_token; $this->expirationTime = time() + $response->expires_in; $this->scope = isset($response->scope) ? $response->scope : $this->scope; return true; } return false; }
[ "public", "function", "requestCredentialsToken", "(", ")", "{", "$", "payload", "=", "base64_encode", "(", "$", "this", "->", "getClientId", "(", ")", ".", "':'", ".", "$", "this", "->", "getClientSecret", "(", ")", ")", ";", "$", "parameters", "=", "[",...
Request an access token using the Client Credentials Flow. @return bool True when an access token was successfully granted, false otherwise.
[ "Request", "an", "access", "token", "using", "the", "Client", "Credentials", "Flow", "." ]
4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7
https://github.com/jwilsson/spotify-web-api-php/blob/4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7/src/Session.php#L174-L198
train
jwilsson/spotify-web-api-php
src/Session.php
Session.requestAccessToken
public function requestAccessToken($authorizationCode) { $parameters = [ 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'code' => $authorizationCode, 'grant_type' => 'authorization_code', 'redirect_uri' => $this->getRedirectUri(), ]; $response = $this->request->account('POST', '/api/token', $parameters, []); $response = $response['body']; if (isset($response->refresh_token) && isset($response->access_token)) { $this->refreshToken = $response->refresh_token; $this->accessToken = $response->access_token; $this->expirationTime = time() + $response->expires_in; $this->scope = isset($response->scope) ? $response->scope : $this->scope; return true; } return false; }
php
public function requestAccessToken($authorizationCode) { $parameters = [ 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'code' => $authorizationCode, 'grant_type' => 'authorization_code', 'redirect_uri' => $this->getRedirectUri(), ]; $response = $this->request->account('POST', '/api/token', $parameters, []); $response = $response['body']; if (isset($response->refresh_token) && isset($response->access_token)) { $this->refreshToken = $response->refresh_token; $this->accessToken = $response->access_token; $this->expirationTime = time() + $response->expires_in; $this->scope = isset($response->scope) ? $response->scope : $this->scope; return true; } return false; }
[ "public", "function", "requestAccessToken", "(", "$", "authorizationCode", ")", "{", "$", "parameters", "=", "[", "'client_id'", "=>", "$", "this", "->", "getClientId", "(", ")", ",", "'client_secret'", "=>", "$", "this", "->", "getClientSecret", "(", ")", "...
Request an access token given an authorization code. @param string $authorizationCode The authorization code from Spotify. @return bool True when the access token was successfully granted, false otherwise.
[ "Request", "an", "access", "token", "given", "an", "authorization", "code", "." ]
4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7
https://github.com/jwilsson/spotify-web-api-php/blob/4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7/src/Session.php#L207-L230
train
jwilsson/spotify-web-api-php
src/SpotifyWebAPI.php
SpotifyWebAPI.idToUri
protected function idToUri($ids, $type) { $type = 'spotify:' . $type . ':'; $ids = array_map(function ($id) use ($type) { if (substr($id, 0, strlen($type)) != $type) { $id = $type . $id; } return $id; }, (array) $ids); return (count($ids) == 1) ? $ids[0] : $ids; }
php
protected function idToUri($ids, $type) { $type = 'spotify:' . $type . ':'; $ids = array_map(function ($id) use ($type) { if (substr($id, 0, strlen($type)) != $type) { $id = $type . $id; } return $id; }, (array) $ids); return (count($ids) == 1) ? $ids[0] : $ids; }
[ "protected", "function", "idToUri", "(", "$", "ids", ",", "$", "type", ")", "{", "$", "type", "=", "'spotify:'", ".", "$", "type", ".", "':'", ";", "$", "ids", "=", "array_map", "(", "function", "(", "$", "id", ")", "use", "(", "$", "type", ")", ...
Convert Spotify object IDs to Spotify URIs. @param array|string $ids ID(s) to convert. @param string $type Spotify object type. @return array|string Spotify URI(s).
[ "Convert", "Spotify", "object", "IDs", "to", "Spotify", "URIs", "." ]
4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7
https://github.com/jwilsson/spotify-web-api-php/blob/4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7/src/SpotifyWebAPI.php#L48-L61
train
jwilsson/spotify-web-api-php
src/SpotifyWebAPI.php
SpotifyWebAPI.uriToId
protected function uriToId($uriIds, $type) { $type = 'spotify:' . $type . ':'; $uriIds = array_map(function ($id) use ($type) { return str_replace($type, '', $id); }, (array) $uriIds); return (count($uriIds) == 1) ? $uriIds[0] : $uriIds; }
php
protected function uriToId($uriIds, $type) { $type = 'spotify:' . $type . ':'; $uriIds = array_map(function ($id) use ($type) { return str_replace($type, '', $id); }, (array) $uriIds); return (count($uriIds) == 1) ? $uriIds[0] : $uriIds; }
[ "protected", "function", "uriToId", "(", "$", "uriIds", ",", "$", "type", ")", "{", "$", "type", "=", "'spotify:'", ".", "$", "type", ".", "':'", ";", "$", "uriIds", "=", "array_map", "(", "function", "(", "$", "id", ")", "use", "(", "$", "type", ...
Convert Spotify URIs to Spotify object IDs @param array|string $uriIds URI(s) to convert. @param string $type Spotify object type. @return array|string Spotify ID(s).
[ "Convert", "Spotify", "URIs", "to", "Spotify", "object", "IDs" ]
4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7
https://github.com/jwilsson/spotify-web-api-php/blob/4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7/src/SpotifyWebAPI.php#L71-L80
train
jwilsson/spotify-web-api-php
src/Request.php
Request.parseBody
protected function parseBody($body, $status) { $this->lastResponse['body'] = json_decode($body, $this->returnType == self::RETURN_ASSOC); if ($status >= 200 && $status <= 299) { return $this->lastResponse['body']; } $body = json_decode($body); $error = isset($body->error) ? $body->error : null; if (isset($error->message) && isset($error->status)) { // API call error throw new SpotifyWebAPIException($error->message, $error->status); } elseif (isset($body->error_description)) { // Auth call error throw new SpotifyWebAPIAuthException($body->error_description, $status); } else { // Something went really wrong throw new SpotifyWebAPIException('An unknown error occurred.', $status); } }
php
protected function parseBody($body, $status) { $this->lastResponse['body'] = json_decode($body, $this->returnType == self::RETURN_ASSOC); if ($status >= 200 && $status <= 299) { return $this->lastResponse['body']; } $body = json_decode($body); $error = isset($body->error) ? $body->error : null; if (isset($error->message) && isset($error->status)) { // API call error throw new SpotifyWebAPIException($error->message, $error->status); } elseif (isset($body->error_description)) { // Auth call error throw new SpotifyWebAPIAuthException($body->error_description, $status); } else { // Something went really wrong throw new SpotifyWebAPIException('An unknown error occurred.', $status); } }
[ "protected", "function", "parseBody", "(", "$", "body", ",", "$", "status", ")", "{", "$", "this", "->", "lastResponse", "[", "'body'", "]", "=", "json_decode", "(", "$", "body", ",", "$", "this", "->", "returnType", "==", "self", "::", "RETURN_ASSOC", ...
Parse the response body and handle API errors. @param string $body The raw, unparsed response body. @param int $status The HTTP status code, used to see if additional error handling is needed. @throws SpotifyWebAPIException @throws SpotifyWebAPIAuthException @return array|object The parsed response body. Type is controlled by `Request::setReturnType()`.
[ "Parse", "the", "response", "body", "and", "handle", "API", "errors", "." ]
4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7
https://github.com/jwilsson/spotify-web-api-php/blob/4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7/src/Request.php#L26-L47
train
jwilsson/spotify-web-api-php
src/Request.php
Request.parseHeaders
protected function parseHeaders($headers) { $headers = str_replace("\r\n", "\n", $headers); $headers = explode("\n", $headers); array_shift($headers); $parsedHeaders = []; foreach ($headers as $header) { list($key, $value) = explode(':', $header, 2); $parsedHeaders[$key] = trim($value); } return $parsedHeaders; }
php
protected function parseHeaders($headers) { $headers = str_replace("\r\n", "\n", $headers); $headers = explode("\n", $headers); array_shift($headers); $parsedHeaders = []; foreach ($headers as $header) { list($key, $value) = explode(':', $header, 2); $parsedHeaders[$key] = trim($value); } return $parsedHeaders; }
[ "protected", "function", "parseHeaders", "(", "$", "headers", ")", "{", "$", "headers", "=", "str_replace", "(", "\"\\r\\n\"", ",", "\"\\n\"", ",", "$", "headers", ")", ";", "$", "headers", "=", "explode", "(", "\"\\n\"", ",", "$", "headers", ")", ";", ...
Parse HTTP response headers. @param string $headers The raw, unparsed response headers. @return array Headers as key–value pairs.
[ "Parse", "HTTP", "response", "headers", "." ]
4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7
https://github.com/jwilsson/spotify-web-api-php/blob/4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7/src/Request.php#L56-L71
train
jwilsson/spotify-web-api-php
src/Request.php
Request.account
public function account($method, $uri, $parameters = [], $headers = []) { return $this->send($method, self::ACCOUNT_URL . $uri, $parameters, $headers); }
php
public function account($method, $uri, $parameters = [], $headers = []) { return $this->send($method, self::ACCOUNT_URL . $uri, $parameters, $headers); }
[ "public", "function", "account", "(", "$", "method", ",", "$", "uri", ",", "$", "parameters", "=", "[", "]", ",", "$", "headers", "=", "[", "]", ")", "{", "return", "$", "this", "->", "send", "(", "$", "method", ",", "self", "::", "ACCOUNT_URL", ...
Make a request to the "account" endpoint. @param string $method The HTTP method to use. @param string $uri The URI to request. @param array $parameters Optional. Query string parameters or HTTP body, depending on $method. @param array $headers Optional. HTTP headers. @throws SpotifyWebAPIException @throws SpotifyWebAPIAuthException @return array Response data. - array|object body The response body. Type is controlled by `Request::setReturnType()`. - array headers Response headers. - int status HTTP status code. - string url The requested URL.
[ "Make", "a", "request", "to", "the", "account", "endpoint", "." ]
4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7
https://github.com/jwilsson/spotify-web-api-php/blob/4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7/src/Request.php#L90-L93
train
jwilsson/spotify-web-api-php
src/Request.php
Request.api
public function api($method, $uri, $parameters = [], $headers = []) { return $this->send($method, self::API_URL . $uri, $parameters, $headers); }
php
public function api($method, $uri, $parameters = [], $headers = []) { return $this->send($method, self::API_URL . $uri, $parameters, $headers); }
[ "public", "function", "api", "(", "$", "method", ",", "$", "uri", ",", "$", "parameters", "=", "[", "]", ",", "$", "headers", "=", "[", "]", ")", "{", "return", "$", "this", "->", "send", "(", "$", "method", ",", "self", "::", "API_URL", ".", "...
Make a request to the "api" endpoint. @param string $method The HTTP method to use. @param string $uri The URI to request. @param array $parameters Optional. Query string parameters or HTTP body, depending on $method. @param array $headers Optional. HTTP headers. @throws SpotifyWebAPIException @throws SpotifyWebAPIAuthException @return array Response data. - array|object body The response body. Type is controlled by `Request::setReturnType()`. - array headers Response headers. - int status HTTP status code. - string url The requested URL.
[ "Make", "a", "request", "to", "the", "api", "endpoint", "." ]
4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7
https://github.com/jwilsson/spotify-web-api-php/blob/4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7/src/Request.php#L112-L115
train
jwilsson/spotify-web-api-php
src/Request.php
Request.send
public function send($method, $url, $parameters = [], $headers = []) { // Reset any old responses $this->lastResponse = []; // Sometimes a stringified JSON object is passed if (is_array($parameters) || is_object($parameters)) { $parameters = http_build_query($parameters); } $mergedHeaders = []; foreach ($headers as $key => $val) { $mergedHeaders[] = "$key: $val"; } $options = [ CURLOPT_CAINFO => __DIR__ . '/cacert.pem', CURLOPT_ENCODING => '', CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => $mergedHeaders, CURLOPT_RETURNTRANSFER => true, ]; $url = rtrim($url, '/'); $method = strtoupper($method); switch ($method) { case 'DELETE': // No break case 'PUT': $options[CURLOPT_CUSTOMREQUEST] = $method; $options[CURLOPT_POSTFIELDS] = $parameters; break; case 'POST': $options[CURLOPT_POST] = true; $options[CURLOPT_POSTFIELDS] = $parameters; break; default: $options[CURLOPT_CUSTOMREQUEST] = $method; if ($parameters) { $url .= '/?' . $parameters; } break; } $options[CURLOPT_URL] = $url; $ch = curl_init(); curl_setopt_array($ch, $options); $response = curl_exec($ch); if (curl_error($ch)) { throw new SpotifyWebAPIException('cURL transport error: ' . curl_errno($ch) . ' ' . curl_error($ch)); } list($headers, $body) = explode("\r\n\r\n", $response, 2); // Skip the first set of headers for proxied requests if (preg_match('/^HTTP\/1\.\d 200 Connection established$/', $headers) === 1) { list($headers, $body) = explode("\r\n\r\n", $body, 2); } $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); $headers = $this->parseHeaders($headers); $this->lastResponse = [ 'headers' => $headers, 'status' => $status, 'url' => $url, ]; // Run this here since we might throw $body = $this->parseBody($body, $status); curl_close($ch); return $this->lastResponse; }
php
public function send($method, $url, $parameters = [], $headers = []) { // Reset any old responses $this->lastResponse = []; // Sometimes a stringified JSON object is passed if (is_array($parameters) || is_object($parameters)) { $parameters = http_build_query($parameters); } $mergedHeaders = []; foreach ($headers as $key => $val) { $mergedHeaders[] = "$key: $val"; } $options = [ CURLOPT_CAINFO => __DIR__ . '/cacert.pem', CURLOPT_ENCODING => '', CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => $mergedHeaders, CURLOPT_RETURNTRANSFER => true, ]; $url = rtrim($url, '/'); $method = strtoupper($method); switch ($method) { case 'DELETE': // No break case 'PUT': $options[CURLOPT_CUSTOMREQUEST] = $method; $options[CURLOPT_POSTFIELDS] = $parameters; break; case 'POST': $options[CURLOPT_POST] = true; $options[CURLOPT_POSTFIELDS] = $parameters; break; default: $options[CURLOPT_CUSTOMREQUEST] = $method; if ($parameters) { $url .= '/?' . $parameters; } break; } $options[CURLOPT_URL] = $url; $ch = curl_init(); curl_setopt_array($ch, $options); $response = curl_exec($ch); if (curl_error($ch)) { throw new SpotifyWebAPIException('cURL transport error: ' . curl_errno($ch) . ' ' . curl_error($ch)); } list($headers, $body) = explode("\r\n\r\n", $response, 2); // Skip the first set of headers for proxied requests if (preg_match('/^HTTP\/1\.\d 200 Connection established$/', $headers) === 1) { list($headers, $body) = explode("\r\n\r\n", $body, 2); } $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); $headers = $this->parseHeaders($headers); $this->lastResponse = [ 'headers' => $headers, 'status' => $status, 'url' => $url, ]; // Run this here since we might throw $body = $this->parseBody($body, $status); curl_close($ch); return $this->lastResponse; }
[ "public", "function", "send", "(", "$", "method", ",", "$", "url", ",", "$", "parameters", "=", "[", "]", ",", "$", "headers", "=", "[", "]", ")", "{", "// Reset any old responses", "$", "this", "->", "lastResponse", "=", "[", "]", ";", "// Sometimes a...
Make a request to Spotify. You'll probably want to use one of the convenience methods instead. @param string $method The HTTP method to use. @param string $url The URL to request. @param array $parameters Optional. Query string parameters or HTTP body, depending on $method. @param array $headers Optional. HTTP headers. @throws SpotifyWebAPIException @throws SpotifyWebAPIAuthException @return array Response data. - array|object body The response body. Type is controlled by `Request::setReturnType()`. - array headers Response headers. - int status HTTP status code. - string url The requested URL.
[ "Make", "a", "request", "to", "Spotify", ".", "You", "ll", "probably", "want", "to", "use", "one", "of", "the", "convenience", "methods", "instead", "." ]
4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7
https://github.com/jwilsson/spotify-web-api-php/blob/4937bd7fd8edd132debdf5ba49ca8cf4c50a1fe7/src/Request.php#L159-L240
train
slimphp/Twig-View
src/Twig.php
Twig.fetchBlock
public function fetchBlock($template, $block, $data = []) { $data = array_merge($this->defaultVariables, $data); return $this->environment->loadTemplate($template)->renderBlock($block, $data); }
php
public function fetchBlock($template, $block, $data = []) { $data = array_merge($this->defaultVariables, $data); return $this->environment->loadTemplate($template)->renderBlock($block, $data); }
[ "public", "function", "fetchBlock", "(", "$", "template", ",", "$", "block", ",", "$", "data", "=", "[", "]", ")", "{", "$", "data", "=", "array_merge", "(", "$", "this", "->", "defaultVariables", ",", "$", "data", ")", ";", "return", "$", "this", ...
Fetch rendered block @param string $template Template pathname relative to templates directory @param string $block Name of the block within the template @param array $data Associative array of template variables @return string
[ "Fetch", "rendered", "block" ]
06ef39b58d60b11a9546893fd0b7fff2bd901798
https://github.com/slimphp/Twig-View/blob/06ef39b58d60b11a9546893fd0b7fff2bd901798/src/Twig.php#L104-L109
train
slimphp/Twig-View
src/Twig.php
Twig.fetchFromString
public function fetchFromString($string ="", $data = []) { $data = array_merge($this->defaultVariables, $data); return $this->environment->createTemplate($string)->render($data); }
php
public function fetchFromString($string ="", $data = []) { $data = array_merge($this->defaultVariables, $data); return $this->environment->createTemplate($string)->render($data); }
[ "public", "function", "fetchFromString", "(", "$", "string", "=", "\"\"", ",", "$", "data", "=", "[", "]", ")", "{", "$", "data", "=", "array_merge", "(", "$", "this", "->", "defaultVariables", ",", "$", "data", ")", ";", "return", "$", "this", "->",...
Fetch rendered string @param string $string String @param array $data Associative array of template variables @return string
[ "Fetch", "rendered", "string" ]
06ef39b58d60b11a9546893fd0b7fff2bd901798
https://github.com/slimphp/Twig-View/blob/06ef39b58d60b11a9546893fd0b7fff2bd901798/src/Twig.php#L119-L124
train
slimphp/Twig-View
src/Twig.php
Twig.render
public function render(ResponseInterface $response, $template, $data = []) { $response->getBody()->write($this->fetch($template, $data)); return $response; }
php
public function render(ResponseInterface $response, $template, $data = []) { $response->getBody()->write($this->fetch($template, $data)); return $response; }
[ "public", "function", "render", "(", "ResponseInterface", "$", "response", ",", "$", "template", ",", "$", "data", "=", "[", "]", ")", "{", "$", "response", "->", "getBody", "(", ")", "->", "write", "(", "$", "this", "->", "fetch", "(", "$", "templat...
Output rendered template @param ResponseInterface $response @param string $template Template pathname relative to templates directory @param array $data Associative array of template variables @return ResponseInterface
[ "Output", "rendered", "template" ]
06ef39b58d60b11a9546893fd0b7fff2bd901798
https://github.com/slimphp/Twig-View/blob/06ef39b58d60b11a9546893fd0b7fff2bd901798/src/Twig.php#L134-L139
train
slimphp/Twig-View
src/Twig.php
Twig.createLoader
private function createLoader(array $paths) { $loader = new \Twig\Loader\FilesystemLoader(); foreach ($paths as $namespace => $path) { if (is_string($namespace)) { $loader->setPaths($path, $namespace); } else { $loader->addPath($path); } } return $loader; }
php
private function createLoader(array $paths) { $loader = new \Twig\Loader\FilesystemLoader(); foreach ($paths as $namespace => $path) { if (is_string($namespace)) { $loader->setPaths($path, $namespace); } else { $loader->addPath($path); } } return $loader; }
[ "private", "function", "createLoader", "(", "array", "$", "paths", ")", "{", "$", "loader", "=", "new", "\\", "Twig", "\\", "Loader", "\\", "FilesystemLoader", "(", ")", ";", "foreach", "(", "$", "paths", "as", "$", "namespace", "=>", "$", "path", ")",...
Create a loader with the given path @param array $paths @return \Twig\Loader\FilesystemLoader
[ "Create", "a", "loader", "with", "the", "given", "path" ]
06ef39b58d60b11a9546893fd0b7fff2bd901798
https://github.com/slimphp/Twig-View/blob/06ef39b58d60b11a9546893fd0b7fff2bd901798/src/Twig.php#L147-L160
train
slimphp/Twig-View
src/TwigExtension.php
TwigExtension.fullUrlFor
public function fullUrlFor($name, $data = [], $queryParams = [], $appName = 'default') { $path = $this->pathFor($name, $data, $queryParams, $appName); /** @var Uri $uri */ if (is_string($this->uri)) { $uri = Uri::createFromString($this->uri); } else { $uri = $this->uri; } $scheme = $uri->getScheme(); $authority = $uri->getAuthority(); $host = ($scheme ? $scheme . ':' : '') . ($authority ? '//' . $authority : ''); return $host.$path; }
php
public function fullUrlFor($name, $data = [], $queryParams = [], $appName = 'default') { $path = $this->pathFor($name, $data, $queryParams, $appName); /** @var Uri $uri */ if (is_string($this->uri)) { $uri = Uri::createFromString($this->uri); } else { $uri = $this->uri; } $scheme = $uri->getScheme(); $authority = $uri->getAuthority(); $host = ($scheme ? $scheme . ':' : '') . ($authority ? '//' . $authority : ''); return $host.$path; }
[ "public", "function", "fullUrlFor", "(", "$", "name", ",", "$", "data", "=", "[", "]", ",", "$", "queryParams", "=", "[", "]", ",", "$", "appName", "=", "'default'", ")", "{", "$", "path", "=", "$", "this", "->", "pathFor", "(", "$", "name", ",",...
Similar to pathFor but returns a fully qualified URL @param string $name The name of the route @param array $data Route placeholders @param array $queryParams @param string $appName @return string fully qualified URL
[ "Similar", "to", "pathFor", "but", "returns", "a", "fully", "qualified", "URL" ]
06ef39b58d60b11a9546893fd0b7fff2bd901798
https://github.com/slimphp/Twig-View/blob/06ef39b58d60b11a9546893fd0b7fff2bd901798/src/TwigExtension.php#L61-L79
train
slimphp/Twig-View
src/TwigExtension.php
TwigExtension.currentPath
public function currentPath($withQueryString = false) { if (is_string($this->uri)) { return $this->uri; } $path = $this->uri->getBasePath() . '/' . ltrim($this->uri->getPath(), '/'); if ($withQueryString && '' !== $query = $this->uri->getQuery()) { $path .= '?' . $query; } return $path; }
php
public function currentPath($withQueryString = false) { if (is_string($this->uri)) { return $this->uri; } $path = $this->uri->getBasePath() . '/' . ltrim($this->uri->getPath(), '/'); if ($withQueryString && '' !== $query = $this->uri->getQuery()) { $path .= '?' . $query; } return $path; }
[ "public", "function", "currentPath", "(", "$", "withQueryString", "=", "false", ")", "{", "if", "(", "is_string", "(", "$", "this", "->", "uri", ")", ")", "{", "return", "$", "this", "->", "uri", ";", "}", "$", "path", "=", "$", "this", "->", "uri"...
Returns current path on given URI. @param bool $withQueryString @return string
[ "Returns", "current", "path", "on", "given", "URI", "." ]
06ef39b58d60b11a9546893fd0b7fff2bd901798
https://github.com/slimphp/Twig-View/blob/06ef39b58d60b11a9546893fd0b7fff2bd901798/src/TwigExtension.php#L102-L115
train
ethanhann/redisearch-php
src/Suggestion.php
Suggestion.add
public function add(string $string, float $score, bool $increment = false, $payload = null) { $args = [ $this->indexName, $string, $score ]; if ($increment) { $args[] = 'INC'; } if (!is_null($payload)) { $args[] = 'PAYLOAD'; $args[] = $payload; } return $this->redisClient->rawCommand('FT.SUGADD', $args); }
php
public function add(string $string, float $score, bool $increment = false, $payload = null) { $args = [ $this->indexName, $string, $score ]; if ($increment) { $args[] = 'INC'; } if (!is_null($payload)) { $args[] = 'PAYLOAD'; $args[] = $payload; } return $this->redisClient->rawCommand('FT.SUGADD', $args); }
[ "public", "function", "add", "(", "string", "$", "string", ",", "float", "$", "score", ",", "bool", "$", "increment", "=", "false", ",", "$", "payload", "=", "null", ")", "{", "$", "args", "=", "[", "$", "this", "->", "indexName", ",", "$", "string...
Add a suggestion string to an auto-complete suggestion dictionary. This is disconnected from the index definitions, and leaves creating and updating suggestion dictionaries to the user. @param string $string @param float $score @param bool $increment @param null $payload @return int
[ "Add", "a", "suggestion", "string", "to", "an", "auto", "-", "complete", "suggestion", "dictionary", ".", "This", "is", "disconnected", "from", "the", "index", "definitions", "and", "leaves", "creating", "and", "updating", "suggestion", "dictionaries", "to", "th...
b3c9ed043753b2d63e1c5ad032cddaa2a63133b6
https://github.com/ethanhann/redisearch-php/blob/b3c9ed043753b2d63e1c5ad032cddaa2a63133b6/src/Suggestion.php#L18-L33
train
ethanhann/redisearch-php
src/Suggestion.php
Suggestion.delete
public function delete(string $string): bool { return $this->redisClient->rawCommand('FT.SUGDEL', [$this->indexName, $string]) === 1; }
php
public function delete(string $string): bool { return $this->redisClient->rawCommand('FT.SUGDEL', [$this->indexName, $string]) === 1; }
[ "public", "function", "delete", "(", "string", "$", "string", ")", ":", "bool", "{", "return", "$", "this", "->", "redisClient", "->", "rawCommand", "(", "'FT.SUGDEL'", ",", "[", "$", "this", "->", "indexName", ",", "$", "string", "]", ")", "===", "1",...
Delete a string from a suggestion index. @param string $string @return bool
[ "Delete", "a", "string", "from", "a", "suggestion", "index", "." ]
b3c9ed043753b2d63e1c5ad032cddaa2a63133b6
https://github.com/ethanhann/redisearch-php/blob/b3c9ed043753b2d63e1c5ad032cddaa2a63133b6/src/Suggestion.php#L41-L44
train
ethanhann/redisearch-php
src/Suggestion.php
Suggestion.get
public function get(string $prefix, bool $fuzzy = false, bool $withPayloads = false, int $max = -1): array { $args = [ $this->indexName, $prefix, ]; if ($fuzzy) { $args[] = 'FUZZY'; } if ($withPayloads) { $args[] = 'WITHPAYLOADS'; } if ($max >= 0) { $args[] = 'MAX'; $args[] = $max; } return $this->redisClient->rawCommand('FT.SUGGET', $args); }
php
public function get(string $prefix, bool $fuzzy = false, bool $withPayloads = false, int $max = -1): array { $args = [ $this->indexName, $prefix, ]; if ($fuzzy) { $args[] = 'FUZZY'; } if ($withPayloads) { $args[] = 'WITHPAYLOADS'; } if ($max >= 0) { $args[] = 'MAX'; $args[] = $max; } return $this->redisClient->rawCommand('FT.SUGGET', $args); }
[ "public", "function", "get", "(", "string", "$", "prefix", ",", "bool", "$", "fuzzy", "=", "false", ",", "bool", "$", "withPayloads", "=", "false", ",", "int", "$", "max", "=", "-", "1", ")", ":", "array", "{", "$", "args", "=", "[", "$", "this",...
Get completion suggestions for a prefix. @param string $prefix @param bool $fuzzy @param bool $withPayloads @param int $max @return array
[ "Get", "completion", "suggestions", "for", "a", "prefix", "." ]
b3c9ed043753b2d63e1c5ad032cddaa2a63133b6
https://github.com/ethanhann/redisearch-php/blob/b3c9ed043753b2d63e1c5ad032cddaa2a63133b6/src/Suggestion.php#L65-L82
train
phpWhois/phpWhois
src/Utils.php
Utils.debugObject
public function debugObject($obj, $indent = 0) { if (is_array($obj)) { $return = ''; foreach ($obj as $k => $v) { $return .= str_repeat('&nbsp;', $indent); if (is_array($v)) { $return .= $k . "->Array\n"; $return .= $this->debugObject($v, $indent + 1); } else { $return .= $k . "->$v\n"; } } return $return; } }
php
public function debugObject($obj, $indent = 0) { if (is_array($obj)) { $return = ''; foreach ($obj as $k => $v) { $return .= str_repeat('&nbsp;', $indent); if (is_array($v)) { $return .= $k . "->Array\n"; $return .= $this->debugObject($v, $indent + 1); } else { $return .= $k . "->$v\n"; } } return $return; } }
[ "public", "function", "debugObject", "(", "$", "obj", ",", "$", "indent", "=", "0", ")", "{", "if", "(", "is_array", "(", "$", "obj", ")", ")", "{", "$", "return", "=", "''", ";", "foreach", "(", "$", "obj", "as", "$", "k", "=>", "$", "v", ")...
Return object or array as formatted string @param $obj @param int $indent @return string
[ "Return", "object", "or", "array", "as", "formatted", "string" ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/Utils.php#L49-L64
train
phpWhois/phpWhois
src/Utils.php
Utils.showHTML
public function showHTML($result, $link_myself = true, $params = 'query=$0&amp;output=nice') { // adds links for HTML output $email_regex = "/([-_\w\.]+)(@)([-_\w\.]+)\b/i"; $html_regex = "/(?:^|\b)((((http|https|ftp):\/\/)|(www\.))([\w\.]+)([,:%#&\/?~=\w+\.-]+))(?:\b|$)/is"; $ip_regex = "/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/i"; $out = ''; $lempty = true; foreach ($result['rawdata'] as $line) { $line = trim($line); if ($line == '') { if ($lempty) { continue; } else { $lempty = true; } } else { $lempty = false; } $out .= $line . "\n"; } if ($lempty) { $out = trim($out); } $out = strip_tags($out); $out = preg_replace($email_regex, '<a href="mailto:$0">$0</a>', $out); $out = preg_replace_callback( $html_regex, function ($matches) { if (substr($matches[0], 0, 4) == 'www.') { $web = $matches[0]; $url = 'http://' . $web; } else { $web = $matches[0]; $url = $web; } return '<a href="' . $url . '" target="_blank">' . $web . '</a>'; }, $out ); if ($link_myself) { if ($params[0] == '/') { $link = $params; } else { $link = $_SERVER['PHP_SELF'] . '?' . $params; } $out = preg_replace($ip_regex, '<a href="' . $link . '">$0</a>', $out); if (isset($result['regrinfo']['domain']['nserver'])) { $nserver = $result['regrinfo']['domain']['nserver']; } else { $nserver = false; } if (isset($result['regrinfo']['network']['nserver'])) { $nserver = $result['regrinfo']['network']['nserver']; } if (is_array($nserver)) { reset($nserver); while (list($host, $ip) = each($nserver)) { $url = '<a href="' . str_replace('$0', $ip, $link) . "\">$host</a>"; $out = str_replace($host, $url, $out); $out = str_replace(strtoupper($host), $url, $out); } } } // Add bold field names $out = preg_replace("/(?m)^([-\s\.&;'\w\t\(\)\/]+:\s*)/", '<b>$1</b>', $out); // Add italics for disclaimer $out = preg_replace("/(?m)^(%.*)/", '<i>$0</i>', $out); return str_replace("\n", "<br/>\n", $out); }
php
public function showHTML($result, $link_myself = true, $params = 'query=$0&amp;output=nice') { // adds links for HTML output $email_regex = "/([-_\w\.]+)(@)([-_\w\.]+)\b/i"; $html_regex = "/(?:^|\b)((((http|https|ftp):\/\/)|(www\.))([\w\.]+)([,:%#&\/?~=\w+\.-]+))(?:\b|$)/is"; $ip_regex = "/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/i"; $out = ''; $lempty = true; foreach ($result['rawdata'] as $line) { $line = trim($line); if ($line == '') { if ($lempty) { continue; } else { $lempty = true; } } else { $lempty = false; } $out .= $line . "\n"; } if ($lempty) { $out = trim($out); } $out = strip_tags($out); $out = preg_replace($email_regex, '<a href="mailto:$0">$0</a>', $out); $out = preg_replace_callback( $html_regex, function ($matches) { if (substr($matches[0], 0, 4) == 'www.') { $web = $matches[0]; $url = 'http://' . $web; } else { $web = $matches[0]; $url = $web; } return '<a href="' . $url . '" target="_blank">' . $web . '</a>'; }, $out ); if ($link_myself) { if ($params[0] == '/') { $link = $params; } else { $link = $_SERVER['PHP_SELF'] . '?' . $params; } $out = preg_replace($ip_regex, '<a href="' . $link . '">$0</a>', $out); if (isset($result['regrinfo']['domain']['nserver'])) { $nserver = $result['regrinfo']['domain']['nserver']; } else { $nserver = false; } if (isset($result['regrinfo']['network']['nserver'])) { $nserver = $result['regrinfo']['network']['nserver']; } if (is_array($nserver)) { reset($nserver); while (list($host, $ip) = each($nserver)) { $url = '<a href="' . str_replace('$0', $ip, $link) . "\">$host</a>"; $out = str_replace($host, $url, $out); $out = str_replace(strtoupper($host), $url, $out); } } } // Add bold field names $out = preg_replace("/(?m)^([-\s\.&;'\w\t\(\)\/]+:\s*)/", '<b>$1</b>', $out); // Add italics for disclaimer $out = preg_replace("/(?m)^(%.*)/", '<i>$0</i>', $out); return str_replace("\n", "<br/>\n", $out); }
[ "public", "function", "showHTML", "(", "$", "result", ",", "$", "link_myself", "=", "true", ",", "$", "params", "=", "'query=$0&amp;output=nice'", ")", "{", "// adds links for HTML output", "$", "email_regex", "=", "\"/([-_\\w\\.]+)(@)([-_\\w\\.]+)\\b/i\"", ";", "$", ...
Get nice HTML output
[ "Get", "nice", "HTML", "output" ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/Utils.php#L74-L160
train
phpWhois/phpWhois
src/Whois.php
Whois.checkDns
public function checkDns(&$result) { if ($this->deepWhois && empty($result['regrinfo']['domain']['nserver'])) { $ns = @dns_get_record($this->query['query'], DNS_NS); if (!is_array($ns)) { return; } $nserver = array(); foreach ($ns as $row) { $nserver[] = $row['target']; } if (count($nserver) > 0) { $result['regrinfo']['domain']['nserver'] = $this->fixNameServer($nserver); } } }
php
public function checkDns(&$result) { if ($this->deepWhois && empty($result['regrinfo']['domain']['nserver'])) { $ns = @dns_get_record($this->query['query'], DNS_NS); if (!is_array($ns)) { return; } $nserver = array(); foreach ($ns as $row) { $nserver[] = $row['target']; } if (count($nserver) > 0) { $result['regrinfo']['domain']['nserver'] = $this->fixNameServer($nserver); } } }
[ "public", "function", "checkDns", "(", "&", "$", "result", ")", "{", "if", "(", "$", "this", "->", "deepWhois", "&&", "empty", "(", "$", "result", "[", "'regrinfo'", "]", "[", "'domain'", "]", "[", "'nserver'", "]", ")", ")", "{", "$", "ns", "=", ...
Get nameservers if missing
[ "Get", "nameservers", "if", "missing" ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/Whois.php#L261-L276
train
phpWhois/phpWhois
src/Whois.php
Whois.getQueryType
public function getQueryType($query) { $ipTools = new IpTools; if ($ipTools->validIp($query, 'ipv4', false)) { if ($ipTools->validIp($query, 'ipv4')) { return self::QTYPE_IPV4; } else { return self::QTYPE_UNKNOWN; } } elseif ($ipTools->validIp($query, 'ipv6', false)) { if ($ipTools->validIp($query, 'ipv6')) { return self::QTYPE_IPV6; } else { return self::QTYPE_UNKNOWN; } } elseif (!empty($query) && strpos($query, '.') !== false) { return self::QTYPE_DOMAIN; } elseif (!empty($query) && strpos($query, '.') === false) { return self::QTYPE_AS; } else { return self::QTYPE_UNKNOWN; } }
php
public function getQueryType($query) { $ipTools = new IpTools; if ($ipTools->validIp($query, 'ipv4', false)) { if ($ipTools->validIp($query, 'ipv4')) { return self::QTYPE_IPV4; } else { return self::QTYPE_UNKNOWN; } } elseif ($ipTools->validIp($query, 'ipv6', false)) { if ($ipTools->validIp($query, 'ipv6')) { return self::QTYPE_IPV6; } else { return self::QTYPE_UNKNOWN; } } elseif (!empty($query) && strpos($query, '.') !== false) { return self::QTYPE_DOMAIN; } elseif (!empty($query) && strpos($query, '.') === false) { return self::QTYPE_AS; } else { return self::QTYPE_UNKNOWN; } }
[ "public", "function", "getQueryType", "(", "$", "query", ")", "{", "$", "ipTools", "=", "new", "IpTools", ";", "if", "(", "$", "ipTools", "->", "validIp", "(", "$", "query", ",", "'ipv4'", ",", "false", ")", ")", "{", "if", "(", "$", "ipTools", "->...
Guess query type @param string $query @return int Query type
[ "Guess", "query", "type" ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/Whois.php#L312-L335
train
phpWhois/phpWhois
src/IpTools.php
IpTools.validIp
public function validIp($ip, $type = 'any', $strict = true) { switch ($type) { case 'any': return $this->validIpv4($ip, $strict) || $this->validIpv6($ip, $strict); break; case 'ipv4': return $this->validIpv4($ip, $strict); break; case 'ipv6': return $this->validIpv6($ip, $strict); break; } return false; }
php
public function validIp($ip, $type = 'any', $strict = true) { switch ($type) { case 'any': return $this->validIpv4($ip, $strict) || $this->validIpv6($ip, $strict); break; case 'ipv4': return $this->validIpv4($ip, $strict); break; case 'ipv6': return $this->validIpv6($ip, $strict); break; } return false; }
[ "public", "function", "validIp", "(", "$", "ip", ",", "$", "type", "=", "'any'", ",", "$", "strict", "=", "true", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "'any'", ":", "return", "$", "this", "->", "validIpv4", "(", "$", "ip", ",",...
Check if ip address is valid @param string $ip IP address for validation @param string $type Type of ip address. Possible value are: any, ipv4, ipv6 @param boolean $strict If true - fail validation on reserved and private ip ranges @return boolean True if ip is valid. False otherwise
[ "Check", "if", "ip", "address", "is", "valid" ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/IpTools.php#L41-L55
train
phpWhois/phpWhois
src/IpTools.php
IpTools.validIpv4
public function validIpv4($ip, $strict = true) { $flags = FILTER_FLAG_IPV4; if ($strict) { $flags = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE; } if (filter_var($ip, FILTER_VALIDATE_IP, array('flags' => $flags)) !== false) { return true; } return false; }
php
public function validIpv4($ip, $strict = true) { $flags = FILTER_FLAG_IPV4; if ($strict) { $flags = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE; } if (filter_var($ip, FILTER_VALIDATE_IP, array('flags' => $flags)) !== false) { return true; } return false; }
[ "public", "function", "validIpv4", "(", "$", "ip", ",", "$", "strict", "=", "true", ")", "{", "$", "flags", "=", "FILTER_FLAG_IPV4", ";", "if", "(", "$", "strict", ")", "{", "$", "flags", "=", "FILTER_FLAG_IPV4", "|", "FILTER_FLAG_NO_PRIV_RANGE", "|", "F...
Check if given IP is valid ipv4 address and doesn't belong to private and reserved ranges @param string $ip Ip address @param boolean $strict If true - fail validation on reserved and private ip ranges @return boolean
[ "Check", "if", "given", "IP", "is", "valid", "ipv4", "address", "and", "doesn", "t", "belong", "to", "private", "and", "reserved", "ranges" ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/IpTools.php#L66-L77
train
phpWhois/phpWhois
src/IpTools.php
IpTools.validIpv6
public function validIpv6($ip, $strict = true) { $flags = FILTER_FLAG_IPV6; if ($strict) { $flags = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE; } if (filter_var($ip, FILTER_VALIDATE_IP, array('flags' => $flags)) !== false) { return true; } return false; }
php
public function validIpv6($ip, $strict = true) { $flags = FILTER_FLAG_IPV6; if ($strict) { $flags = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE; } if (filter_var($ip, FILTER_VALIDATE_IP, array('flags' => $flags)) !== false) { return true; } return false; }
[ "public", "function", "validIpv6", "(", "$", "ip", ",", "$", "strict", "=", "true", ")", "{", "$", "flags", "=", "FILTER_FLAG_IPV6", ";", "if", "(", "$", "strict", ")", "{", "$", "flags", "=", "FILTER_FLAG_IPV6", "|", "FILTER_FLAG_NO_PRIV_RANGE", ";", "}...
Check if given IP is valid ipv6 address and doesn't belong to private ranges @param string $ip Ip address @param boolean $strict If true - fail validation on reserved and private ip ranges @return boolean
[ "Check", "if", "given", "IP", "is", "valid", "ipv6", "address", "and", "doesn", "t", "belong", "to", "private", "ranges" ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/IpTools.php#L87-L99
train
phpWhois/phpWhois
src/IpTools.php
IpTools.getClientIp
public function getClientIp() { if (!empty($_SERVER['HTTP_CLIENT_IP']) && $this->validIp($_SERVER['HTTP_CLIENT_IP'])) { return $_SERVER['HTTP_CLIENT_IP']; } if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { foreach (explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']) as $ip) { if ($this->validIp(trim($ip))) { return trim($ip); } } } if (!empty($_SERVER['HTTP_X_FORWARDED']) && $this->validIp($_SERVER['HTTP_X_FORWARDED'])) { return $_SERVER['HTTP_X_FORWARDED']; } if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && $this->validIp($_SERVER['HTTP_FORWARDED_FOR'])) { return $_SERVER['HTTP_FORWARDED_FOR']; } if (!empty($_SERVER['HTTP_FORWARDED']) && $this->validIp($_SERVER['HTTP_FORWARDED'])) { return $_SERVER['HTTP_FORWARDED']; } return $_SERVER['REMOTE_ADDR']; }
php
public function getClientIp() { if (!empty($_SERVER['HTTP_CLIENT_IP']) && $this->validIp($_SERVER['HTTP_CLIENT_IP'])) { return $_SERVER['HTTP_CLIENT_IP']; } if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { foreach (explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']) as $ip) { if ($this->validIp(trim($ip))) { return trim($ip); } } } if (!empty($_SERVER['HTTP_X_FORWARDED']) && $this->validIp($_SERVER['HTTP_X_FORWARDED'])) { return $_SERVER['HTTP_X_FORWARDED']; } if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && $this->validIp($_SERVER['HTTP_FORWARDED_FOR'])) { return $_SERVER['HTTP_FORWARDED_FOR']; } if (!empty($_SERVER['HTTP_FORWARDED']) && $this->validIp($_SERVER['HTTP_FORWARDED'])) { return $_SERVER['HTTP_FORWARDED']; } return $_SERVER['REMOTE_ADDR']; }
[ "public", "function", "getClientIp", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "_SERVER", "[", "'HTTP_CLIENT_IP'", "]", ")", "&&", "$", "this", "->", "validIp", "(", "$", "_SERVER", "[", "'HTTP_CLIENT_IP'", "]", ")", ")", "{", "return", "$", ...
Try to get real IP from client web request @return string
[ "Try", "to", "get", "real", "IP", "from", "client", "web", "request" ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/IpTools.php#L106-L133
train
phpWhois/phpWhois
src/IpTools.php
IpTools.cidrConv
public function cidrConv($net) { $start = strtok($net, '/'); $n = 3 - substr_count($net, '.'); if ($n > 0) { for ($i = $n; $i > 0; $i--) { $start .= '.0'; } } $bits1 = str_pad(decbin(ip2long($start)), 32, '0', 'STR_PAD_LEFT'); $net = pow(2, (32 - substr(strstr($net, '/'), 1))) - 1; $bits2 = str_pad(decbin($net), 32, '0', 'STR_PAD_LEFT'); $final = ''; for ($i = 0; $i < 32; $i++) { if ($bits1[$i] == $bits2[$i]) { $final .= $bits1[$i]; } if ($bits1[$i] == 1 and $bits2[$i] == 0) { $final .= $bits1[$i]; } if ($bits1[$i] == 0 and $bits2[$i] == 1) { $final .= $bits2[$i]; } } return $start . " - " . long2ip(bindec($final)); }
php
public function cidrConv($net) { $start = strtok($net, '/'); $n = 3 - substr_count($net, '.'); if ($n > 0) { for ($i = $n; $i > 0; $i--) { $start .= '.0'; } } $bits1 = str_pad(decbin(ip2long($start)), 32, '0', 'STR_PAD_LEFT'); $net = pow(2, (32 - substr(strstr($net, '/'), 1))) - 1; $bits2 = str_pad(decbin($net), 32, '0', 'STR_PAD_LEFT'); $final = ''; for ($i = 0; $i < 32; $i++) { if ($bits1[$i] == $bits2[$i]) { $final .= $bits1[$i]; } if ($bits1[$i] == 1 and $bits2[$i] == 0) { $final .= $bits1[$i]; } if ($bits1[$i] == 0 and $bits2[$i] == 1) { $final .= $bits2[$i]; } } return $start . " - " . long2ip(bindec($final)); }
[ "public", "function", "cidrConv", "(", "$", "net", ")", "{", "$", "start", "=", "strtok", "(", "$", "net", ",", "'/'", ")", ";", "$", "n", "=", "3", "-", "substr_count", "(", "$", "net", ",", "'.'", ")", ";", "if", "(", "$", "n", ">", "0", ...
Convert CIDR to net range @TODO provide example @param string $net @return string
[ "Convert", "CIDR", "to", "net", "range" ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/IpTools.php#L143-L172
train
phpWhois/phpWhois
src/WhoisClient.php
WhoisClient.setWhoisInfo
public function setWhoisInfo($result) { $info = array( 'server' => $this->query['server'], ); if (!empty($this->query['args'])) { $info['args'] = $this->query['args']; } else { $info['args'] = $this->query['query']; } if (!empty($this->query['server_port'])) { $info['port'] = $this->query['server_port']; } else { $info['port'] = 43; } if (isset($result['regyinfo']['whois'])) { unset($result['regyinfo']['whois']); } if (isset($result['regyinfo']['rwhois'])) { unset($result['regyinfo']['rwhois']); } $result['regyinfo']['servers'][] = $info; return $result; }
php
public function setWhoisInfo($result) { $info = array( 'server' => $this->query['server'], ); if (!empty($this->query['args'])) { $info['args'] = $this->query['args']; } else { $info['args'] = $this->query['query']; } if (!empty($this->query['server_port'])) { $info['port'] = $this->query['server_port']; } else { $info['port'] = 43; } if (isset($result['regyinfo']['whois'])) { unset($result['regyinfo']['whois']); } if (isset($result['regyinfo']['rwhois'])) { unset($result['regyinfo']['rwhois']); } $result['regyinfo']['servers'][] = $info; return $result; }
[ "public", "function", "setWhoisInfo", "(", "$", "result", ")", "{", "$", "info", "=", "array", "(", "'server'", "=>", "$", "this", "->", "query", "[", "'server'", "]", ",", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "query", "[", ...
Adds whois server query information to result @param $result array Result array @return array Original result array with server query information
[ "Adds", "whois", "server", "query", "information", "to", "result" ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/WhoisClient.php#L312-L341
train
phpWhois/phpWhois
src/WhoisClient.php
WhoisClient.httpQuery
public function httpQuery() { //echo ini_get('allow_url_fopen'); //if (ini_get('allow_url_fopen')) $lines = @file($this->query['server']); if (!$lines) { return false; } $output = ''; $pre = ''; while (list($key, $val) = each($lines)) { $val = trim($val); $pos = strpos(strtoupper($val), '<PRE>'); if ($pos !== false) { $pre = "\n"; $output .= substr($val, 0, $pos) . "\n"; $val = substr($val, $pos + 5); } $pos = strpos(strtoupper($val), '</PRE>'); if ($pos !== false) { $pre = ''; $output .= substr($val, 0, $pos) . "\n"; $val = substr($val, $pos + 6); } $output .= $val . $pre; } $search = array( '<BR>', '<P>', '</TITLE>', '</H1>', '</H2>', '</H3>', '<br>', '<p>', '</title>', '</h1>', '</h2>', '</h3>'); $output = str_replace($search, "\n", $output); $output = str_replace('<TD', ' <td', $output); $output = str_replace('<td', ' <td', $output); $output = str_replace('<tr', "\n<tr", $output); $output = str_replace('<TR', "\n<tr", $output); $output = str_replace('&nbsp;', ' ', $output); $output = strip_tags($output); $output = explode("\n", $output); $rawdata = array(); $null = 0; while (list($key, $val) = each($output)) { $val = trim($val); if ($val == '') { if (++$null > 2) { continue; } } else { $null = 0; } $rawdata[] = $val; } return $rawdata; }
php
public function httpQuery() { //echo ini_get('allow_url_fopen'); //if (ini_get('allow_url_fopen')) $lines = @file($this->query['server']); if (!$lines) { return false; } $output = ''; $pre = ''; while (list($key, $val) = each($lines)) { $val = trim($val); $pos = strpos(strtoupper($val), '<PRE>'); if ($pos !== false) { $pre = "\n"; $output .= substr($val, 0, $pos) . "\n"; $val = substr($val, $pos + 5); } $pos = strpos(strtoupper($val), '</PRE>'); if ($pos !== false) { $pre = ''; $output .= substr($val, 0, $pos) . "\n"; $val = substr($val, $pos + 6); } $output .= $val . $pre; } $search = array( '<BR>', '<P>', '</TITLE>', '</H1>', '</H2>', '</H3>', '<br>', '<p>', '</title>', '</h1>', '</h2>', '</h3>'); $output = str_replace($search, "\n", $output); $output = str_replace('<TD', ' <td', $output); $output = str_replace('<td', ' <td', $output); $output = str_replace('<tr', "\n<tr", $output); $output = str_replace('<TR', "\n<tr", $output); $output = str_replace('&nbsp;', ' ', $output); $output = strip_tags($output); $output = explode("\n", $output); $rawdata = array(); $null = 0; while (list($key, $val) = each($output)) { $val = trim($val); if ($val == '') { if (++$null > 2) { continue; } } else { $null = 0; } $rawdata[] = $val; } return $rawdata; }
[ "public", "function", "httpQuery", "(", ")", "{", "//echo ini_get('allow_url_fopen');", "//if (ini_get('allow_url_fopen'))", "$", "lines", "=", "@", "file", "(", "$", "this", "->", "query", "[", "'server'", "]", ")", ";", "if", "(", "!", "$", "lines", ")", "...
Convert html output to plain text @return array Rawdata
[ "Convert", "html", "output", "to", "plain", "text" ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/WhoisClient.php#L348-L410
train
phpWhois/phpWhois
src/WhoisClient.php
WhoisClient.connect
public function connect($server = null) { if (empty($server)) { $server = $this->query['server']; } /** @TODO Throw an exception here */ if (empty($server)) { return false; } $port = $this->query['server_port']; $parsed = $this->parseServer($server); $server = $parsed['host']; if (array_key_exists('port', $parsed)) { $port = $parsed['port']; } // Enter connection attempt loop $retry = 0; while ($retry <= $this->retry) { // Set query status $this->query['status'] = 'ready'; // Connect to whois port $ptr = @fsockopen($server, $port, $errno, $errstr, $this->stimeout); if ($ptr > 0) { $this->query['status'] = 'ok'; return $ptr; } // Failed this attempt $this->query['status'] = 'error'; $this->query['error'][] = $errstr; $retry++; // Sleep before retrying sleep($this->sleep); } // If we get this far, it hasn't worked return false; }
php
public function connect($server = null) { if (empty($server)) { $server = $this->query['server']; } /** @TODO Throw an exception here */ if (empty($server)) { return false; } $port = $this->query['server_port']; $parsed = $this->parseServer($server); $server = $parsed['host']; if (array_key_exists('port', $parsed)) { $port = $parsed['port']; } // Enter connection attempt loop $retry = 0; while ($retry <= $this->retry) { // Set query status $this->query['status'] = 'ready'; // Connect to whois port $ptr = @fsockopen($server, $port, $errno, $errstr, $this->stimeout); if ($ptr > 0) { $this->query['status'] = 'ok'; return $ptr; } // Failed this attempt $this->query['status'] = 'error'; $this->query['error'][] = $errstr; $retry++; // Sleep before retrying sleep($this->sleep); } // If we get this far, it hasn't worked return false; }
[ "public", "function", "connect", "(", "$", "server", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "server", ")", ")", "{", "$", "server", "=", "$", "this", "->", "query", "[", "'server'", "]", ";", "}", "/** @TODO Throw an exception here */", "...
Open a socket to the whois server. @param string|null $server Server address to connect. If null, $this->query['server'] will be used @return resource|false Returns a socket connection pointer on success, or -1 on failure
[ "Open", "a", "socket", "to", "the", "whois", "server", "." ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/WhoisClient.php#L419-L466
train
phpWhois/phpWhois
src/WhoisClient.php
WhoisClient.process
public function process(&$result, $deep_whois = true) { $handler_name = str_replace('.', '_', $this->query['handler']); // If the handler has not already been included somehow, include it now $HANDLER_FLAG = sprintf("__%s_HANDLER__", strtoupper($handler_name)); if (!defined($HANDLER_FLAG)) { include($this->query['file']); } // If the handler has still not been included, append to query errors list and return if (!defined($HANDLER_FLAG)) { $this->query['errstr'][] = "Can't find $handler_name handler: " . $this->query['file']; return $result; } if (!$this->gtldRecurse && $this->query['file'] == 'whois.gtld.php') { return $result; } // Pass result to handler $object = $handler_name . '_handler'; $handler = new $object(''); // If handler returned an error, append it to the query errors list if (isset($handler->query['errstr'])) { $this->query['errstr'][] = $handler->query['errstr']; } $handler->deepWhois = $deep_whois; // Process $res = $handler->parse($result, $this->query['query']); // Return the result return $res; }
php
public function process(&$result, $deep_whois = true) { $handler_name = str_replace('.', '_', $this->query['handler']); // If the handler has not already been included somehow, include it now $HANDLER_FLAG = sprintf("__%s_HANDLER__", strtoupper($handler_name)); if (!defined($HANDLER_FLAG)) { include($this->query['file']); } // If the handler has still not been included, append to query errors list and return if (!defined($HANDLER_FLAG)) { $this->query['errstr'][] = "Can't find $handler_name handler: " . $this->query['file']; return $result; } if (!$this->gtldRecurse && $this->query['file'] == 'whois.gtld.php') { return $result; } // Pass result to handler $object = $handler_name . '_handler'; $handler = new $object(''); // If handler returned an error, append it to the query errors list if (isset($handler->query['errstr'])) { $this->query['errstr'][] = $handler->query['errstr']; } $handler->deepWhois = $deep_whois; // Process $res = $handler->parse($result, $this->query['query']); // Return the result return $res; }
[ "public", "function", "process", "(", "&", "$", "result", ",", "$", "deep_whois", "=", "true", ")", "{", "$", "handler_name", "=", "str_replace", "(", "'.'", ",", "'_'", ",", "$", "this", "->", "query", "[", "'handler'", "]", ")", ";", "// If the handl...
Post-process result with handler class. @return array On success, returns the result from the handler. On failure, returns passed result unaltered.
[ "Post", "-", "process", "result", "with", "handler", "class", "." ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/WhoisClient.php#L475-L514
train
phpWhois/phpWhois
src/WhoisClient.php
WhoisClient.fixNameServer
public function fixNameServer($nserver) { $dns = array(); foreach ($nserver as $val) { $val = str_replace(array('[', ']', '(', ')'), '', trim($val)); $val = str_replace("\t", ' ', $val); $parts = explode(' ', $val); $host = ''; $ip = ''; foreach ($parts as $p) { if (substr($p, -1) == '.') { $p = substr($p, 0, -1); } if ((ip2long($p) == -1) or (ip2long($p) === false)) { // Hostname ? if ($host == '' && preg_match('/^[\w\-]+(\.[\w\-]+)+$/', $p)) { $host = $p; } } else { // IP Address $ip = $p; } } // Valid host name ? if ($host == '') { continue; } // Get ip address if ($ip == '') { $ip = gethostbyname($host); if ($ip == $host) { $ip = '(DOES NOT EXIST)'; } } if (substr($host, -1, 1) == '.') { $host = substr($host, 0, -1); } $dns[strtolower($host)] = $ip; } return $dns; }
php
public function fixNameServer($nserver) { $dns = array(); foreach ($nserver as $val) { $val = str_replace(array('[', ']', '(', ')'), '', trim($val)); $val = str_replace("\t", ' ', $val); $parts = explode(' ', $val); $host = ''; $ip = ''; foreach ($parts as $p) { if (substr($p, -1) == '.') { $p = substr($p, 0, -1); } if ((ip2long($p) == -1) or (ip2long($p) === false)) { // Hostname ? if ($host == '' && preg_match('/^[\w\-]+(\.[\w\-]+)+$/', $p)) { $host = $p; } } else { // IP Address $ip = $p; } } // Valid host name ? if ($host == '') { continue; } // Get ip address if ($ip == '') { $ip = gethostbyname($host); if ($ip == $host) { $ip = '(DOES NOT EXIST)'; } } if (substr($host, -1, 1) == '.') { $host = substr($host, 0, -1); } $dns[strtolower($host)] = $ip; } return $dns; }
[ "public", "function", "fixNameServer", "(", "$", "nserver", ")", "{", "$", "dns", "=", "array", "(", ")", ";", "foreach", "(", "$", "nserver", "as", "$", "val", ")", "{", "$", "val", "=", "str_replace", "(", "array", "(", "'['", ",", "']'", ",", ...
Remove unnecessary symbols from nameserver received from whois server @param string[] $nserver List of received nameservers @return string[]
[ "Remove", "unnecessary", "symbols", "from", "nameserver", "received", "from", "whois", "server" ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/WhoisClient.php#L598-L646
train
phpWhois/phpWhois
src/WhoisClient.php
WhoisClient.parseServer
public function parseServer($server) { $server = trim($server); $server = preg_replace('/\/$/', '', $server); $ipTools = new IpTools; if ($ipTools->validIpv6($server)) { $result = array('host' => "[$server]"); } else { $parsed = parse_url($server); if (array_key_exists('path', $parsed) && !array_key_exists('host', $parsed)) { $host = preg_replace('/\//', '', $parsed['path']); // if host is ipv6 with port. Example: [1a80:1f45::ebb:12]:8080 if (preg_match('/^(\[[a-f0-9:]+\]):(\d{1,5})$/i', $host, $matches)) { $result = array('host' => $matches[1], 'port' => $matches[2]); } else { $result = array('host' => $host); } } else { $result = $parsed; } } return $result; }
php
public function parseServer($server) { $server = trim($server); $server = preg_replace('/\/$/', '', $server); $ipTools = new IpTools; if ($ipTools->validIpv6($server)) { $result = array('host' => "[$server]"); } else { $parsed = parse_url($server); if (array_key_exists('path', $parsed) && !array_key_exists('host', $parsed)) { $host = preg_replace('/\//', '', $parsed['path']); // if host is ipv6 with port. Example: [1a80:1f45::ebb:12]:8080 if (preg_match('/^(\[[a-f0-9:]+\]):(\d{1,5})$/i', $host, $matches)) { $result = array('host' => $matches[1], 'port' => $matches[2]); } else { $result = array('host' => $host); } } else { $result = $parsed; } } return $result; }
[ "public", "function", "parseServer", "(", "$", "server", ")", "{", "$", "server", "=", "trim", "(", "$", "server", ")", ";", "$", "server", "=", "preg_replace", "(", "'/\\/$/'", ",", "''", ",", "$", "server", ")", ";", "$", "ipTools", "=", "new", "...
Parse server string into array with host and port keys @param $server server string in various formattes @return array Array containing 'host' key with server host and 'port' if defined in original $server string
[ "Parse", "server", "string", "into", "array", "with", "host", "and", "port", "keys" ]
32a5e85cc833f9b886c86123f7be5ada3d326272
https://github.com/phpWhois/phpWhois/blob/32a5e85cc833f9b886c86123f7be5ada3d326272/src/WhoisClient.php#L654-L678
train
rollbar/rollbar-php
src/DataBuilder.php
DataBuilder.getSourceLines
private function getSourceLines($filename) { $rawSource = file_get_contents($filename); $source = explode(PHP_EOL, $rawSource); if (count($source) === 1) { if (substr_count($rawSource, "\n") > substr_count($rawSource, "\r")) { $source = explode("\n", $rawSource); } else { $source = explode("\r", $rawSource); } } $source = str_replace(array("\n", "\t", "\r"), '', $source); return $source; }
php
private function getSourceLines($filename) { $rawSource = file_get_contents($filename); $source = explode(PHP_EOL, $rawSource); if (count($source) === 1) { if (substr_count($rawSource, "\n") > substr_count($rawSource, "\r")) { $source = explode("\n", $rawSource); } else { $source = explode("\r", $rawSource); } } $source = str_replace(array("\n", "\t", "\r"), '', $source); return $source; }
[ "private", "function", "getSourceLines", "(", "$", "filename", ")", "{", "$", "rawSource", "=", "file_get_contents", "(", "$", "filename", ")", ";", "$", "source", "=", "explode", "(", "PHP_EOL", ",", "$", "rawSource", ")", ";", "if", "(", "count", "(", ...
Parses an array of code lines from source file with given filename. Attempts to automatically detect the line break character used in the file. @param string $filename @return string[] An array of lines of code from the given source file.
[ "Parses", "an", "array", "of", "code", "lines", "from", "source", "file", "with", "given", "filename", "." ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/DataBuilder.php#L1037-L1054
train
rollbar/rollbar-php
src/DataBuilder.php
DataBuilder.generateErrorWrapper
public function generateErrorWrapper($errno, $errstr, $errfile, $errline) { return new ErrorWrapper( $errno, $errstr, $errfile, $errline, $this->buildErrorTrace($errfile, $errline), $this->utilities ); }
php
public function generateErrorWrapper($errno, $errstr, $errfile, $errline) { return new ErrorWrapper( $errno, $errstr, $errfile, $errline, $this->buildErrorTrace($errfile, $errline), $this->utilities ); }
[ "public", "function", "generateErrorWrapper", "(", "$", "errno", ",", "$", "errstr", ",", "$", "errfile", ",", "$", "errline", ")", "{", "return", "new", "ErrorWrapper", "(", "$", "errno", ",", "$", "errstr", ",", "$", "errfile", ",", "$", "errline", "...
Wrap a PHP error in an ErrorWrapper class and add backtrace information @param string $errno @param string $errstr @param string $errfile @param string $errline @return ErrorWrapper
[ "Wrap", "a", "PHP", "error", "in", "an", "ErrorWrapper", "class", "and", "add", "backtrace", "information" ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/DataBuilder.php#L1066-L1076
train
rollbar/rollbar-php
src/DataBuilder.php
DataBuilder.buildErrorTrace
protected function buildErrorTrace($errfile, $errline) { if ($this->captureErrorStacktraces) { $backTrace = $this->fetchErrorTrace(); $backTrace = $this->stripShutdownFrames($backTrace); // Add the final frame array_unshift( $backTrace, array('file' => $errfile, 'line' => $errline) ); } else { $backTrace = array(); } return $backTrace; }
php
protected function buildErrorTrace($errfile, $errline) { if ($this->captureErrorStacktraces) { $backTrace = $this->fetchErrorTrace(); $backTrace = $this->stripShutdownFrames($backTrace); // Add the final frame array_unshift( $backTrace, array('file' => $errfile, 'line' => $errline) ); } else { $backTrace = array(); } return $backTrace; }
[ "protected", "function", "buildErrorTrace", "(", "$", "errfile", ",", "$", "errline", ")", "{", "if", "(", "$", "this", "->", "captureErrorStacktraces", ")", "{", "$", "backTrace", "=", "$", "this", "->", "fetchErrorTrace", "(", ")", ";", "$", "backTrace",...
Fetches the stack trace for fatal and regular errors. @var string $errfile @var string $errline @return Rollbar\ErrorWrapper
[ "Fetches", "the", "stack", "trace", "for", "fatal", "and", "regular", "errors", "." ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/DataBuilder.php#L1086-L1103
train
rollbar/rollbar-php
src/Truncation/Truncation.php
Truncation.truncate
public function truncate(EncodedPayload $payload) { foreach (static::$truncationStrategies as $strategy) { $strategy = new $strategy($this); if (!$strategy->applies($payload)) { continue; } if (!$this->needsTruncating($payload, $strategy)) { break; } $this->config->verboseLogger()->debug('Applying truncation strategy ' . get_class($strategy)); $payload = $strategy->execute($payload); } return $payload; }
php
public function truncate(EncodedPayload $payload) { foreach (static::$truncationStrategies as $strategy) { $strategy = new $strategy($this); if (!$strategy->applies($payload)) { continue; } if (!$this->needsTruncating($payload, $strategy)) { break; } $this->config->verboseLogger()->debug('Applying truncation strategy ' . get_class($strategy)); $payload = $strategy->execute($payload); } return $payload; }
[ "public", "function", "truncate", "(", "EncodedPayload", "$", "payload", ")", "{", "foreach", "(", "static", "::", "$", "truncationStrategies", "as", "$", "strategy", ")", "{", "$", "strategy", "=", "new", "$", "strategy", "(", "$", "this", ")", ";", "if...
Applies truncation strategies in order to keep the payload size under configured limit. @param \Rollbar\Payload\EncodedPayload $payload @param string $strategy @return \Rollbar\Payload\EncodedPayload
[ "Applies", "truncation", "strategies", "in", "order", "to", "keep", "the", "payload", "size", "under", "configured", "limit", "." ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/Truncation/Truncation.php#L45-L64
train
rollbar/rollbar-php
src/Config.php
Config.shouldIgnoreError
public function shouldIgnoreError($errno) { if ($this->useErrorReporting && ($errno & error_reporting()) === 0) { // ignore due to error_reporting level $this->verboseLogger()->debug("Ignore (error below allowed error_reporting level)"); return true; } if ($this->includedErrno != -1 && ($errno & $this->includedErrno) != $errno) { // ignore $this->verboseLogger()->debug("Ignore due to included_errno level"); return true; } if (isset($this->errorSampleRates[$errno])) { // get a float in the range [0, 1) // mt_rand() is inclusive, so add 1 to mt_randmax $float_rand = mt_rand() / ($this->mtRandmax + 1); if ($float_rand > $this->errorSampleRates[$errno]) { // skip $this->verboseLogger()->debug("Skip due to error sample rating"); return true; } } return false; }
php
public function shouldIgnoreError($errno) { if ($this->useErrorReporting && ($errno & error_reporting()) === 0) { // ignore due to error_reporting level $this->verboseLogger()->debug("Ignore (error below allowed error_reporting level)"); return true; } if ($this->includedErrno != -1 && ($errno & $this->includedErrno) != $errno) { // ignore $this->verboseLogger()->debug("Ignore due to included_errno level"); return true; } if (isset($this->errorSampleRates[$errno])) { // get a float in the range [0, 1) // mt_rand() is inclusive, so add 1 to mt_randmax $float_rand = mt_rand() / ($this->mtRandmax + 1); if ($float_rand > $this->errorSampleRates[$errno]) { // skip $this->verboseLogger()->debug("Skip due to error sample rating"); return true; } } return false; }
[ "public", "function", "shouldIgnoreError", "(", "$", "errno", ")", "{", "if", "(", "$", "this", "->", "useErrorReporting", "&&", "(", "$", "errno", "&", "error_reporting", "(", ")", ")", "===", "0", ")", "{", "// ignore due to error_reporting level", "$", "t...
Check if the error should be ignored due to `included_errno` config, `use_error_reporting` config or `error_sample_rates` config. @param errno @return bool
[ "Check", "if", "the", "error", "should", "be", "ignored", "due", "to", "included_errno", "config", "use_error_reporting", "config", "or", "error_sample_rates", "config", "." ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/Config.php#L888-L914
train
rollbar/rollbar-php
src/Config.php
Config.shouldIgnoreException
public function shouldIgnoreException(\Exception $toLog) { // get a float in the range [0, 1) // mt_rand() is inclusive, so add 1 to mt_randmax $floatRand = mt_rand() / ($this->mtRandmax + 1); if ($floatRand > $this->exceptionSampleRate($toLog)) { // skip $this->verboseLogger()->debug("Skip exception due to exception sample rating"); return true; } return false; }
php
public function shouldIgnoreException(\Exception $toLog) { // get a float in the range [0, 1) // mt_rand() is inclusive, so add 1 to mt_randmax $floatRand = mt_rand() / ($this->mtRandmax + 1); if ($floatRand > $this->exceptionSampleRate($toLog)) { // skip $this->verboseLogger()->debug("Skip exception due to exception sample rating"); return true; } return false; }
[ "public", "function", "shouldIgnoreException", "(", "\\", "Exception", "$", "toLog", ")", "{", "// get a float in the range [0, 1)", "// mt_rand() is inclusive, so add 1 to mt_randmax", "$", "floatRand", "=", "mt_rand", "(", ")", "/", "(", "$", "this", "->", "mtRandmax"...
Check if the exception should be ignored due to configured exception sample rates. @param \Exception $toLog @return bool
[ "Check", "if", "the", "exception", "should", "be", "ignored", "due", "to", "configured", "exception", "sample", "rates", "." ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/Config.php#L937-L949
train
rollbar/rollbar-php
src/Config.php
Config.exceptionSampleRate
public function exceptionSampleRate(\Exception $toLog) { $sampleRate = 1.0; if (count($this->exceptionSampleRates) == 0) { return $sampleRate; } $exceptionClasses = array(); $class = get_class($toLog); while ($class) { $exceptionClasses []= $class; $class = get_parent_class($class); } $exceptionClasses = array_reverse($exceptionClasses); foreach ($exceptionClasses as $exceptionClass) { if (isset($this->exceptionSampleRates["$exceptionClass"])) { $sampleRate = $this->exceptionSampleRates["$exceptionClass"]; } } return $sampleRate; }
php
public function exceptionSampleRate(\Exception $toLog) { $sampleRate = 1.0; if (count($this->exceptionSampleRates) == 0) { return $sampleRate; } $exceptionClasses = array(); $class = get_class($toLog); while ($class) { $exceptionClasses []= $class; $class = get_parent_class($class); } $exceptionClasses = array_reverse($exceptionClasses); foreach ($exceptionClasses as $exceptionClass) { if (isset($this->exceptionSampleRates["$exceptionClass"])) { $sampleRate = $this->exceptionSampleRates["$exceptionClass"]; } } return $sampleRate; }
[ "public", "function", "exceptionSampleRate", "(", "\\", "Exception", "$", "toLog", ")", "{", "$", "sampleRate", "=", "1.0", ";", "if", "(", "count", "(", "$", "this", "->", "exceptionSampleRates", ")", "==", "0", ")", "{", "return", "$", "sampleRate", ";...
Calculate what's the chance of logging this exception according to exception sampling. @param \Exception $toLog @return float
[ "Calculate", "what", "s", "the", "chance", "of", "logging", "this", "exception", "according", "to", "exception", "sampling", "." ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/Config.php#L959-L982
train
rollbar/rollbar-php
src/RollbarJsHelper.php
RollbarJsHelper.buildJs
public static function buildJs( $config, $headers = null, $nonce = null, $customJs = "" ) { $helper = new self($config); return $helper->addJs($headers, $nonce, $customJs); }
php
public static function buildJs( $config, $headers = null, $nonce = null, $customJs = "" ) { $helper = new self($config); return $helper->addJs($headers, $nonce, $customJs); }
[ "public", "static", "function", "buildJs", "(", "$", "config", ",", "$", "headers", "=", "null", ",", "$", "nonce", "=", "null", ",", "$", "customJs", "=", "\"\"", ")", "{", "$", "helper", "=", "new", "self", "(", "$", "config", ")", ";", "return",...
Shortcut method for building the RollbarJS Javascript @param array $config @see addJs() @param string $nonce @see addJs() @param string $customJs @see addJs() @return string
[ "Shortcut", "method", "for", "building", "the", "RollbarJS", "Javascript" ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/RollbarJsHelper.php#L27-L35
train
rollbar/rollbar-php
src/RollbarJsHelper.php
RollbarJsHelper.addJs
public function addJs($headers = null, $nonce = null, $customJs = "") { return $this->scriptTag( $this->configJsTag() . $this->jsSnippet() . ";" . $customJs, $headers, $nonce ); }
php
public function addJs($headers = null, $nonce = null, $customJs = "") { return $this->scriptTag( $this->configJsTag() . $this->jsSnippet() . ";" . $customJs, $headers, $nonce ); }
[ "public", "function", "addJs", "(", "$", "headers", "=", "null", ",", "$", "nonce", "=", "null", ",", "$", "customJs", "=", "\"\"", ")", "{", "return", "$", "this", "->", "scriptTag", "(", "$", "this", "->", "configJsTag", "(", ")", ".", "$", "this...
Build Javascript required to include RollbarJS on an HTML page @param array $headers Response headers usually retrieved through headers_list() used to verify if nonce should be added to script tags based on Content-Security-Policy @param string $nonce Content-Security-Policy nonce string if exists @param strong $customJs Additional JavaScript to add at the end of RollbarJs snippet @return string
[ "Build", "Javascript", "required", "to", "include", "RollbarJS", "on", "an", "HTML", "page" ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/RollbarJsHelper.php#L50-L57
train
rollbar/rollbar-php
src/RollbarJsHelper.php
RollbarJsHelper.shouldAddJs
public function shouldAddJs($status, $headers) { return $status == 200 && $this->isHtml($headers) && !$this->hasAttachment($headers); /** * @todo not sure if below two conditions will be applicable */ /* !env[JS_IS_INJECTED_KEY] */ /* && !streaming?(env) */ }
php
public function shouldAddJs($status, $headers) { return $status == 200 && $this->isHtml($headers) && !$this->hasAttachment($headers); /** * @todo not sure if below two conditions will be applicable */ /* !env[JS_IS_INJECTED_KEY] */ /* && !streaming?(env) */ }
[ "public", "function", "shouldAddJs", "(", "$", "status", ",", "$", "headers", ")", "{", "return", "$", "status", "==", "200", "&&", "$", "this", "->", "isHtml", "(", "$", "headers", ")", "&&", "!", "$", "this", "->", "hasAttachment", "(", "$", "heade...
Should JS snippet be added to the HTTP response @param int $status @param array $headers @return boolean
[ "Should", "JS", "snippet", "be", "added", "to", "the", "HTTP", "response" ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/RollbarJsHelper.php#L97-L109
train
rollbar/rollbar-php
src/RollbarJsHelper.php
RollbarJsHelper.shouldAppendNonce
public function shouldAppendNonce($headers) { foreach ($headers as $header) { if (strpos($header, 'Content-Security-Policy') !== false && strpos($header, "'unsafe-inline'") !== false) { return true; } } return false; }
php
public function shouldAppendNonce($headers) { foreach ($headers as $header) { if (strpos($header, 'Content-Security-Policy') !== false && strpos($header, "'unsafe-inline'") !== false) { return true; } } return false; }
[ "public", "function", "shouldAppendNonce", "(", "$", "headers", ")", "{", "foreach", "(", "$", "headers", "as", "$", "header", ")", "{", "if", "(", "strpos", "(", "$", "header", ",", "'Content-Security-Policy'", ")", "!==", "false", "&&", "strpos", "(", ...
Is `nonce` attribute on the script tag needed? @param array $headers @return boolean
[ "Is", "nonce", "attribute", "on", "the", "script", "tag", "needed?" ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/RollbarJsHelper.php#L142-L152
train
rollbar/rollbar-php
src/RollbarJsHelper.php
RollbarJsHelper.scriptTag
public function scriptTag($content, $headers = null, $nonce = null) { if ($headers !== null && $this->shouldAppendNonce($headers)) { if (!$nonce) { throw new \Exception( 'Content-Security-Policy is script-src '. 'inline-unsafe but nonce value not provided.' ); } return "\n<script type=\"text/javascript\" nonce=\"$nonce\">$content</script>"; } return "\n<script type=\"text/javascript\">$content</script>"; }
php
public function scriptTag($content, $headers = null, $nonce = null) { if ($headers !== null && $this->shouldAppendNonce($headers)) { if (!$nonce) { throw new \Exception( 'Content-Security-Policy is script-src '. 'inline-unsafe but nonce value not provided.' ); } return "\n<script type=\"text/javascript\" nonce=\"$nonce\">$content</script>"; } return "\n<script type=\"text/javascript\">$content</script>"; }
[ "public", "function", "scriptTag", "(", "$", "content", ",", "$", "headers", "=", "null", ",", "$", "nonce", "=", "null", ")", "{", "if", "(", "$", "headers", "!==", "null", "&&", "$", "this", "->", "shouldAppendNonce", "(", "$", "headers", ")", ")",...
Build safe HTML script tag @param string $content @param array $headers @param @return string
[ "Build", "safe", "HTML", "script", "tag" ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/RollbarJsHelper.php#L163-L176
train
rollbar/rollbar-php
src/Scrubber.php
Scrubber.scrub
public function scrub(&$data, $replacement = '********', $path = '') { $fields = $this->getScrubFields(); if (!$fields || !$data) { return $data; } // Scrub fields is case insensitive, so force all fields to lowercase $fields = array_change_key_case(array_flip($fields), CASE_LOWER); return $this->internalScrub($data, $fields, $replacement, $path); }
php
public function scrub(&$data, $replacement = '********', $path = '') { $fields = $this->getScrubFields(); if (!$fields || !$data) { return $data; } // Scrub fields is case insensitive, so force all fields to lowercase $fields = array_change_key_case(array_flip($fields), CASE_LOWER); return $this->internalScrub($data, $fields, $replacement, $path); }
[ "public", "function", "scrub", "(", "&", "$", "data", ",", "$", "replacement", "=", "'********'", ",", "$", "path", "=", "''", ")", "{", "$", "fields", "=", "$", "this", "->", "getScrubFields", "(", ")", ";", "if", "(", "!", "$", "fields", "||", ...
Scrub a data structure including arrays and query strings. @param mixed $data Data to be scrubbed. @param array $fields Sequence of field names to scrub. @param string $replacement Character used for scrubbing. @param string $path Path of traversal in the array
[ "Scrub", "a", "data", "structure", "including", "arrays", "and", "query", "strings", "." ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/Scrubber.php#L52-L64
train
rollbar/rollbar-php
src/Handlers/FatalHandler.php
FatalHandler.isFatal
protected function isFatal($lastError) { return !is_null($lastError) && in_array($lastError['type'], self::$fatalErrors, true) && // don't log uncaught exceptions as they were handled by exceptionHandler() !(isset($lastError['message']) && strpos($lastError['message'], 'Uncaught') === 0); }
php
protected function isFatal($lastError) { return !is_null($lastError) && in_array($lastError['type'], self::$fatalErrors, true) && // don't log uncaught exceptions as they were handled by exceptionHandler() !(isset($lastError['message']) && strpos($lastError['message'], 'Uncaught') === 0); }
[ "protected", "function", "isFatal", "(", "$", "lastError", ")", "{", "return", "!", "is_null", "(", "$", "lastError", ")", "&&", "in_array", "(", "$", "lastError", "[", "'type'", "]", ",", "self", "::", "$", "fatalErrors", ",", "true", ")", "&&", "// d...
Check if the error triggered is indeed a fatal error. @var array $lastError Information fetched from error_get_last(). @return bool
[ "Check", "if", "the", "error", "triggered", "is", "indeed", "a", "fatal", "error", "." ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/Handlers/FatalHandler.php#L55-L63
train
rollbar/rollbar-php
src/Rollbar.php
Rollbar.report_php_error
public static function report_php_error($errno, $errstr, $errfile, $errline) { self::$errorHandler->handle($errno, $errstr, $errfile, $errline); return false; }
php
public static function report_php_error($errno, $errstr, $errfile, $errline) { self::$errorHandler->handle($errno, $errstr, $errfile, $errline); return false; }
[ "public", "static", "function", "report_php_error", "(", "$", "errno", ",", "$", "errstr", ",", "$", "errfile", ",", "$", "errline", ")", "{", "self", "::", "$", "errorHandler", "->", "handle", "(", "$", "errno", ",", "$", "errstr", ",", "$", "errfile"...
This function must return false so that the default php error handler runs @deprecated 1.0.0 This method has been replaced by ::log
[ "This", "function", "must", "return", "false", "so", "that", "the", "default", "php", "error", "handler", "runs" ]
889501d445e6096c037f7098e2a7121657290de8
https://github.com/rollbar/rollbar-php/blob/889501d445e6096c037f7098e2a7121657290de8/src/Rollbar.php#L278-L282
train
rap2hpoutre/fast-excel
src/Exportable.php
Exportable.prepareCollection
protected function prepareCollection() { $need_conversion = false; $first_row = $this->data->first(); if (!$first_row) { return; } foreach ($first_row as $item) { if (!is_string($item)) { $need_conversion = true; } } if ($need_conversion) { $this->transform(); } }
php
protected function prepareCollection() { $need_conversion = false; $first_row = $this->data->first(); if (!$first_row) { return; } foreach ($first_row as $item) { if (!is_string($item)) { $need_conversion = true; } } if ($need_conversion) { $this->transform(); } }
[ "protected", "function", "prepareCollection", "(", ")", "{", "$", "need_conversion", "=", "false", ";", "$", "first_row", "=", "$", "this", "->", "data", "->", "first", "(", ")", ";", "if", "(", "!", "$", "first_row", ")", "{", "return", ";", "}", "f...
Prepare collection by removing non string if required.
[ "Prepare", "collection", "by", "removing", "non", "string", "if", "required", "." ]
1e4193fe9066348b099aa65137518ef7171358c3
https://github.com/rap2hpoutre/fast-excel/blob/1e4193fe9066348b099aa65137518ef7171358c3/src/Exportable.php#L135-L152
train
rap2hpoutre/fast-excel
src/Exportable.php
Exportable.transform
private function transform() { $this->data->transform(function ($data) { return collect($data)->map(function ($value) { return is_int($value) || is_float($value) || is_null($value) ? (string) $value : $value; })->filter(function ($value) { return is_string($value); }); }); }
php
private function transform() { $this->data->transform(function ($data) { return collect($data)->map(function ($value) { return is_int($value) || is_float($value) || is_null($value) ? (string) $value : $value; })->filter(function ($value) { return is_string($value); }); }); }
[ "private", "function", "transform", "(", ")", "{", "$", "this", "->", "data", "->", "transform", "(", "function", "(", "$", "data", ")", "{", "return", "collect", "(", "$", "data", ")", "->", "map", "(", "function", "(", "$", "value", ")", "{", "re...
Transform the collection.
[ "Transform", "the", "collection", "." ]
1e4193fe9066348b099aa65137518ef7171358c3
https://github.com/rap2hpoutre/fast-excel/blob/1e4193fe9066348b099aa65137518ef7171358c3/src/Exportable.php#L157-L166
train
markrogoyski/math-php
src/Trigonometry.php
Trigonometry.unitCircle
public static function unitCircle(int $points = 11): array { $n = $points - 1; $unit_circle = []; for ($i = 0; $i <= $n; $i++) { $x = cos(2 * pi() * $i / ($n)); $y = sin(2 * pi() * $i / ($n)); $unit_circle[] = [$x, $y]; } return $unit_circle; }
php
public static function unitCircle(int $points = 11): array { $n = $points - 1; $unit_circle = []; for ($i = 0; $i <= $n; $i++) { $x = cos(2 * pi() * $i / ($n)); $y = sin(2 * pi() * $i / ($n)); $unit_circle[] = [$x, $y]; } return $unit_circle; }
[ "public", "static", "function", "unitCircle", "(", "int", "$", "points", "=", "11", ")", ":", "array", "{", "$", "n", "=", "$", "points", "-", "1", ";", "$", "unit_circle", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<...
Produce a given number of points on a unit circle The first point is repeated at the end as well to provide overlap. For example: unitCircle(5) would return the array: [[1, 0], [0, 1], [-1, 0], [0, -1], [1, 0]] @param int $points number of points @return array
[ "Produce", "a", "given", "number", "of", "points", "on", "a", "unit", "circle" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Trigonometry.php#L20-L32
train
markrogoyski/math-php
src/NumericalAnalysis/NumericalIntegration/Validation.php
Validation.isSpacingConstant
public static function isSpacingConstant(array $sorted) { $x = 0; $length = count($sorted); $spacing = ($sorted[$length-1][$x]-$sorted[0][$x])/($length-1); for ($i = 1; $i < $length - 1; $i++) { if ($sorted[$i+1][$x] - $sorted[$i][$x] !== $spacing) { throw new Exception\BadDataException('The size of each subinterval must be the same. Provide points with constant spacing.'); } } }
php
public static function isSpacingConstant(array $sorted) { $x = 0; $length = count($sorted); $spacing = ($sorted[$length-1][$x]-$sorted[0][$x])/($length-1); for ($i = 1; $i < $length - 1; $i++) { if ($sorted[$i+1][$x] - $sorted[$i][$x] !== $spacing) { throw new Exception\BadDataException('The size of each subinterval must be the same. Provide points with constant spacing.'); } } }
[ "public", "static", "function", "isSpacingConstant", "(", "array", "$", "sorted", ")", "{", "$", "x", "=", "0", ";", "$", "length", "=", "count", "(", "$", "sorted", ")", ";", "$", "spacing", "=", "(", "$", "sorted", "[", "$", "length", "-", "1", ...
Ensures that the length of each subinterval is equal, or equivalently, that the spacing between each point is equal @param array $sorted Points sorted by (increasing) x-component @throws Exception if the spacing between any two points is not equal to the average spacing between every point
[ "Ensures", "that", "the", "length", "of", "each", "subinterval", "is", "equal", "or", "equivalently", "that", "the", "spacing", "between", "each", "point", "is", "equal" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/NumericalAnalysis/NumericalIntegration/Validation.php#L20-L31
train
markrogoyski/math-php
src/Statistics/Regression/WeightedLinear.php
WeightedLinear.calculate
public function calculate() { $this->parameters = $this->leastSquares($this->ys, $this->xs, $this->ws)->getColumn(0); }
php
public function calculate() { $this->parameters = $this->leastSquares($this->ys, $this->xs, $this->ws)->getColumn(0); }
[ "public", "function", "calculate", "(", ")", "{", "$", "this", "->", "parameters", "=", "$", "this", "->", "leastSquares", "(", "$", "this", "->", "ys", ",", "$", "this", "->", "xs", ",", "$", "this", "->", "ws", ")", "->", "getColumn", "(", "0", ...
Calculates the regression parameters. @throws Exception\MatrixException
[ "Calculates", "the", "regression", "parameters", "." ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Statistics/Regression/WeightedLinear.php#L44-L47
train
markrogoyski/math-php
src/Probability/Distribution/Discrete/Uniform.php
Uniform.cdf
public function cdf(int $k): float { $a = $this->a; $b = $this->b; if ($k < $a) { return 0; } if ($k > $b) { return 1; } $n = $b - $a + 1; return ($k - $a + 1) / $n; }
php
public function cdf(int $k): float { $a = $this->a; $b = $this->b; if ($k < $a) { return 0; } if ($k > $b) { return 1; } $n = $b - $a + 1; return ($k - $a + 1) / $n; }
[ "public", "function", "cdf", "(", "int", "$", "k", ")", ":", "float", "{", "$", "a", "=", "$", "this", "->", "a", ";", "$", "b", "=", "$", "this", "->", "b", ";", "if", "(", "$", "k", "<", "$", "a", ")", "{", "return", "0", ";", "}", "i...
Cumulative distribution function k - a + 1 pmf = --------- n Percentile n = b - a + 1 @param int $k percentile @return float
[ "Cumulative", "distribution", "function" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Probability/Distribution/Discrete/Uniform.php#L89-L104
train
markrogoyski/math-php
src/Probability/Distribution/Discrete/Uniform.php
Uniform.mean
public function mean(): float { $a = $this->a; $b = $this->b; return ($a + $b) / 2; }
php
public function mean(): float { $a = $this->a; $b = $this->b; return ($a + $b) / 2; }
[ "public", "function", "mean", "(", ")", ":", "float", "{", "$", "a", "=", "$", "this", "->", "a", ";", "$", "b", "=", "$", "this", "->", "b", ";", "return", "(", "$", "a", "+", "$", "b", ")", "/", "2", ";", "}" ]
Mean of the distribution a + b μ = ----- 2 @return float
[ "Mean", "of", "the", "distribution" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Probability/Distribution/Discrete/Uniform.php#L115-L121
train
markrogoyski/math-php
src/Probability/Distribution/Discrete/Uniform.php
Uniform.median
public function median(): float { $a = $this->a; $b = $this->b; return ($a + $b) / 2; }
php
public function median(): float { $a = $this->a; $b = $this->b; return ($a + $b) / 2; }
[ "public", "function", "median", "(", ")", ":", "float", "{", "$", "a", "=", "$", "this", "->", "a", ";", "$", "b", "=", "$", "this", "->", "b", ";", "return", "(", "$", "a", "+", "$", "b", ")", "/", "2", ";", "}" ]
Median of the distribution a + b μ = ----- 2 @return float
[ "Median", "of", "the", "distribution" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Probability/Distribution/Discrete/Uniform.php#L132-L138
train
markrogoyski/math-php
src/Probability/Distribution/Discrete/Uniform.php
Uniform.variance
public function variance(): float { $a = $this->a; $b = $this->b; return (($b - $a + 1)**2 - 1) / 12; }
php
public function variance(): float { $a = $this->a; $b = $this->b; return (($b - $a + 1)**2 - 1) / 12; }
[ "public", "function", "variance", "(", ")", ":", "float", "{", "$", "a", "=", "$", "this", "->", "a", ";", "$", "b", "=", "$", "this", "->", "b", ";", "return", "(", "(", "$", "b", "-", "$", "a", "+", "1", ")", "**", "2", "-", "1", ")", ...
Variance of the distribution (b - a + 1)² - 1 σ² = ---------------- 12 @return float
[ "Variance", "of", "the", "distribution" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Probability/Distribution/Discrete/Uniform.php#L149-L155
train
markrogoyski/math-php
src/Sequence/Advanced.php
Advanced.magicSquares
public static function magicSquares(int $n): array { if ($n < 0) { return []; } $M = []; for ($i = 0; $i < $n; $i++) { $M[] = ($i * ($i**2 + 1)) / 2; } return $M; }
php
public static function magicSquares(int $n): array { if ($n < 0) { return []; } $M = []; for ($i = 0; $i < $n; $i++) { $M[] = ($i * ($i**2 + 1)) / 2; } return $M; }
[ "public", "static", "function", "magicSquares", "(", "int", "$", "n", ")", ":", "array", "{", "if", "(", "$", "n", "<", "0", ")", "{", "return", "[", "]", ";", "}", "$", "M", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "...
Magic squares series The constant sum in every row, column and diagonal of a magic square is called the magic constant or magic sum, M. https://oeis.org/A006003 https://edublognss.wordpress.com/2013/04/16/famous-mathematical-sequences-and-series/ n(n² + 1) M = --------- 2 Example: n = 6 Sequence: 0, 1, 5, 15, 34, 65 Array index: 0, 1, 2, 3, 4, 5, @param int $n How many numbers in the sequence @return array
[ "Magic", "squares", "series", "The", "constant", "sum", "in", "every", "row", "column", "and", "diagonal", "of", "a", "magic", "square", "is", "called", "the", "magic", "constant", "or", "magic", "sum", "M", "." ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Sequence/Advanced.php#L435-L448
train
markrogoyski/math-php
src/Functions/Bitwise.php
Bitwise.add
public static function add(int $a, int $b): array { /** @var int|float due to potential overflow */ $sum = $a + $b; if (is_int($sum)) { $overflow = (($a < 0 || $b < 0) && $sum >= 0) || ($a < 0 && $b < 0); } elseif ($a > 0 && $b > 0) { $sum = $a - \PHP_INT_MAX + $b - 1 + \PHP_INT_MIN; $overflow = false; } else { $a -= \PHP_INT_MIN; $b -= \PHP_INT_MIN; $sum = $a + $b; $overflow = true; } return [ 'overflow' => $overflow, 'value' => $sum, ]; }
php
public static function add(int $a, int $b): array { /** @var int|float due to potential overflow */ $sum = $a + $b; if (is_int($sum)) { $overflow = (($a < 0 || $b < 0) && $sum >= 0) || ($a < 0 && $b < 0); } elseif ($a > 0 && $b > 0) { $sum = $a - \PHP_INT_MAX + $b - 1 + \PHP_INT_MIN; $overflow = false; } else { $a -= \PHP_INT_MIN; $b -= \PHP_INT_MIN; $sum = $a + $b; $overflow = true; } return [ 'overflow' => $overflow, 'value' => $sum, ]; }
[ "public", "static", "function", "add", "(", "int", "$", "a", ",", "int", "$", "b", ")", ":", "array", "{", "/** @var int|float due to potential overflow */", "$", "sum", "=", "$", "a", "+", "$", "b", ";", "if", "(", "is_int", "(", "$", "sum", ")", ")...
Add two ints ignoring the signing bit. 8 bit examples: 0d15 + 0d1 = 0d16 0b00001111 + 0b00000001 = 0b00010000 0d127 + 0d1 = 0d-128 0b01111111 + 0b00000001 = 0b10000000 0d-1 + 0d1 = 0d0 0b11111111 + 0b00000001 = 0b00000000 :overflow = true 0d-1 + 0d-1 = 0d-2 0b11111111 + 0b11111111 = 0b11111110: overflow = true Scenarios 1) Result is an integer $a and $b are negative, the most significant bit will overflow. If only one is negative, the most significant bit will overflow if the sum is positive. 2) Result is not an integer a) a and b are positive If $a + $b overflows as a signed int, it is now a negative int, but the most significant bit will not overflow. b) a and b are not both positive The sum of two "large" negative numbers will both overflow the most significant bit and the signed int. The values of $a and $b have to be shifted towards zero to prevent the signed int from overflowing. We are removing the most significant bit from the ints by subtractingPHP_INT_MIN to prevent overflow. $a = 1001, $b = 1010, return [true, '0011] because \PHP_INT_MIN = 1000, Giving $a - 1000 = 0001, $b - 1000 = 0010. @param int $a @param int $b @return array 'overflow' is true if the result is larger than the bits in an int 'value' is the result of the addition ignoring any overflow.
[ "Add", "two", "ints", "ignoring", "the", "signing", "bit", "." ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Functions/Bitwise.php#L46-L67
train
markrogoyski/math-php
src/Statistics/Distribution.php
Distribution.relativeFrequency
public static function relativeFrequency(array $values): array { $sample_size = count($values); $relative_frequencies = array(); foreach (self::frequency($values) as $subject => $frequency) { $relative_frequencies[$subject] = $frequency / $sample_size; } return $relative_frequencies; }
php
public static function relativeFrequency(array $values): array { $sample_size = count($values); $relative_frequencies = array(); foreach (self::frequency($values) as $subject => $frequency) { $relative_frequencies[$subject] = $frequency / $sample_size; } return $relative_frequencies; }
[ "public", "static", "function", "relativeFrequency", "(", "array", "$", "values", ")", ":", "array", "{", "$", "sample_size", "=", "count", "(", "$", "values", ")", ";", "$", "relative_frequencies", "=", "array", "(", ")", ";", "foreach", "(", "self", ":...
Relative frequency distribution Frequency distribution relative to the sample size. Relative Frequency = Frequency / Sample Size The values of the input array will be the keys of the result array. The relative frequency of the values will be the value of the result array for that key. @param array $values Ex: ( A, A, A, A, A, A, B, B, B, C ) @return array relative frequency distribution Ex: ( A => 0.6, B => 0.3, C => 0.1 )
[ "Relative", "frequency", "distribution", "Frequency", "distribution", "relative", "to", "the", "sample", "size", "." ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Statistics/Distribution.php#L49-L57
train
markrogoyski/math-php
src/Statistics/Distribution.php
Distribution.cumulativeFrequency
public static function cumulativeFrequency(array $values): array { $running_total = 0; $cumulative_frequencies = array(); foreach (self::frequency($values) as $value => $frequency) { $running_total += $frequency; $cumulative_frequencies[$value] = $running_total; } return $cumulative_frequencies; }
php
public static function cumulativeFrequency(array $values): array { $running_total = 0; $cumulative_frequencies = array(); foreach (self::frequency($values) as $value => $frequency) { $running_total += $frequency; $cumulative_frequencies[$value] = $running_total; } return $cumulative_frequencies; }
[ "public", "static", "function", "cumulativeFrequency", "(", "array", "$", "values", ")", ":", "array", "{", "$", "running_total", "=", "0", ";", "$", "cumulative_frequencies", "=", "array", "(", ")", ";", "foreach", "(", "self", "::", "frequency", "(", "$"...
Cumulative frequency distribution The values of the input array will be the keys of the result array. The cumulative frequency of the values will be the value of the result array for that key. @param array $values Ex: ( A, A, A, A, A, A, B, B, B, C ) @return array cumulative frequency distribution Ex: ( A => 6, B => 9, C => 10 )
[ "Cumulative", "frequency", "distribution" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Statistics/Distribution.php#L69-L78
train
markrogoyski/math-php
src/Statistics/Distribution.php
Distribution.cumulativeRelativeFrequency
public static function cumulativeRelativeFrequency(array $values): array { $sample_size = count($values); $cumulative_frequencies = self::cumulativeFrequency($values); return array_map( function ($frequency) use ($sample_size) { return $frequency / $sample_size; }, $cumulative_frequencies ); }
php
public static function cumulativeRelativeFrequency(array $values): array { $sample_size = count($values); $cumulative_frequencies = self::cumulativeFrequency($values); return array_map( function ($frequency) use ($sample_size) { return $frequency / $sample_size; }, $cumulative_frequencies ); }
[ "public", "static", "function", "cumulativeRelativeFrequency", "(", "array", "$", "values", ")", ":", "array", "{", "$", "sample_size", "=", "count", "(", "$", "values", ")", ";", "$", "cumulative_frequencies", "=", "self", "::", "cumulativeFrequency", "(", "$...
Cumulative relative frequency distribution Cumulative frequency distribution relative to the sample size. Cumulative relative frequency = cumulative frequency / sample size The values of the input array will be the keys of the result array. The cumulative frequency of the values will be the value of the result array for that key. @param array $values Ex: ( A, A, A, A, A, A, B, B, B, C ) @return array cumulative relative frequency distribution Ex: ( A => 0.6, B => 0.9, C => 1 )
[ "Cumulative", "relative", "frequency", "distribution", "Cumulative", "frequency", "distribution", "relative", "to", "the", "sample", "size", "." ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Statistics/Distribution.php#L93-L103
train
markrogoyski/math-php
src/Probability/Distribution/Table/StandardNormal.php
StandardNormal.getZScoreForConfidenceInterval
public static function getZScoreForConfidenceInterval(string $cl): float { if (!array_key_exists($cl, self::Z_SCORES_FOR_CONFIDENCE_INTERVALS)) { throw new Exception\BadDataException('Not a valid confidence level'); } return self::Z_SCORES_FOR_CONFIDENCE_INTERVALS[$cl]; }
php
public static function getZScoreForConfidenceInterval(string $cl): float { if (!array_key_exists($cl, self::Z_SCORES_FOR_CONFIDENCE_INTERVALS)) { throw new Exception\BadDataException('Not a valid confidence level'); } return self::Z_SCORES_FOR_CONFIDENCE_INTERVALS[$cl]; }
[ "public", "static", "function", "getZScoreForConfidenceInterval", "(", "string", "$", "cl", ")", ":", "float", "{", "if", "(", "!", "array_key_exists", "(", "$", "cl", ",", "self", "::", "Z_SCORES_FOR_CONFIDENCE_INTERVALS", ")", ")", "{", "throw", "new", "Exce...
Get Z score for confidence interval @param string $cl confidence level @return float Z score @throws Exception\BadDataException
[ "Get", "Z", "score", "for", "confidence", "interval" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Probability/Distribution/Table/StandardNormal.php#L157-L163
train
markrogoyski/math-php
src/Functions/Map/Single.php
Single.min
public static function min(array $xs, $value): array { return array_map( function ($x) use ($value) { return min($x, $value); }, $xs ); }
php
public static function min(array $xs, $value): array { return array_map( function ($x) use ($value) { return min($x, $value); }, $xs ); }
[ "public", "static", "function", "min", "(", "array", "$", "xs", ",", "$", "value", ")", ":", "array", "{", "return", "array_map", "(", "function", "(", "$", "x", ")", "use", "(", "$", "value", ")", "{", "return", "min", "(", "$", "x", ",", "$", ...
Map min value Each element in array is compared against the value, and the min of each is returned. @param array $xs @param number $value @return array
[ "Map", "min", "value", "Each", "element", "in", "array", "is", "compared", "against", "the", "value", "and", "the", "min", "of", "each", "is", "returned", "." ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Functions/Map/Single.php#L209-L217
train
markrogoyski/math-php
src/Functions/Map/Single.php
Single.max
public static function max(array $xs, $value): array { return array_map( function ($x) use ($value) { return max($x, $value); }, $xs ); }
php
public static function max(array $xs, $value): array { return array_map( function ($x) use ($value) { return max($x, $value); }, $xs ); }
[ "public", "static", "function", "max", "(", "array", "$", "xs", ",", "$", "value", ")", ":", "array", "{", "return", "array_map", "(", "function", "(", "$", "x", ")", "use", "(", "$", "value", ")", "{", "return", "max", "(", "$", "x", ",", "$", ...
Map max value Each element in the array is compared against the value, and the max of each is returned. @param array $xs @param number $value @return array
[ "Map", "max", "value", "Each", "element", "in", "the", "array", "is", "compared", "against", "the", "value", "and", "the", "max", "of", "each", "is", "returned", "." ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Functions/Map/Single.php#L229-L237
train
markrogoyski/math-php
src/Statistics/Regression/TheilSen.php
TheilSen.calculate
public function calculate() { // The slopes array will be a list of slopes between all pairs of points $slopes = []; $n = count($this->points); for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { $pointi = $this->points[$i]; $pointj = $this->points[$j]; if ($pointj[0] != $pointi[0]) { $slopes[] = ($pointj[1] - $pointi[1]) / ($pointj[0] - $pointi[0]); } } } $this->m = Average::median($slopes); $this->b = Average::median($this->ys) - ($this->m * Average::median($this->xs)); $this->parameters = [$this->b, $this->m]; }
php
public function calculate() { // The slopes array will be a list of slopes between all pairs of points $slopes = []; $n = count($this->points); for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { $pointi = $this->points[$i]; $pointj = $this->points[$j]; if ($pointj[0] != $pointi[0]) { $slopes[] = ($pointj[1] - $pointi[1]) / ($pointj[0] - $pointi[0]); } } } $this->m = Average::median($slopes); $this->b = Average::median($this->ys) - ($this->m * Average::median($this->xs)); $this->parameters = [$this->b, $this->m]; }
[ "public", "function", "calculate", "(", ")", "{", "// The slopes array will be a list of slopes between all pairs of points", "$", "slopes", "=", "[", "]", ";", "$", "n", "=", "count", "(", "$", "this", "->", "points", ")", ";", "for", "(", "$", "i", "=", "0...
Calculate the regression parameters using the Theil-Sen method Procedure: Calculate the slopes of all pairs of points and select the median value Calculate the intercept using the slope, and the medians of the X and Y values. b = Ymedian - (m * Xmedian)
[ "Calculate", "the", "regression", "parameters", "using", "the", "Theil", "-", "Sen", "method" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/Statistics/Regression/TheilSen.php#L34-L53
train
markrogoyski/math-php
src/LinearAlgebra/MatrixFactory.php
MatrixFactory.downshiftPermutation
public static function downshiftPermutation(int $n): Matrix { $I = self::identity($n)->getMatrix(); $bottom_row = array_pop($I); array_unshift($I, $bottom_row); return self::create($I); }
php
public static function downshiftPermutation(int $n): Matrix { $I = self::identity($n)->getMatrix(); $bottom_row = array_pop($I); array_unshift($I, $bottom_row); return self::create($I); }
[ "public", "static", "function", "downshiftPermutation", "(", "int", "$", "n", ")", ":", "Matrix", "{", "$", "I", "=", "self", "::", "identity", "(", "$", "n", ")", "->", "getMatrix", "(", ")", ";", "$", "bottom_row", "=", "array_pop", "(", "$", "I", ...
Downshift permutation matrix Pushes the components of a vector down one notch with wraparound [0, 0, 0, 1] [x₁] [x₄] [1, 0, 0, 0] [x₂] [x₁] D₄x = [0, 1, 0, 0] [x₃] = [x₂] [0, 0, 1, 0] [x₄] [x₃] @param int $n @return Matrix @throws Exception\BadDataException @throws Exception\IncorrectTypeException @throws Exception\MathException @throws Exception\MatrixException @throws Exception\OutOfBoundsException if n < 0
[ "Downshift", "permutation", "matrix", "Pushes", "the", "components", "of", "a", "vector", "down", "one", "notch", "with", "wraparound" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/LinearAlgebra/MatrixFactory.php#L165-L173
train
markrogoyski/math-php
src/LinearAlgebra/MatrixFactory.php
MatrixFactory.zero
public static function zero(int $m, int $n): Matrix { if ($m < 1 || $n < 1) { throw new Exception\OutOfBoundsException("m and n must be > 0. m = $m, n = $n"); } $R = []; for ($i = 0; $i < $m; $i++) { for ($j = 0; $j < $n; $j++) { $R[$i][$j] = 0; } } return self::create($R); }
php
public static function zero(int $m, int $n): Matrix { if ($m < 1 || $n < 1) { throw new Exception\OutOfBoundsException("m and n must be > 0. m = $m, n = $n"); } $R = []; for ($i = 0; $i < $m; $i++) { for ($j = 0; $j < $n; $j++) { $R[$i][$j] = 0; } } return self::create($R); }
[ "public", "static", "function", "zero", "(", "int", "$", "m", ",", "int", "$", "n", ")", ":", "Matrix", "{", "if", "(", "$", "m", "<", "1", "||", "$", "n", "<", "1", ")", "{", "throw", "new", "Exception", "\\", "OutOfBoundsException", "(", "\"m a...
Zero matrix - m x n matrix with all elements being zeros Example: m = 3; n = 3 [0 0 0] A = [0 0 0] [0 0 0] @param int $m rows @param int $n columns @return Matrix @throws Exception\BadDataException @throws Exception\IncorrectTypeException @throws Exception\MathException @throws Exception\MatrixException @throws Exception\OutOfBoundsException if m < 1 or n < 1
[ "Zero", "matrix", "-", "m", "x", "n", "matrix", "with", "all", "elements", "being", "zeros" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/LinearAlgebra/MatrixFactory.php#L215-L230
train
markrogoyski/math-php
src/LinearAlgebra/MatrixFactory.php
MatrixFactory.checkParams
private static function checkParams(array $A): bool { if (empty($A)) { throw new Exception\BadDataException('Array data not provided for Matrix creation'); } if (isset($A[0]) && is_array($A[0])) { $column_count = count($A[0]); foreach ($A as $i => $row) { if (count($row) !== $column_count) { throw new Exception\MatrixException("Row $i has a different column count: " . count($row) . "; was expecting $column_count."); } } } return true; }
php
private static function checkParams(array $A): bool { if (empty($A)) { throw new Exception\BadDataException('Array data not provided for Matrix creation'); } if (isset($A[0]) && is_array($A[0])) { $column_count = count($A[0]); foreach ($A as $i => $row) { if (count($row) !== $column_count) { throw new Exception\MatrixException("Row $i has a different column count: " . count($row) . "; was expecting $column_count."); } } } return true; }
[ "private", "static", "function", "checkParams", "(", "array", "$", "A", ")", ":", "bool", "{", "if", "(", "empty", "(", "$", "A", ")", ")", "{", "throw", "new", "Exception", "\\", "BadDataException", "(", "'Array data not provided for Matrix creation'", ")", ...
Check input parameters @param array $A @return bool @throws Exception\BadDataException if array data not provided for matrix creation @throws Exception\MatrixException if any row has a different column count
[ "Check", "input", "parameters" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/LinearAlgebra/MatrixFactory.php#L371-L387
train
markrogoyski/math-php
src/LinearAlgebra/MatrixFactory.php
MatrixFactory.determineMatrixType
private static function determineMatrixType(array $A, int $vandermonde_n = null): string { $m = count($A); // 1-dimensional array is how we create diagonal and vandermonde matrices, // as well as matrices from an array of vectors $one_dimensional = count(array_filter($A, 'is_array')) === 0; if ($one_dimensional) { $is_array_of_vectors = array_reduce( $A, function ($carry, $item) { return $carry && ($item instanceof Vector); }, true ); if ($is_array_of_vectors) { return 'from_vectors'; } if (is_null($vandermonde_n)) { return 'diagonal'; } if ($m === $vandermonde_n) { return 'vandermonde_square'; } return 'vandermonde'; } // Square Matrices have the same number of rows (m) and columns (n) $n = count($A[0]); if ($m === $n) { // closures are objects, so we need to separate them out. if (is_object($A[0][0])) { if ($A[0][0] instanceof \Closure) { return 'function_square'; } else { return 'object_square'; } } return 'square'; } // Non square Matrices // First check to make sure it isn't something strange if (is_array($A[0][0])) { return 'unknown'; } // Then check remaining matrix types if (is_callable($A[0][0])) { return 'function'; } return 'matrix'; }
php
private static function determineMatrixType(array $A, int $vandermonde_n = null): string { $m = count($A); // 1-dimensional array is how we create diagonal and vandermonde matrices, // as well as matrices from an array of vectors $one_dimensional = count(array_filter($A, 'is_array')) === 0; if ($one_dimensional) { $is_array_of_vectors = array_reduce( $A, function ($carry, $item) { return $carry && ($item instanceof Vector); }, true ); if ($is_array_of_vectors) { return 'from_vectors'; } if (is_null($vandermonde_n)) { return 'diagonal'; } if ($m === $vandermonde_n) { return 'vandermonde_square'; } return 'vandermonde'; } // Square Matrices have the same number of rows (m) and columns (n) $n = count($A[0]); if ($m === $n) { // closures are objects, so we need to separate them out. if (is_object($A[0][0])) { if ($A[0][0] instanceof \Closure) { return 'function_square'; } else { return 'object_square'; } } return 'square'; } // Non square Matrices // First check to make sure it isn't something strange if (is_array($A[0][0])) { return 'unknown'; } // Then check remaining matrix types if (is_callable($A[0][0])) { return 'function'; } return 'matrix'; }
[ "private", "static", "function", "determineMatrixType", "(", "array", "$", "A", ",", "int", "$", "vandermonde_n", "=", "null", ")", ":", "string", "{", "$", "m", "=", "count", "(", "$", "A", ")", ";", "// 1-dimensional array is how we create diagonal and vanderm...
Determine what type of matrix to create @param array $A 1- or 2-dimensional array of Matrix data 1-dimensional array for Diagonal and Vandermonde matrices 2-dimensional array for Square, Function, and regular Matrices @param int|null $vandermonde_n Optional n for Vandermonde matrix @return string indicating what matrix type to create
[ "Determine", "what", "type", "of", "matrix", "to", "create" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/LinearAlgebra/MatrixFactory.php#L399-L450
train
markrogoyski/math-php
src/LinearAlgebra/MatrixFactory.php
MatrixFactory.createFromVectors
private static function createFromVectors(array $A): Matrix { // Check that all vectors are the same length $m = $A[0]->getN(); $n = count($A); for ($j = 1; $j < $n; $j++) { if ($A[$j]->getN() !== $m) { throw new Exception\MatrixException('Vectors being combined into matrix have different lengths'); } } // Concatenate all the vectors $R = []; foreach ($A as $V) { $R[] = $V->getVector(); } // Transpose to create matrix from the vector columns return (new Matrix($R))->transpose(); }
php
private static function createFromVectors(array $A): Matrix { // Check that all vectors are the same length $m = $A[0]->getN(); $n = count($A); for ($j = 1; $j < $n; $j++) { if ($A[$j]->getN() !== $m) { throw new Exception\MatrixException('Vectors being combined into matrix have different lengths'); } } // Concatenate all the vectors $R = []; foreach ($A as $V) { $R[] = $V->getVector(); } // Transpose to create matrix from the vector columns return (new Matrix($R))->transpose(); }
[ "private", "static", "function", "createFromVectors", "(", "array", "$", "A", ")", ":", "Matrix", "{", "// Check that all vectors are the same length", "$", "m", "=", "$", "A", "[", "0", "]", "->", "getN", "(", ")", ";", "$", "n", "=", "count", "(", "$",...
Create a matrix from an array of Vectors Example: [1] [4] [7] [8] X₁ = [2] X₂ = [2] X₃ = [8] X₄ = [4] [1] [13] [1] [5] [1 4 7 8] R = [2 2 8 4] [1 13 1 5] @param array $A array of Vectors @return Matrix @throws Exception\MatrixException if the Vectors are not all the same length @throws Exception\IncorrectTypeException @throws Exception\BadDataException
[ "Create", "a", "matrix", "from", "an", "array", "of", "Vectors" ]
4a2934a23bcb1fe7767c9205d630e38018c16556
https://github.com/markrogoyski/math-php/blob/4a2934a23bcb1fe7767c9205d630e38018c16556/src/LinearAlgebra/MatrixFactory.php#L472-L491
train