repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
39
1.84M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
RubixML/RubixML
src/Other/Specifications/DatasetIsCompatibleWithEstimator.php
DatasetIsCompatibleWithEstimator.check
public static function check(Dataset $dataset, Estimator $estimator) : void { $types = $dataset->uniqueTypes(); $same = array_intersect($types, $estimator->compatibility()); if (count($same) < count($types)) { throw new InvalidArgumentException('Estimator is not' . ' compatible with the data types given.'); } }
php
public static function check(Dataset $dataset, Estimator $estimator) : void { $types = $dataset->uniqueTypes(); $same = array_intersect($types, $estimator->compatibility()); if (count($same) < count($types)) { throw new InvalidArgumentException('Estimator is not' . ' compatible with the data types given.'); } }
[ "public", "static", "function", "check", "(", "Dataset", "$", "dataset", ",", "Estimator", "$", "estimator", ")", ":", "void", "{", "$", "types", "=", "$", "dataset", "->", "uniqueTypes", "(", ")", ";", "$", "same", "=", "array_intersect", "(", "$", "types", ",", "$", "estimator", "->", "compatibility", "(", ")", ")", ";", "if", "(", "count", "(", "$", "same", ")", "<", "count", "(", "$", "types", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Estimator is not'", ".", "' compatible with the data types given.'", ")", ";", "}", "}" ]
Perform a check. @param \Rubix\ML\Datasets\Dataset $dataset @param \Rubix\ML\Estimator $estimator @throws \InvalidArgumentException
[ "Perform", "a", "check", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Specifications/DatasetIsCompatibleWithEstimator.php#L18-L28
RubixML/RubixML
src/CrossValidation/Reports/AggregateReport.php
AggregateReport.generate
public function generate(array $predictions, array $labels) : array { $results = []; foreach ($this->reports as $index => $report) { $results[$index] = $report->generate($predictions, $labels); } return $results; }
php
public function generate(array $predictions, array $labels) : array { $results = []; foreach ($this->reports as $index => $report) { $results[$index] = $report->generate($predictions, $labels); } return $results; }
[ "public", "function", "generate", "(", "array", "$", "predictions", ",", "array", "$", "labels", ")", ":", "array", "{", "$", "results", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "reports", "as", "$", "index", "=>", "$", "report", ")", "{", "$", "results", "[", "$", "index", "]", "=", "$", "report", "->", "generate", "(", "$", "predictions", ",", "$", "labels", ")", ";", "}", "return", "$", "results", ";", "}" ]
Generate the report. @param array $predictions @param array $labels @return array
[ "Generate", "the", "report", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CrossValidation/Reports/AggregateReport.php#L87-L96
RubixML/RubixML
src/Other/Strategies/Lottery.php
Lottery.fit
public function fit(array $values) : void { if (empty($values)) { throw new InvalidArgumentException('Strategy must be fit with' . ' at least 1 value.'); } $categories = array_values(array_unique($values)); $this->categories = $categories; $this->k = count($categories); }
php
public function fit(array $values) : void { if (empty($values)) { throw new InvalidArgumentException('Strategy must be fit with' . ' at least 1 value.'); } $categories = array_values(array_unique($values)); $this->categories = $categories; $this->k = count($categories); }
[ "public", "function", "fit", "(", "array", "$", "values", ")", ":", "void", "{", "if", "(", "empty", "(", "$", "values", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Strategy must be fit with'", ".", "' at least 1 value.'", ")", ";", "}", "$", "categories", "=", "array_values", "(", "array_unique", "(", "$", "values", ")", ")", ";", "$", "this", "->", "categories", "=", "$", "categories", ";", "$", "this", "->", "k", "=", "count", "(", "$", "categories", ")", ";", "}" ]
Fit the guessing strategy to a set of values. @param array $values @throws \RuntimeException
[ "Fit", "the", "guessing", "strategy", "to", "a", "set", "of", "values", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Strategies/Lottery.php#L41-L52
RubixML/RubixML
src/Other/Strategies/Lottery.php
Lottery.guess
public function guess() : string { if (!$this->categories or !$this->k) { throw new RuntimeException('Strategy has not been fitted.'); } $index = rand(0, $this->k - 1); return $this->categories[$index]; }
php
public function guess() : string { if (!$this->categories or !$this->k) { throw new RuntimeException('Strategy has not been fitted.'); } $index = rand(0, $this->k - 1); return $this->categories[$index]; }
[ "public", "function", "guess", "(", ")", ":", "string", "{", "if", "(", "!", "$", "this", "->", "categories", "or", "!", "$", "this", "->", "k", ")", "{", "throw", "new", "RuntimeException", "(", "'Strategy has not been fitted.'", ")", ";", "}", "$", "index", "=", "rand", "(", "0", ",", "$", "this", "->", "k", "-", "1", ")", ";", "return", "$", "this", "->", "categories", "[", "$", "index", "]", ";", "}" ]
Make a guess. @throws \RuntimeException @return string
[ "Make", "a", "guess", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Strategies/Lottery.php#L60-L69
RubixML/RubixML
src/Classifiers/NaiveBayes.php
NaiveBayes.priors
public function priors() : array { $priors = []; if (is_array($this->priors)) { $max = logsumexp($this->priors); foreach ($this->priors as $class => $probability) { $priors[$class] = exp($probability - $max); } } return $priors; }
php
public function priors() : array { $priors = []; if (is_array($this->priors)) { $max = logsumexp($this->priors); foreach ($this->priors as $class => $probability) { $priors[$class] = exp($probability - $max); } } return $priors; }
[ "public", "function", "priors", "(", ")", ":", "array", "{", "$", "priors", "=", "[", "]", ";", "if", "(", "is_array", "(", "$", "this", "->", "priors", ")", ")", "{", "$", "max", "=", "logsumexp", "(", "$", "this", "->", "priors", ")", ";", "foreach", "(", "$", "this", "->", "priors", "as", "$", "class", "=>", "$", "probability", ")", "{", "$", "priors", "[", "$", "class", "]", "=", "exp", "(", "$", "probability", "-", "$", "max", ")", ";", "}", "}", "return", "$", "priors", ";", "}" ]
Return the class prior probabilities. @return array
[ "Return", "the", "class", "prior", "probabilities", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/NaiveBayes.php#L178-L191
RubixML/RubixML
src/Classifiers/NaiveBayes.php
NaiveBayes.train
public function train(Dataset $dataset) : void { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('This Estimator requires a' . ' Labeled training set.'); } $classes = $dataset->possibleOutcomes(); $this->classes = $classes; $this->weights = array_fill_keys($classes, 0); $this->counts = $this->probs = array_fill_keys( $classes, array_fill(0, $dataset->numColumns(), []) ); $this->partial($dataset); }
php
public function train(Dataset $dataset) : void { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('This Estimator requires a' . ' Labeled training set.'); } $classes = $dataset->possibleOutcomes(); $this->classes = $classes; $this->weights = array_fill_keys($classes, 0); $this->counts = $this->probs = array_fill_keys( $classes, array_fill(0, $dataset->numColumns(), []) ); $this->partial($dataset); }
[ "public", "function", "train", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "if", "(", "!", "$", "dataset", "instanceof", "Labeled", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'This Estimator requires a'", ".", "' Labeled training set.'", ")", ";", "}", "$", "classes", "=", "$", "dataset", "->", "possibleOutcomes", "(", ")", ";", "$", "this", "->", "classes", "=", "$", "classes", ";", "$", "this", "->", "weights", "=", "array_fill_keys", "(", "$", "classes", ",", "0", ")", ";", "$", "this", "->", "counts", "=", "$", "this", "->", "probs", "=", "array_fill_keys", "(", "$", "classes", ",", "array_fill", "(", "0", ",", "$", "dataset", "->", "numColumns", "(", ")", ",", "[", "]", ")", ")", ";", "$", "this", "->", "partial", "(", "$", "dataset", ")", ";", "}" ]
Train the estimator with a dataset. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException
[ "Train", "the", "estimator", "with", "a", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/NaiveBayes.php#L210-L228
RubixML/RubixML
src/Classifiers/NaiveBayes.php
NaiveBayes.partial
public function partial(Dataset $dataset) : void { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('This Estimator requires a' . ' Labeled training set.'); } if (!$dataset->homogeneous() or $dataset->columnType(0) !== DataType::CATEGORICAL) { throw new InvalidArgumentException('This estimator only works' . ' with categorical features.'); } if (empty($this->weights) or empty($this->counts) or empty($this->probs)) { $this->train($dataset); return; } foreach ($dataset->stratify() as $class => $stratum) { $classCounts = $this->counts[$class]; $classProbs = $this->probs[$class]; foreach ($stratum->columns() as $column => $values) { $columnCounts = $classCounts[$column]; $counts = array_count_values($values); foreach ($counts as $category => $count) { if (isset($columnCounts[$category])) { $columnCounts[$category] += $count; } else { $columnCounts[$category] = $count; } } $total = (array_sum($columnCounts) + (count($columnCounts) * $this->alpha)) ?: EPSILON; $probs = []; foreach ($columnCounts as $category => $count) { $probs[$category] = log(($count + $this->alpha) / $total); } $classCounts[$column] = $columnCounts; $classProbs[$column] = $probs; } $this->counts[$class] = $classCounts; $this->probs[$class] = $classProbs; $this->weights[$class] += $stratum->numRows(); } if ($this->fitPriors) { $total = (array_sum($this->weights) + (count($this->weights) * $this->alpha)) ?: EPSILON; foreach ($this->weights as $class => $weight) { $this->priors[$class] = log(($weight + $this->alpha) / $total); } } }
php
public function partial(Dataset $dataset) : void { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('This Estimator requires a' . ' Labeled training set.'); } if (!$dataset->homogeneous() or $dataset->columnType(0) !== DataType::CATEGORICAL) { throw new InvalidArgumentException('This estimator only works' . ' with categorical features.'); } if (empty($this->weights) or empty($this->counts) or empty($this->probs)) { $this->train($dataset); return; } foreach ($dataset->stratify() as $class => $stratum) { $classCounts = $this->counts[$class]; $classProbs = $this->probs[$class]; foreach ($stratum->columns() as $column => $values) { $columnCounts = $classCounts[$column]; $counts = array_count_values($values); foreach ($counts as $category => $count) { if (isset($columnCounts[$category])) { $columnCounts[$category] += $count; } else { $columnCounts[$category] = $count; } } $total = (array_sum($columnCounts) + (count($columnCounts) * $this->alpha)) ?: EPSILON; $probs = []; foreach ($columnCounts as $category => $count) { $probs[$category] = log(($count + $this->alpha) / $total); } $classCounts[$column] = $columnCounts; $classProbs[$column] = $probs; } $this->counts[$class] = $classCounts; $this->probs[$class] = $classProbs; $this->weights[$class] += $stratum->numRows(); } if ($this->fitPriors) { $total = (array_sum($this->weights) + (count($this->weights) * $this->alpha)) ?: EPSILON; foreach ($this->weights as $class => $weight) { $this->priors[$class] = log(($weight + $this->alpha) / $total); } } }
[ "public", "function", "partial", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "if", "(", "!", "$", "dataset", "instanceof", "Labeled", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'This Estimator requires a'", ".", "' Labeled training set.'", ")", ";", "}", "if", "(", "!", "$", "dataset", "->", "homogeneous", "(", ")", "or", "$", "dataset", "->", "columnType", "(", "0", ")", "!==", "DataType", "::", "CATEGORICAL", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'This estimator only works'", ".", "' with categorical features.'", ")", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "weights", ")", "or", "empty", "(", "$", "this", "->", "counts", ")", "or", "empty", "(", "$", "this", "->", "probs", ")", ")", "{", "$", "this", "->", "train", "(", "$", "dataset", ")", ";", "return", ";", "}", "foreach", "(", "$", "dataset", "->", "stratify", "(", ")", "as", "$", "class", "=>", "$", "stratum", ")", "{", "$", "classCounts", "=", "$", "this", "->", "counts", "[", "$", "class", "]", ";", "$", "classProbs", "=", "$", "this", "->", "probs", "[", "$", "class", "]", ";", "foreach", "(", "$", "stratum", "->", "columns", "(", ")", "as", "$", "column", "=>", "$", "values", ")", "{", "$", "columnCounts", "=", "$", "classCounts", "[", "$", "column", "]", ";", "$", "counts", "=", "array_count_values", "(", "$", "values", ")", ";", "foreach", "(", "$", "counts", "as", "$", "category", "=>", "$", "count", ")", "{", "if", "(", "isset", "(", "$", "columnCounts", "[", "$", "category", "]", ")", ")", "{", "$", "columnCounts", "[", "$", "category", "]", "+=", "$", "count", ";", "}", "else", "{", "$", "columnCounts", "[", "$", "category", "]", "=", "$", "count", ";", "}", "}", "$", "total", "=", "(", "array_sum", "(", "$", "columnCounts", ")", "+", "(", "count", "(", "$", "columnCounts", ")", "*", "$", "this", "->", "alpha", ")", ")", "?", ":", "EPSILON", ";", "$", "probs", "=", "[", "]", ";", "foreach", "(", "$", "columnCounts", "as", "$", "category", "=>", "$", "count", ")", "{", "$", "probs", "[", "$", "category", "]", "=", "log", "(", "(", "$", "count", "+", "$", "this", "->", "alpha", ")", "/", "$", "total", ")", ";", "}", "$", "classCounts", "[", "$", "column", "]", "=", "$", "columnCounts", ";", "$", "classProbs", "[", "$", "column", "]", "=", "$", "probs", ";", "}", "$", "this", "->", "counts", "[", "$", "class", "]", "=", "$", "classCounts", ";", "$", "this", "->", "probs", "[", "$", "class", "]", "=", "$", "classProbs", ";", "$", "this", "->", "weights", "[", "$", "class", "]", "+=", "$", "stratum", "->", "numRows", "(", ")", ";", "}", "if", "(", "$", "this", "->", "fitPriors", ")", "{", "$", "total", "=", "(", "array_sum", "(", "$", "this", "->", "weights", ")", "+", "(", "count", "(", "$", "this", "->", "weights", ")", "*", "$", "this", "->", "alpha", ")", ")", "?", ":", "EPSILON", ";", "foreach", "(", "$", "this", "->", "weights", "as", "$", "class", "=>", "$", "weight", ")", "{", "$", "this", "->", "priors", "[", "$", "class", "]", "=", "log", "(", "(", "$", "weight", "+", "$", "this", "->", "alpha", ")", "/", "$", "total", ")", ";", "}", "}", "}" ]
Compute the rolling counts and conditional probabilities. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException
[ "Compute", "the", "rolling", "counts", "and", "conditional", "probabilities", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/NaiveBayes.php#L236-L299
RubixML/RubixML
src/Classifiers/NaiveBayes.php
NaiveBayes.predict
public function predict(Dataset $dataset) : array { if (empty($this->weights) or empty($this->probs)) { throw new RuntimeException('The learner has not' . ' been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $predictions = []; foreach ($dataset as $sample) { $jll = $this->jointLogLikelihood($sample); $predictions[] = argmax($jll); } return $predictions; }
php
public function predict(Dataset $dataset) : array { if (empty($this->weights) or empty($this->probs)) { throw new RuntimeException('The learner has not' . ' been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $predictions = []; foreach ($dataset as $sample) { $jll = $this->jointLogLikelihood($sample); $predictions[] = argmax($jll); } return $predictions; }
[ "public", "function", "predict", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "if", "(", "empty", "(", "$", "this", "->", "weights", ")", "or", "empty", "(", "$", "this", "->", "probs", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'The learner has not'", ".", "' been trained.'", ")", ";", "}", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "$", "predictions", "=", "[", "]", ";", "foreach", "(", "$", "dataset", "as", "$", "sample", ")", "{", "$", "jll", "=", "$", "this", "->", "jointLogLikelihood", "(", "$", "sample", ")", ";", "$", "predictions", "[", "]", "=", "argmax", "(", "$", "jll", ")", ";", "}", "return", "$", "predictions", ";", "}" ]
Make predictions from a dataset. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException @throws \RuntimeException @return array
[ "Make", "predictions", "from", "a", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/NaiveBayes.php#L309-L327
RubixML/RubixML
src/Classifiers/NaiveBayes.php
NaiveBayes.jointLogLikelihood
protected function jointLogLikelihood(array $sample) : array { $likelihoods = []; foreach ($this->probs as $class => $probs) { $likelihood = $this->priors[$class] ?? LOG_EPSILON; foreach ($sample as $column => $feature) { $likelihood += $probs[$column][$feature] ?? LOG_EPSILON; } $likelihoods[$class] = $likelihood; } return $likelihoods; }
php
protected function jointLogLikelihood(array $sample) : array { $likelihoods = []; foreach ($this->probs as $class => $probs) { $likelihood = $this->priors[$class] ?? LOG_EPSILON; foreach ($sample as $column => $feature) { $likelihood += $probs[$column][$feature] ?? LOG_EPSILON; } $likelihoods[$class] = $likelihood; } return $likelihoods; }
[ "protected", "function", "jointLogLikelihood", "(", "array", "$", "sample", ")", ":", "array", "{", "$", "likelihoods", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "probs", "as", "$", "class", "=>", "$", "probs", ")", "{", "$", "likelihood", "=", "$", "this", "->", "priors", "[", "$", "class", "]", "??", "LOG_EPSILON", ";", "foreach", "(", "$", "sample", "as", "$", "column", "=>", "$", "feature", ")", "{", "$", "likelihood", "+=", "$", "probs", "[", "$", "column", "]", "[", "$", "feature", "]", "??", "LOG_EPSILON", ";", "}", "$", "likelihoods", "[", "$", "class", "]", "=", "$", "likelihood", ";", "}", "return", "$", "likelihoods", ";", "}" ]
Calculate the joint log likelihood of a sample being a member of each class. @param array $sample @return array
[ "Calculate", "the", "joint", "log", "likelihood", "of", "a", "sample", "being", "a", "member", "of", "each", "class", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/NaiveBayes.php#L371-L386
RubixML/RubixML
src/Classifiers/AdaBoost.php
AdaBoost.train
public function train(Dataset $dataset) : void { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('This estimator requires a' . ' labeled training set.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); if ($this->logger) { $this->logger->info('Learner init ' . Params::stringify([ 'base' => $this->base, 'estimators' => $this->estimators, 'rate' => $this->rate, 'ratio' => $this->ratio, 'tolerance' => $this->tolerance, ])); } $this->classes = $dataset->possibleOutcomes(); $labels = $dataset->labels(); $n = $dataset->numRows(); $p = (int) round($this->ratio * $n); $k = count($this->classes); $this->weights = array_fill(0, $n, 1 / $n); $this->ensemble = $this->influences = $this->steps = []; for ($epoch = 1; $epoch <= $this->estimators; $epoch++) { $estimator = clone $this->base; $subset = $dataset->randomWeightedSubsetWithReplacement($p, $this->weights); $estimator->train($subset); $predictions = $estimator->predict($dataset); $loss = 0.; foreach ($predictions as $i => $prediction) { if ($prediction !== $labels[$i]) { $loss += $this->weights[$i]; } } $total = array_sum($this->weights); $loss /= $total; $influence = $this->rate * (log((1. - $loss) / ($loss ?: EPSILON)) + log($k - 1)); $this->ensemble[] = $estimator; $this->steps[] = $loss; $this->influences[] = $influence; if ($this->logger) { $this->logger->info("Epoch $epoch complete, loss=$loss"); } if (is_nan($loss) or $total <= 0) { break 1; } if ($loss < $this->tolerance) { break 1; } foreach ($predictions as $i => $prediction) { if ($prediction !== $labels[$i]) { $this->weights[$i] *= exp($influence); } } $total = array_sum($this->weights); foreach ($this->weights as &$weight) { $weight /= $total; } } if ($this->logger) { $this->logger->info('Training complete'); } }
php
public function train(Dataset $dataset) : void { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('This estimator requires a' . ' labeled training set.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); if ($this->logger) { $this->logger->info('Learner init ' . Params::stringify([ 'base' => $this->base, 'estimators' => $this->estimators, 'rate' => $this->rate, 'ratio' => $this->ratio, 'tolerance' => $this->tolerance, ])); } $this->classes = $dataset->possibleOutcomes(); $labels = $dataset->labels(); $n = $dataset->numRows(); $p = (int) round($this->ratio * $n); $k = count($this->classes); $this->weights = array_fill(0, $n, 1 / $n); $this->ensemble = $this->influences = $this->steps = []; for ($epoch = 1; $epoch <= $this->estimators; $epoch++) { $estimator = clone $this->base; $subset = $dataset->randomWeightedSubsetWithReplacement($p, $this->weights); $estimator->train($subset); $predictions = $estimator->predict($dataset); $loss = 0.; foreach ($predictions as $i => $prediction) { if ($prediction !== $labels[$i]) { $loss += $this->weights[$i]; } } $total = array_sum($this->weights); $loss /= $total; $influence = $this->rate * (log((1. - $loss) / ($loss ?: EPSILON)) + log($k - 1)); $this->ensemble[] = $estimator; $this->steps[] = $loss; $this->influences[] = $influence; if ($this->logger) { $this->logger->info("Epoch $epoch complete, loss=$loss"); } if (is_nan($loss) or $total <= 0) { break 1; } if ($loss < $this->tolerance) { break 1; } foreach ($predictions as $i => $prediction) { if ($prediction !== $labels[$i]) { $this->weights[$i] *= exp($influence); } } $total = array_sum($this->weights); foreach ($this->weights as &$weight) { $weight /= $total; } } if ($this->logger) { $this->logger->info('Training complete'); } }
[ "public", "function", "train", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "if", "(", "!", "$", "dataset", "instanceof", "Labeled", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'This estimator requires a'", ".", "' labeled training set.'", ")", ";", "}", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Learner init '", ".", "Params", "::", "stringify", "(", "[", "'base'", "=>", "$", "this", "->", "base", ",", "'estimators'", "=>", "$", "this", "->", "estimators", ",", "'rate'", "=>", "$", "this", "->", "rate", ",", "'ratio'", "=>", "$", "this", "->", "ratio", ",", "'tolerance'", "=>", "$", "this", "->", "tolerance", ",", "]", ")", ")", ";", "}", "$", "this", "->", "classes", "=", "$", "dataset", "->", "possibleOutcomes", "(", ")", ";", "$", "labels", "=", "$", "dataset", "->", "labels", "(", ")", ";", "$", "n", "=", "$", "dataset", "->", "numRows", "(", ")", ";", "$", "p", "=", "(", "int", ")", "round", "(", "$", "this", "->", "ratio", "*", "$", "n", ")", ";", "$", "k", "=", "count", "(", "$", "this", "->", "classes", ")", ";", "$", "this", "->", "weights", "=", "array_fill", "(", "0", ",", "$", "n", ",", "1", "/", "$", "n", ")", ";", "$", "this", "->", "ensemble", "=", "$", "this", "->", "influences", "=", "$", "this", "->", "steps", "=", "[", "]", ";", "for", "(", "$", "epoch", "=", "1", ";", "$", "epoch", "<=", "$", "this", "->", "estimators", ";", "$", "epoch", "++", ")", "{", "$", "estimator", "=", "clone", "$", "this", "->", "base", ";", "$", "subset", "=", "$", "dataset", "->", "randomWeightedSubsetWithReplacement", "(", "$", "p", ",", "$", "this", "->", "weights", ")", ";", "$", "estimator", "->", "train", "(", "$", "subset", ")", ";", "$", "predictions", "=", "$", "estimator", "->", "predict", "(", "$", "dataset", ")", ";", "$", "loss", "=", "0.", ";", "foreach", "(", "$", "predictions", "as", "$", "i", "=>", "$", "prediction", ")", "{", "if", "(", "$", "prediction", "!==", "$", "labels", "[", "$", "i", "]", ")", "{", "$", "loss", "+=", "$", "this", "->", "weights", "[", "$", "i", "]", ";", "}", "}", "$", "total", "=", "array_sum", "(", "$", "this", "->", "weights", ")", ";", "$", "loss", "/=", "$", "total", ";", "$", "influence", "=", "$", "this", "->", "rate", "*", "(", "log", "(", "(", "1.", "-", "$", "loss", ")", "/", "(", "$", "loss", "?", ":", "EPSILON", ")", ")", "+", "log", "(", "$", "k", "-", "1", ")", ")", ";", "$", "this", "->", "ensemble", "[", "]", "=", "$", "estimator", ";", "$", "this", "->", "steps", "[", "]", "=", "$", "loss", ";", "$", "this", "->", "influences", "[", "]", "=", "$", "influence", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "\"Epoch $epoch complete, loss=$loss\"", ")", ";", "}", "if", "(", "is_nan", "(", "$", "loss", ")", "or", "$", "total", "<=", "0", ")", "{", "break", "1", ";", "}", "if", "(", "$", "loss", "<", "$", "this", "->", "tolerance", ")", "{", "break", "1", ";", "}", "foreach", "(", "$", "predictions", "as", "$", "i", "=>", "$", "prediction", ")", "{", "if", "(", "$", "prediction", "!==", "$", "labels", "[", "$", "i", "]", ")", "{", "$", "this", "->", "weights", "[", "$", "i", "]", "*=", "exp", "(", "$", "influence", ")", ";", "}", "}", "$", "total", "=", "array_sum", "(", "$", "this", "->", "weights", ")", ";", "foreach", "(", "$", "this", "->", "weights", "as", "&", "$", "weight", ")", "{", "$", "weight", "/=", "$", "total", ";", "}", "}", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Training complete'", ")", ";", "}", "}" ]
Train a boosted enemble of *weak* classifiers assigning an influence value to each one and re-weighting the training data accordingly to reflect how difficult a particular sample is to classify. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException
[ "Train", "a", "boosted", "enemble", "of", "*", "weak", "*", "classifiers", "assigning", "an", "influence", "value", "to", "each", "one", "and", "re", "-", "weighting", "the", "training", "data", "accordingly", "to", "reflect", "how", "difficult", "a", "particular", "sample", "is", "to", "classify", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/AdaBoost.php#L239-L327
RubixML/RubixML
src/Classifiers/AdaBoost.php
AdaBoost.predict
public function predict(Dataset $dataset) : array { if (empty($this->ensemble) or empty($this->influences)) { throw new RuntimeException('The learner has not' . ' been trained.'); } return array_map('Rubix\ML\argmax', $this->score($dataset)); }
php
public function predict(Dataset $dataset) : array { if (empty($this->ensemble) or empty($this->influences)) { throw new RuntimeException('The learner has not' . ' been trained.'); } return array_map('Rubix\ML\argmax', $this->score($dataset)); }
[ "public", "function", "predict", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "if", "(", "empty", "(", "$", "this", "->", "ensemble", ")", "or", "empty", "(", "$", "this", "->", "influences", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'The learner has not'", ".", "' been trained.'", ")", ";", "}", "return", "array_map", "(", "'Rubix\\ML\\argmax'", ",", "$", "this", "->", "score", "(", "$", "dataset", ")", ")", ";", "}" ]
Make predictions from a dataset. @param \Rubix\ML\Datasets\Dataset $dataset @throws \RuntimeException @return array
[ "Make", "predictions", "from", "a", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/AdaBoost.php#L336-L344
RubixML/RubixML
src/Classifiers/AdaBoost.php
AdaBoost.proba
public function proba(Dataset $dataset) : array { if (empty($this->ensemble) or empty($this->influences)) { throw new RuntimeException('The learner has not' . ' been trained.'); } $scores = $this->score($dataset); $probabilities = []; foreach ($scores as $scores) { $total = array_sum($scores) ?: EPSILON; $dist = []; foreach ($scores as $class => $score) { $dist[$class] = $score / $total; } $probabilities[] = $dist; } return $probabilities; }
php
public function proba(Dataset $dataset) : array { if (empty($this->ensemble) or empty($this->influences)) { throw new RuntimeException('The learner has not' . ' been trained.'); } $scores = $this->score($dataset); $probabilities = []; foreach ($scores as $scores) { $total = array_sum($scores) ?: EPSILON; $dist = []; foreach ($scores as $class => $score) { $dist[$class] = $score / $total; } $probabilities[] = $dist; } return $probabilities; }
[ "public", "function", "proba", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "if", "(", "empty", "(", "$", "this", "->", "ensemble", ")", "or", "empty", "(", "$", "this", "->", "influences", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'The learner has not'", ".", "' been trained.'", ")", ";", "}", "$", "scores", "=", "$", "this", "->", "score", "(", "$", "dataset", ")", ";", "$", "probabilities", "=", "[", "]", ";", "foreach", "(", "$", "scores", "as", "$", "scores", ")", "{", "$", "total", "=", "array_sum", "(", "$", "scores", ")", "?", ":", "EPSILON", ";", "$", "dist", "=", "[", "]", ";", "foreach", "(", "$", "scores", "as", "$", "class", "=>", "$", "score", ")", "{", "$", "dist", "[", "$", "class", "]", "=", "$", "score", "/", "$", "total", ";", "}", "$", "probabilities", "[", "]", "=", "$", "dist", ";", "}", "return", "$", "probabilities", ";", "}" ]
Estimate probabilities for each possible outcome. @param \Rubix\ML\Datasets\Dataset $dataset @throws \RuntimeException @return array
[ "Estimate", "probabilities", "for", "each", "possible", "outcome", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/AdaBoost.php#L353-L377
RubixML/RubixML
src/Classifiers/AdaBoost.php
AdaBoost.score
protected function score(Dataset $dataset) : array { $scores = array_fill( 0, $dataset->numRows(), array_fill_keys($this->classes, 0.) ); foreach ($this->ensemble as $i => $estimator) { $influence = $this->influences[$i]; foreach ($estimator->predict($dataset) as $j => $prediction) { $scores[$j][$prediction] += $influence; } } return $scores; }
php
protected function score(Dataset $dataset) : array { $scores = array_fill( 0, $dataset->numRows(), array_fill_keys($this->classes, 0.) ); foreach ($this->ensemble as $i => $estimator) { $influence = $this->influences[$i]; foreach ($estimator->predict($dataset) as $j => $prediction) { $scores[$j][$prediction] += $influence; } } return $scores; }
[ "protected", "function", "score", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "$", "scores", "=", "array_fill", "(", "0", ",", "$", "dataset", "->", "numRows", "(", ")", ",", "array_fill_keys", "(", "$", "this", "->", "classes", ",", "0.", ")", ")", ";", "foreach", "(", "$", "this", "->", "ensemble", "as", "$", "i", "=>", "$", "estimator", ")", "{", "$", "influence", "=", "$", "this", "->", "influences", "[", "$", "i", "]", ";", "foreach", "(", "$", "estimator", "->", "predict", "(", "$", "dataset", ")", "as", "$", "j", "=>", "$", "prediction", ")", "{", "$", "scores", "[", "$", "j", "]", "[", "$", "prediction", "]", "+=", "$", "influence", ";", "}", "}", "return", "$", "scores", ";", "}" ]
Return the influence scores for each sample in the dataset. @param \Rubix\ML\Datasets\Dataset $dataset @throws \RuntimeException @throws \InvalidArgumentException @return array
[ "Return", "the", "influence", "scores", "for", "each", "sample", "in", "the", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/AdaBoost.php#L387-L404
RubixML/RubixML
src/Classifiers/KNearestNeighbors.php
KNearestNeighbors.partial
public function partial(Dataset $dataset) : void { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('This estimator requires a' . ' labeled training set.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $this->classes = array_unique(array_merge($this->classes, $dataset->possibleOutcomes())); $this->samples = array_merge($this->samples, $dataset->samples()); $this->labels = array_merge($this->labels, $dataset->labels()); }
php
public function partial(Dataset $dataset) : void { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('This estimator requires a' . ' labeled training set.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $this->classes = array_unique(array_merge($this->classes, $dataset->possibleOutcomes())); $this->samples = array_merge($this->samples, $dataset->samples()); $this->labels = array_merge($this->labels, $dataset->labels()); }
[ "public", "function", "partial", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "if", "(", "!", "$", "dataset", "instanceof", "Labeled", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'This estimator requires a'", ".", "' labeled training set.'", ")", ";", "}", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "$", "this", "->", "classes", "=", "array_unique", "(", "array_merge", "(", "$", "this", "->", "classes", ",", "$", "dataset", "->", "possibleOutcomes", "(", ")", ")", ")", ";", "$", "this", "->", "samples", "=", "array_merge", "(", "$", "this", "->", "samples", ",", "$", "dataset", "->", "samples", "(", ")", ")", ";", "$", "this", "->", "labels", "=", "array_merge", "(", "$", "this", "->", "labels", ",", "$", "dataset", "->", "labels", "(", ")", ")", ";", "}" ]
Store the sample and outcome arrays. No other work to be done as this is a lazy learning algorithm. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException
[ "Store", "the", "sample", "and", "outcome", "arrays", ".", "No", "other", "work", "to", "be", "done", "as", "this", "is", "a", "lazy", "learning", "algorithm", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/KNearestNeighbors.php#L153-L165
RubixML/RubixML
src/Classifiers/KNearestNeighbors.php
KNearestNeighbors.predict
public function predict(Dataset $dataset) : array { if (empty($this->samples) or empty($this->labels)) { throw new RuntimeException('The learner has not' . ' been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $predictions = []; foreach ($dataset as $sample) { [$labels, $distances] = $this->nearest($sample); if ($this->weighted) { $weights = array_fill_keys($labels, 0.); foreach ($labels as $i => $label) { $weights[$label] += 1. / (1. + $distances[$i]); } } else { $weights = array_count_values($labels); } $predictions[] = argmax($weights); } return $predictions; }
php
public function predict(Dataset $dataset) : array { if (empty($this->samples) or empty($this->labels)) { throw new RuntimeException('The learner has not' . ' been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $predictions = []; foreach ($dataset as $sample) { [$labels, $distances] = $this->nearest($sample); if ($this->weighted) { $weights = array_fill_keys($labels, 0.); foreach ($labels as $i => $label) { $weights[$label] += 1. / (1. + $distances[$i]); } } else { $weights = array_count_values($labels); } $predictions[] = argmax($weights); } return $predictions; }
[ "public", "function", "predict", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "if", "(", "empty", "(", "$", "this", "->", "samples", ")", "or", "empty", "(", "$", "this", "->", "labels", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'The learner has not'", ".", "' been trained.'", ")", ";", "}", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "$", "predictions", "=", "[", "]", ";", "foreach", "(", "$", "dataset", "as", "$", "sample", ")", "{", "[", "$", "labels", ",", "$", "distances", "]", "=", "$", "this", "->", "nearest", "(", "$", "sample", ")", ";", "if", "(", "$", "this", "->", "weighted", ")", "{", "$", "weights", "=", "array_fill_keys", "(", "$", "labels", ",", "0.", ")", ";", "foreach", "(", "$", "labels", "as", "$", "i", "=>", "$", "label", ")", "{", "$", "weights", "[", "$", "label", "]", "+=", "1.", "/", "(", "1.", "+", "$", "distances", "[", "$", "i", "]", ")", ";", "}", "}", "else", "{", "$", "weights", "=", "array_count_values", "(", "$", "labels", ")", ";", "}", "$", "predictions", "[", "]", "=", "argmax", "(", "$", "weights", ")", ";", "}", "return", "$", "predictions", ";", "}" ]
Make predictions from a dataset. @param \Rubix\ML\Datasets\Dataset $dataset @throws \RuntimeException @throws \InvalidArgumentException @return array
[ "Make", "predictions", "from", "a", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/KNearestNeighbors.php#L175-L203
RubixML/RubixML
src/Classifiers/KNearestNeighbors.php
KNearestNeighbors.proba
public function proba(Dataset $dataset) : array { if (empty($this->samples) or empty($this->labels)) { throw new RuntimeException('The learner has not' . ' been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $template = array_fill_keys($this->classes, 0.); $probabilities = []; foreach ($dataset as $sample) { [$labels, $distances] = $this->nearest($sample); if ($this->weighted) { $weights = array_fill_keys($labels, 0.); foreach ($labels as $i => $label) { $weights[$label] += 1. / (1. + $distances[$i]); } } else { $weights = array_count_values($labels); } $total = array_sum($weights) ?: EPSILON; $dist = $template; foreach ($weights as $class => $weight) { $dist[$class] = $weight / $total; } $probabilities[] = $dist; } return $probabilities; }
php
public function proba(Dataset $dataset) : array { if (empty($this->samples) or empty($this->labels)) { throw new RuntimeException('The learner has not' . ' been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $template = array_fill_keys($this->classes, 0.); $probabilities = []; foreach ($dataset as $sample) { [$labels, $distances] = $this->nearest($sample); if ($this->weighted) { $weights = array_fill_keys($labels, 0.); foreach ($labels as $i => $label) { $weights[$label] += 1. / (1. + $distances[$i]); } } else { $weights = array_count_values($labels); } $total = array_sum($weights) ?: EPSILON; $dist = $template; foreach ($weights as $class => $weight) { $dist[$class] = $weight / $total; } $probabilities[] = $dist; } return $probabilities; }
[ "public", "function", "proba", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "if", "(", "empty", "(", "$", "this", "->", "samples", ")", "or", "empty", "(", "$", "this", "->", "labels", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'The learner has not'", ".", "' been trained.'", ")", ";", "}", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "$", "template", "=", "array_fill_keys", "(", "$", "this", "->", "classes", ",", "0.", ")", ";", "$", "probabilities", "=", "[", "]", ";", "foreach", "(", "$", "dataset", "as", "$", "sample", ")", "{", "[", "$", "labels", ",", "$", "distances", "]", "=", "$", "this", "->", "nearest", "(", "$", "sample", ")", ";", "if", "(", "$", "this", "->", "weighted", ")", "{", "$", "weights", "=", "array_fill_keys", "(", "$", "labels", ",", "0.", ")", ";", "foreach", "(", "$", "labels", "as", "$", "i", "=>", "$", "label", ")", "{", "$", "weights", "[", "$", "label", "]", "+=", "1.", "/", "(", "1.", "+", "$", "distances", "[", "$", "i", "]", ")", ";", "}", "}", "else", "{", "$", "weights", "=", "array_count_values", "(", "$", "labels", ")", ";", "}", "$", "total", "=", "array_sum", "(", "$", "weights", ")", "?", ":", "EPSILON", ";", "$", "dist", "=", "$", "template", ";", "foreach", "(", "$", "weights", "as", "$", "class", "=>", "$", "weight", ")", "{", "$", "dist", "[", "$", "class", "]", "=", "$", "weight", "/", "$", "total", ";", "}", "$", "probabilities", "[", "]", "=", "$", "dist", ";", "}", "return", "$", "probabilities", ";", "}" ]
Estimate probabilities for each possible outcome. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException @throws \RuntimeException @return array
[ "Estimate", "probabilities", "for", "each", "possible", "outcome", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/KNearestNeighbors.php#L213-L251
RubixML/RubixML
src/Classifiers/KNearestNeighbors.php
KNearestNeighbors.nearest
protected function nearest(array $sample) : array { $distances = []; foreach ($this->samples as $neighbor) { $distances[] = $this->kernel->compute($sample, $neighbor); } asort($distances); $distances = array_slice($distances, 0, $this->k, true); $labels = array_intersect_key($this->labels, $distances); return [$labels, $distances]; }
php
protected function nearest(array $sample) : array { $distances = []; foreach ($this->samples as $neighbor) { $distances[] = $this->kernel->compute($sample, $neighbor); } asort($distances); $distances = array_slice($distances, 0, $this->k, true); $labels = array_intersect_key($this->labels, $distances); return [$labels, $distances]; }
[ "protected", "function", "nearest", "(", "array", "$", "sample", ")", ":", "array", "{", "$", "distances", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "samples", "as", "$", "neighbor", ")", "{", "$", "distances", "[", "]", "=", "$", "this", "->", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "neighbor", ")", ";", "}", "asort", "(", "$", "distances", ")", ";", "$", "distances", "=", "array_slice", "(", "$", "distances", ",", "0", ",", "$", "this", "->", "k", ",", "true", ")", ";", "$", "labels", "=", "array_intersect_key", "(", "$", "this", "->", "labels", ",", "$", "distances", ")", ";", "return", "[", "$", "labels", ",", "$", "distances", "]", ";", "}" ]
Find the K nearest neighbors to the given sample vector using the brute force method. @param array $sample @return array[]
[ "Find", "the", "K", "nearest", "neighbors", "to", "the", "given", "sample", "vector", "using", "the", "brute", "force", "method", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/KNearestNeighbors.php#L260-L275
RubixML/RubixML
src/NeuralNet/Layers/Placeholder1D.php
Placeholder1D.forward
public function forward(Matrix $input) : Matrix { if ($input->m() !== $this->inputs) { throw new InvalidArgumentException('The number of feature columns' . ' must equal the number of inputs. ' . " {$input->m()} found, but $this->inputs needed."); } return $input; }
php
public function forward(Matrix $input) : Matrix { if ($input->m() !== $this->inputs) { throw new InvalidArgumentException('The number of feature columns' . ' must equal the number of inputs. ' . " {$input->m()} found, but $this->inputs needed."); } return $input; }
[ "public", "function", "forward", "(", "Matrix", "$", "input", ")", ":", "Matrix", "{", "if", "(", "$", "input", "->", "m", "(", ")", "!==", "$", "this", "->", "inputs", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The number of feature columns'", ".", "' must equal the number of inputs. '", ".", "\" {$input->m()} found, but $this->inputs needed.\"", ")", ";", "}", "return", "$", "input", ";", "}" ]
Compute a forward pass through the layer. @param \Rubix\Tensor\Matrix $input @throws \InvalidArgumentException @return \Rubix\Tensor\Matrix
[ "Compute", "a", "forward", "pass", "through", "the", "layer", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/Placeholder1D.php#L68-L77
RubixML/RubixML
src/NeuralNet/FeedForward.php
FeedForward.layers
public function layers() : Generator { yield $this->input; foreach ($this->hidden as $hidden) { yield $hidden; } yield $this->output; }
php
public function layers() : Generator { yield $this->input; foreach ($this->hidden as $hidden) { yield $hidden; } yield $this->output; }
[ "public", "function", "layers", "(", ")", ":", "Generator", "{", "yield", "$", "this", "->", "input", ";", "foreach", "(", "$", "this", "->", "hidden", "as", "$", "hidden", ")", "{", "yield", "$", "hidden", ";", "}", "yield", "$", "this", "->", "output", ";", "}" ]
Return all the layers in the network. @return \Generator
[ "Return", "all", "the", "layers", "in", "the", "network", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/FeedForward.php#L146-L155
RubixML/RubixML
src/NeuralNet/FeedForward.php
FeedForward.parametric
public function parametric() : Generator { foreach ($this->hidden as $layer) { if ($layer instanceof Parametric) { yield $layer; } } if ($this->output instanceof Parametric) { yield $this->output; } }
php
public function parametric() : Generator { foreach ($this->hidden as $layer) { if ($layer instanceof Parametric) { yield $layer; } } if ($this->output instanceof Parametric) { yield $this->output; } }
[ "public", "function", "parametric", "(", ")", ":", "Generator", "{", "foreach", "(", "$", "this", "->", "hidden", "as", "$", "layer", ")", "{", "if", "(", "$", "layer", "instanceof", "Parametric", ")", "{", "yield", "$", "layer", ";", "}", "}", "if", "(", "$", "this", "->", "output", "instanceof", "Parametric", ")", "{", "yield", "$", "this", "->", "output", ";", "}", "}" ]
The parametric layers of the network. i.e. the layers that have weights. @return \Generator
[ "The", "parametric", "layers", "of", "the", "network", ".", "i", ".", "e", ".", "the", "layers", "that", "have", "weights", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/FeedForward.php#L162-L173
RubixML/RubixML
src/NeuralNet/FeedForward.php
FeedForward.roundtrip
public function roundtrip(Labeled $batch) : float { $input = Matrix::quick($batch->samples())->transpose(); $this->feed($input); return $this->backpropagate($batch->labels()); }
php
public function roundtrip(Labeled $batch) : float { $input = Matrix::quick($batch->samples())->transpose(); $this->feed($input); return $this->backpropagate($batch->labels()); }
[ "public", "function", "roundtrip", "(", "Labeled", "$", "batch", ")", ":", "float", "{", "$", "input", "=", "Matrix", "::", "quick", "(", "$", "batch", "->", "samples", "(", ")", ")", "->", "transpose", "(", ")", ";", "$", "this", "->", "feed", "(", "$", "input", ")", ";", "return", "$", "this", "->", "backpropagate", "(", "$", "batch", "->", "labels", "(", ")", ")", ";", "}" ]
Do a forward and backward pass of the network in one call. Returns the loss from the backward pass. @param \Rubix\ML\Datasets\Labeled $batch @return float
[ "Do", "a", "forward", "and", "backward", "pass", "of", "the", "network", "in", "one", "call", ".", "Returns", "the", "loss", "from", "the", "backward", "pass", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/FeedForward.php#L193-L200
RubixML/RubixML
src/NeuralNet/FeedForward.php
FeedForward.feed
public function feed(Matrix $input) : Matrix { $input = $this->input->forward($input); foreach ($this->hidden as $hidden) { $input = $hidden->forward($input); } return $this->output->forward($input); }
php
public function feed(Matrix $input) : Matrix { $input = $this->input->forward($input); foreach ($this->hidden as $hidden) { $input = $hidden->forward($input); } return $this->output->forward($input); }
[ "public", "function", "feed", "(", "Matrix", "$", "input", ")", ":", "Matrix", "{", "$", "input", "=", "$", "this", "->", "input", "->", "forward", "(", "$", "input", ")", ";", "foreach", "(", "$", "this", "->", "hidden", "as", "$", "hidden", ")", "{", "$", "input", "=", "$", "hidden", "->", "forward", "(", "$", "input", ")", ";", "}", "return", "$", "this", "->", "output", "->", "forward", "(", "$", "input", ")", ";", "}" ]
Feed a batch through the network and return a matrix of activations. @param \Rubix\Tensor\Matrix $input @return \Rubix\Tensor\Matrix
[ "Feed", "a", "batch", "through", "the", "network", "and", "return", "a", "matrix", "of", "activations", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/FeedForward.php#L208-L217
RubixML/RubixML
src/NeuralNet/FeedForward.php
FeedForward.infer
public function infer(Matrix $input) : Tensor { $input = $this->input->infer($input); foreach ($this->hidden as $hidden) { $input = $hidden->infer($input); } return $this->output->infer($input); }
php
public function infer(Matrix $input) : Tensor { $input = $this->input->infer($input); foreach ($this->hidden as $hidden) { $input = $hidden->infer($input); } return $this->output->infer($input); }
[ "public", "function", "infer", "(", "Matrix", "$", "input", ")", ":", "Tensor", "{", "$", "input", "=", "$", "this", "->", "input", "->", "infer", "(", "$", "input", ")", ";", "foreach", "(", "$", "this", "->", "hidden", "as", "$", "hidden", ")", "{", "$", "input", "=", "$", "hidden", "->", "infer", "(", "$", "input", ")", ";", "}", "return", "$", "this", "->", "output", "->", "infer", "(", "$", "input", ")", ";", "}" ]
Run an inference pass and return the activations at the output layer. @param \Rubix\Tensor\Matrix $input @return \Rubix\Tensor\Matrix
[ "Run", "an", "inference", "pass", "and", "return", "the", "activations", "at", "the", "output", "layer", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/FeedForward.php#L225-L234
RubixML/RubixML
src/NeuralNet/FeedForward.php
FeedForward.backpropagate
public function backpropagate(array $labels) : float { [$gradient, $loss] = $this->output->back($labels, $this->optimizer); foreach ($this->backPass as $layer) { $gradient = $layer->back($gradient, $this->optimizer); } return $loss; }
php
public function backpropagate(array $labels) : float { [$gradient, $loss] = $this->output->back($labels, $this->optimizer); foreach ($this->backPass as $layer) { $gradient = $layer->back($gradient, $this->optimizer); } return $loss; }
[ "public", "function", "backpropagate", "(", "array", "$", "labels", ")", ":", "float", "{", "[", "$", "gradient", ",", "$", "loss", "]", "=", "$", "this", "->", "output", "->", "back", "(", "$", "labels", ",", "$", "this", "->", "optimizer", ")", ";", "foreach", "(", "$", "this", "->", "backPass", "as", "$", "layer", ")", "{", "$", "gradient", "=", "$", "layer", "->", "back", "(", "$", "gradient", ",", "$", "this", "->", "optimizer", ")", ";", "}", "return", "$", "loss", ";", "}" ]
Backpropagate the gradient produced by the cost function and return the loss calculated by the output layer's cost function. @param array $labels @return float
[ "Backpropagate", "the", "gradient", "produced", "by", "the", "cost", "function", "and", "return", "the", "loss", "calculated", "by", "the", "output", "layer", "s", "cost", "function", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/FeedForward.php#L243-L252
RubixML/RubixML
src/NeuralNet/FeedForward.php
FeedForward.restore
public function restore(Snapshot $snapshot) : void { foreach ($snapshot as [$layer, $params]) { if ($layer instanceof Parametric) { $layer->restore($params); } } }
php
public function restore(Snapshot $snapshot) : void { foreach ($snapshot as [$layer, $params]) { if ($layer instanceof Parametric) { $layer->restore($params); } } }
[ "public", "function", "restore", "(", "Snapshot", "$", "snapshot", ")", ":", "void", "{", "foreach", "(", "$", "snapshot", "as", "[", "$", "layer", ",", "$", "params", "]", ")", "{", "if", "(", "$", "layer", "instanceof", "Parametric", ")", "{", "$", "layer", "->", "restore", "(", "$", "params", ")", ";", "}", "}", "}" ]
Restore the network parameters from a snapshot. @param \Rubix\ML\NeuralNet\Snapshot $snapshot
[ "Restore", "the", "network", "parameters", "from", "a", "snapshot", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/FeedForward.php#L259-L266
RubixML/RubixML
src/NeuralNet/Layers/Noise.php
Noise.forward
public function forward(Matrix $input) : Matrix { $noise = Matrix::gaussian(...$input->shape()) ->multiply($this->stdDev); return $input->add($noise); }
php
public function forward(Matrix $input) : Matrix { $noise = Matrix::gaussian(...$input->shape()) ->multiply($this->stdDev); return $input->add($noise); }
[ "public", "function", "forward", "(", "Matrix", "$", "input", ")", ":", "Matrix", "{", "$", "noise", "=", "Matrix", "::", "gaussian", "(", "...", "$", "input", "->", "shape", "(", ")", ")", "->", "multiply", "(", "$", "this", "->", "stdDev", ")", ";", "return", "$", "input", "->", "add", "(", "$", "noise", ")", ";", "}" ]
Compute a forward pass through the layer. @param \Rubix\Tensor\Matrix $input @return \Rubix\Tensor\Matrix
[ "Compute", "a", "forward", "pass", "through", "the", "layer", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/Noise.php#L93-L99
RubixML/RubixML
src/Other/Tokenizers/Word.php
Word.tokenize
public function tokenize(string $string) : array { $words = []; preg_match_all(self::WORD_REGEX, $string, $words); return $words[0]; }
php
public function tokenize(string $string) : array { $words = []; preg_match_all(self::WORD_REGEX, $string, $words); return $words[0]; }
[ "public", "function", "tokenize", "(", "string", "$", "string", ")", ":", "array", "{", "$", "words", "=", "[", "]", ";", "preg_match_all", "(", "self", "::", "WORD_REGEX", ",", "$", "string", ",", "$", "words", ")", ";", "return", "$", "words", "[", "0", "]", ";", "}" ]
Tokenize a block of text. @param string $string @return array
[ "Tokenize", "a", "block", "of", "text", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Tokenizers/Word.php#L24-L31
RubixML/RubixML
src/Transformers/SparseRandomProjector.php
SparseRandomProjector.fit
public function fit(Dataset $dataset) : void { if (!$dataset->homogeneous() or $dataset->columnType(0) !== DataType::CONTINUOUS) { throw new InvalidArgumentException('This transformer only works' . ' with continuous features.'); } $columns = $dataset->numColumns(); $p = count(static::DISTRIBUTION) - 1; $r = []; for ($i = 0; $i < $columns; $i++) { $row = []; for ($j = 0; $j < $this->dimensions; $j++) { $row[] = static::DISTRIBUTION[rand(0, $p)]; } $r[] = $row; } $this->r = Matrix::quick($r); }
php
public function fit(Dataset $dataset) : void { if (!$dataset->homogeneous() or $dataset->columnType(0) !== DataType::CONTINUOUS) { throw new InvalidArgumentException('This transformer only works' . ' with continuous features.'); } $columns = $dataset->numColumns(); $p = count(static::DISTRIBUTION) - 1; $r = []; for ($i = 0; $i < $columns; $i++) { $row = []; for ($j = 0; $j < $this->dimensions; $j++) { $row[] = static::DISTRIBUTION[rand(0, $p)]; } $r[] = $row; } $this->r = Matrix::quick($r); }
[ "public", "function", "fit", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "if", "(", "!", "$", "dataset", "->", "homogeneous", "(", ")", "or", "$", "dataset", "->", "columnType", "(", "0", ")", "!==", "DataType", "::", "CONTINUOUS", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'This transformer only works'", ".", "' with continuous features.'", ")", ";", "}", "$", "columns", "=", "$", "dataset", "->", "numColumns", "(", ")", ";", "$", "p", "=", "count", "(", "static", "::", "DISTRIBUTION", ")", "-", "1", ";", "$", "r", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "columns", ";", "$", "i", "++", ")", "{", "$", "row", "=", "[", "]", ";", "for", "(", "$", "j", "=", "0", ";", "$", "j", "<", "$", "this", "->", "dimensions", ";", "$", "j", "++", ")", "{", "$", "row", "[", "]", "=", "static", "::", "DISTRIBUTION", "[", "rand", "(", "0", ",", "$", "p", ")", "]", ";", "}", "$", "r", "[", "]", "=", "$", "row", ";", "}", "$", "this", "->", "r", "=", "Matrix", "::", "quick", "(", "$", "r", ")", ";", "}" ]
Fit the transformer to the dataset. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException
[ "Fit", "the", "transformer", "to", "the", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/SparseRandomProjector.php#L36-L60
RubixML/RubixML
src/CrossValidation/Metrics/MedianAbsoluteError.php
MedianAbsoluteError.score
public function score(array $predictions, array $labels) : float { if (empty($predictions)) { return 0.; } if (count($predictions) !== count($labels)) { throw new InvalidArgumentException('The number of labels' . ' must equal the number of predictions.'); } $errors = []; foreach ($predictions as $i => $prediction) { $errors[] = abs($labels[$i] - $prediction); } return -Stats::median($errors); }
php
public function score(array $predictions, array $labels) : float { if (empty($predictions)) { return 0.; } if (count($predictions) !== count($labels)) { throw new InvalidArgumentException('The number of labels' . ' must equal the number of predictions.'); } $errors = []; foreach ($predictions as $i => $prediction) { $errors[] = abs($labels[$i] - $prediction); } return -Stats::median($errors); }
[ "public", "function", "score", "(", "array", "$", "predictions", ",", "array", "$", "labels", ")", ":", "float", "{", "if", "(", "empty", "(", "$", "predictions", ")", ")", "{", "return", "0.", ";", "}", "if", "(", "count", "(", "$", "predictions", ")", "!==", "count", "(", "$", "labels", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The number of labels'", ".", "' must equal the number of predictions.'", ")", ";", "}", "$", "errors", "=", "[", "]", ";", "foreach", "(", "$", "predictions", "as", "$", "i", "=>", "$", "prediction", ")", "{", "$", "errors", "[", "]", "=", "abs", "(", "$", "labels", "[", "$", "i", "]", "-", "$", "prediction", ")", ";", "}", "return", "-", "Stats", "::", "median", "(", "$", "errors", ")", ";", "}" ]
Score a set of predictions. @param array $predictions @param array $labels @throws \InvalidArgumentException @return float
[ "Score", "a", "set", "of", "predictions", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CrossValidation/Metrics/MedianAbsoluteError.php#L51-L69
RubixML/RubixML
src/Graph/KDTree.php
KDTree.grow
public function grow(Labeled $dataset) : void { $this->root = Coordinate::split($dataset); $stack = [$this->root]; while ($stack) { $current = array_pop($stack); if (!$current instanceof Coordinate) { continue 1; } [$left, $right] = $current->groups(); if ($left->numRows() > $this->maxLeafSize) { $node = Coordinate::split($left); $current->attachLeft($node); $stack[] = $node; } else { $current->attachLeft(Neighborhood::terminate($left)); } if ($right->numRows() > $this->maxLeafSize) { $node = Coordinate::split($right); $current->attachRight($node); $stack[] = $node; } else { $current->attachRight(Neighborhood::terminate($right)); } $current->cleanup(); } }
php
public function grow(Labeled $dataset) : void { $this->root = Coordinate::split($dataset); $stack = [$this->root]; while ($stack) { $current = array_pop($stack); if (!$current instanceof Coordinate) { continue 1; } [$left, $right] = $current->groups(); if ($left->numRows() > $this->maxLeafSize) { $node = Coordinate::split($left); $current->attachLeft($node); $stack[] = $node; } else { $current->attachLeft(Neighborhood::terminate($left)); } if ($right->numRows() > $this->maxLeafSize) { $node = Coordinate::split($right); $current->attachRight($node); $stack[] = $node; } else { $current->attachRight(Neighborhood::terminate($right)); } $current->cleanup(); } }
[ "public", "function", "grow", "(", "Labeled", "$", "dataset", ")", ":", "void", "{", "$", "this", "->", "root", "=", "Coordinate", "::", "split", "(", "$", "dataset", ")", ";", "$", "stack", "=", "[", "$", "this", "->", "root", "]", ";", "while", "(", "$", "stack", ")", "{", "$", "current", "=", "array_pop", "(", "$", "stack", ")", ";", "if", "(", "!", "$", "current", "instanceof", "Coordinate", ")", "{", "continue", "1", ";", "}", "[", "$", "left", ",", "$", "right", "]", "=", "$", "current", "->", "groups", "(", ")", ";", "if", "(", "$", "left", "->", "numRows", "(", ")", ">", "$", "this", "->", "maxLeafSize", ")", "{", "$", "node", "=", "Coordinate", "::", "split", "(", "$", "left", ")", ";", "$", "current", "->", "attachLeft", "(", "$", "node", ")", ";", "$", "stack", "[", "]", "=", "$", "node", ";", "}", "else", "{", "$", "current", "->", "attachLeft", "(", "Neighborhood", "::", "terminate", "(", "$", "left", ")", ")", ";", "}", "if", "(", "$", "right", "->", "numRows", "(", ")", ">", "$", "this", "->", "maxLeafSize", ")", "{", "$", "node", "=", "Coordinate", "::", "split", "(", "$", "right", ")", ";", "$", "current", "->", "attachRight", "(", "$", "node", ")", ";", "$", "stack", "[", "]", "=", "$", "node", ";", "}", "else", "{", "$", "current", "->", "attachRight", "(", "Neighborhood", "::", "terminate", "(", "$", "right", ")", ")", ";", "}", "$", "current", "->", "cleanup", "(", ")", ";", "}", "}" ]
Insert a root node into the tree and recursively split the training data until a terminating condition is met. @param \Rubix\ML\Datasets\Labeled $dataset
[ "Insert", "a", "root", "node", "into", "the", "tree", "and", "recursively", "split", "the", "training", "data", "until", "a", "terminating", "condition", "is", "met", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/KDTree.php#L111-L148
RubixML/RubixML
src/Graph/KDTree.php
KDTree.search
public function search(array $sample) : ?Neighborhood { $current = $this->root; while ($current) { if ($current instanceof Coordinate) { if ($sample[$current->column()] < $current->value()) { $current = $current->left(); } else { $current = $current->right(); } continue 1; } if ($current instanceof Neighborhood) { return $current; } } return null; }
php
public function search(array $sample) : ?Neighborhood { $current = $this->root; while ($current) { if ($current instanceof Coordinate) { if ($sample[$current->column()] < $current->value()) { $current = $current->left(); } else { $current = $current->right(); } continue 1; } if ($current instanceof Neighborhood) { return $current; } } return null; }
[ "public", "function", "search", "(", "array", "$", "sample", ")", ":", "?", "Neighborhood", "{", "$", "current", "=", "$", "this", "->", "root", ";", "while", "(", "$", "current", ")", "{", "if", "(", "$", "current", "instanceof", "Coordinate", ")", "{", "if", "(", "$", "sample", "[", "$", "current", "->", "column", "(", ")", "]", "<", "$", "current", "->", "value", "(", ")", ")", "{", "$", "current", "=", "$", "current", "->", "left", "(", ")", ";", "}", "else", "{", "$", "current", "=", "$", "current", "->", "right", "(", ")", ";", "}", "continue", "1", ";", "}", "if", "(", "$", "current", "instanceof", "Neighborhood", ")", "{", "return", "$", "current", ";", "}", "}", "return", "null", ";", "}" ]
Search the tree for a neighborhood and return an array of samples and labels. @param array $sample @return \Rubix\ML\Graph\Nodes\Neighborhood|null
[ "Search", "the", "tree", "for", "a", "neighborhood", "and", "return", "an", "array", "of", "samples", "and", "labels", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/KDTree.php#L157-L178
RubixML/RubixML
src/Graph/KDTree.php
KDTree.nearest
public function nearest(array $sample, int $k = 1) : array { if ($k < 1) { throw new InvalidArgumentException('The number of nearest' . " neighbors must be greater than 0, $k given."); } $neighborhood = $this->search($sample); if (!$neighborhood) { return [[], []]; } $distances = $labels = []; $visited = new SplObjectStorage(); $stack = [$neighborhood]; while ($stack) { $current = array_pop($stack); if ($visited->contains($current)) { continue 1; } $visited->attach($current); $parent = $current->parent(); if ($parent) { $stack[] = $parent; } if ($current instanceof Neighborhood) { foreach ($current->samples() as $neighbor) { $distances[] = $this->kernel->compute($sample, $neighbor); } $labels = array_merge($labels, $current->labels()); array_multisort($distances, $labels); continue 1; } $target = $distances[$k - 1] ?? INF; foreach ($current->children() as $child) { if ($visited->contains($child)) { continue 1; } if ($child instanceof Box) { foreach ($child->sides() as $side) { $distance = $this->kernel->compute($sample, $side); if ($distance < $target) { $stack[] = $child; continue 2; } } } $visited->attach($child); } } $distances = array_slice($distances, 0, $k); $labels = array_slice($labels, 0, $k); return [$labels, $distances]; }
php
public function nearest(array $sample, int $k = 1) : array { if ($k < 1) { throw new InvalidArgumentException('The number of nearest' . " neighbors must be greater than 0, $k given."); } $neighborhood = $this->search($sample); if (!$neighborhood) { return [[], []]; } $distances = $labels = []; $visited = new SplObjectStorage(); $stack = [$neighborhood]; while ($stack) { $current = array_pop($stack); if ($visited->contains($current)) { continue 1; } $visited->attach($current); $parent = $current->parent(); if ($parent) { $stack[] = $parent; } if ($current instanceof Neighborhood) { foreach ($current->samples() as $neighbor) { $distances[] = $this->kernel->compute($sample, $neighbor); } $labels = array_merge($labels, $current->labels()); array_multisort($distances, $labels); continue 1; } $target = $distances[$k - 1] ?? INF; foreach ($current->children() as $child) { if ($visited->contains($child)) { continue 1; } if ($child instanceof Box) { foreach ($child->sides() as $side) { $distance = $this->kernel->compute($sample, $side); if ($distance < $target) { $stack[] = $child; continue 2; } } } $visited->attach($child); } } $distances = array_slice($distances, 0, $k); $labels = array_slice($labels, 0, $k); return [$labels, $distances]; }
[ "public", "function", "nearest", "(", "array", "$", "sample", ",", "int", "$", "k", "=", "1", ")", ":", "array", "{", "if", "(", "$", "k", "<", "1", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The number of nearest'", ".", "\" neighbors must be greater than 0, $k given.\"", ")", ";", "}", "$", "neighborhood", "=", "$", "this", "->", "search", "(", "$", "sample", ")", ";", "if", "(", "!", "$", "neighborhood", ")", "{", "return", "[", "[", "]", ",", "[", "]", "]", ";", "}", "$", "distances", "=", "$", "labels", "=", "[", "]", ";", "$", "visited", "=", "new", "SplObjectStorage", "(", ")", ";", "$", "stack", "=", "[", "$", "neighborhood", "]", ";", "while", "(", "$", "stack", ")", "{", "$", "current", "=", "array_pop", "(", "$", "stack", ")", ";", "if", "(", "$", "visited", "->", "contains", "(", "$", "current", ")", ")", "{", "continue", "1", ";", "}", "$", "visited", "->", "attach", "(", "$", "current", ")", ";", "$", "parent", "=", "$", "current", "->", "parent", "(", ")", ";", "if", "(", "$", "parent", ")", "{", "$", "stack", "[", "]", "=", "$", "parent", ";", "}", "if", "(", "$", "current", "instanceof", "Neighborhood", ")", "{", "foreach", "(", "$", "current", "->", "samples", "(", ")", "as", "$", "neighbor", ")", "{", "$", "distances", "[", "]", "=", "$", "this", "->", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "neighbor", ")", ";", "}", "$", "labels", "=", "array_merge", "(", "$", "labels", ",", "$", "current", "->", "labels", "(", ")", ")", ";", "array_multisort", "(", "$", "distances", ",", "$", "labels", ")", ";", "continue", "1", ";", "}", "$", "target", "=", "$", "distances", "[", "$", "k", "-", "1", "]", "??", "INF", ";", "foreach", "(", "$", "current", "->", "children", "(", ")", "as", "$", "child", ")", "{", "if", "(", "$", "visited", "->", "contains", "(", "$", "child", ")", ")", "{", "continue", "1", ";", "}", "if", "(", "$", "child", "instanceof", "Box", ")", "{", "foreach", "(", "$", "child", "->", "sides", "(", ")", "as", "$", "side", ")", "{", "$", "distance", "=", "$", "this", "->", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "side", ")", ";", "if", "(", "$", "distance", "<", "$", "target", ")", "{", "$", "stack", "[", "]", "=", "$", "child", ";", "continue", "2", ";", "}", "}", "}", "$", "visited", "->", "attach", "(", "$", "child", ")", ";", "}", "}", "$", "distances", "=", "array_slice", "(", "$", "distances", ",", "0", ",", "$", "k", ")", ";", "$", "labels", "=", "array_slice", "(", "$", "labels", ",", "0", ",", "$", "k", ")", ";", "return", "[", "$", "labels", ",", "$", "distances", "]", ";", "}" ]
Run a k nearest neighbors search of every neighborhood and return the labels and distances in a 2-tuple. @param array $sample @param int $k @throws \InvalidArgumentException @return array[]
[ "Run", "a", "k", "nearest", "neighbors", "search", "of", "every", "neighborhood", "and", "return", "the", "labels", "and", "distances", "in", "a", "2", "-", "tuple", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/KDTree.php#L189-L262
RubixML/RubixML
src/Classifiers/SVC.php
SVC.train
public function train(Dataset $dataset) : void { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('This estimator requires a' . ' labeled training set.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $this->classes = $dataset->possibleOutcomes(); $mapping = array_flip($this->classes); $labels = $dataset->labels(); $data = []; foreach ($dataset as $i => $sample) { $data[] = array_merge([$mapping[$labels[$i]]], $sample); } $this->model = $this->svm->train($data); }
php
public function train(Dataset $dataset) : void { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('This estimator requires a' . ' labeled training set.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $this->classes = $dataset->possibleOutcomes(); $mapping = array_flip($this->classes); $labels = $dataset->labels(); $data = []; foreach ($dataset as $i => $sample) { $data[] = array_merge([$mapping[$labels[$i]]], $sample); } $this->model = $this->svm->train($data); }
[ "public", "function", "train", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "if", "(", "!", "$", "dataset", "instanceof", "Labeled", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'This estimator requires a'", ".", "' labeled training set.'", ")", ";", "}", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "$", "this", "->", "classes", "=", "$", "dataset", "->", "possibleOutcomes", "(", ")", ";", "$", "mapping", "=", "array_flip", "(", "$", "this", "->", "classes", ")", ";", "$", "labels", "=", "$", "dataset", "->", "labels", "(", ")", ";", "$", "data", "=", "[", "]", ";", "foreach", "(", "$", "dataset", "as", "$", "i", "=>", "$", "sample", ")", "{", "$", "data", "[", "]", "=", "array_merge", "(", "[", "$", "mapping", "[", "$", "labels", "[", "$", "i", "]", "]", "]", ",", "$", "sample", ")", ";", "}", "$", "this", "->", "model", "=", "$", "this", "->", "svm", "->", "train", "(", "$", "data", ")", ";", "}" ]
Train the learner with a dataset. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException
[ "Train", "the", "learner", "with", "a", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/SVC.php#L150-L172
RubixML/RubixML
src/Graph/BallTree.php
BallTree.grow
public function grow(Dataset $dataset) : void { $this->root = Hypersphere::split($dataset, $this->kernel); $stack = [$this->root]; while ($stack) { $current = array_pop($stack); if (!$current instanceof Hypersphere) { continue 1; } [$left, $right] = $current->groups(); if ($left->numRows() > $this->maxLeafSize) { $node = Hypersphere::split($left, $this->kernel); $current->attachLeft($node); $stack[] = $node; } else { $node = Cluster::terminate($left, $this->kernel); $current->attachLeft($node); } if ($right->numRows() > $this->maxLeafSize) { $node = Hypersphere::split($right, $this->kernel); $current->attachRight($node); $stack[] = $node; } else { $node = Cluster::terminate($right, $this->kernel); $current->attachRight($node); } $current->cleanup(); } }
php
public function grow(Dataset $dataset) : void { $this->root = Hypersphere::split($dataset, $this->kernel); $stack = [$this->root]; while ($stack) { $current = array_pop($stack); if (!$current instanceof Hypersphere) { continue 1; } [$left, $right] = $current->groups(); if ($left->numRows() > $this->maxLeafSize) { $node = Hypersphere::split($left, $this->kernel); $current->attachLeft($node); $stack[] = $node; } else { $node = Cluster::terminate($left, $this->kernel); $current->attachLeft($node); } if ($right->numRows() > $this->maxLeafSize) { $node = Hypersphere::split($right, $this->kernel); $current->attachRight($node); $stack[] = $node; } else { $node = Cluster::terminate($right, $this->kernel); $current->attachRight($node); } $current->cleanup(); } }
[ "public", "function", "grow", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "$", "this", "->", "root", "=", "Hypersphere", "::", "split", "(", "$", "dataset", ",", "$", "this", "->", "kernel", ")", ";", "$", "stack", "=", "[", "$", "this", "->", "root", "]", ";", "while", "(", "$", "stack", ")", "{", "$", "current", "=", "array_pop", "(", "$", "stack", ")", ";", "if", "(", "!", "$", "current", "instanceof", "Hypersphere", ")", "{", "continue", "1", ";", "}", "[", "$", "left", ",", "$", "right", "]", "=", "$", "current", "->", "groups", "(", ")", ";", "if", "(", "$", "left", "->", "numRows", "(", ")", ">", "$", "this", "->", "maxLeafSize", ")", "{", "$", "node", "=", "Hypersphere", "::", "split", "(", "$", "left", ",", "$", "this", "->", "kernel", ")", ";", "$", "current", "->", "attachLeft", "(", "$", "node", ")", ";", "$", "stack", "[", "]", "=", "$", "node", ";", "}", "else", "{", "$", "node", "=", "Cluster", "::", "terminate", "(", "$", "left", ",", "$", "this", "->", "kernel", ")", ";", "$", "current", "->", "attachLeft", "(", "$", "node", ")", ";", "}", "if", "(", "$", "right", "->", "numRows", "(", ")", ">", "$", "this", "->", "maxLeafSize", ")", "{", "$", "node", "=", "Hypersphere", "::", "split", "(", "$", "right", ",", "$", "this", "->", "kernel", ")", ";", "$", "current", "->", "attachRight", "(", "$", "node", ")", ";", "$", "stack", "[", "]", "=", "$", "node", ";", "}", "else", "{", "$", "node", "=", "Cluster", "::", "terminate", "(", "$", "right", ",", "$", "this", "->", "kernel", ")", ";", "$", "current", "->", "attachRight", "(", "$", "node", ")", ";", "}", "$", "current", "->", "cleanup", "(", ")", ";", "}", "}" ]
Insert a root node into the tree and recursively split the training data until a terminating condition is met. @param \Rubix\ML\Datasets\Dataset $dataset
[ "Insert", "a", "root", "node", "into", "the", "tree", "and", "recursively", "split", "the", "training", "data", "until", "a", "terminating", "condition", "is", "met", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/BallTree.php#L112-L153
RubixML/RubixML
src/Graph/BallTree.php
BallTree.range
public function range(array $sample, float $radius) : array { if ($radius <= 0.) { throw new InvalidArgumentException('Radius must be' . " greater than 0, $radius given."); } $samples = $labels = $distances = []; $stack = [$this->root]; while ($stack) { $current = array_pop($stack); if (!$current instanceof BinaryNode) { continue 1; } if ($current instanceof Cluster) { foreach ($current->samples() as $i => $neighbor) { $distance = $this->kernel->compute($sample, $neighbor); if ($distance <= $radius) { $samples[] = $neighbor; $labels[] = $current->label($i); $distances[] = $distance; } } continue 1; } foreach ($current->children() as $child) { if ($child instanceof Ball) { $distance = $this->kernel->compute($sample, $child->center()); if ($distance <= ($child->radius() + $radius)) { $stack[] = $child; } } } } return [$samples, $labels, $distances]; }
php
public function range(array $sample, float $radius) : array { if ($radius <= 0.) { throw new InvalidArgumentException('Radius must be' . " greater than 0, $radius given."); } $samples = $labels = $distances = []; $stack = [$this->root]; while ($stack) { $current = array_pop($stack); if (!$current instanceof BinaryNode) { continue 1; } if ($current instanceof Cluster) { foreach ($current->samples() as $i => $neighbor) { $distance = $this->kernel->compute($sample, $neighbor); if ($distance <= $radius) { $samples[] = $neighbor; $labels[] = $current->label($i); $distances[] = $distance; } } continue 1; } foreach ($current->children() as $child) { if ($child instanceof Ball) { $distance = $this->kernel->compute($sample, $child->center()); if ($distance <= ($child->radius() + $radius)) { $stack[] = $child; } } } } return [$samples, $labels, $distances]; }
[ "public", "function", "range", "(", "array", "$", "sample", ",", "float", "$", "radius", ")", ":", "array", "{", "if", "(", "$", "radius", "<=", "0.", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Radius must be'", ".", "\" greater than 0, $radius given.\"", ")", ";", "}", "$", "samples", "=", "$", "labels", "=", "$", "distances", "=", "[", "]", ";", "$", "stack", "=", "[", "$", "this", "->", "root", "]", ";", "while", "(", "$", "stack", ")", "{", "$", "current", "=", "array_pop", "(", "$", "stack", ")", ";", "if", "(", "!", "$", "current", "instanceof", "BinaryNode", ")", "{", "continue", "1", ";", "}", "if", "(", "$", "current", "instanceof", "Cluster", ")", "{", "foreach", "(", "$", "current", "->", "samples", "(", ")", "as", "$", "i", "=>", "$", "neighbor", ")", "{", "$", "distance", "=", "$", "this", "->", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "neighbor", ")", ";", "if", "(", "$", "distance", "<=", "$", "radius", ")", "{", "$", "samples", "[", "]", "=", "$", "neighbor", ";", "$", "labels", "[", "]", "=", "$", "current", "->", "label", "(", "$", "i", ")", ";", "$", "distances", "[", "]", "=", "$", "distance", ";", "}", "}", "continue", "1", ";", "}", "foreach", "(", "$", "current", "->", "children", "(", ")", "as", "$", "child", ")", "{", "if", "(", "$", "child", "instanceof", "Ball", ")", "{", "$", "distance", "=", "$", "this", "->", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "child", "->", "center", "(", ")", ")", ";", "if", "(", "$", "distance", "<=", "(", "$", "child", "->", "radius", "(", ")", "+", "$", "radius", ")", ")", "{", "$", "stack", "[", "]", "=", "$", "child", ";", "}", "}", "}", "}", "return", "[", "$", "samples", ",", "$", "labels", ",", "$", "distances", "]", ";", "}" ]
Run a range search over every cluster within radius and return the labels and distances in a 2-tuple. @param array $sample @param float $radius @throws \InvalidArgumentException @return array[]
[ "Run", "a", "range", "search", "over", "every", "cluster", "within", "radius", "and", "return", "the", "labels", "and", "distances", "in", "a", "2", "-", "tuple", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/BallTree.php#L164-L208
RubixML/RubixML
src/Transformers/WordCountVectorizer.php
WordCountVectorizer.fit
public function fit(Dataset $dataset) : void { $columns = $dataset->columnsByType(DataType::CATEGORICAL); $this->vocabulary = []; foreach ($columns as $column => $values) { $tfs = $dfs = []; foreach ($values as $text) { $tokens = $this->tokenizer->tokenize($text); $counts = array_count_values($tokens); foreach ($counts as $token => $count) { if (isset($tfs[$token])) { $tfs[$token] += $count; $dfs[$token] += 1; } else { $tfs[$token] = $count; $dfs[$token] = 1; } } } if ($this->minDocumentFrequency > 1) { foreach ($dfs as $token => $frequency) { if ($frequency < $this->minDocumentFrequency) { unset($tfs[$token]); } } } if (count($tfs) > $this->maxVocabulary) { arsort($tfs); $tfs = array_slice($tfs, 0, $this->maxVocabulary, true); } $this->vocabulary[$column] = array_combine( array_keys($tfs), range(0, count($tfs) - 1) ) ?: []; } }
php
public function fit(Dataset $dataset) : void { $columns = $dataset->columnsByType(DataType::CATEGORICAL); $this->vocabulary = []; foreach ($columns as $column => $values) { $tfs = $dfs = []; foreach ($values as $text) { $tokens = $this->tokenizer->tokenize($text); $counts = array_count_values($tokens); foreach ($counts as $token => $count) { if (isset($tfs[$token])) { $tfs[$token] += $count; $dfs[$token] += 1; } else { $tfs[$token] = $count; $dfs[$token] = 1; } } } if ($this->minDocumentFrequency > 1) { foreach ($dfs as $token => $frequency) { if ($frequency < $this->minDocumentFrequency) { unset($tfs[$token]); } } } if (count($tfs) > $this->maxVocabulary) { arsort($tfs); $tfs = array_slice($tfs, 0, $this->maxVocabulary, true); } $this->vocabulary[$column] = array_combine( array_keys($tfs), range(0, count($tfs) - 1) ) ?: []; } }
[ "public", "function", "fit", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "$", "columns", "=", "$", "dataset", "->", "columnsByType", "(", "DataType", "::", "CATEGORICAL", ")", ";", "$", "this", "->", "vocabulary", "=", "[", "]", ";", "foreach", "(", "$", "columns", "as", "$", "column", "=>", "$", "values", ")", "{", "$", "tfs", "=", "$", "dfs", "=", "[", "]", ";", "foreach", "(", "$", "values", "as", "$", "text", ")", "{", "$", "tokens", "=", "$", "this", "->", "tokenizer", "->", "tokenize", "(", "$", "text", ")", ";", "$", "counts", "=", "array_count_values", "(", "$", "tokens", ")", ";", "foreach", "(", "$", "counts", "as", "$", "token", "=>", "$", "count", ")", "{", "if", "(", "isset", "(", "$", "tfs", "[", "$", "token", "]", ")", ")", "{", "$", "tfs", "[", "$", "token", "]", "+=", "$", "count", ";", "$", "dfs", "[", "$", "token", "]", "+=", "1", ";", "}", "else", "{", "$", "tfs", "[", "$", "token", "]", "=", "$", "count", ";", "$", "dfs", "[", "$", "token", "]", "=", "1", ";", "}", "}", "}", "if", "(", "$", "this", "->", "minDocumentFrequency", ">", "1", ")", "{", "foreach", "(", "$", "dfs", "as", "$", "token", "=>", "$", "frequency", ")", "{", "if", "(", "$", "frequency", "<", "$", "this", "->", "minDocumentFrequency", ")", "{", "unset", "(", "$", "tfs", "[", "$", "token", "]", ")", ";", "}", "}", "}", "if", "(", "count", "(", "$", "tfs", ")", ">", "$", "this", "->", "maxVocabulary", ")", "{", "arsort", "(", "$", "tfs", ")", ";", "$", "tfs", "=", "array_slice", "(", "$", "tfs", ",", "0", ",", "$", "this", "->", "maxVocabulary", ",", "true", ")", ";", "}", "$", "this", "->", "vocabulary", "[", "$", "column", "]", "=", "array_combine", "(", "array_keys", "(", "$", "tfs", ")", ",", "range", "(", "0", ",", "count", "(", "$", "tfs", ")", "-", "1", ")", ")", "?", ":", "[", "]", ";", "}", "}" ]
Fit the transformer to the dataset. @param \Rubix\ML\Datasets\Dataset $dataset
[ "Fit", "the", "transformer", "to", "the", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/WordCountVectorizer.php#L118-L162
RubixML/RubixML
src/Transformers/WordCountVectorizer.php
WordCountVectorizer.transform
public function transform(array &$samples) : void { if ($this->vocabulary === null) { throw new RuntimeException('Transformer is not fitted.'); } $templates = []; foreach ($this->vocabulary as $column => $vocabulary) { $templates[$column] = array_fill(0, count($vocabulary), 0); } foreach ($samples as &$sample) { $vectors = []; foreach ($this->vocabulary as $column => $vocabulary) { $text = $sample[$column]; $tokens = $this->tokenizer->tokenize($text); $counts = array_count_values($tokens); $features = $templates[$column]; foreach ($counts as $token => $count) { if (isset($vocabulary[$token])) { $features[$vocabulary[$token]] = $count; } } $vectors[] = $features; unset($sample[$column]); } $sample = array_merge($sample, ...$vectors); } }
php
public function transform(array &$samples) : void { if ($this->vocabulary === null) { throw new RuntimeException('Transformer is not fitted.'); } $templates = []; foreach ($this->vocabulary as $column => $vocabulary) { $templates[$column] = array_fill(0, count($vocabulary), 0); } foreach ($samples as &$sample) { $vectors = []; foreach ($this->vocabulary as $column => $vocabulary) { $text = $sample[$column]; $tokens = $this->tokenizer->tokenize($text); $counts = array_count_values($tokens); $features = $templates[$column]; foreach ($counts as $token => $count) { if (isset($vocabulary[$token])) { $features[$vocabulary[$token]] = $count; } } $vectors[] = $features; unset($sample[$column]); } $sample = array_merge($sample, ...$vectors); } }
[ "public", "function", "transform", "(", "array", "&", "$", "samples", ")", ":", "void", "{", "if", "(", "$", "this", "->", "vocabulary", "===", "null", ")", "{", "throw", "new", "RuntimeException", "(", "'Transformer is not fitted.'", ")", ";", "}", "$", "templates", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "vocabulary", "as", "$", "column", "=>", "$", "vocabulary", ")", "{", "$", "templates", "[", "$", "column", "]", "=", "array_fill", "(", "0", ",", "count", "(", "$", "vocabulary", ")", ",", "0", ")", ";", "}", "foreach", "(", "$", "samples", "as", "&", "$", "sample", ")", "{", "$", "vectors", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "vocabulary", "as", "$", "column", "=>", "$", "vocabulary", ")", "{", "$", "text", "=", "$", "sample", "[", "$", "column", "]", ";", "$", "tokens", "=", "$", "this", "->", "tokenizer", "->", "tokenize", "(", "$", "text", ")", ";", "$", "counts", "=", "array_count_values", "(", "$", "tokens", ")", ";", "$", "features", "=", "$", "templates", "[", "$", "column", "]", ";", "foreach", "(", "$", "counts", "as", "$", "token", "=>", "$", "count", ")", "{", "if", "(", "isset", "(", "$", "vocabulary", "[", "$", "token", "]", ")", ")", "{", "$", "features", "[", "$", "vocabulary", "[", "$", "token", "]", "]", "=", "$", "count", ";", "}", "}", "$", "vectors", "[", "]", "=", "$", "features", ";", "unset", "(", "$", "sample", "[", "$", "column", "]", ")", ";", "}", "$", "sample", "=", "array_merge", "(", "$", "sample", ",", "...", "$", "vectors", ")", ";", "}", "}" ]
Transform the dataset in place. @param array $samples @throws \RuntimeException
[ "Transform", "the", "dataset", "in", "place", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/WordCountVectorizer.php#L170-L207
RubixML/RubixML
src/Regressors/SVR.php
SVR.predict
public function predict(Dataset $dataset) : array { if (!$this->model) { throw new RuntimeException('Estimator has not been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); return array_map([$this->model, 'predict'], $dataset->samples()); }
php
public function predict(Dataset $dataset) : array { if (!$this->model) { throw new RuntimeException('Estimator has not been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); return array_map([$this->model, 'predict'], $dataset->samples()); }
[ "public", "function", "predict", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "if", "(", "!", "$", "this", "->", "model", ")", "{", "throw", "new", "RuntimeException", "(", "'Estimator has not been trained.'", ")", ";", "}", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "return", "array_map", "(", "[", "$", "this", "->", "model", ",", "'predict'", "]", ",", "$", "dataset", "->", "samples", "(", ")", ")", ";", "}" ]
Make predictions from a dataset. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException @throws \RuntimeException @return array
[ "Make", "predictions", "from", "a", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Regressors/SVR.php#L181-L190
RubixML/RubixML
src/Datasets/Generators/SwissRoll.php
SwissRoll.generate
public function generate(int $n) : Dataset { $t = Vector::rand($n)->multiply(2)->add(1) ->multiply(1.5 * M_PI); $x = $t->multiply($t->cos()); $y = Vector::rand($n)->multiply($this->depth); $z = $t->multiply($t->sin()); $noise = Matrix::gaussian($n, 3) ->multiply($this->noise); $samples = Matrix::stack([$x, $y, $z]) ->transpose() ->add($noise) ->multiply($this->scale) ->add($this->center) ->asArray(); $labels = $t->asArray(); return Labeled::quick($samples, $labels); }
php
public function generate(int $n) : Dataset { $t = Vector::rand($n)->multiply(2)->add(1) ->multiply(1.5 * M_PI); $x = $t->multiply($t->cos()); $y = Vector::rand($n)->multiply($this->depth); $z = $t->multiply($t->sin()); $noise = Matrix::gaussian($n, 3) ->multiply($this->noise); $samples = Matrix::stack([$x, $y, $z]) ->transpose() ->add($noise) ->multiply($this->scale) ->add($this->center) ->asArray(); $labels = $t->asArray(); return Labeled::quick($samples, $labels); }
[ "public", "function", "generate", "(", "int", "$", "n", ")", ":", "Dataset", "{", "$", "t", "=", "Vector", "::", "rand", "(", "$", "n", ")", "->", "multiply", "(", "2", ")", "->", "add", "(", "1", ")", "->", "multiply", "(", "1.5", "*", "M_PI", ")", ";", "$", "x", "=", "$", "t", "->", "multiply", "(", "$", "t", "->", "cos", "(", ")", ")", ";", "$", "y", "=", "Vector", "::", "rand", "(", "$", "n", ")", "->", "multiply", "(", "$", "this", "->", "depth", ")", ";", "$", "z", "=", "$", "t", "->", "multiply", "(", "$", "t", "->", "sin", "(", ")", ")", ";", "$", "noise", "=", "Matrix", "::", "gaussian", "(", "$", "n", ",", "3", ")", "->", "multiply", "(", "$", "this", "->", "noise", ")", ";", "$", "samples", "=", "Matrix", "::", "stack", "(", "[", "$", "x", ",", "$", "y", ",", "$", "z", "]", ")", "->", "transpose", "(", ")", "->", "add", "(", "$", "noise", ")", "->", "multiply", "(", "$", "this", "->", "scale", ")", "->", "add", "(", "$", "this", "->", "center", ")", "->", "asArray", "(", ")", ";", "$", "labels", "=", "$", "t", "->", "asArray", "(", ")", ";", "return", "Labeled", "::", "quick", "(", "$", "samples", ",", "$", "labels", ")", ";", "}" ]
Generate n data points. @param int $n @return \Rubix\ML\Datasets\Dataset
[ "Generate", "n", "data", "points", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Generators/SwissRoll.php#L110-L132
RubixML/RubixML
src/NeuralNet/Optimizers/Cyclical.php
Cyclical.step
public function step(Parameter $param, Tensor $gradient) : void { $cycle = floor(1 + $this->n / (2 * $this->steps)); $x = abs($this->n / $this->steps - 2 * $cycle + 1); $scale = $this->decay ** $this->n; $rate = $this->lower + $this->range * max(0, 1 - $x) * $scale; $param->update($gradient->multiply($rate)); $this->n++; }
php
public function step(Parameter $param, Tensor $gradient) : void { $cycle = floor(1 + $this->n / (2 * $this->steps)); $x = abs($this->n / $this->steps - 2 * $cycle + 1); $scale = $this->decay ** $this->n; $rate = $this->lower + $this->range * max(0, 1 - $x) * $scale; $param->update($gradient->multiply($rate)); $this->n++; }
[ "public", "function", "step", "(", "Parameter", "$", "param", ",", "Tensor", "$", "gradient", ")", ":", "void", "{", "$", "cycle", "=", "floor", "(", "1", "+", "$", "this", "->", "n", "/", "(", "2", "*", "$", "this", "->", "steps", ")", ")", ";", "$", "x", "=", "abs", "(", "$", "this", "->", "n", "/", "$", "this", "->", "steps", "-", "2", "*", "$", "cycle", "+", "1", ")", ";", "$", "scale", "=", "$", "this", "->", "decay", "**", "$", "this", "->", "n", ";", "$", "rate", "=", "$", "this", "->", "lower", "+", "$", "this", "->", "range", "*", "max", "(", "0", ",", "1", "-", "$", "x", ")", "*", "$", "scale", ";", "$", "param", "->", "update", "(", "$", "gradient", "->", "multiply", "(", "$", "rate", ")", ")", ";", "$", "this", "->", "n", "++", ";", "}" ]
Take a step of gradient descent for a given parameter. @param \Rubix\ML\NeuralNet\Parameters\Parameter $param @param \Rubix\Tensor\Tensor $gradient
[ "Take", "a", "step", "of", "gradient", "descent", "for", "a", "given", "parameter", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Optimizers/Cyclical.php#L116-L129
RubixML/RubixML
src/Other/Helpers/DataType.php
DataType.determine
public static function determine($data) : int { switch (gettype($data)) { case 'string': return self::CATEGORICAL; case 'double': return self::CONTINUOUS; case 'integer': return self::CONTINUOUS; case 'resource': return self::RESOURCE; default: return self::OTHER; } }
php
public static function determine($data) : int { switch (gettype($data)) { case 'string': return self::CATEGORICAL; case 'double': return self::CONTINUOUS; case 'integer': return self::CONTINUOUS; case 'resource': return self::RESOURCE; default: return self::OTHER; } }
[ "public", "static", "function", "determine", "(", "$", "data", ")", ":", "int", "{", "switch", "(", "gettype", "(", "$", "data", ")", ")", "{", "case", "'string'", ":", "return", "self", "::", "CATEGORICAL", ";", "case", "'double'", ":", "return", "self", "::", "CONTINUOUS", ";", "case", "'integer'", ":", "return", "self", "::", "CONTINUOUS", ";", "case", "'resource'", ":", "return", "self", "::", "RESOURCE", ";", "default", ":", "return", "self", "::", "OTHER", ";", "}", "}" ]
Return the integer encoded data type. @param mixed $data @return int
[ "Return", "the", "integer", "encoded", "data", "type", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Helpers/DataType.php#L32-L50
RubixML/RubixML
src/Graph/Nodes/Coordinate.php
Coordinate.split
public static function split(Labeled $dataset) : self { $columns = $dataset->columns(); $variances = array_map([Stats::class, 'variance'], $columns); $column = argmax($variances); $value = Stats::median($columns[$column]); $groups = $dataset->partition($column, $value); $min = $max = []; foreach ($columns as $values) { $min[] = min($values); $max[] = max($values); } return new self($column, $value, $groups, $min, $max); }
php
public static function split(Labeled $dataset) : self { $columns = $dataset->columns(); $variances = array_map([Stats::class, 'variance'], $columns); $column = argmax($variances); $value = Stats::median($columns[$column]); $groups = $dataset->partition($column, $value); $min = $max = []; foreach ($columns as $values) { $min[] = min($values); $max[] = max($values); } return new self($column, $value, $groups, $min, $max); }
[ "public", "static", "function", "split", "(", "Labeled", "$", "dataset", ")", ":", "self", "{", "$", "columns", "=", "$", "dataset", "->", "columns", "(", ")", ";", "$", "variances", "=", "array_map", "(", "[", "Stats", "::", "class", ",", "'variance'", "]", ",", "$", "columns", ")", ";", "$", "column", "=", "argmax", "(", "$", "variances", ")", ";", "$", "value", "=", "Stats", "::", "median", "(", "$", "columns", "[", "$", "column", "]", ")", ";", "$", "groups", "=", "$", "dataset", "->", "partition", "(", "$", "column", ",", "$", "value", ")", ";", "$", "min", "=", "$", "max", "=", "[", "]", ";", "foreach", "(", "$", "columns", "as", "$", "values", ")", "{", "$", "min", "[", "]", "=", "min", "(", "$", "values", ")", ";", "$", "max", "[", "]", "=", "max", "(", "$", "values", ")", ";", "}", "return", "new", "self", "(", "$", "column", ",", "$", "value", ",", "$", "groups", ",", "$", "min", ",", "$", "max", ")", ";", "}" ]
Factory method to build a coordinate node from a labeled dataset using the column with the highest variance as the column for the split. @param \Rubix\ML\Datasets\Labeled $dataset @return self
[ "Factory", "method", "to", "build", "a", "coordinate", "node", "from", "a", "labeled", "dataset", "using", "the", "column", "with", "the", "highest", "variance", "as", "the", "column", "for", "the", "split", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/Coordinate.php#L66-L86
RubixML/RubixML
src/NeuralNet/Layers/AlphaDropout.php
AlphaDropout.forward
public function forward(Matrix $input) : Matrix { $mask = Matrix::rand(...$input->shape()) ->greater($this->ratio); $saturation = $mask->map([$this, 'saturate']); $this->mask = $mask; return $input->multiply($mask) ->add($saturation) ->multiply($this->alpha) ->add($this->beta); }
php
public function forward(Matrix $input) : Matrix { $mask = Matrix::rand(...$input->shape()) ->greater($this->ratio); $saturation = $mask->map([$this, 'saturate']); $this->mask = $mask; return $input->multiply($mask) ->add($saturation) ->multiply($this->alpha) ->add($this->beta); }
[ "public", "function", "forward", "(", "Matrix", "$", "input", ")", ":", "Matrix", "{", "$", "mask", "=", "Matrix", "::", "rand", "(", "...", "$", "input", "->", "shape", "(", ")", ")", "->", "greater", "(", "$", "this", "->", "ratio", ")", ";", "$", "saturation", "=", "$", "mask", "->", "map", "(", "[", "$", "this", ",", "'saturate'", "]", ")", ";", "$", "this", "->", "mask", "=", "$", "mask", ";", "return", "$", "input", "->", "multiply", "(", "$", "mask", ")", "->", "add", "(", "$", "saturation", ")", "->", "multiply", "(", "$", "this", "->", "alpha", ")", "->", "add", "(", "$", "this", "->", "beta", ")", ";", "}" ]
Compute a forward pass through the layer. @param \Rubix\Tensor\Matrix $input @return \Rubix\Tensor\Matrix
[ "Compute", "a", "forward", "pass", "through", "the", "layer", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/AlphaDropout.php#L59-L72
RubixML/RubixML
src/Transformers/TextNormalizer.php
TextNormalizer.transform
public function transform(array &$samples) : void { foreach ($samples as &$sample) { foreach ($sample as &$feature) { if (is_string($feature)) { if ($this->trim) { $feature = preg_replace(self::SPACES_REGEX, self::SPACE, trim($feature)) ?: ''; } $feature = strtolower($feature); } } } }
php
public function transform(array &$samples) : void { foreach ($samples as &$sample) { foreach ($sample as &$feature) { if (is_string($feature)) { if ($this->trim) { $feature = preg_replace(self::SPACES_REGEX, self::SPACE, trim($feature)) ?: ''; } $feature = strtolower($feature); } } } }
[ "public", "function", "transform", "(", "array", "&", "$", "samples", ")", ":", "void", "{", "foreach", "(", "$", "samples", "as", "&", "$", "sample", ")", "{", "foreach", "(", "$", "sample", "as", "&", "$", "feature", ")", "{", "if", "(", "is_string", "(", "$", "feature", ")", ")", "{", "if", "(", "$", "this", "->", "trim", ")", "{", "$", "feature", "=", "preg_replace", "(", "self", "::", "SPACES_REGEX", ",", "self", "::", "SPACE", ",", "trim", "(", "$", "feature", ")", ")", "?", ":", "''", ";", "}", "$", "feature", "=", "strtolower", "(", "$", "feature", ")", ";", "}", "}", "}", "}" ]
Transform the dataset in place. @param array $samples
[ "Transform", "the", "dataset", "in", "place", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/TextNormalizer.php#L40-L53
RubixML/RubixML
src/Graph/Nodes/Cluster.php
Cluster.terminate
public static function terminate(Dataset $dataset, Distance $kernel) : self { $samples = $dataset->samples(); $labels = $dataset instanceof Labeled ? $dataset->labels() : null; $center = Matrix::quick($samples) ->transpose() ->mean() ->asArray(); $distances = []; foreach ($samples as $sample) { $distances[] = $kernel->compute($sample, $center); } $radius = max($distances); return new self($samples, $labels, $center, $radius); }
php
public static function terminate(Dataset $dataset, Distance $kernel) : self { $samples = $dataset->samples(); $labels = $dataset instanceof Labeled ? $dataset->labels() : null; $center = Matrix::quick($samples) ->transpose() ->mean() ->asArray(); $distances = []; foreach ($samples as $sample) { $distances[] = $kernel->compute($sample, $center); } $radius = max($distances); return new self($samples, $labels, $center, $radius); }
[ "public", "static", "function", "terminate", "(", "Dataset", "$", "dataset", ",", "Distance", "$", "kernel", ")", ":", "self", "{", "$", "samples", "=", "$", "dataset", "->", "samples", "(", ")", ";", "$", "labels", "=", "$", "dataset", "instanceof", "Labeled", "?", "$", "dataset", "->", "labels", "(", ")", ":", "null", ";", "$", "center", "=", "Matrix", "::", "quick", "(", "$", "samples", ")", "->", "transpose", "(", ")", "->", "mean", "(", ")", "->", "asArray", "(", ")", ";", "$", "distances", "=", "[", "]", ";", "foreach", "(", "$", "samples", "as", "$", "sample", ")", "{", "$", "distances", "[", "]", "=", "$", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "center", ")", ";", "}", "$", "radius", "=", "max", "(", "$", "distances", ")", ";", "return", "new", "self", "(", "$", "samples", ",", "$", "labels", ",", "$", "center", ",", "$", "radius", ")", ";", "}" ]
Terminate a branch with a dataset. @param \Rubix\ML\Datasets\Dataset $dataset @param \Rubix\ML\Kernels\Distance\Distance $kernel @return self
[ "Terminate", "a", "branch", "with", "a", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/Cluster.php#L58-L77
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.array_replace_recursive
public static function array_replace_recursive($array1, $array2) { if (function_exists('array_replace_recursive')) { return array_replace_recursive($array1, $array2); } foreach ($array2 as $key => $value) { if (is_array($value)) { $array1[$key] = self::array_replace_recursive($array1[$key], $value); } else { $array1[$key] = $value; } } return $array1; }
php
public static function array_replace_recursive($array1, $array2) { if (function_exists('array_replace_recursive')) { return array_replace_recursive($array1, $array2); } foreach ($array2 as $key => $value) { if (is_array($value)) { $array1[$key] = self::array_replace_recursive($array1[$key], $value); } else { $array1[$key] = $value; } } return $array1; }
[ "public", "static", "function", "array_replace_recursive", "(", "$", "array1", ",", "$", "array2", ")", "{", "if", "(", "function_exists", "(", "'array_replace_recursive'", ")", ")", "{", "return", "array_replace_recursive", "(", "$", "array1", ",", "$", "array2", ")", ";", "}", "foreach", "(", "$", "array2", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "array1", "[", "$", "key", "]", "=", "self", "::", "array_replace_recursive", "(", "$", "array1", "[", "$", "key", "]", ",", "$", "value", ")", ";", "}", "else", "{", "$", "array1", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "array1", ";", "}" ]
Custom array_replace_recursive to be used if PHP < 5.3 Replaces elements from passed arrays into the first array recursively. @param array $array1 The array in which elements are replaced @param array $array2 The array from which elements will be extracted @return array Returns an array, or NULL if an error occurs.
[ "Custom", "array_replace_recursive", "to", "be", "used", "if", "PHP", "<", "5", ".", "3", "Replaces", "elements", "from", "passed", "arrays", "into", "the", "first", "array", "recursively", "." ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L221-L235
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getTableWhere
public function getTableWhere($tableName) { if (!empty($this->tableWheres[$tableName])) { return $this->tableWheres[$tableName]; } elseif ($this->dumpSettings['where']) { return $this->dumpSettings['where']; } return false; }
php
public function getTableWhere($tableName) { if (!empty($this->tableWheres[$tableName])) { return $this->tableWheres[$tableName]; } elseif ($this->dumpSettings['where']) { return $this->dumpSettings['where']; } return false; }
[ "public", "function", "getTableWhere", "(", "$", "tableName", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "tableWheres", "[", "$", "tableName", "]", ")", ")", "{", "return", "$", "this", "->", "tableWheres", "[", "$", "tableName", "]", ";", "}", "elseif", "(", "$", "this", "->", "dumpSettings", "[", "'where'", "]", ")", "{", "return", "$", "this", "->", "dumpSettings", "[", "'where'", "]", ";", "}", "return", "false", ";", "}" ]
@param $tableName @return boolean|mixed
[ "@param", "$tableName" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L253-L262
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getTableLimit
public function getTableLimit($tableName) { if (empty($this->tableLimits[$tableName])) { return false; } $limit = $this->tableLimits[$tableName]; if (!is_numeric($limit)) { return false; } return $limit; }
php
public function getTableLimit($tableName) { if (empty($this->tableLimits[$tableName])) { return false; } $limit = $this->tableLimits[$tableName]; if (!is_numeric($limit)) { return false; } return $limit; }
[ "public", "function", "getTableLimit", "(", "$", "tableName", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "tableLimits", "[", "$", "tableName", "]", ")", ")", "{", "return", "false", ";", "}", "$", "limit", "=", "$", "this", "->", "tableLimits", "[", "$", "tableName", "]", ";", "if", "(", "!", "is_numeric", "(", "$", "limit", ")", ")", "{", "return", "false", ";", "}", "return", "$", "limit", ";", "}" ]
Returns the LIMIT for the table. Must be numeric to be returned. @param $tableName @return boolean
[ "Returns", "the", "LIMIT", "for", "the", "table", ".", "Must", "be", "numeric", "to", "be", "returned", "." ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L280-L292
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.parseDsn
private function parseDsn($dsn) { if (empty($dsn) || (false === ($pos = strpos($dsn, ":")))) { throw new Exception("Empty DSN string"); } $this->dsn = $dsn; $this->dbType = strtolower(substr($dsn, 0, $pos)); // always returns a string if (empty($this->dbType)) { throw new Exception("Missing database type from DSN string"); } $dsn = substr($dsn, $pos + 1); foreach (explode(";", $dsn) as $kvp) { $kvpArr = explode("=", $kvp); $this->dsnArray[strtolower($kvpArr[0])] = $kvpArr[1]; } if (empty($this->dsnArray['host']) && empty($this->dsnArray['unix_socket'])) { throw new Exception("Missing host from DSN string"); } $this->host = (!empty($this->dsnArray['host'])) ? $this->dsnArray['host'] : $this->dsnArray['unix_socket']; if (empty($this->dsnArray['dbname'])) { throw new Exception("Missing database name from DSN string"); } $this->dbName = $this->dsnArray['dbname']; return true; }
php
private function parseDsn($dsn) { if (empty($dsn) || (false === ($pos = strpos($dsn, ":")))) { throw new Exception("Empty DSN string"); } $this->dsn = $dsn; $this->dbType = strtolower(substr($dsn, 0, $pos)); if (empty($this->dbType)) { throw new Exception("Missing database type from DSN string"); } $dsn = substr($dsn, $pos + 1); foreach (explode(";", $dsn) as $kvp) { $kvpArr = explode("=", $kvp); $this->dsnArray[strtolower($kvpArr[0])] = $kvpArr[1]; } if (empty($this->dsnArray['host']) && empty($this->dsnArray['unix_socket'])) { throw new Exception("Missing host from DSN string"); } $this->host = (!empty($this->dsnArray['host'])) ? $this->dsnArray['host'] : $this->dsnArray['unix_socket']; if (empty($this->dsnArray['dbname'])) { throw new Exception("Missing database name from DSN string"); } $this->dbName = $this->dsnArray['dbname']; return true; }
[ "private", "function", "parseDsn", "(", "$", "dsn", ")", "{", "if", "(", "empty", "(", "$", "dsn", ")", "||", "(", "false", "===", "(", "$", "pos", "=", "strpos", "(", "$", "dsn", ",", "\":\"", ")", ")", ")", ")", "{", "throw", "new", "Exception", "(", "\"Empty DSN string\"", ")", ";", "}", "$", "this", "->", "dsn", "=", "$", "dsn", ";", "$", "this", "->", "dbType", "=", "strtolower", "(", "substr", "(", "$", "dsn", ",", "0", ",", "$", "pos", ")", ")", ";", "// always returns a string", "if", "(", "empty", "(", "$", "this", "->", "dbType", ")", ")", "{", "throw", "new", "Exception", "(", "\"Missing database type from DSN string\"", ")", ";", "}", "$", "dsn", "=", "substr", "(", "$", "dsn", ",", "$", "pos", "+", "1", ")", ";", "foreach", "(", "explode", "(", "\";\"", ",", "$", "dsn", ")", "as", "$", "kvp", ")", "{", "$", "kvpArr", "=", "explode", "(", "\"=\"", ",", "$", "kvp", ")", ";", "$", "this", "->", "dsnArray", "[", "strtolower", "(", "$", "kvpArr", "[", "0", "]", ")", "]", "=", "$", "kvpArr", "[", "1", "]", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "dsnArray", "[", "'host'", "]", ")", "&&", "empty", "(", "$", "this", "->", "dsnArray", "[", "'unix_socket'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "\"Missing host from DSN string\"", ")", ";", "}", "$", "this", "->", "host", "=", "(", "!", "empty", "(", "$", "this", "->", "dsnArray", "[", "'host'", "]", ")", ")", "?", "$", "this", "->", "dsnArray", "[", "'host'", "]", ":", "$", "this", "->", "dsnArray", "[", "'unix_socket'", "]", ";", "if", "(", "empty", "(", "$", "this", "->", "dsnArray", "[", "'dbname'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "\"Missing database name from DSN string\"", ")", ";", "}", "$", "this", "->", "dbName", "=", "$", "this", "->", "dsnArray", "[", "'dbname'", "]", ";", "return", "true", ";", "}" ]
Parse DSN string and extract dbname value Several examples of a DSN string mysql:host=localhost;dbname=testdb mysql:host=localhost;port=3307;dbname=testdb mysql:unix_socket=/tmp/mysql.sock;dbname=testdb @param string $dsn dsn string to parse @return boolean
[ "Parse", "DSN", "string", "and", "extract", "dbname", "value", "Several", "examples", "of", "a", "DSN", "string", "mysql", ":", "host", "=", "localhost", ";", "dbname", "=", "testdb", "mysql", ":", "host", "=", "localhost", ";", "port", "=", "3307", ";", "dbname", "=", "testdb", "mysql", ":", "unix_socket", "=", "/", "tmp", "/", "mysql", ".", "sock", ";", "dbname", "=", "testdb" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L304-L338
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.connect
private function connect() { // Connecting with PDO. try { switch ($this->dbType) { case 'sqlite': $this->dbHandler = @new PDO("sqlite:".$this->dbName, null, null, $this->pdoSettings); break; case 'mysql': case 'pgsql': case 'dblib': $this->dbHandler = @new PDO( $this->dsn, $this->user, $this->pass, $this->pdoSettings ); // Execute init commands once connected foreach ($this->dumpSettings['init_commands'] as $stmt) { $this->dbHandler->exec($stmt); } // Store server version $this->version = $this->dbHandler->getAttribute(PDO::ATTR_SERVER_VERSION); break; default: throw new Exception("Unsupported database type (".$this->dbType.")"); } } catch (PDOException $e) { throw new Exception( "Connection to ".$this->dbType." failed with message: ". $e->getMessage() ); } if (is_null($this->dbHandler)) { throw new Exception("Connection to ".$this->dbType."failed"); } $this->dbHandler->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL); $this->typeAdapter = TypeAdapterFactory::create($this->dbType, $this->dbHandler, $this->dumpSettings); }
php
private function connect() { try { switch ($this->dbType) { case 'sqlite': $this->dbHandler = @new PDO("sqlite:".$this->dbName, null, null, $this->pdoSettings); break; case 'mysql': case 'pgsql': case 'dblib': $this->dbHandler = @new PDO( $this->dsn, $this->user, $this->pass, $this->pdoSettings ); foreach ($this->dumpSettings['init_commands'] as $stmt) { $this->dbHandler->exec($stmt); } $this->version = $this->dbHandler->getAttribute(PDO::ATTR_SERVER_VERSION); break; default: throw new Exception("Unsupported database type (".$this->dbType.")"); } } catch (PDOException $e) { throw new Exception( "Connection to ".$this->dbType." failed with message: ". $e->getMessage() ); } if (is_null($this->dbHandler)) { throw new Exception("Connection to ".$this->dbType."failed"); } $this->dbHandler->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL); $this->typeAdapter = TypeAdapterFactory::create($this->dbType, $this->dbHandler, $this->dumpSettings); }
[ "private", "function", "connect", "(", ")", "{", "// Connecting with PDO.", "try", "{", "switch", "(", "$", "this", "->", "dbType", ")", "{", "case", "'sqlite'", ":", "$", "this", "->", "dbHandler", "=", "@", "new", "PDO", "(", "\"sqlite:\"", ".", "$", "this", "->", "dbName", ",", "null", ",", "null", ",", "$", "this", "->", "pdoSettings", ")", ";", "break", ";", "case", "'mysql'", ":", "case", "'pgsql'", ":", "case", "'dblib'", ":", "$", "this", "->", "dbHandler", "=", "@", "new", "PDO", "(", "$", "this", "->", "dsn", ",", "$", "this", "->", "user", ",", "$", "this", "->", "pass", ",", "$", "this", "->", "pdoSettings", ")", ";", "// Execute init commands once connected", "foreach", "(", "$", "this", "->", "dumpSettings", "[", "'init_commands'", "]", "as", "$", "stmt", ")", "{", "$", "this", "->", "dbHandler", "->", "exec", "(", "$", "stmt", ")", ";", "}", "// Store server version", "$", "this", "->", "version", "=", "$", "this", "->", "dbHandler", "->", "getAttribute", "(", "PDO", "::", "ATTR_SERVER_VERSION", ")", ";", "break", ";", "default", ":", "throw", "new", "Exception", "(", "\"Unsupported database type (\"", ".", "$", "this", "->", "dbType", ".", "\")\"", ")", ";", "}", "}", "catch", "(", "PDOException", "$", "e", ")", "{", "throw", "new", "Exception", "(", "\"Connection to \"", ".", "$", "this", "->", "dbType", ".", "\" failed with message: \"", ".", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "if", "(", "is_null", "(", "$", "this", "->", "dbHandler", ")", ")", "{", "throw", "new", "Exception", "(", "\"Connection to \"", ".", "$", "this", "->", "dbType", ".", "\"failed\"", ")", ";", "}", "$", "this", "->", "dbHandler", "->", "setAttribute", "(", "PDO", "::", "ATTR_ORACLE_NULLS", ",", "PDO", "::", "NULL_NATURAL", ")", ";", "$", "this", "->", "typeAdapter", "=", "TypeAdapterFactory", "::", "create", "(", "$", "this", "->", "dbType", ",", "$", "this", "->", "dbHandler", ",", "$", "this", "->", "dumpSettings", ")", ";", "}" ]
Connect with PDO. @return null
[ "Connect", "with", "PDO", "." ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L345-L385
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.start
public function start($filename = '') { // Output file can be redefined here if (!empty($filename)) { $this->fileName = $filename; } // Connect to database $this->connect(); // Create output file $this->compressManager->open($this->fileName); // Write some basic info to output file $this->compressManager->write($this->getDumpFileHeader()); // Store server settings and use sanner defaults to dump $this->compressManager->write( $this->typeAdapter->backup_parameters() ); if ($this->dumpSettings['databases']) { $this->compressManager->write( $this->typeAdapter->getDatabaseHeader($this->dbName) ); if ($this->dumpSettings['add-drop-database']) { $this->compressManager->write( $this->typeAdapter->add_drop_database($this->dbName) ); } } // Get table, view, trigger, procedures and events structures from // database. $this->getDatabaseStructureTables(); $this->getDatabaseStructureViews(); $this->getDatabaseStructureTriggers(); $this->getDatabaseStructureProcedures(); $this->getDatabaseStructureEvents(); if ($this->dumpSettings['databases']) { $this->compressManager->write( $this->typeAdapter->databases($this->dbName) ); } // If there still are some tables/views in include-tables array, // that means that some tables or views weren't found. // Give proper error and exit. // This check will be removed once include-tables supports regexps. if (0 < count($this->dumpSettings['include-tables'])) { $name = implode(",", $this->dumpSettings['include-tables']); throw new Exception("Table (".$name.") not found in database"); } $this->exportTables(); $this->exportTriggers(); $this->exportViews(); $this->exportProcedures(); $this->exportEvents(); // Restore saved parameters. $this->compressManager->write( $this->typeAdapter->restore_parameters() ); // Write some stats to output file. $this->compressManager->write($this->getDumpFileFooter()); // Close output file. $this->compressManager->close(); return; }
php
public function start($filename = '') { if (!empty($filename)) { $this->fileName = $filename; } $this->connect(); $this->compressManager->open($this->fileName); $this->compressManager->write($this->getDumpFileHeader()); $this->compressManager->write( $this->typeAdapter->backup_parameters() ); if ($this->dumpSettings['databases']) { $this->compressManager->write( $this->typeAdapter->getDatabaseHeader($this->dbName) ); if ($this->dumpSettings['add-drop-database']) { $this->compressManager->write( $this->typeAdapter->add_drop_database($this->dbName) ); } } $this->getDatabaseStructureTables(); $this->getDatabaseStructureViews(); $this->getDatabaseStructureTriggers(); $this->getDatabaseStructureProcedures(); $this->getDatabaseStructureEvents(); if ($this->dumpSettings['databases']) { $this->compressManager->write( $this->typeAdapter->databases($this->dbName) ); } if (0 < count($this->dumpSettings['include-tables'])) { $name = implode(",", $this->dumpSettings['include-tables']); throw new Exception("Table (".$name.") not found in database"); } $this->exportTables(); $this->exportTriggers(); $this->exportViews(); $this->exportProcedures(); $this->exportEvents(); $this->compressManager->write( $this->typeAdapter->restore_parameters() ); $this->compressManager->write($this->getDumpFileFooter()); $this->compressManager->close(); return; }
[ "public", "function", "start", "(", "$", "filename", "=", "''", ")", "{", "// Output file can be redefined here", "if", "(", "!", "empty", "(", "$", "filename", ")", ")", "{", "$", "this", "->", "fileName", "=", "$", "filename", ";", "}", "// Connect to database", "$", "this", "->", "connect", "(", ")", ";", "// Create output file", "$", "this", "->", "compressManager", "->", "open", "(", "$", "this", "->", "fileName", ")", ";", "// Write some basic info to output file", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "getDumpFileHeader", "(", ")", ")", ";", "// Store server settings and use sanner defaults to dump", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "backup_parameters", "(", ")", ")", ";", "if", "(", "$", "this", "->", "dumpSettings", "[", "'databases'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "getDatabaseHeader", "(", "$", "this", "->", "dbName", ")", ")", ";", "if", "(", "$", "this", "->", "dumpSettings", "[", "'add-drop-database'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "add_drop_database", "(", "$", "this", "->", "dbName", ")", ")", ";", "}", "}", "// Get table, view, trigger, procedures and events structures from", "// database.", "$", "this", "->", "getDatabaseStructureTables", "(", ")", ";", "$", "this", "->", "getDatabaseStructureViews", "(", ")", ";", "$", "this", "->", "getDatabaseStructureTriggers", "(", ")", ";", "$", "this", "->", "getDatabaseStructureProcedures", "(", ")", ";", "$", "this", "->", "getDatabaseStructureEvents", "(", ")", ";", "if", "(", "$", "this", "->", "dumpSettings", "[", "'databases'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "databases", "(", "$", "this", "->", "dbName", ")", ")", ";", "}", "// If there still are some tables/views in include-tables array,", "// that means that some tables or views weren't found.", "// Give proper error and exit.", "// This check will be removed once include-tables supports regexps.", "if", "(", "0", "<", "count", "(", "$", "this", "->", "dumpSettings", "[", "'include-tables'", "]", ")", ")", "{", "$", "name", "=", "implode", "(", "\",\"", ",", "$", "this", "->", "dumpSettings", "[", "'include-tables'", "]", ")", ";", "throw", "new", "Exception", "(", "\"Table (\"", ".", "$", "name", ".", "\") not found in database\"", ")", ";", "}", "$", "this", "->", "exportTables", "(", ")", ";", "$", "this", "->", "exportTriggers", "(", ")", ";", "$", "this", "->", "exportViews", "(", ")", ";", "$", "this", "->", "exportProcedures", "(", ")", ";", "$", "this", "->", "exportEvents", "(", ")", ";", "// Restore saved parameters.", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "restore_parameters", "(", ")", ")", ";", "// Write some stats to output file.", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "getDumpFileFooter", "(", ")", ")", ";", "// Close output file.", "$", "this", "->", "compressManager", "->", "close", "(", ")", ";", "return", ";", "}" ]
Primary function, triggers dumping. @param string $filename Name of file to write sql dump to @return null @throws \Exception
[ "Primary", "function", "triggers", "dumping", "." ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L394-L465
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getDumpFileHeader
private function getDumpFileHeader() { $header = ''; if (!$this->dumpSettings['skip-comments']) { // Some info about software, source and time $header = "-- mysqldump-php https://github.com/ifsnop/mysqldump-php".PHP_EOL. "--".PHP_EOL. "-- Host: {$this->host}\tDatabase: {$this->dbName}".PHP_EOL. "-- ------------------------------------------------------".PHP_EOL; if (!empty($this->version)) { $header .= "-- Server version \t".$this->version.PHP_EOL; } if (!$this->dumpSettings['skip-dump-date']) { $header .= "-- Date: ".date('r').PHP_EOL.PHP_EOL; } } return $header; }
php
private function getDumpFileHeader() { $header = ''; if (!$this->dumpSettings['skip-comments']) { $header = "-- mysqldump-php https: "--".PHP_EOL. "-- Host: {$this->host}\tDatabase: {$this->dbName}".PHP_EOL. "-- ------------------------------------------------------".PHP_EOL; if (!empty($this->version)) { $header .= "-- Server version \t".$this->version.PHP_EOL; } if (!$this->dumpSettings['skip-dump-date']) { $header .= "-- Date: ".date('r').PHP_EOL.PHP_EOL; } } return $header; }
[ "private", "function", "getDumpFileHeader", "(", ")", "{", "$", "header", "=", "''", ";", "if", "(", "!", "$", "this", "->", "dumpSettings", "[", "'skip-comments'", "]", ")", "{", "// Some info about software, source and time", "$", "header", "=", "\"-- mysqldump-php https://github.com/ifsnop/mysqldump-php\"", ".", "PHP_EOL", ".", "\"--\"", ".", "PHP_EOL", ".", "\"-- Host: {$this->host}\\tDatabase: {$this->dbName}\"", ".", "PHP_EOL", ".", "\"-- ------------------------------------------------------\"", ".", "PHP_EOL", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "version", ")", ")", "{", "$", "header", ".=", "\"-- Server version \\t\"", ".", "$", "this", "->", "version", ".", "PHP_EOL", ";", "}", "if", "(", "!", "$", "this", "->", "dumpSettings", "[", "'skip-dump-date'", "]", ")", "{", "$", "header", ".=", "\"-- Date: \"", ".", "date", "(", "'r'", ")", ".", "PHP_EOL", ".", "PHP_EOL", ";", "}", "}", "return", "$", "header", ";", "}" ]
Returns header for dump file. @return string
[ "Returns", "header", "for", "dump", "file", "." ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L472-L491
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getDumpFileFooter
private function getDumpFileFooter() { $footer = ''; if (!$this->dumpSettings['skip-comments']) { $footer .= '-- Dump completed'; if (!$this->dumpSettings['skip-dump-date']) { $footer .= ' on: '.date('r'); } $footer .= PHP_EOL; } return $footer; }
php
private function getDumpFileFooter() { $footer = ''; if (!$this->dumpSettings['skip-comments']) { $footer .= '-- Dump completed'; if (!$this->dumpSettings['skip-dump-date']) { $footer .= ' on: '.date('r'); } $footer .= PHP_EOL; } return $footer; }
[ "private", "function", "getDumpFileFooter", "(", ")", "{", "$", "footer", "=", "''", ";", "if", "(", "!", "$", "this", "->", "dumpSettings", "[", "'skip-comments'", "]", ")", "{", "$", "footer", ".=", "'-- Dump completed'", ";", "if", "(", "!", "$", "this", "->", "dumpSettings", "[", "'skip-dump-date'", "]", ")", "{", "$", "footer", ".=", "' on: '", ".", "date", "(", "'r'", ")", ";", "}", "$", "footer", ".=", "PHP_EOL", ";", "}", "return", "$", "footer", ";", "}" ]
Returns footer for dump file. @return string
[ "Returns", "footer", "for", "dump", "file", "." ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L498-L510
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getDatabaseStructureTables
private function getDatabaseStructureTables() { // Listing all tables from database if (empty($this->dumpSettings['include-tables'])) { // include all tables for now, blacklisting happens later foreach ($this->dbHandler->query($this->typeAdapter->show_tables($this->dbName)) as $row) { array_push($this->tables, current($row)); } } else { // include only the tables mentioned in include-tables foreach ($this->dbHandler->query($this->typeAdapter->show_tables($this->dbName)) as $row) { if (in_array(current($row), $this->dumpSettings['include-tables'], true)) { array_push($this->tables, current($row)); $elem = array_search( current($row), $this->dumpSettings['include-tables'] ); unset($this->dumpSettings['include-tables'][$elem]); } } } return; }
php
private function getDatabaseStructureTables() { if (empty($this->dumpSettings['include-tables'])) { foreach ($this->dbHandler->query($this->typeAdapter->show_tables($this->dbName)) as $row) { array_push($this->tables, current($row)); } } else { foreach ($this->dbHandler->query($this->typeAdapter->show_tables($this->dbName)) as $row) { if (in_array(current($row), $this->dumpSettings['include-tables'], true)) { array_push($this->tables, current($row)); $elem = array_search( current($row), $this->dumpSettings['include-tables'] ); unset($this->dumpSettings['include-tables'][$elem]); } } } return; }
[ "private", "function", "getDatabaseStructureTables", "(", ")", "{", "// Listing all tables from database", "if", "(", "empty", "(", "$", "this", "->", "dumpSettings", "[", "'include-tables'", "]", ")", ")", "{", "// include all tables for now, blacklisting happens later", "foreach", "(", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "this", "->", "typeAdapter", "->", "show_tables", "(", "$", "this", "->", "dbName", ")", ")", "as", "$", "row", ")", "{", "array_push", "(", "$", "this", "->", "tables", ",", "current", "(", "$", "row", ")", ")", ";", "}", "}", "else", "{", "// include only the tables mentioned in include-tables", "foreach", "(", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "this", "->", "typeAdapter", "->", "show_tables", "(", "$", "this", "->", "dbName", ")", ")", "as", "$", "row", ")", "{", "if", "(", "in_array", "(", "current", "(", "$", "row", ")", ",", "$", "this", "->", "dumpSettings", "[", "'include-tables'", "]", ",", "true", ")", ")", "{", "array_push", "(", "$", "this", "->", "tables", ",", "current", "(", "$", "row", ")", ")", ";", "$", "elem", "=", "array_search", "(", "current", "(", "$", "row", ")", ",", "$", "this", "->", "dumpSettings", "[", "'include-tables'", "]", ")", ";", "unset", "(", "$", "this", "->", "dumpSettings", "[", "'include-tables'", "]", "[", "$", "elem", "]", ")", ";", "}", "}", "}", "return", ";", "}" ]
Reads table names from database. Fills $this->tables array so they will be dumped later. @return null
[ "Reads", "table", "names", "from", "database", ".", "Fills", "$this", "-", ">", "tables", "array", "so", "they", "will", "be", "dumped", "later", "." ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L518-L540
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getDatabaseStructureViews
private function getDatabaseStructureViews() { // Listing all views from database if (empty($this->dumpSettings['include-views'])) { // include all views for now, blacklisting happens later foreach ($this->dbHandler->query($this->typeAdapter->show_views($this->dbName)) as $row) { array_push($this->views, current($row)); } } else { // include only the tables mentioned in include-tables foreach ($this->dbHandler->query($this->typeAdapter->show_views($this->dbName)) as $row) { if (in_array(current($row), $this->dumpSettings['include-views'], true)) { array_push($this->views, current($row)); $elem = array_search( current($row), $this->dumpSettings['include-views'] ); unset($this->dumpSettings['include-views'][$elem]); } } } return; }
php
private function getDatabaseStructureViews() { if (empty($this->dumpSettings['include-views'])) { foreach ($this->dbHandler->query($this->typeAdapter->show_views($this->dbName)) as $row) { array_push($this->views, current($row)); } } else { foreach ($this->dbHandler->query($this->typeAdapter->show_views($this->dbName)) as $row) { if (in_array(current($row), $this->dumpSettings['include-views'], true)) { array_push($this->views, current($row)); $elem = array_search( current($row), $this->dumpSettings['include-views'] ); unset($this->dumpSettings['include-views'][$elem]); } } } return; }
[ "private", "function", "getDatabaseStructureViews", "(", ")", "{", "// Listing all views from database", "if", "(", "empty", "(", "$", "this", "->", "dumpSettings", "[", "'include-views'", "]", ")", ")", "{", "// include all views for now, blacklisting happens later", "foreach", "(", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "this", "->", "typeAdapter", "->", "show_views", "(", "$", "this", "->", "dbName", ")", ")", "as", "$", "row", ")", "{", "array_push", "(", "$", "this", "->", "views", ",", "current", "(", "$", "row", ")", ")", ";", "}", "}", "else", "{", "// include only the tables mentioned in include-tables", "foreach", "(", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "this", "->", "typeAdapter", "->", "show_views", "(", "$", "this", "->", "dbName", ")", ")", "as", "$", "row", ")", "{", "if", "(", "in_array", "(", "current", "(", "$", "row", ")", ",", "$", "this", "->", "dumpSettings", "[", "'include-views'", "]", ",", "true", ")", ")", "{", "array_push", "(", "$", "this", "->", "views", ",", "current", "(", "$", "row", ")", ")", ";", "$", "elem", "=", "array_search", "(", "current", "(", "$", "row", ")", ",", "$", "this", "->", "dumpSettings", "[", "'include-views'", "]", ")", ";", "unset", "(", "$", "this", "->", "dumpSettings", "[", "'include-views'", "]", "[", "$", "elem", "]", ")", ";", "}", "}", "}", "return", ";", "}" ]
Reads view names from database. Fills $this->tables array so they will be dumped later. @return null
[ "Reads", "view", "names", "from", "database", ".", "Fills", "$this", "-", ">", "tables", "array", "so", "they", "will", "be", "dumped", "later", "." ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L548-L570
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getDatabaseStructureTriggers
private function getDatabaseStructureTriggers() { // Listing all triggers from database if (false === $this->dumpSettings['skip-triggers']) { foreach ($this->dbHandler->query($this->typeAdapter->show_triggers($this->dbName)) as $row) { array_push($this->triggers, $row['Trigger']); } } return; }
php
private function getDatabaseStructureTriggers() { if (false === $this->dumpSettings['skip-triggers']) { foreach ($this->dbHandler->query($this->typeAdapter->show_triggers($this->dbName)) as $row) { array_push($this->triggers, $row['Trigger']); } } return; }
[ "private", "function", "getDatabaseStructureTriggers", "(", ")", "{", "// Listing all triggers from database", "if", "(", "false", "===", "$", "this", "->", "dumpSettings", "[", "'skip-triggers'", "]", ")", "{", "foreach", "(", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "this", "->", "typeAdapter", "->", "show_triggers", "(", "$", "this", "->", "dbName", ")", ")", "as", "$", "row", ")", "{", "array_push", "(", "$", "this", "->", "triggers", ",", "$", "row", "[", "'Trigger'", "]", ")", ";", "}", "}", "return", ";", "}" ]
Reads trigger names from database. Fills $this->tables array so they will be dumped later. @return null
[ "Reads", "trigger", "names", "from", "database", ".", "Fills", "$this", "-", ">", "tables", "array", "so", "they", "will", "be", "dumped", "later", "." ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L578-L587
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getDatabaseStructureProcedures
private function getDatabaseStructureProcedures() { // Listing all procedures from database if ($this->dumpSettings['routines']) { foreach ($this->dbHandler->query($this->typeAdapter->show_procedures($this->dbName)) as $row) { array_push($this->procedures, $row['procedure_name']); } } return; }
php
private function getDatabaseStructureProcedures() { if ($this->dumpSettings['routines']) { foreach ($this->dbHandler->query($this->typeAdapter->show_procedures($this->dbName)) as $row) { array_push($this->procedures, $row['procedure_name']); } } return; }
[ "private", "function", "getDatabaseStructureProcedures", "(", ")", "{", "// Listing all procedures from database", "if", "(", "$", "this", "->", "dumpSettings", "[", "'routines'", "]", ")", "{", "foreach", "(", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "this", "->", "typeAdapter", "->", "show_procedures", "(", "$", "this", "->", "dbName", ")", ")", "as", "$", "row", ")", "{", "array_push", "(", "$", "this", "->", "procedures", ",", "$", "row", "[", "'procedure_name'", "]", ")", ";", "}", "}", "return", ";", "}" ]
Reads procedure names from database. Fills $this->tables array so they will be dumped later. @return null
[ "Reads", "procedure", "names", "from", "database", ".", "Fills", "$this", "-", ">", "tables", "array", "so", "they", "will", "be", "dumped", "later", "." ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L595-L604
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getDatabaseStructureEvents
private function getDatabaseStructureEvents() { // Listing all events from database if ($this->dumpSettings['events']) { foreach ($this->dbHandler->query($this->typeAdapter->show_events($this->dbName)) as $row) { array_push($this->events, $row['event_name']); } } return; }
php
private function getDatabaseStructureEvents() { if ($this->dumpSettings['events']) { foreach ($this->dbHandler->query($this->typeAdapter->show_events($this->dbName)) as $row) { array_push($this->events, $row['event_name']); } } return; }
[ "private", "function", "getDatabaseStructureEvents", "(", ")", "{", "// Listing all events from database", "if", "(", "$", "this", "->", "dumpSettings", "[", "'events'", "]", ")", "{", "foreach", "(", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "this", "->", "typeAdapter", "->", "show_events", "(", "$", "this", "->", "dbName", ")", ")", "as", "$", "row", ")", "{", "array_push", "(", "$", "this", "->", "events", ",", "$", "row", "[", "'event_name'", "]", ")", ";", "}", "}", "return", ";", "}" ]
Reads event names from database. Fills $this->tables array so they will be dumped later. @return null
[ "Reads", "event", "names", "from", "database", ".", "Fills", "$this", "-", ">", "tables", "array", "so", "they", "will", "be", "dumped", "later", "." ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L612-L621
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.matches
private function matches($table, $arr) { $match = false; foreach ($arr as $pattern) { if ('/' != $pattern[0]) { continue; } if (1 == preg_match($pattern, $table)) { $match = true; } } return in_array($table, $arr) || $match; }
php
private function matches($table, $arr) { $match = false; foreach ($arr as $pattern) { if ('/' != $pattern[0]) { continue; } if (1 == preg_match($pattern, $table)) { $match = true; } } return in_array($table, $arr) || $match; }
[ "private", "function", "matches", "(", "$", "table", ",", "$", "arr", ")", "{", "$", "match", "=", "false", ";", "foreach", "(", "$", "arr", "as", "$", "pattern", ")", "{", "if", "(", "'/'", "!=", "$", "pattern", "[", "0", "]", ")", "{", "continue", ";", "}", "if", "(", "1", "==", "preg_match", "(", "$", "pattern", ",", "$", "table", ")", ")", "{", "$", "match", "=", "true", ";", "}", "}", "return", "in_array", "(", "$", "table", ",", "$", "arr", ")", "||", "$", "match", ";", "}" ]
Compare if $table name matches with a definition inside $arr @param $table string @param $arr array with strings or patterns @return boolean
[ "Compare", "if", "$table", "name", "matches", "with", "a", "definition", "inside", "$arr" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L629-L643
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.exportTables
private function exportTables() { // Exporting tables one by one foreach ($this->tables as $table) { if ($this->matches($table, $this->dumpSettings['exclude-tables'])) { continue; } $this->getTableStructure($table); if (false === $this->dumpSettings['no-data']) { // don't break compatibility with old trigger $this->listValues($table); } elseif (true === $this->dumpSettings['no-data'] || $this->matches($table, $this->dumpSettings['no-data'])) { continue; } else { $this->listValues($table); } } }
php
private function exportTables() { foreach ($this->tables as $table) { if ($this->matches($table, $this->dumpSettings['exclude-tables'])) { continue; } $this->getTableStructure($table); if (false === $this->dumpSettings['no-data']) { $this->listValues($table); } elseif (true === $this->dumpSettings['no-data'] || $this->matches($table, $this->dumpSettings['no-data'])) { continue; } else { $this->listValues($table); } } }
[ "private", "function", "exportTables", "(", ")", "{", "// Exporting tables one by one", "foreach", "(", "$", "this", "->", "tables", "as", "$", "table", ")", "{", "if", "(", "$", "this", "->", "matches", "(", "$", "table", ",", "$", "this", "->", "dumpSettings", "[", "'exclude-tables'", "]", ")", ")", "{", "continue", ";", "}", "$", "this", "->", "getTableStructure", "(", "$", "table", ")", ";", "if", "(", "false", "===", "$", "this", "->", "dumpSettings", "[", "'no-data'", "]", ")", "{", "// don't break compatibility with old trigger", "$", "this", "->", "listValues", "(", "$", "table", ")", ";", "}", "elseif", "(", "true", "===", "$", "this", "->", "dumpSettings", "[", "'no-data'", "]", "||", "$", "this", "->", "matches", "(", "$", "table", ",", "$", "this", "->", "dumpSettings", "[", "'no-data'", "]", ")", ")", "{", "continue", ";", "}", "else", "{", "$", "this", "->", "listValues", "(", "$", "table", ")", ";", "}", "}", "}" ]
Exports all the tables selected from database @return null
[ "Exports", "all", "the", "tables", "selected", "from", "database" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L650-L667
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.exportViews
private function exportViews() { if (false === $this->dumpSettings['no-create-info']) { // Exporting views one by one foreach ($this->views as $view) { if ($this->matches($view, $this->dumpSettings['exclude-tables'])) { continue; } $this->tableColumnTypes[$view] = $this->getTableColumnTypes($view); $this->getViewStructureTable($view); } foreach ($this->views as $view) { if ($this->matches($view, $this->dumpSettings['exclude-tables'])) { continue; } $this->getViewStructureView($view); } } }
php
private function exportViews() { if (false === $this->dumpSettings['no-create-info']) { foreach ($this->views as $view) { if ($this->matches($view, $this->dumpSettings['exclude-tables'])) { continue; } $this->tableColumnTypes[$view] = $this->getTableColumnTypes($view); $this->getViewStructureTable($view); } foreach ($this->views as $view) { if ($this->matches($view, $this->dumpSettings['exclude-tables'])) { continue; } $this->getViewStructureView($view); } } }
[ "private", "function", "exportViews", "(", ")", "{", "if", "(", "false", "===", "$", "this", "->", "dumpSettings", "[", "'no-create-info'", "]", ")", "{", "// Exporting views one by one", "foreach", "(", "$", "this", "->", "views", "as", "$", "view", ")", "{", "if", "(", "$", "this", "->", "matches", "(", "$", "view", ",", "$", "this", "->", "dumpSettings", "[", "'exclude-tables'", "]", ")", ")", "{", "continue", ";", "}", "$", "this", "->", "tableColumnTypes", "[", "$", "view", "]", "=", "$", "this", "->", "getTableColumnTypes", "(", "$", "view", ")", ";", "$", "this", "->", "getViewStructureTable", "(", "$", "view", ")", ";", "}", "foreach", "(", "$", "this", "->", "views", "as", "$", "view", ")", "{", "if", "(", "$", "this", "->", "matches", "(", "$", "view", ",", "$", "this", "->", "dumpSettings", "[", "'exclude-tables'", "]", ")", ")", "{", "continue", ";", "}", "$", "this", "->", "getViewStructureView", "(", "$", "view", ")", ";", "}", "}", "}" ]
Exports all the views found in database @return null
[ "Exports", "all", "the", "views", "found", "in", "database" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L674-L692
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getTableStructure
private function getTableStructure($tableName) { if (!$this->dumpSettings['no-create-info']) { $ret = ''; if (!$this->dumpSettings['skip-comments']) { $ret = "--".PHP_EOL. "-- Table structure for table `$tableName`".PHP_EOL. "--".PHP_EOL.PHP_EOL; } $stmt = $this->typeAdapter->show_create_table($tableName); foreach ($this->dbHandler->query($stmt) as $r) { $this->compressManager->write($ret); if ($this->dumpSettings['add-drop-table']) { $this->compressManager->write( $this->typeAdapter->drop_table($tableName) ); } $this->compressManager->write( $this->typeAdapter->create_table($r) ); break; } } $this->tableColumnTypes[$tableName] = $this->getTableColumnTypes($tableName); return; }
php
private function getTableStructure($tableName) { if (!$this->dumpSettings['no-create-info']) { $ret = ''; if (!$this->dumpSettings['skip-comments']) { $ret = "--".PHP_EOL. "-- Table structure for table `$tableName`".PHP_EOL. "--".PHP_EOL.PHP_EOL; } $stmt = $this->typeAdapter->show_create_table($tableName); foreach ($this->dbHandler->query($stmt) as $r) { $this->compressManager->write($ret); if ($this->dumpSettings['add-drop-table']) { $this->compressManager->write( $this->typeAdapter->drop_table($tableName) ); } $this->compressManager->write( $this->typeAdapter->create_table($r) ); break; } } $this->tableColumnTypes[$tableName] = $this->getTableColumnTypes($tableName); return; }
[ "private", "function", "getTableStructure", "(", "$", "tableName", ")", "{", "if", "(", "!", "$", "this", "->", "dumpSettings", "[", "'no-create-info'", "]", ")", "{", "$", "ret", "=", "''", ";", "if", "(", "!", "$", "this", "->", "dumpSettings", "[", "'skip-comments'", "]", ")", "{", "$", "ret", "=", "\"--\"", ".", "PHP_EOL", ".", "\"-- Table structure for table `$tableName`\"", ".", "PHP_EOL", ".", "\"--\"", ".", "PHP_EOL", ".", "PHP_EOL", ";", "}", "$", "stmt", "=", "$", "this", "->", "typeAdapter", "->", "show_create_table", "(", "$", "tableName", ")", ";", "foreach", "(", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "stmt", ")", "as", "$", "r", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "ret", ")", ";", "if", "(", "$", "this", "->", "dumpSettings", "[", "'add-drop-table'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "drop_table", "(", "$", "tableName", ")", ")", ";", "}", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "create_table", "(", "$", "r", ")", ")", ";", "break", ";", "}", "}", "$", "this", "->", "tableColumnTypes", "[", "$", "tableName", "]", "=", "$", "this", "->", "getTableColumnTypes", "(", "$", "tableName", ")", ";", "return", ";", "}" ]
Table structure extractor @todo move specific mysql code to typeAdapter @param string $tableName Name of table to export @return null
[ "Table", "structure", "extractor" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L740-L765
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getTableColumnTypes
private function getTableColumnTypes($tableName) { $columnTypes = array(); $columns = $this->dbHandler->query( $this->typeAdapter->show_columns($tableName) ); $columns->setFetchMode(PDO::FETCH_ASSOC); foreach ($columns as $key => $col) { $types = $this->typeAdapter->parseColumnType($col); $columnTypes[$col['Field']] = array( 'is_numeric'=> $types['is_numeric'], 'is_blob' => $types['is_blob'], 'type' => $types['type'], 'type_sql' => $col['Type'], 'is_virtual' => $types['is_virtual'] ); } return $columnTypes; }
php
private function getTableColumnTypes($tableName) { $columnTypes = array(); $columns = $this->dbHandler->query( $this->typeAdapter->show_columns($tableName) ); $columns->setFetchMode(PDO::FETCH_ASSOC); foreach ($columns as $key => $col) { $types = $this->typeAdapter->parseColumnType($col); $columnTypes[$col['Field']] = array( 'is_numeric'=> $types['is_numeric'], 'is_blob' => $types['is_blob'], 'type' => $types['type'], 'type_sql' => $col['Type'], 'is_virtual' => $types['is_virtual'] ); } return $columnTypes; }
[ "private", "function", "getTableColumnTypes", "(", "$", "tableName", ")", "{", "$", "columnTypes", "=", "array", "(", ")", ";", "$", "columns", "=", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "this", "->", "typeAdapter", "->", "show_columns", "(", "$", "tableName", ")", ")", ";", "$", "columns", "->", "setFetchMode", "(", "PDO", "::", "FETCH_ASSOC", ")", ";", "foreach", "(", "$", "columns", "as", "$", "key", "=>", "$", "col", ")", "{", "$", "types", "=", "$", "this", "->", "typeAdapter", "->", "parseColumnType", "(", "$", "col", ")", ";", "$", "columnTypes", "[", "$", "col", "[", "'Field'", "]", "]", "=", "array", "(", "'is_numeric'", "=>", "$", "types", "[", "'is_numeric'", "]", ",", "'is_blob'", "=>", "$", "types", "[", "'is_blob'", "]", ",", "'type'", "=>", "$", "types", "[", "'type'", "]", ",", "'type_sql'", "=>", "$", "col", "[", "'Type'", "]", ",", "'is_virtual'", "=>", "$", "types", "[", "'is_virtual'", "]", ")", ";", "}", "return", "$", "columnTypes", ";", "}" ]
Store column types to create data dumps and for Stand-In tables @param string $tableName Name of table to export @return array type column types detailed
[ "Store", "column", "types", "to", "create", "data", "dumps", "and", "for", "Stand", "-", "In", "tables" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L774-L794
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getViewStructureTable
private function getViewStructureTable($viewName) { if (!$this->dumpSettings['skip-comments']) { $ret = "--".PHP_EOL. "-- Stand-In structure for view `${viewName}`".PHP_EOL. "--".PHP_EOL.PHP_EOL; $this->compressManager->write($ret); } $stmt = $this->typeAdapter->show_create_view($viewName); // create views as tables, to resolve dependencies foreach ($this->dbHandler->query($stmt) as $r) { if ($this->dumpSettings['add-drop-table']) { $this->compressManager->write( $this->typeAdapter->drop_view($viewName) ); } $this->compressManager->write( $this->createStandInTable($viewName) ); break; } }
php
private function getViewStructureTable($viewName) { if (!$this->dumpSettings['skip-comments']) { $ret = "--".PHP_EOL. "-- Stand-In structure for view `${viewName}`".PHP_EOL. "--".PHP_EOL.PHP_EOL; $this->compressManager->write($ret); } $stmt = $this->typeAdapter->show_create_view($viewName); foreach ($this->dbHandler->query($stmt) as $r) { if ($this->dumpSettings['add-drop-table']) { $this->compressManager->write( $this->typeAdapter->drop_view($viewName) ); } $this->compressManager->write( $this->createStandInTable($viewName) ); break; } }
[ "private", "function", "getViewStructureTable", "(", "$", "viewName", ")", "{", "if", "(", "!", "$", "this", "->", "dumpSettings", "[", "'skip-comments'", "]", ")", "{", "$", "ret", "=", "\"--\"", ".", "PHP_EOL", ".", "\"-- Stand-In structure for view `${viewName}`\"", ".", "PHP_EOL", ".", "\"--\"", ".", "PHP_EOL", ".", "PHP_EOL", ";", "$", "this", "->", "compressManager", "->", "write", "(", "$", "ret", ")", ";", "}", "$", "stmt", "=", "$", "this", "->", "typeAdapter", "->", "show_create_view", "(", "$", "viewName", ")", ";", "// create views as tables, to resolve dependencies", "foreach", "(", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "stmt", ")", "as", "$", "r", ")", "{", "if", "(", "$", "this", "->", "dumpSettings", "[", "'add-drop-table'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "drop_view", "(", "$", "viewName", ")", ")", ";", "}", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "createStandInTable", "(", "$", "viewName", ")", ")", ";", "break", ";", "}", "}" ]
View structure extractor, create table (avoids cyclic references) @todo move mysql specific code to typeAdapter @param string $viewName Name of view to export @return null
[ "View", "structure", "extractor", "create", "table", "(", "avoids", "cyclic", "references", ")" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L803-L826
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.createStandInTable
public function createStandInTable($viewName) { $ret = array(); foreach ($this->tableColumnTypes[$viewName] as $k => $v) { $ret[] = "`${k}` ${v['type_sql']}"; } $ret = implode(PHP_EOL.",", $ret); $ret = "CREATE TABLE IF NOT EXISTS `$viewName` (". PHP_EOL.$ret.PHP_EOL.");".PHP_EOL; return $ret; }
php
public function createStandInTable($viewName) { $ret = array(); foreach ($this->tableColumnTypes[$viewName] as $k => $v) { $ret[] = "`${k}` ${v['type_sql']}"; } $ret = implode(PHP_EOL.",", $ret); $ret = "CREATE TABLE IF NOT EXISTS `$viewName` (". PHP_EOL.$ret.PHP_EOL.");".PHP_EOL; return $ret; }
[ "public", "function", "createStandInTable", "(", "$", "viewName", ")", "{", "$", "ret", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "tableColumnTypes", "[", "$", "viewName", "]", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "ret", "[", "]", "=", "\"`${k}` ${v['type_sql']}\"", ";", "}", "$", "ret", "=", "implode", "(", "PHP_EOL", ".", "\",\"", ",", "$", "ret", ")", ";", "$", "ret", "=", "\"CREATE TABLE IF NOT EXISTS `$viewName` (\"", ".", "PHP_EOL", ".", "$", "ret", ".", "PHP_EOL", ".", "\");\"", ".", "PHP_EOL", ";", "return", "$", "ret", ";", "}" ]
Write a create table statement for the table Stand-In, show create table would return a create algorithm when used on a view @param string $viewName Name of view to export @return string create statement
[ "Write", "a", "create", "table", "statement", "for", "the", "table", "Stand", "-", "In", "show", "create", "table", "would", "return", "a", "create", "algorithm", "when", "used", "on", "a", "view" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L835-L847
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getViewStructureView
private function getViewStructureView($viewName) { if (!$this->dumpSettings['skip-comments']) { $ret = "--".PHP_EOL. "-- View structure for view `${viewName}`".PHP_EOL. "--".PHP_EOL.PHP_EOL; $this->compressManager->write($ret); } $stmt = $this->typeAdapter->show_create_view($viewName); // create views, to resolve dependencies // replacing tables with views foreach ($this->dbHandler->query($stmt) as $r) { // because we must replace table with view, we should delete it $this->compressManager->write( $this->typeAdapter->drop_view($viewName) ); $this->compressManager->write( $this->typeAdapter->create_view($r) ); break; } }
php
private function getViewStructureView($viewName) { if (!$this->dumpSettings['skip-comments']) { $ret = "--".PHP_EOL. "-- View structure for view `${viewName}`".PHP_EOL. "--".PHP_EOL.PHP_EOL; $this->compressManager->write($ret); } $stmt = $this->typeAdapter->show_create_view($viewName); foreach ($this->dbHandler->query($stmt) as $r) { $this->compressManager->write( $this->typeAdapter->drop_view($viewName) ); $this->compressManager->write( $this->typeAdapter->create_view($r) ); break; } }
[ "private", "function", "getViewStructureView", "(", "$", "viewName", ")", "{", "if", "(", "!", "$", "this", "->", "dumpSettings", "[", "'skip-comments'", "]", ")", "{", "$", "ret", "=", "\"--\"", ".", "PHP_EOL", ".", "\"-- View structure for view `${viewName}`\"", ".", "PHP_EOL", ".", "\"--\"", ".", "PHP_EOL", ".", "PHP_EOL", ";", "$", "this", "->", "compressManager", "->", "write", "(", "$", "ret", ")", ";", "}", "$", "stmt", "=", "$", "this", "->", "typeAdapter", "->", "show_create_view", "(", "$", "viewName", ")", ";", "// create views, to resolve dependencies", "// replacing tables with views", "foreach", "(", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "stmt", ")", "as", "$", "r", ")", "{", "// because we must replace table with view, we should delete it", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "drop_view", "(", "$", "viewName", ")", ")", ";", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "create_view", "(", "$", "r", ")", ")", ";", "break", ";", "}", "}" ]
View structure extractor, create view @todo move mysql specific code to typeAdapter @param string $viewName Name of view to export @return null
[ "View", "structure", "extractor", "create", "view" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L856-L878
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getTriggerStructure
private function getTriggerStructure($triggerName) { $stmt = $this->typeAdapter->show_create_trigger($triggerName); foreach ($this->dbHandler->query($stmt) as $r) { if ($this->dumpSettings['add-drop-trigger']) { $this->compressManager->write( $this->typeAdapter->add_drop_trigger($triggerName) ); } $this->compressManager->write( $this->typeAdapter->create_trigger($r) ); return; } }
php
private function getTriggerStructure($triggerName) { $stmt = $this->typeAdapter->show_create_trigger($triggerName); foreach ($this->dbHandler->query($stmt) as $r) { if ($this->dumpSettings['add-drop-trigger']) { $this->compressManager->write( $this->typeAdapter->add_drop_trigger($triggerName) ); } $this->compressManager->write( $this->typeAdapter->create_trigger($r) ); return; } }
[ "private", "function", "getTriggerStructure", "(", "$", "triggerName", ")", "{", "$", "stmt", "=", "$", "this", "->", "typeAdapter", "->", "show_create_trigger", "(", "$", "triggerName", ")", ";", "foreach", "(", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "stmt", ")", "as", "$", "r", ")", "{", "if", "(", "$", "this", "->", "dumpSettings", "[", "'add-drop-trigger'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "add_drop_trigger", "(", "$", "triggerName", ")", ")", ";", "}", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "create_trigger", "(", "$", "r", ")", ")", ";", "return", ";", "}", "}" ]
Trigger structure extractor @param string $triggerName Name of trigger to export @return null
[ "Trigger", "structure", "extractor" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L886-L900
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getProcedureStructure
private function getProcedureStructure($procedureName) { if (!$this->dumpSettings['skip-comments']) { $ret = "--".PHP_EOL. "-- Dumping routines for database '".$this->dbName."'".PHP_EOL. "--".PHP_EOL.PHP_EOL; $this->compressManager->write($ret); } $stmt = $this->typeAdapter->show_create_procedure($procedureName); foreach ($this->dbHandler->query($stmt) as $r) { $this->compressManager->write( $this->typeAdapter->create_procedure($r) ); return; } }
php
private function getProcedureStructure($procedureName) { if (!$this->dumpSettings['skip-comments']) { $ret = "--".PHP_EOL. "-- Dumping routines for database '".$this->dbName."'".PHP_EOL. "--".PHP_EOL.PHP_EOL; $this->compressManager->write($ret); } $stmt = $this->typeAdapter->show_create_procedure($procedureName); foreach ($this->dbHandler->query($stmt) as $r) { $this->compressManager->write( $this->typeAdapter->create_procedure($r) ); return; } }
[ "private", "function", "getProcedureStructure", "(", "$", "procedureName", ")", "{", "if", "(", "!", "$", "this", "->", "dumpSettings", "[", "'skip-comments'", "]", ")", "{", "$", "ret", "=", "\"--\"", ".", "PHP_EOL", ".", "\"-- Dumping routines for database '\"", ".", "$", "this", "->", "dbName", ".", "\"'\"", ".", "PHP_EOL", ".", "\"--\"", ".", "PHP_EOL", ".", "PHP_EOL", ";", "$", "this", "->", "compressManager", "->", "write", "(", "$", "ret", ")", ";", "}", "$", "stmt", "=", "$", "this", "->", "typeAdapter", "->", "show_create_procedure", "(", "$", "procedureName", ")", ";", "foreach", "(", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "stmt", ")", "as", "$", "r", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "create_procedure", "(", "$", "r", ")", ")", ";", "return", ";", "}", "}" ]
Procedure structure extractor @param string $procedureName Name of procedure to export @return null
[ "Procedure", "structure", "extractor" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L908-L923
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getEventStructure
private function getEventStructure($eventName) { if (!$this->dumpSettings['skip-comments']) { $ret = "--".PHP_EOL. "-- Dumping events for database '".$this->dbName."'".PHP_EOL. "--".PHP_EOL.PHP_EOL; $this->compressManager->write($ret); } $stmt = $this->typeAdapter->show_create_event($eventName); foreach ($this->dbHandler->query($stmt) as $r) { $this->compressManager->write( $this->typeAdapter->create_event($r) ); return; } }
php
private function getEventStructure($eventName) { if (!$this->dumpSettings['skip-comments']) { $ret = "--".PHP_EOL. "-- Dumping events for database '".$this->dbName."'".PHP_EOL. "--".PHP_EOL.PHP_EOL; $this->compressManager->write($ret); } $stmt = $this->typeAdapter->show_create_event($eventName); foreach ($this->dbHandler->query($stmt) as $r) { $this->compressManager->write( $this->typeAdapter->create_event($r) ); return; } }
[ "private", "function", "getEventStructure", "(", "$", "eventName", ")", "{", "if", "(", "!", "$", "this", "->", "dumpSettings", "[", "'skip-comments'", "]", ")", "{", "$", "ret", "=", "\"--\"", ".", "PHP_EOL", ".", "\"-- Dumping events for database '\"", ".", "$", "this", "->", "dbName", ".", "\"'\"", ".", "PHP_EOL", ".", "\"--\"", ".", "PHP_EOL", ".", "PHP_EOL", ";", "$", "this", "->", "compressManager", "->", "write", "(", "$", "ret", ")", ";", "}", "$", "stmt", "=", "$", "this", "->", "typeAdapter", "->", "show_create_event", "(", "$", "eventName", ")", ";", "foreach", "(", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "stmt", ")", "as", "$", "r", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "create_event", "(", "$", "r", ")", ")", ";", "return", ";", "}", "}" ]
Event structure extractor @param string $eventName Name of event to export @return null
[ "Event", "structure", "extractor" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L931-L946
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.prepareColumnValues
private function prepareColumnValues($tableName, $row) { $ret = array(); $columnTypes = $this->tableColumnTypes[$tableName]; foreach ($row as $colName => $colValue) { $colValue = $this->hookTransformColumnValue($tableName, $colName, $colValue, $row); $ret[] = $this->escape($colValue, $columnTypes[$colName]); } return $ret; }
php
private function prepareColumnValues($tableName, $row) { $ret = array(); $columnTypes = $this->tableColumnTypes[$tableName]; foreach ($row as $colName => $colValue) { $colValue = $this->hookTransformColumnValue($tableName, $colName, $colValue, $row); $ret[] = $this->escape($colValue, $columnTypes[$colName]); } return $ret; }
[ "private", "function", "prepareColumnValues", "(", "$", "tableName", ",", "$", "row", ")", "{", "$", "ret", "=", "array", "(", ")", ";", "$", "columnTypes", "=", "$", "this", "->", "tableColumnTypes", "[", "$", "tableName", "]", ";", "foreach", "(", "$", "row", "as", "$", "colName", "=>", "$", "colValue", ")", "{", "$", "colValue", "=", "$", "this", "->", "hookTransformColumnValue", "(", "$", "tableName", ",", "$", "colName", ",", "$", "colValue", ",", "$", "row", ")", ";", "$", "ret", "[", "]", "=", "$", "this", "->", "escape", "(", "$", "colValue", ",", "$", "columnTypes", "[", "$", "colName", "]", ")", ";", "}", "return", "$", "ret", ";", "}" ]
Prepare values for output @param string $tableName Name of table which contains rows @param array $row Associative array of column names and values to be quoted @return array
[ "Prepare", "values", "for", "output" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L957-L967
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.escape
private function escape($colValue, $colType) { if (is_null($colValue)) { return "NULL"; } elseif ($this->dumpSettings['hex-blob'] && $colType['is_blob']) { if ($colType['type'] == 'bit' || !empty($colValue)) { return "0x${colValue}"; } else { return "''"; } } elseif ($colType['is_numeric']) { return $colValue; } return $this->dbHandler->quote($colValue); }
php
private function escape($colValue, $colType) { if (is_null($colValue)) { return "NULL"; } elseif ($this->dumpSettings['hex-blob'] && $colType['is_blob']) { if ($colType['type'] == 'bit' || !empty($colValue)) { return "0x${colValue}"; } else { return "''"; } } elseif ($colType['is_numeric']) { return $colValue; } return $this->dbHandler->quote($colValue); }
[ "private", "function", "escape", "(", "$", "colValue", ",", "$", "colType", ")", "{", "if", "(", "is_null", "(", "$", "colValue", ")", ")", "{", "return", "\"NULL\"", ";", "}", "elseif", "(", "$", "this", "->", "dumpSettings", "[", "'hex-blob'", "]", "&&", "$", "colType", "[", "'is_blob'", "]", ")", "{", "if", "(", "$", "colType", "[", "'type'", "]", "==", "'bit'", "||", "!", "empty", "(", "$", "colValue", ")", ")", "{", "return", "\"0x${colValue}\"", ";", "}", "else", "{", "return", "\"''\"", ";", "}", "}", "elseif", "(", "$", "colType", "[", "'is_numeric'", "]", ")", "{", "return", "$", "colValue", ";", "}", "return", "$", "this", "->", "dbHandler", "->", "quote", "(", "$", "colValue", ")", ";", "}" ]
Escape values with quotes when needed @param string $tableName Name of table which contains rows @param array $row Associative array of column names and values to be quoted @return string
[ "Escape", "values", "with", "quotes", "when", "needed" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L977-L992
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.hookTransformColumnValue
protected function hookTransformColumnValue($tableName, $colName, $colValue, $row) { if (!$this->transformColumnValueCallable) { return $colValue; } return call_user_func_array($this->transformColumnValueCallable, array( $tableName, $colName, $colValue, $row )); }
php
protected function hookTransformColumnValue($tableName, $colName, $colValue, $row) { if (!$this->transformColumnValueCallable) { return $colValue; } return call_user_func_array($this->transformColumnValueCallable, array( $tableName, $colName, $colValue, $row )); }
[ "protected", "function", "hookTransformColumnValue", "(", "$", "tableName", ",", "$", "colName", ",", "$", "colValue", ",", "$", "row", ")", "{", "if", "(", "!", "$", "this", "->", "transformColumnValueCallable", ")", "{", "return", "$", "colValue", ";", "}", "return", "call_user_func_array", "(", "$", "this", "->", "transformColumnValueCallable", ",", "array", "(", "$", "tableName", ",", "$", "colName", ",", "$", "colValue", ",", "$", "row", ")", ")", ";", "}" ]
Give extending classes an opportunity to transform column values @param string $tableName Name of table which contains rows @param string $colName Name of the column in question @param string $colValue Value of the column in question @return string
[ "Give", "extending", "classes", "an", "opportunity", "to", "transform", "column", "values" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L1015-L1027
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.listValues
private function listValues($tableName) { $this->prepareListValues($tableName); $onlyOnce = true; $lineSize = 0; // colStmt is used to form a query to obtain row values $colStmt = $this->getColumnStmt($tableName); // colNames is used to get the name of the columns when using complete-insert if ($this->dumpSettings['complete-insert']) { $colNames = $this->getColumnNames($tableName); } $stmt = "SELECT ".implode(",", $colStmt)." FROM `$tableName`"; // Table specific conditions override the default 'where' $condition = $this->getTableWhere($tableName); if ($condition) { $stmt .= " WHERE {$condition}"; } $limit = $this->getTableLimit($tableName); if ($limit) { $stmt .= " LIMIT {$limit}"; } $resultSet = $this->dbHandler->query($stmt); $resultSet->setFetchMode(PDO::FETCH_ASSOC); $ignore = $this->dumpSettings['insert-ignore'] ? ' IGNORE' : ''; $count = 0; foreach ($resultSet as $row) { $count++; $vals = $this->prepareColumnValues($tableName, $row); if ($onlyOnce || !$this->dumpSettings['extended-insert']) { if ($this->dumpSettings['complete-insert']) { $lineSize += $this->compressManager->write( "INSERT$ignore INTO `$tableName` (". implode(", ", $colNames). ") VALUES (".implode(",", $vals).")" ); } else { $lineSize += $this->compressManager->write( "INSERT$ignore INTO `$tableName` VALUES (".implode(",", $vals).")" ); } $onlyOnce = false; } else { $lineSize += $this->compressManager->write(",(".implode(",", $vals).")"); } if (($lineSize > $this->dumpSettings['net_buffer_length']) || !$this->dumpSettings['extended-insert']) { $onlyOnce = true; $lineSize = $this->compressManager->write(";".PHP_EOL); } } $resultSet->closeCursor(); if (!$onlyOnce) { $this->compressManager->write(";".PHP_EOL); } $this->endListValues($tableName, $count); }
php
private function listValues($tableName) { $this->prepareListValues($tableName); $onlyOnce = true; $lineSize = 0; $colStmt = $this->getColumnStmt($tableName); if ($this->dumpSettings['complete-insert']) { $colNames = $this->getColumnNames($tableName); } $stmt = "SELECT ".implode(",", $colStmt)." FROM `$tableName`"; $condition = $this->getTableWhere($tableName); if ($condition) { $stmt .= " WHERE {$condition}"; } $limit = $this->getTableLimit($tableName); if ($limit) { $stmt .= " LIMIT {$limit}"; } $resultSet = $this->dbHandler->query($stmt); $resultSet->setFetchMode(PDO::FETCH_ASSOC); $ignore = $this->dumpSettings['insert-ignore'] ? ' IGNORE' : ''; $count = 0; foreach ($resultSet as $row) { $count++; $vals = $this->prepareColumnValues($tableName, $row); if ($onlyOnce || !$this->dumpSettings['extended-insert']) { if ($this->dumpSettings['complete-insert']) { $lineSize += $this->compressManager->write( "INSERT$ignore INTO `$tableName` (". implode(", ", $colNames). ") VALUES (".implode(",", $vals).")" ); } else { $lineSize += $this->compressManager->write( "INSERT$ignore INTO `$tableName` VALUES (".implode(",", $vals).")" ); } $onlyOnce = false; } else { $lineSize += $this->compressManager->write(",(".implode(",", $vals).")"); } if (($lineSize > $this->dumpSettings['net_buffer_length']) || !$this->dumpSettings['extended-insert']) { $onlyOnce = true; $lineSize = $this->compressManager->write(";".PHP_EOL); } } $resultSet->closeCursor(); if (!$onlyOnce) { $this->compressManager->write(";".PHP_EOL); } $this->endListValues($tableName, $count); }
[ "private", "function", "listValues", "(", "$", "tableName", ")", "{", "$", "this", "->", "prepareListValues", "(", "$", "tableName", ")", ";", "$", "onlyOnce", "=", "true", ";", "$", "lineSize", "=", "0", ";", "// colStmt is used to form a query to obtain row values", "$", "colStmt", "=", "$", "this", "->", "getColumnStmt", "(", "$", "tableName", ")", ";", "// colNames is used to get the name of the columns when using complete-insert", "if", "(", "$", "this", "->", "dumpSettings", "[", "'complete-insert'", "]", ")", "{", "$", "colNames", "=", "$", "this", "->", "getColumnNames", "(", "$", "tableName", ")", ";", "}", "$", "stmt", "=", "\"SELECT \"", ".", "implode", "(", "\",\"", ",", "$", "colStmt", ")", ".", "\" FROM `$tableName`\"", ";", "// Table specific conditions override the default 'where'", "$", "condition", "=", "$", "this", "->", "getTableWhere", "(", "$", "tableName", ")", ";", "if", "(", "$", "condition", ")", "{", "$", "stmt", ".=", "\" WHERE {$condition}\"", ";", "}", "$", "limit", "=", "$", "this", "->", "getTableLimit", "(", "$", "tableName", ")", ";", "if", "(", "$", "limit", ")", "{", "$", "stmt", ".=", "\" LIMIT {$limit}\"", ";", "}", "$", "resultSet", "=", "$", "this", "->", "dbHandler", "->", "query", "(", "$", "stmt", ")", ";", "$", "resultSet", "->", "setFetchMode", "(", "PDO", "::", "FETCH_ASSOC", ")", ";", "$", "ignore", "=", "$", "this", "->", "dumpSettings", "[", "'insert-ignore'", "]", "?", "' IGNORE'", ":", "''", ";", "$", "count", "=", "0", ";", "foreach", "(", "$", "resultSet", "as", "$", "row", ")", "{", "$", "count", "++", ";", "$", "vals", "=", "$", "this", "->", "prepareColumnValues", "(", "$", "tableName", ",", "$", "row", ")", ";", "if", "(", "$", "onlyOnce", "||", "!", "$", "this", "->", "dumpSettings", "[", "'extended-insert'", "]", ")", "{", "if", "(", "$", "this", "->", "dumpSettings", "[", "'complete-insert'", "]", ")", "{", "$", "lineSize", "+=", "$", "this", "->", "compressManager", "->", "write", "(", "\"INSERT$ignore INTO `$tableName` (\"", ".", "implode", "(", "\", \"", ",", "$", "colNames", ")", ".", "\") VALUES (\"", ".", "implode", "(", "\",\"", ",", "$", "vals", ")", ".", "\")\"", ")", ";", "}", "else", "{", "$", "lineSize", "+=", "$", "this", "->", "compressManager", "->", "write", "(", "\"INSERT$ignore INTO `$tableName` VALUES (\"", ".", "implode", "(", "\",\"", ",", "$", "vals", ")", ".", "\")\"", ")", ";", "}", "$", "onlyOnce", "=", "false", ";", "}", "else", "{", "$", "lineSize", "+=", "$", "this", "->", "compressManager", "->", "write", "(", "\",(\"", ".", "implode", "(", "\",\"", ",", "$", "vals", ")", ".", "\")\"", ")", ";", "}", "if", "(", "(", "$", "lineSize", ">", "$", "this", "->", "dumpSettings", "[", "'net_buffer_length'", "]", ")", "||", "!", "$", "this", "->", "dumpSettings", "[", "'extended-insert'", "]", ")", "{", "$", "onlyOnce", "=", "true", ";", "$", "lineSize", "=", "$", "this", "->", "compressManager", "->", "write", "(", "\";\"", ".", "PHP_EOL", ")", ";", "}", "}", "$", "resultSet", "->", "closeCursor", "(", ")", ";", "if", "(", "!", "$", "onlyOnce", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "\";\"", ".", "PHP_EOL", ")", ";", "}", "$", "this", "->", "endListValues", "(", "$", "tableName", ",", "$", "count", ")", ";", "}" ]
Table rows extractor @param string $tableName Name of table to export @return null
[ "Table", "rows", "extractor" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L1036-L1103
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.prepareListValues
public function prepareListValues($tableName) { if (!$this->dumpSettings['skip-comments']) { $this->compressManager->write( "--".PHP_EOL. "-- Dumping data for table `$tableName`".PHP_EOL. "--".PHP_EOL.PHP_EOL ); } if ($this->dumpSettings['single-transaction']) { $this->dbHandler->exec($this->typeAdapter->setup_transaction()); $this->dbHandler->exec($this->typeAdapter->start_transaction()); } if ($this->dumpSettings['lock-tables']) { $this->typeAdapter->lock_table($tableName); } if ($this->dumpSettings['add-locks']) { $this->compressManager->write( $this->typeAdapter->start_add_lock_table($tableName) ); } if ($this->dumpSettings['disable-keys']) { $this->compressManager->write( $this->typeAdapter->start_add_disable_keys($tableName) ); } // Disable autocommit for faster reload if ($this->dumpSettings['no-autocommit']) { $this->compressManager->write( $this->typeAdapter->start_disable_autocommit() ); } return; }
php
public function prepareListValues($tableName) { if (!$this->dumpSettings['skip-comments']) { $this->compressManager->write( "--".PHP_EOL. "-- Dumping data for table `$tableName`".PHP_EOL. "--".PHP_EOL.PHP_EOL ); } if ($this->dumpSettings['single-transaction']) { $this->dbHandler->exec($this->typeAdapter->setup_transaction()); $this->dbHandler->exec($this->typeAdapter->start_transaction()); } if ($this->dumpSettings['lock-tables']) { $this->typeAdapter->lock_table($tableName); } if ($this->dumpSettings['add-locks']) { $this->compressManager->write( $this->typeAdapter->start_add_lock_table($tableName) ); } if ($this->dumpSettings['disable-keys']) { $this->compressManager->write( $this->typeAdapter->start_add_disable_keys($tableName) ); } if ($this->dumpSettings['no-autocommit']) { $this->compressManager->write( $this->typeAdapter->start_disable_autocommit() ); } return; }
[ "public", "function", "prepareListValues", "(", "$", "tableName", ")", "{", "if", "(", "!", "$", "this", "->", "dumpSettings", "[", "'skip-comments'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "\"--\"", ".", "PHP_EOL", ".", "\"-- Dumping data for table `$tableName`\"", ".", "PHP_EOL", ".", "\"--\"", ".", "PHP_EOL", ".", "PHP_EOL", ")", ";", "}", "if", "(", "$", "this", "->", "dumpSettings", "[", "'single-transaction'", "]", ")", "{", "$", "this", "->", "dbHandler", "->", "exec", "(", "$", "this", "->", "typeAdapter", "->", "setup_transaction", "(", ")", ")", ";", "$", "this", "->", "dbHandler", "->", "exec", "(", "$", "this", "->", "typeAdapter", "->", "start_transaction", "(", ")", ")", ";", "}", "if", "(", "$", "this", "->", "dumpSettings", "[", "'lock-tables'", "]", ")", "{", "$", "this", "->", "typeAdapter", "->", "lock_table", "(", "$", "tableName", ")", ";", "}", "if", "(", "$", "this", "->", "dumpSettings", "[", "'add-locks'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "start_add_lock_table", "(", "$", "tableName", ")", ")", ";", "}", "if", "(", "$", "this", "->", "dumpSettings", "[", "'disable-keys'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "start_add_disable_keys", "(", "$", "tableName", ")", ")", ";", "}", "// Disable autocommit for faster reload", "if", "(", "$", "this", "->", "dumpSettings", "[", "'no-autocommit'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "start_disable_autocommit", "(", ")", ")", ";", "}", "return", ";", "}" ]
Table rows extractor, append information prior to dump @param string $tableName Name of table to export @return null
[ "Table", "rows", "extractor", "append", "information", "prior", "to", "dump" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L1112-L1151
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.endListValues
public function endListValues($tableName, $count = 0) { if ($this->dumpSettings['disable-keys']) { $this->compressManager->write( $this->typeAdapter->end_add_disable_keys($tableName) ); } if ($this->dumpSettings['add-locks']) { $this->compressManager->write( $this->typeAdapter->end_add_lock_table($tableName) ); } if ($this->dumpSettings['single-transaction']) { $this->dbHandler->exec($this->typeAdapter->commit_transaction()); } if ($this->dumpSettings['lock-tables']) { $this->typeAdapter->unlock_table($tableName); } // Commit to enable autocommit if ($this->dumpSettings['no-autocommit']) { $this->compressManager->write( $this->typeAdapter->end_disable_autocommit() ); } $this->compressManager->write(PHP_EOL); if (!$this->dumpSettings['skip-comments']) { $this->compressManager->write( "-- Dumped table `".$tableName."` with $count row(s)".PHP_EOL. '--'.PHP_EOL.PHP_EOL ); } return; }
php
public function endListValues($tableName, $count = 0) { if ($this->dumpSettings['disable-keys']) { $this->compressManager->write( $this->typeAdapter->end_add_disable_keys($tableName) ); } if ($this->dumpSettings['add-locks']) { $this->compressManager->write( $this->typeAdapter->end_add_lock_table($tableName) ); } if ($this->dumpSettings['single-transaction']) { $this->dbHandler->exec($this->typeAdapter->commit_transaction()); } if ($this->dumpSettings['lock-tables']) { $this->typeAdapter->unlock_table($tableName); } if ($this->dumpSettings['no-autocommit']) { $this->compressManager->write( $this->typeAdapter->end_disable_autocommit() ); } $this->compressManager->write(PHP_EOL); if (!$this->dumpSettings['skip-comments']) { $this->compressManager->write( "-- Dumped table `".$tableName."` with $count row(s)".PHP_EOL. '--'.PHP_EOL.PHP_EOL ); } return; }
[ "public", "function", "endListValues", "(", "$", "tableName", ",", "$", "count", "=", "0", ")", "{", "if", "(", "$", "this", "->", "dumpSettings", "[", "'disable-keys'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "end_add_disable_keys", "(", "$", "tableName", ")", ")", ";", "}", "if", "(", "$", "this", "->", "dumpSettings", "[", "'add-locks'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "end_add_lock_table", "(", "$", "tableName", ")", ")", ";", "}", "if", "(", "$", "this", "->", "dumpSettings", "[", "'single-transaction'", "]", ")", "{", "$", "this", "->", "dbHandler", "->", "exec", "(", "$", "this", "->", "typeAdapter", "->", "commit_transaction", "(", ")", ")", ";", "}", "if", "(", "$", "this", "->", "dumpSettings", "[", "'lock-tables'", "]", ")", "{", "$", "this", "->", "typeAdapter", "->", "unlock_table", "(", "$", "tableName", ")", ";", "}", "// Commit to enable autocommit", "if", "(", "$", "this", "->", "dumpSettings", "[", "'no-autocommit'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "$", "this", "->", "typeAdapter", "->", "end_disable_autocommit", "(", ")", ")", ";", "}", "$", "this", "->", "compressManager", "->", "write", "(", "PHP_EOL", ")", ";", "if", "(", "!", "$", "this", "->", "dumpSettings", "[", "'skip-comments'", "]", ")", "{", "$", "this", "->", "compressManager", "->", "write", "(", "\"-- Dumped table `\"", ".", "$", "tableName", ".", "\"` with $count row(s)\"", ".", "PHP_EOL", ".", "'--'", ".", "PHP_EOL", ".", "PHP_EOL", ")", ";", "}", "return", ";", "}" ]
Table rows extractor, close locks and commits after dump @param string $tableName Name of table to export. @param integer $count Number of rows inserted. @return void
[ "Table", "rows", "extractor", "close", "locks", "and", "commits", "after", "dump" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L1161-L1200
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getColumnStmt
public function getColumnStmt($tableName) { $colStmt = array(); foreach ($this->tableColumnTypes[$tableName] as $colName => $colType) { if ($colType['type'] == 'bit' && $this->dumpSettings['hex-blob']) { $colStmt[] = "LPAD(HEX(`${colName}`),2,'0') AS `${colName}`"; } elseif ($colType['is_blob'] && $this->dumpSettings['hex-blob']) { $colStmt[] = "HEX(`${colName}`) AS `${colName}`"; } elseif ($colType['is_virtual']) { $this->dumpSettings['complete-insert'] = true; continue; } else { $colStmt[] = "`${colName}`"; } } return $colStmt; }
php
public function getColumnStmt($tableName) { $colStmt = array(); foreach ($this->tableColumnTypes[$tableName] as $colName => $colType) { if ($colType['type'] == 'bit' && $this->dumpSettings['hex-blob']) { $colStmt[] = "LPAD(HEX(`${colName}`),2,'0') AS `${colName}`"; } elseif ($colType['is_blob'] && $this->dumpSettings['hex-blob']) { $colStmt[] = "HEX(`${colName}`) AS `${colName}`"; } elseif ($colType['is_virtual']) { $this->dumpSettings['complete-insert'] = true; continue; } else { $colStmt[] = "`${colName}`"; } } return $colStmt; }
[ "public", "function", "getColumnStmt", "(", "$", "tableName", ")", "{", "$", "colStmt", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "tableColumnTypes", "[", "$", "tableName", "]", "as", "$", "colName", "=>", "$", "colType", ")", "{", "if", "(", "$", "colType", "[", "'type'", "]", "==", "'bit'", "&&", "$", "this", "->", "dumpSettings", "[", "'hex-blob'", "]", ")", "{", "$", "colStmt", "[", "]", "=", "\"LPAD(HEX(`${colName}`),2,'0') AS `${colName}`\"", ";", "}", "elseif", "(", "$", "colType", "[", "'is_blob'", "]", "&&", "$", "this", "->", "dumpSettings", "[", "'hex-blob'", "]", ")", "{", "$", "colStmt", "[", "]", "=", "\"HEX(`${colName}`) AS `${colName}`\"", ";", "}", "elseif", "(", "$", "colType", "[", "'is_virtual'", "]", ")", "{", "$", "this", "->", "dumpSettings", "[", "'complete-insert'", "]", "=", "true", ";", "continue", ";", "}", "else", "{", "$", "colStmt", "[", "]", "=", "\"`${colName}`\"", ";", "}", "}", "return", "$", "colStmt", ";", "}" ]
Build SQL List of all columns on current table which will be used for selecting @param string $tableName Name of table to get columns @return array SQL sentence with columns for select
[ "Build", "SQL", "List", "of", "all", "columns", "on", "current", "table", "which", "will", "be", "used", "for", "selecting" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L1209-L1226
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
Mysqldump.getColumnNames
public function getColumnNames($tableName) { $colNames = array(); foreach ($this->tableColumnTypes[$tableName] as $colName => $colType) { if ($colType['is_virtual']) { $this->dumpSettings['complete-insert'] = true; continue; } else { $colNames[] = "`${colName}`"; } } return $colNames; }
php
public function getColumnNames($tableName) { $colNames = array(); foreach ($this->tableColumnTypes[$tableName] as $colName => $colType) { if ($colType['is_virtual']) { $this->dumpSettings['complete-insert'] = true; continue; } else { $colNames[] = "`${colName}`"; } } return $colNames; }
[ "public", "function", "getColumnNames", "(", "$", "tableName", ")", "{", "$", "colNames", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "tableColumnTypes", "[", "$", "tableName", "]", "as", "$", "colName", "=>", "$", "colType", ")", "{", "if", "(", "$", "colType", "[", "'is_virtual'", "]", ")", "{", "$", "this", "->", "dumpSettings", "[", "'complete-insert'", "]", "=", "true", ";", "continue", ";", "}", "else", "{", "$", "colNames", "[", "]", "=", "\"`${colName}`\"", ";", "}", "}", "return", "$", "colNames", ";", "}" ]
Build SQL List of all columns on current table which will be used for inserting @param string $tableName Name of table to get columns @return array columns for sql sentence for insert
[ "Build", "SQL", "List", "of", "all", "columns", "on", "current", "table", "which", "will", "be", "used", "for", "inserting" ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L1235-L1247
ifsnop/mysqldump-php
src/Ifsnop/Mysqldump/Mysqldump.php
TypeAdapterMysql.parseColumnType
public function parseColumnType($colType) { $colInfo = array(); $colParts = explode(" ", $colType['Type']); if ($fparen = strpos($colParts[0], "(")) { $colInfo['type'] = substr($colParts[0], 0, $fparen); $colInfo['length'] = str_replace(")", "", substr($colParts[0], $fparen + 1)); $colInfo['attributes'] = isset($colParts[1]) ? $colParts[1] : null; } else { $colInfo['type'] = $colParts[0]; } $colInfo['is_numeric'] = in_array($colInfo['type'], $this->mysqlTypes['numerical']); $colInfo['is_blob'] = in_array($colInfo['type'], $this->mysqlTypes['blob']); // for virtual columns that are of type 'Extra', column type // could by "STORED GENERATED" or "VIRTUAL GENERATED" // MySQL reference: https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html $colInfo['is_virtual'] = strpos($colType['Extra'], "VIRTUAL GENERATED") !== false || strpos($colType['Extra'], "STORED GENERATED") !== false; return $colInfo; }
php
public function parseColumnType($colType) { $colInfo = array(); $colParts = explode(" ", $colType['Type']); if ($fparen = strpos($colParts[0], "(")) { $colInfo['type'] = substr($colParts[0], 0, $fparen); $colInfo['length'] = str_replace(")", "", substr($colParts[0], $fparen + 1)); $colInfo['attributes'] = isset($colParts[1]) ? $colParts[1] : null; } else { $colInfo['type'] = $colParts[0]; } $colInfo['is_numeric'] = in_array($colInfo['type'], $this->mysqlTypes['numerical']); $colInfo['is_blob'] = in_array($colInfo['type'], $this->mysqlTypes['blob']); $colInfo['is_virtual'] = strpos($colType['Extra'], "VIRTUAL GENERATED") !== false || strpos($colType['Extra'], "STORED GENERATED") !== false; return $colInfo; }
[ "public", "function", "parseColumnType", "(", "$", "colType", ")", "{", "$", "colInfo", "=", "array", "(", ")", ";", "$", "colParts", "=", "explode", "(", "\" \"", ",", "$", "colType", "[", "'Type'", "]", ")", ";", "if", "(", "$", "fparen", "=", "strpos", "(", "$", "colParts", "[", "0", "]", ",", "\"(\"", ")", ")", "{", "$", "colInfo", "[", "'type'", "]", "=", "substr", "(", "$", "colParts", "[", "0", "]", ",", "0", ",", "$", "fparen", ")", ";", "$", "colInfo", "[", "'length'", "]", "=", "str_replace", "(", "\")\"", ",", "\"\"", ",", "substr", "(", "$", "colParts", "[", "0", "]", ",", "$", "fparen", "+", "1", ")", ")", ";", "$", "colInfo", "[", "'attributes'", "]", "=", "isset", "(", "$", "colParts", "[", "1", "]", ")", "?", "$", "colParts", "[", "1", "]", ":", "null", ";", "}", "else", "{", "$", "colInfo", "[", "'type'", "]", "=", "$", "colParts", "[", "0", "]", ";", "}", "$", "colInfo", "[", "'is_numeric'", "]", "=", "in_array", "(", "$", "colInfo", "[", "'type'", "]", ",", "$", "this", "->", "mysqlTypes", "[", "'numerical'", "]", ")", ";", "$", "colInfo", "[", "'is_blob'", "]", "=", "in_array", "(", "$", "colInfo", "[", "'type'", "]", ",", "$", "this", "->", "mysqlTypes", "[", "'blob'", "]", ")", ";", "// for virtual columns that are of type 'Extra', column type", "// could by \"STORED GENERATED\" or \"VIRTUAL GENERATED\"", "// MySQL reference: https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html", "$", "colInfo", "[", "'is_virtual'", "]", "=", "strpos", "(", "$", "colType", "[", "'Extra'", "]", ",", "\"VIRTUAL GENERATED\"", ")", "!==", "false", "||", "strpos", "(", "$", "colType", "[", "'Extra'", "]", ",", "\"STORED GENERATED\"", ")", "!==", "false", ";", "return", "$", "colInfo", ";", "}" ]
Decode column metadata and fill info structure. type, is_numeric and is_blob will always be available. @param array $colType Array returned from "SHOW COLUMNS FROM tableName" @return array
[ "Decode", "column", "metadata", "and", "fill", "info", "structure", ".", "type", "is_numeric", "and", "is_blob", "will", "always", "be", "available", "." ]
train
https://github.com/ifsnop/mysqldump-php/blob/aaaecaef045686e9f8d2e4925be267994a5d8a72/src/Ifsnop/Mysqldump/Mysqldump.php#L2056-L2076
fideloper/TrustedProxy
src/TrustProxies.php
TrustProxies.handle
public function handle(Request $request, Closure $next) { $request::setTrustedProxies([], $this->getTrustedHeaderNames()); // Reset trusted proxies between requests $this->setTrustedProxyIpAddresses($request); return $next($request); }
php
public function handle(Request $request, Closure $next) { $request::setTrustedProxies([], $this->getTrustedHeaderNames()); $this->setTrustedProxyIpAddresses($request); return $next($request); }
[ "public", "function", "handle", "(", "Request", "$", "request", ",", "Closure", "$", "next", ")", "{", "$", "request", "::", "setTrustedProxies", "(", "[", "]", ",", "$", "this", "->", "getTrustedHeaderNames", "(", ")", ")", ";", "// Reset trusted proxies between requests", "$", "this", "->", "setTrustedProxyIpAddresses", "(", "$", "request", ")", ";", "return", "$", "next", "(", "$", "request", ")", ";", "}" ]
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @throws \Symfony\Component\HttpKernel\Exception\HttpException @return mixed
[ "Handle", "an", "incoming", "request", "." ]
train
https://github.com/fideloper/TrustedProxy/blob/2585e8ef63b11115df22f1af94d7be5e9445ec96/src/TrustProxies.php#L52-L58
fideloper/TrustedProxy
src/TrustProxies.php
TrustProxies.setTrustedProxyIpAddresses
protected function setTrustedProxyIpAddresses(Request $request) { $trustedIps = $this->proxies ?: $this->config->get('trustedproxy.proxies'); // Trust any IP address that calls us // `**` for backwards compatibility, but is deprecated if ($trustedIps === '*' || $trustedIps === '**') { return $this->setTrustedProxyIpAddressesToTheCallingIp($request); } // Support IPs addresses separated by comma $trustedIps = is_string($trustedIps) ? array_map('trim', explode(',', $trustedIps)) : $trustedIps; // Only trust specific IP addresses if (is_array($trustedIps)) { return $this->setTrustedProxyIpAddressesToSpecificIps($request, $trustedIps); } }
php
protected function setTrustedProxyIpAddresses(Request $request) { $trustedIps = $this->proxies ?: $this->config->get('trustedproxy.proxies'); if ($trustedIps === '*' || $trustedIps === '**') { return $this->setTrustedProxyIpAddressesToTheCallingIp($request); } $trustedIps = is_string($trustedIps) ? array_map('trim', explode(',', $trustedIps)) : $trustedIps; if (is_array($trustedIps)) { return $this->setTrustedProxyIpAddressesToSpecificIps($request, $trustedIps); } }
[ "protected", "function", "setTrustedProxyIpAddresses", "(", "Request", "$", "request", ")", "{", "$", "trustedIps", "=", "$", "this", "->", "proxies", "?", ":", "$", "this", "->", "config", "->", "get", "(", "'trustedproxy.proxies'", ")", ";", "// Trust any IP address that calls us", "// `**` for backwards compatibility, but is deprecated", "if", "(", "$", "trustedIps", "===", "'*'", "||", "$", "trustedIps", "===", "'**'", ")", "{", "return", "$", "this", "->", "setTrustedProxyIpAddressesToTheCallingIp", "(", "$", "request", ")", ";", "}", "// Support IPs addresses separated by comma", "$", "trustedIps", "=", "is_string", "(", "$", "trustedIps", ")", "?", "array_map", "(", "'trim'", ",", "explode", "(", "','", ",", "$", "trustedIps", ")", ")", ":", "$", "trustedIps", ";", "// Only trust specific IP addresses", "if", "(", "is_array", "(", "$", "trustedIps", ")", ")", "{", "return", "$", "this", "->", "setTrustedProxyIpAddressesToSpecificIps", "(", "$", "request", ",", "$", "trustedIps", ")", ";", "}", "}" ]
Sets the trusted proxies on the request to the value of trustedproxy.proxies @param \Illuminate\Http\Request $request
[ "Sets", "the", "trusted", "proxies", "on", "the", "request", "to", "the", "value", "of", "trustedproxy", ".", "proxies" ]
train
https://github.com/fideloper/TrustedProxy/blob/2585e8ef63b11115df22f1af94d7be5e9445ec96/src/TrustProxies.php#L65-L82
fideloper/TrustedProxy
src/TrustProxies.php
TrustProxies.setTrustedProxyIpAddressesToTheCallingIp
private function setTrustedProxyIpAddressesToTheCallingIp(Request $request) { $request->setTrustedProxies([$request->server->get('REMOTE_ADDR')], $this->getTrustedHeaderNames()); }
php
private function setTrustedProxyIpAddressesToTheCallingIp(Request $request) { $request->setTrustedProxies([$request->server->get('REMOTE_ADDR')], $this->getTrustedHeaderNames()); }
[ "private", "function", "setTrustedProxyIpAddressesToTheCallingIp", "(", "Request", "$", "request", ")", "{", "$", "request", "->", "setTrustedProxies", "(", "[", "$", "request", "->", "server", "->", "get", "(", "'REMOTE_ADDR'", ")", "]", ",", "$", "this", "->", "getTrustedHeaderNames", "(", ")", ")", ";", "}" ]
Set the trusted proxy to be the IP address calling this servers @param \Illuminate\Http\Request $request
[ "Set", "the", "trusted", "proxy", "to", "be", "the", "IP", "address", "calling", "this", "servers" ]
train
https://github.com/fideloper/TrustedProxy/blob/2585e8ef63b11115df22f1af94d7be5e9445ec96/src/TrustProxies.php#L100-L103
fideloper/TrustedProxy
src/TrustProxies.php
TrustProxies.getTrustedHeaderNames
protected function getTrustedHeaderNames() { $headers = $this->headers ?: $this->config->get('trustedproxy.headers'); switch ($headers) { case 'HEADER_X_FORWARDED_AWS_ELB': case Request::HEADER_X_FORWARDED_AWS_ELB: return Request::HEADER_X_FORWARDED_AWS_ELB; break; case 'HEADER_FORWARDED': case Request::HEADER_FORWARDED: return Request::HEADER_FORWARDED; break; default: return Request::HEADER_X_FORWARDED_ALL; } // Should never reach this point return $headers; }
php
protected function getTrustedHeaderNames() { $headers = $this->headers ?: $this->config->get('trustedproxy.headers'); switch ($headers) { case 'HEADER_X_FORWARDED_AWS_ELB': case Request::HEADER_X_FORWARDED_AWS_ELB: return Request::HEADER_X_FORWARDED_AWS_ELB; break; case 'HEADER_FORWARDED': case Request::HEADER_FORWARDED: return Request::HEADER_FORWARDED; break; default: return Request::HEADER_X_FORWARDED_ALL; } return $headers; }
[ "protected", "function", "getTrustedHeaderNames", "(", ")", "{", "$", "headers", "=", "$", "this", "->", "headers", "?", ":", "$", "this", "->", "config", "->", "get", "(", "'trustedproxy.headers'", ")", ";", "switch", "(", "$", "headers", ")", "{", "case", "'HEADER_X_FORWARDED_AWS_ELB'", ":", "case", "Request", "::", "HEADER_X_FORWARDED_AWS_ELB", ":", "return", "Request", "::", "HEADER_X_FORWARDED_AWS_ELB", ";", "break", ";", "case", "'HEADER_FORWARDED'", ":", "case", "Request", "::", "HEADER_FORWARDED", ":", "return", "Request", "::", "HEADER_FORWARDED", ";", "break", ";", "default", ":", "return", "Request", "::", "HEADER_X_FORWARDED_ALL", ";", "}", "// Should never reach this point", "return", "$", "headers", ";", "}" ]
Retrieve trusted header name(s), falling back to defaults if config not set. @return int A bit field of Request::HEADER_*, to set which headers to trust from your proxies.
[ "Retrieve", "trusted", "header", "name", "(", "s", ")", "falling", "back", "to", "defaults", "if", "config", "not", "set", "." ]
train
https://github.com/fideloper/TrustedProxy/blob/2585e8ef63b11115df22f1af94d7be5e9445ec96/src/TrustProxies.php#L110-L128
yajra/laravel-oci8
src/Oci8/Oci8Connection.php
Oci8Connection.setSchema
public function setSchema($schema) { $this->schema = $schema; $sessionVars = [ 'CURRENT_SCHEMA' => $schema, ]; return $this->setSessionVars($sessionVars); }
php
public function setSchema($schema) { $this->schema = $schema; $sessionVars = [ 'CURRENT_SCHEMA' => $schema, ]; return $this->setSessionVars($sessionVars); }
[ "public", "function", "setSchema", "(", "$", "schema", ")", "{", "$", "this", "->", "schema", "=", "$", "schema", ";", "$", "sessionVars", "=", "[", "'CURRENT_SCHEMA'", "=>", "$", "schema", ",", "]", ";", "return", "$", "this", "->", "setSessionVars", "(", "$", "sessionVars", ")", ";", "}" ]
Set current schema. @param string $schema @return $this
[ "Set", "current", "schema", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Oci8Connection.php#L71-L79
yajra/laravel-oci8
src/Oci8/Oci8Connection.php
Oci8Connection.setSessionVars
public function setSessionVars(array $sessionVars) { $vars = []; foreach ($sessionVars as $option => $value) { if (strtoupper($option) == 'CURRENT_SCHEMA' || strtoupper($option) == 'EDITION') { $vars[] = "$option = $value"; } else { $vars[] = "$option = '$value'"; } } if ($vars) { $sql = 'ALTER SESSION SET ' . implode(' ', $vars); $this->statement($sql); } return $this; }
php
public function setSessionVars(array $sessionVars) { $vars = []; foreach ($sessionVars as $option => $value) { if (strtoupper($option) == 'CURRENT_SCHEMA' || strtoupper($option) == 'EDITION') { $vars[] = "$option = $value"; } else { $vars[] = "$option = '$value'"; } } if ($vars) { $sql = 'ALTER SESSION SET ' . implode(' ', $vars); $this->statement($sql); } return $this; }
[ "public", "function", "setSessionVars", "(", "array", "$", "sessionVars", ")", "{", "$", "vars", "=", "[", "]", ";", "foreach", "(", "$", "sessionVars", "as", "$", "option", "=>", "$", "value", ")", "{", "if", "(", "strtoupper", "(", "$", "option", ")", "==", "'CURRENT_SCHEMA'", "||", "strtoupper", "(", "$", "option", ")", "==", "'EDITION'", ")", "{", "$", "vars", "[", "]", "=", "\"$option = $value\"", ";", "}", "else", "{", "$", "vars", "[", "]", "=", "\"$option = '$value'\"", ";", "}", "}", "if", "(", "$", "vars", ")", "{", "$", "sql", "=", "'ALTER SESSION SET '", ".", "implode", "(", "' '", ",", "$", "vars", ")", ";", "$", "this", "->", "statement", "(", "$", "sql", ")", ";", "}", "return", "$", "this", ";", "}" ]
Update oracle session variables. @param array $sessionVars @return $this
[ "Update", "oracle", "session", "variables", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Oci8Connection.php#L87-L104
yajra/laravel-oci8
src/Oci8/Oci8Connection.php
Oci8Connection.table
public function table($table) { $processor = $this->getPostProcessor(); $query = new QueryBuilder($this, $this->getQueryGrammar(), $processor); return $query->from($table); }
php
public function table($table) { $processor = $this->getPostProcessor(); $query = new QueryBuilder($this, $this->getQueryGrammar(), $processor); return $query->from($table); }
[ "public", "function", "table", "(", "$", "table", ")", "{", "$", "processor", "=", "$", "this", "->", "getPostProcessor", "(", ")", ";", "$", "query", "=", "new", "QueryBuilder", "(", "$", "this", ",", "$", "this", "->", "getQueryGrammar", "(", ")", ",", "$", "processor", ")", ";", "return", "$", "query", "->", "from", "(", "$", "table", ")", ";", "}" ]
Begin a fluent query against a database table. @param string $table @return \Yajra\Oci8\Query\OracleBuilder
[ "Begin", "a", "fluent", "query", "against", "a", "database", "table", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Oci8Connection.php#L168-L175
yajra/laravel-oci8
src/Oci8/Oci8Connection.php
Oci8Connection.getDoctrineConnection
public function getDoctrineConnection() { if (is_null($this->doctrineConnection)) { $data = ['pdo' => $this->getPdo(), 'user' => $this->getConfig('username')]; $this->doctrineConnection = new DoctrineConnection( $data, $this->getDoctrineDriver() ); } return $this->doctrineConnection; }
php
public function getDoctrineConnection() { if (is_null($this->doctrineConnection)) { $data = ['pdo' => $this->getPdo(), 'user' => $this->getConfig('username')]; $this->doctrineConnection = new DoctrineConnection( $data, $this->getDoctrineDriver() ); } return $this->doctrineConnection; }
[ "public", "function", "getDoctrineConnection", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "doctrineConnection", ")", ")", "{", "$", "data", "=", "[", "'pdo'", "=>", "$", "this", "->", "getPdo", "(", ")", ",", "'user'", "=>", "$", "this", "->", "getConfig", "(", "'username'", ")", "]", ";", "$", "this", "->", "doctrineConnection", "=", "new", "DoctrineConnection", "(", "$", "data", ",", "$", "this", "->", "getDoctrineDriver", "(", ")", ")", ";", "}", "return", "$", "this", "->", "doctrineConnection", ";", "}" ]
Get doctrine connection. @return \Doctrine\DBAL\Connection
[ "Get", "doctrine", "connection", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Oci8Connection.php#L198-L209
yajra/laravel-oci8
src/Oci8/Oci8Connection.php
Oci8Connection.executeFunction
public function executeFunction($functionName, array $bindings = [], $returnType = PDO::PARAM_STR, $length = null) { $stmt = $this->createStatementFromFunction($functionName, $bindings); $stmt = $this->addBindingsToStatement($stmt, $bindings); $stmt->bindParam(':result', $result, $returnType, $length); $stmt->execute(); return $result; }
php
public function executeFunction($functionName, array $bindings = [], $returnType = PDO::PARAM_STR, $length = null) { $stmt = $this->createStatementFromFunction($functionName, $bindings); $stmt = $this->addBindingsToStatement($stmt, $bindings); $stmt->bindParam(':result', $result, $returnType, $length); $stmt->execute(); return $result; }
[ "public", "function", "executeFunction", "(", "$", "functionName", ",", "array", "$", "bindings", "=", "[", "]", ",", "$", "returnType", "=", "PDO", "::", "PARAM_STR", ",", "$", "length", "=", "null", ")", "{", "$", "stmt", "=", "$", "this", "->", "createStatementFromFunction", "(", "$", "functionName", ",", "$", "bindings", ")", ";", "$", "stmt", "=", "$", "this", "->", "addBindingsToStatement", "(", "$", "stmt", ",", "$", "bindings", ")", ";", "$", "stmt", "->", "bindParam", "(", "':result'", ",", "$", "result", ",", "$", "returnType", ",", "$", "length", ")", ";", "$", "stmt", "->", "execute", "(", ")", ";", "return", "$", "result", ";", "}" ]
Execute a PL/SQL Function and return its value. Usage: DB::executeFunction('function_name(:binding_1,:binding_n)', [':binding_1' => 'hi', ':binding_n' => 'bye'], PDO::PARAM_LOB). @param string $functionName @param array $bindings (kvp array) @param int $returnType (PDO::PARAM_*) @param int $length @return mixed $returnType
[ "Execute", "a", "PL", "/", "SQL", "Function", "and", "return", "its", "value", ".", "Usage", ":", "DB", "::", "executeFunction", "(", "function_name", "(", ":", "binding_1", ":", "binding_n", ")", "[", ":", "binding_1", "=", ">", "hi", ":", "binding_n", "=", ">", "bye", "]", "PDO", "::", "PARAM_LOB", ")", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Oci8Connection.php#L232-L242
yajra/laravel-oci8
src/Oci8/Oci8Connection.php
Oci8Connection.executeProcedure
public function executeProcedure($procedureName, array $bindings = []) { $stmt = $this->createStatementFromProcedure($procedureName, $bindings); $stmt = $this->addBindingsToStatement($stmt, $bindings); return $stmt->execute(); }
php
public function executeProcedure($procedureName, array $bindings = []) { $stmt = $this->createStatementFromProcedure($procedureName, $bindings); $stmt = $this->addBindingsToStatement($stmt, $bindings); return $stmt->execute(); }
[ "public", "function", "executeProcedure", "(", "$", "procedureName", ",", "array", "$", "bindings", "=", "[", "]", ")", "{", "$", "stmt", "=", "$", "this", "->", "createStatementFromProcedure", "(", "$", "procedureName", ",", "$", "bindings", ")", ";", "$", "stmt", "=", "$", "this", "->", "addBindingsToStatement", "(", "$", "stmt", ",", "$", "bindings", ")", ";", "return", "$", "stmt", "->", "execute", "(", ")", ";", "}" ]
Execute a PL/SQL Procedure and return its results. Usage: DB::executeProcedure($procedureName, $bindings). $bindings looks like: $bindings = [ 'p_userid' => $id ]; @param string $procedureName @param array $bindings @return bool
[ "Execute", "a", "PL", "/", "SQL", "Procedure", "and", "return", "its", "results", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Oci8Connection.php#L257-L264
yajra/laravel-oci8
src/Oci8/Oci8Connection.php
Oci8Connection.executeProcedureWithCursor
public function executeProcedureWithCursor($procedureName, array $bindings = [], $cursorName = ':cursor') { $stmt = $this->createStatementFromProcedure($procedureName, $bindings, $cursorName); $stmt = $this->addBindingsToStatement($stmt, $bindings); $cursor = null; $stmt->bindParam($cursorName, $cursor, PDO::PARAM_STMT); $stmt->execute(); $statement = new Statement($cursor, $this->getPdo(), $this->getPdo()->getOptions()); $statement->execute(); $results = $statement->fetchAll(PDO::FETCH_OBJ); $statement->closeCursor(); return $results; }
php
public function executeProcedureWithCursor($procedureName, array $bindings = [], $cursorName = ':cursor') { $stmt = $this->createStatementFromProcedure($procedureName, $bindings, $cursorName); $stmt = $this->addBindingsToStatement($stmt, $bindings); $cursor = null; $stmt->bindParam($cursorName, $cursor, PDO::PARAM_STMT); $stmt->execute(); $statement = new Statement($cursor, $this->getPdo(), $this->getPdo()->getOptions()); $statement->execute(); $results = $statement->fetchAll(PDO::FETCH_OBJ); $statement->closeCursor(); return $results; }
[ "public", "function", "executeProcedureWithCursor", "(", "$", "procedureName", ",", "array", "$", "bindings", "=", "[", "]", ",", "$", "cursorName", "=", "':cursor'", ")", "{", "$", "stmt", "=", "$", "this", "->", "createStatementFromProcedure", "(", "$", "procedureName", ",", "$", "bindings", ",", "$", "cursorName", ")", ";", "$", "stmt", "=", "$", "this", "->", "addBindingsToStatement", "(", "$", "stmt", ",", "$", "bindings", ")", ";", "$", "cursor", "=", "null", ";", "$", "stmt", "->", "bindParam", "(", "$", "cursorName", ",", "$", "cursor", ",", "PDO", "::", "PARAM_STMT", ")", ";", "$", "stmt", "->", "execute", "(", ")", ";", "$", "statement", "=", "new", "Statement", "(", "$", "cursor", ",", "$", "this", "->", "getPdo", "(", ")", ",", "$", "this", "->", "getPdo", "(", ")", "->", "getOptions", "(", ")", ")", ";", "$", "statement", "->", "execute", "(", ")", ";", "$", "results", "=", "$", "statement", "->", "fetchAll", "(", "PDO", "::", "FETCH_OBJ", ")", ";", "$", "statement", "->", "closeCursor", "(", ")", ";", "return", "$", "results", ";", "}" ]
Execute a PL/SQL Procedure and return its cursor result. Usage: DB::executeProcedureWithCursor($procedureName, $bindings). https://docs.oracle.com/cd/E17781_01/appdev.112/e18555/ch_six_ref_cur.htm#TDPPH218 @param string $procedureName @param array $bindings @param string $cursorName @return array
[ "Execute", "a", "PL", "/", "SQL", "Procedure", "and", "return", "its", "cursor", "result", ".", "Usage", ":", "DB", "::", "executeProcedureWithCursor", "(", "$procedureName", "$bindings", ")", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Oci8Connection.php#L277-L293
yajra/laravel-oci8
src/Oci8/Oci8Connection.php
Oci8Connection.createSqlFromProcedure
public function createSqlFromProcedure($procedureName, array $bindings, $cursor = false) { $paramsString = implode(',', array_map(function ($param) { return ':' . $param; }, array_keys($bindings))); $prefix = count($bindings) ? ',' : ''; $cursor = $cursor ? $prefix . $cursor : null; return sprintf('begin %s(%s%s); end;', $procedureName, $paramsString, $cursor); }
php
public function createSqlFromProcedure($procedureName, array $bindings, $cursor = false) { $paramsString = implode(',', array_map(function ($param) { return ':' . $param; }, array_keys($bindings))); $prefix = count($bindings) ? ',' : ''; $cursor = $cursor ? $prefix . $cursor : null; return sprintf('begin %s(%s%s); end;', $procedureName, $paramsString, $cursor); }
[ "public", "function", "createSqlFromProcedure", "(", "$", "procedureName", ",", "array", "$", "bindings", ",", "$", "cursor", "=", "false", ")", "{", "$", "paramsString", "=", "implode", "(", "','", ",", "array_map", "(", "function", "(", "$", "param", ")", "{", "return", "':'", ".", "$", "param", ";", "}", ",", "array_keys", "(", "$", "bindings", ")", ")", ")", ";", "$", "prefix", "=", "count", "(", "$", "bindings", ")", "?", "','", ":", "''", ";", "$", "cursor", "=", "$", "cursor", "?", "$", "prefix", ".", "$", "cursor", ":", "null", ";", "return", "sprintf", "(", "'begin %s(%s%s); end;'", ",", "$", "procedureName", ",", "$", "paramsString", ",", "$", "cursor", ")", ";", "}" ]
Creates sql command to run a procedure with bindings. @param string $procedureName @param array $bindings @param string|bool $cursor @return string
[ "Creates", "sql", "command", "to", "run", "a", "procedure", "with", "bindings", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Oci8Connection.php#L303-L313
yajra/laravel-oci8
src/Oci8/Oci8Connection.php
Oci8Connection.createStatementFromProcedure
public function createStatementFromProcedure($procedureName, array $bindings, $cursorName = false) { $sql = $this->createSqlFromProcedure($procedureName, $bindings, $cursorName); return $this->getPdo()->prepare($sql); }
php
public function createStatementFromProcedure($procedureName, array $bindings, $cursorName = false) { $sql = $this->createSqlFromProcedure($procedureName, $bindings, $cursorName); return $this->getPdo()->prepare($sql); }
[ "public", "function", "createStatementFromProcedure", "(", "$", "procedureName", ",", "array", "$", "bindings", ",", "$", "cursorName", "=", "false", ")", "{", "$", "sql", "=", "$", "this", "->", "createSqlFromProcedure", "(", "$", "procedureName", ",", "$", "bindings", ",", "$", "cursorName", ")", ";", "return", "$", "this", "->", "getPdo", "(", ")", "->", "prepare", "(", "$", "sql", ")", ";", "}" ]
Creates statement from procedure. @param string $procedureName @param array $bindings @param string|bool $cursorName @return PDOStatement
[ "Creates", "statement", "from", "procedure", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Oci8Connection.php#L323-L328
yajra/laravel-oci8
src/Oci8/Oci8Connection.php
Oci8Connection.createStatementFromFunction
public function createStatementFromFunction($functionName, array $bindings) { $bindings = $bindings ? ':' . implode(', :', array_keys($bindings)) : ''; $sql = sprintf('begin :result := %s(%s); end;', $functionName, $bindings); return $this->getPdo()->prepare($sql); }
php
public function createStatementFromFunction($functionName, array $bindings) { $bindings = $bindings ? ':' . implode(', :', array_keys($bindings)) : ''; $sql = sprintf('begin :result := %s(%s); end;', $functionName, $bindings); return $this->getPdo()->prepare($sql); }
[ "public", "function", "createStatementFromFunction", "(", "$", "functionName", ",", "array", "$", "bindings", ")", "{", "$", "bindings", "=", "$", "bindings", "?", "':'", ".", "implode", "(", "', :'", ",", "array_keys", "(", "$", "bindings", ")", ")", ":", "''", ";", "$", "sql", "=", "sprintf", "(", "'begin :result := %s(%s); end;'", ",", "$", "functionName", ",", "$", "bindings", ")", ";", "return", "$", "this", "->", "getPdo", "(", ")", "->", "prepare", "(", "$", "sql", ")", ";", "}" ]
Create statement from function. @param string $functionName @param array $bindings @return PDOStatement
[ "Create", "statement", "from", "function", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Oci8Connection.php#L337-L344
yajra/laravel-oci8
src/Oci8/Oci8Connection.php
Oci8Connection.bindValues
public function bindValues($statement, $bindings) { foreach ($bindings as $key => $value) { $statement->bindParam($key, $bindings[$key]); } }
php
public function bindValues($statement, $bindings) { foreach ($bindings as $key => $value) { $statement->bindParam($key, $bindings[$key]); } }
[ "public", "function", "bindValues", "(", "$", "statement", ",", "$", "bindings", ")", "{", "foreach", "(", "$", "bindings", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "statement", "->", "bindParam", "(", "$", "key", ",", "$", "bindings", "[", "$", "key", "]", ")", ";", "}", "}" ]
Bind values to their parameters in the given statement. @param PDOStatement $statement @param array $bindings
[ "Bind", "values", "to", "their", "parameters", "in", "the", "given", "statement", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Oci8Connection.php#L352-L357
yajra/laravel-oci8
src/Oci8/Oci8Connection.php
Oci8Connection.addBindingsToStatement
public function addBindingsToStatement(PDOStatement $stmt, array $bindings) { foreach ($bindings as $key => &$binding) { $value = &$binding; $type = PDO::PARAM_STR; $length = -1; if (is_array($binding)) { $value = &$binding['value']; $type = array_key_exists('type', $binding) ? $binding['type'] : PDO::PARAM_STR; $length = array_key_exists('length', $binding) ? $binding['length'] : -1; } $stmt->bindParam(':' . $key, $value, $type, $length); } return $stmt; }
php
public function addBindingsToStatement(PDOStatement $stmt, array $bindings) { foreach ($bindings as $key => &$binding) { $value = &$binding; $type = PDO::PARAM_STR; $length = -1; if (is_array($binding)) { $value = &$binding['value']; $type = array_key_exists('type', $binding) ? $binding['type'] : PDO::PARAM_STR; $length = array_key_exists('length', $binding) ? $binding['length'] : -1; } $stmt->bindParam(':' . $key, $value, $type, $length); } return $stmt; }
[ "public", "function", "addBindingsToStatement", "(", "PDOStatement", "$", "stmt", ",", "array", "$", "bindings", ")", "{", "foreach", "(", "$", "bindings", "as", "$", "key", "=>", "&", "$", "binding", ")", "{", "$", "value", "=", "&", "$", "binding", ";", "$", "type", "=", "PDO", "::", "PARAM_STR", ";", "$", "length", "=", "-", "1", ";", "if", "(", "is_array", "(", "$", "binding", ")", ")", "{", "$", "value", "=", "&", "$", "binding", "[", "'value'", "]", ";", "$", "type", "=", "array_key_exists", "(", "'type'", ",", "$", "binding", ")", "?", "$", "binding", "[", "'type'", "]", ":", "PDO", "::", "PARAM_STR", ";", "$", "length", "=", "array_key_exists", "(", "'length'", ",", "$", "binding", ")", "?", "$", "binding", "[", "'length'", "]", ":", "-", "1", ";", "}", "$", "stmt", "->", "bindParam", "(", "':'", ".", "$", "key", ",", "$", "value", ",", "$", "type", ",", "$", "length", ")", ";", "}", "return", "$", "stmt", ";", "}" ]
Add bindings to statement. @param array $bindings @param PDOStatement $stmt @return PDOStatement
[ "Add", "bindings", "to", "statement", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Oci8Connection.php#L430-L447
yajra/laravel-oci8
src/Oci8/Oci8Connection.php
Oci8Connection.causedByLostConnection
protected function causedByLostConnection(Throwable $e) { if (parent::causedByLostConnection($e)) { return true; } $lostConnectionErrors = [ 'ORA-03113', //End-of-file on communication channel 'ORA-03114', //Not Connected to Oracle 'ORA-03135', //Connection lost contact 'ORA-12170', //Connect timeout occurred 'ORA-12537', //Connection closed 'ORA-27146', //Post/wait initialization failed 'ORA-25408', //Can not safely replay call 'ORA-56600', //Illegal Call ]; $additionalErrors = null; $options = isset($this->config['options']) ? $this->config['options'] : []; if (array_key_exists(static::RECONNECT_ERRORS, $options)) { $additionalErrors = $this->config['options'][static::RECONNECT_ERRORS]; } if (is_array($additionalErrors)) { $lostConnectionErrors = array_merge($lostConnectionErrors, $this->config['options'][static::RECONNECT_ERRORS]); } return Str::contains($e->getMessage(), $lostConnectionErrors); }
php
protected function causedByLostConnection(Throwable $e) { if (parent::causedByLostConnection($e)) { return true; } $lostConnectionErrors = [ 'ORA-03113', 'ORA-03114', 'ORA-03135', 'ORA-12170', 'ORA-12537', 'ORA-27146', 'ORA-25408', 'ORA-56600', ]; $additionalErrors = null; $options = isset($this->config['options']) ? $this->config['options'] : []; if (array_key_exists(static::RECONNECT_ERRORS, $options)) { $additionalErrors = $this->config['options'][static::RECONNECT_ERRORS]; } if (is_array($additionalErrors)) { $lostConnectionErrors = array_merge($lostConnectionErrors, $this->config['options'][static::RECONNECT_ERRORS]); } return Str::contains($e->getMessage(), $lostConnectionErrors); }
[ "protected", "function", "causedByLostConnection", "(", "Throwable", "$", "e", ")", "{", "if", "(", "parent", "::", "causedByLostConnection", "(", "$", "e", ")", ")", "{", "return", "true", ";", "}", "$", "lostConnectionErrors", "=", "[", "'ORA-03113'", ",", "//End-of-file on communication channel", "'ORA-03114'", ",", "//Not Connected to Oracle", "'ORA-03135'", ",", "//Connection lost contact", "'ORA-12170'", ",", "//Connect timeout occurred", "'ORA-12537'", ",", "//Connection closed", "'ORA-27146'", ",", "//Post/wait initialization failed", "'ORA-25408'", ",", "//Can not safely replay call", "'ORA-56600'", ",", "//Illegal Call", "]", ";", "$", "additionalErrors", "=", "null", ";", "$", "options", "=", "isset", "(", "$", "this", "->", "config", "[", "'options'", "]", ")", "?", "$", "this", "->", "config", "[", "'options'", "]", ":", "[", "]", ";", "if", "(", "array_key_exists", "(", "static", "::", "RECONNECT_ERRORS", ",", "$", "options", ")", ")", "{", "$", "additionalErrors", "=", "$", "this", "->", "config", "[", "'options'", "]", "[", "static", "::", "RECONNECT_ERRORS", "]", ";", "}", "if", "(", "is_array", "(", "$", "additionalErrors", ")", ")", "{", "$", "lostConnectionErrors", "=", "array_merge", "(", "$", "lostConnectionErrors", ",", "$", "this", "->", "config", "[", "'options'", "]", "[", "static", "::", "RECONNECT_ERRORS", "]", ")", ";", "}", "return", "Str", "::", "contains", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "lostConnectionErrors", ")", ";", "}" ]
Determine if the given exception was caused by a lost connection. @param \Exception $e @return bool
[ "Determine", "if", "the", "given", "exception", "was", "caused", "by", "a", "lost", "connection", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Oci8Connection.php#L455-L485
yajra/laravel-oci8
src/Oci8/Auth/OracleUserProvider.php
OracleUserProvider.retrieveByCredentials
public function retrieveByCredentials(array $credentials) { if (empty($credentials)) { return; } // First we will add each credential element to the query as a where clause. // Then we can execute the query and, if we found a user, return it in a // Eloquent User "model" that will be utilized by the Guard instances. $query = $this->createModel()->newQuery(); foreach ($credentials as $key => $value) { if (! Str::contains($key, 'password')) { $query->whereRaw("upper({$key}) = upper(?)", [$value]); } } return $query->first(); }
php
public function retrieveByCredentials(array $credentials) { if (empty($credentials)) { return; } $query = $this->createModel()->newQuery(); foreach ($credentials as $key => $value) { if (! Str::contains($key, 'password')) { $query->whereRaw("upper({$key}) = upper(?)", [$value]); } } return $query->first(); }
[ "public", "function", "retrieveByCredentials", "(", "array", "$", "credentials", ")", "{", "if", "(", "empty", "(", "$", "credentials", ")", ")", "{", "return", ";", "}", "// First we will add each credential element to the query as a where clause.", "// Then we can execute the query and, if we found a user, return it in a", "// Eloquent User \"model\" that will be utilized by the Guard instances.", "$", "query", "=", "$", "this", "->", "createModel", "(", ")", "->", "newQuery", "(", ")", ";", "foreach", "(", "$", "credentials", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "Str", "::", "contains", "(", "$", "key", ",", "'password'", ")", ")", "{", "$", "query", "->", "whereRaw", "(", "\"upper({$key}) = upper(?)\"", ",", "[", "$", "value", "]", ")", ";", "}", "}", "return", "$", "query", "->", "first", "(", ")", ";", "}" ]
Retrieve a user by the given credentials. @param array $credentials @return \Illuminate\Contracts\Auth\Authenticatable|null
[ "Retrieve", "a", "user", "by", "the", "given", "credentials", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Auth/OracleUserProvider.php#L16-L34
yajra/laravel-oci8
src/Oci8/Eloquent/OracleEloquent.php
OracleEloquent.update
public function update(array $attributes = [], array $options = []) { if (! $this->exists) { return false; } // If dirty attributes contains binary field // extract binary fields to new array if ($this->extractBinaries($attributes)) { return $this->newQuery()->updateLob($attributes, $this->binaryFields, $this->getKeyName()); } return $this->fill($attributes)->save($options); }
php
public function update(array $attributes = [], array $options = []) { if (! $this->exists) { return false; } if ($this->extractBinaries($attributes)) { return $this->newQuery()->updateLob($attributes, $this->binaryFields, $this->getKeyName()); } return $this->fill($attributes)->save($options); }
[ "public", "function", "update", "(", "array", "$", "attributes", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "$", "this", "->", "exists", ")", "{", "return", "false", ";", "}", "// If dirty attributes contains binary field", "// extract binary fields to new array", "if", "(", "$", "this", "->", "extractBinaries", "(", "$", "attributes", ")", ")", "{", "return", "$", "this", "->", "newQuery", "(", ")", "->", "updateLob", "(", "$", "attributes", ",", "$", "this", "->", "binaryFields", ",", "$", "this", "->", "getKeyName", "(", ")", ")", ";", "}", "return", "$", "this", "->", "fill", "(", "$", "attributes", ")", "->", "save", "(", "$", "options", ")", ";", "}" ]
Update the model in the database. @param array $attributes @param array $options @return bool|int
[ "Update", "the", "model", "in", "the", "database", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Eloquent/OracleEloquent.php#L83-L96
yajra/laravel-oci8
src/Oci8/Eloquent/OracleEloquent.php
OracleEloquent.extractBinaries
protected function extractBinaries(&$attributes) { // If attributes contains binary field // extract binary fields to new array $binaries = []; if ($this->checkBinary($attributes) && $this->getConnection() instanceof Oci8Connection) { foreach ($attributes as $key => $value) { if (in_array($key, $this->binaries)) { $binaries[$key] = $value; unset($attributes[$key]); } } } return $this->binaryFields = $binaries; }
php
protected function extractBinaries(&$attributes) { $binaries = []; if ($this->checkBinary($attributes) && $this->getConnection() instanceof Oci8Connection) { foreach ($attributes as $key => $value) { if (in_array($key, $this->binaries)) { $binaries[$key] = $value; unset($attributes[$key]); } } } return $this->binaryFields = $binaries; }
[ "protected", "function", "extractBinaries", "(", "&", "$", "attributes", ")", "{", "// If attributes contains binary field", "// extract binary fields to new array", "$", "binaries", "=", "[", "]", ";", "if", "(", "$", "this", "->", "checkBinary", "(", "$", "attributes", ")", "&&", "$", "this", "->", "getConnection", "(", ")", "instanceof", "Oci8Connection", ")", "{", "foreach", "(", "$", "attributes", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "in_array", "(", "$", "key", ",", "$", "this", "->", "binaries", ")", ")", "{", "$", "binaries", "[", "$", "key", "]", "=", "$", "value", ";", "unset", "(", "$", "attributes", "[", "$", "key", "]", ")", ";", "}", "}", "}", "return", "$", "this", "->", "binaryFields", "=", "$", "binaries", ";", "}" ]
Extract binary fields from given attributes. @param array $attributes @return array
[ "Extract", "binary", "fields", "from", "given", "attributes", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Eloquent/OracleEloquent.php#L104-L119
yajra/laravel-oci8
src/Oci8/Eloquent/OracleEloquent.php
OracleEloquent.checkBinary
protected function checkBinary(array $attributes) { foreach ($attributes as $key => $value) { // if attribute is in binary field list if (in_array($key, $this->binaries)) { return true; } } return false; }
php
protected function checkBinary(array $attributes) { foreach ($attributes as $key => $value) { if (in_array($key, $this->binaries)) { return true; } } return false; }
[ "protected", "function", "checkBinary", "(", "array", "$", "attributes", ")", "{", "foreach", "(", "$", "attributes", "as", "$", "key", "=>", "$", "value", ")", "{", "// if attribute is in binary field list", "if", "(", "in_array", "(", "$", "key", ",", "$", "this", "->", "binaries", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if attributes contains binary field. @param array $attributes @return bool
[ "Check", "if", "attributes", "contains", "binary", "field", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Eloquent/OracleEloquent.php#L127-L137
yajra/laravel-oci8
src/Oci8/Eloquent/OracleEloquent.php
OracleEloquent.getQualifiedKeyName
public function getQualifiedKeyName() { $pos = strpos($this->getTable(), '@'); if ($pos === false) { return $this->getTable() . '.' . $this->getKeyName(); } $table = substr($this->getTable(), 0, $pos); $dbLink = substr($this->getTable(), $pos); return $table . '.' . $this->getKeyName() . $dbLink; }
php
public function getQualifiedKeyName() { $pos = strpos($this->getTable(), '@'); if ($pos === false) { return $this->getTable() . '.' . $this->getKeyName(); } $table = substr($this->getTable(), 0, $pos); $dbLink = substr($this->getTable(), $pos); return $table . '.' . $this->getKeyName() . $dbLink; }
[ "public", "function", "getQualifiedKeyName", "(", ")", "{", "$", "pos", "=", "strpos", "(", "$", "this", "->", "getTable", "(", ")", ",", "'@'", ")", ";", "if", "(", "$", "pos", "===", "false", ")", "{", "return", "$", "this", "->", "getTable", "(", ")", ".", "'.'", ".", "$", "this", "->", "getKeyName", "(", ")", ";", "}", "$", "table", "=", "substr", "(", "$", "this", "->", "getTable", "(", ")", ",", "0", ",", "$", "pos", ")", ";", "$", "dbLink", "=", "substr", "(", "$", "this", "->", "getTable", "(", ")", ",", "$", "pos", ")", ";", "return", "$", "table", ".", "'.'", ".", "$", "this", "->", "getKeyName", "(", ")", ".", "$", "dbLink", ";", "}" ]
Get the table qualified key name. @return string
[ "Get", "the", "table", "qualified", "key", "name", "." ]
train
https://github.com/yajra/laravel-oci8/blob/0318976c23e06f20212f57ac162b4ec8af963c6c/src/Oci8/Eloquent/OracleEloquent.php#L144-L156