Methods that delegate and delegate

I am looking at a code path that needs to create MyObject instance.
It starts with a method:

MyObject createMyObject() {      //... } 

this delegates off to another object, which delegates off to another object which then creates MyObjects and passes it back up to the original method.

I thought it makes more sense that createMyObject creates the MyObject instance and just gets what it needs from other methods.

So, I am wondering if I am looking at a code smell or anti-pattern what the name of it is?

Witch one of these methods is better/safer to use? Simple MySql or MySql Class?

Witch one of these methods is better/safer to use? And what benefits i could get using one or other? I m really new to classes.

Simple mysqli:

connection.php

$  DBServer = "localhost"; $  DBPort = "3306"; $  DBUser = "root"; $  DBPass = ""; $  DBName = "test";  $  conn = new mysqli($  DBServer, $  DBUser, $  DBPass, $  DBName, $  DBPort); if ($  conn->connect_error) {     echo "Database connection failed: " . $  conn->connect_error, E_USER_ERROR; } mysqli_set_charset($  conn,"utf8"); 

index.php

include_once("connection.php");  $  l_name = mysqli_real_escape_string($  conn, $  _GET['l_name']);  $  query = mysqli_query($  conn, "SELECT * FROM test WHERE lname='".$  l_name."'"); while($  row = mysqli_fetch_array($  query)){     echo $  row['f_name'].' '.$  row['l_name'].'<br>'; } 

mysqli with class:

connection.php

class Connect {      var $  host = 'localhost';     var $  user = 'root';     var $  pass = '';     var $  db = 'test';     var $  con;      function connect() {         $  con = mysqli_connect($  this->host, $  this->user, $  this->pass, $  this->db);          if (!$  con) {             //die('Could not connect to database!');         } else {             $  this->con = $  con; //echo 'Connection established!';         }         mysqli_set_charset($  this->con,"utf8");          return $  this->con;      }      function close() {         mysqli_close($  con);     }  } 

index.php

include_once("connection.php");  $  con = new Connect(); $  con->connect();  $  l_name = mysqli_real_escape_string($  con->con, $  _GET['l_name']);  $  query = mysqli_query($  con->con, "SELECT * FROM test WHERE lname='".$  l_name."'"); while($  row = mysqli_fetch_array($  query)){     echo $  row['f_name'].' '.$  row['l_name'].'<br>'; } 

Thanks in advance!

Creative and standard methods of getting rid of Fog [on hold]

I have a game to run tomorrow with Drow who will be using the Darkness and Faerie Fire spells, so I’ve spent a lot of time getting my head straight on the rules of Unseen Combat. When reading through the rpg.stackexchange I realized Fog Cloud would be a good solution if the PC’s start getting slaughtered, to normalize the advantage/disadvantage situation before I screw up and get a TPK. But I’m not up to date on all the 5e spells, how many work against Fog?

  • Also if anyone thinks they could help with clarifying this question, feel free to edit it, I would appreciate it.

Magento 2 magic methods phpunit tests

I’ve started learning and at the same time writing tests for my Magento 2 custom development. Not a ride in the park. It feels like digging a pit in the sand sometimes. I got to the point where I need to test something like:

$  payment->setPaymentReminderSendStatus(true)->save(); 

Writing something like below won’t work.

$  this->orderPaymentMockSend->expects($  this->once())     ->method('setPaymentReminderSendStatus')     ->with($  paymentReminderSentStatus)     ->willReturnSelf() ; 

It will fail with the message: Trying to configure method setPaymentReminderSendStatus which cannot be configured because it does not exist, has not been specified, is final, or is static, which is true because the setters and getters are handled by \Magento\Framework\DataObject::__call magic method.

A colleague suggested mocking the payment object like below, but to me it feels a bit like hardcoding.

$  this->orderPaymentMockSend = $  this->getMockBuilder(Payment::class)     ->disableOriginalConstructor()     ->setMethods(['setPaymentReminderSendStatus'])     ->getMock() ; 

I’m also looking at maybe mocking the \Magento\Framework\DataObject object to be able to use the __call method (I don’t if this is even possible or if I’m overthinking it).

What would be the best practice in this case?

Statistical methods using PHP (mean, co/variance, standard deviation, skew, correlation)


Functionality

This class has a list of basic statistical functions such as mean, variance, standard deviation, skewness and so on and it works okay, running these functions over past 30 days equity charts.

It extends a mother class that estimates very close future prices of a list of equities using an API delayed 60-seconds chart data.

Would you be so kind and possibly review it for maybe performance, efficiency, math, or best coding practices?

Code

// Config class for path and other constants require_once __DIR__ . "/ConstEQ.php";  /**  * This is an extended class with basic statistical method  * Stock  */ class ST extends EQ implements ConstEQ {      /**      *      * @return a number equal to mean of values of an array      */     public static function getMean($  array)     {         if (count($  array) == 0) {             return ConstEQ::NEAR_ZERO_NUMBER;         } else {             return array_sum($  array) / count($  array);         }     }      /**      *      * @return a number normalized in between 0 to 1      */     public static function getNormalize($  value, $  min, $  max)     {         if ($  max - $  min != 0) {             $  normalized = 2 * (($  value - $  min) / ($  max - $  min)) - 1;         } else {             $  normalized = 2 * (($  value - $  min)) - 1;         }         return $  normalized;     }      /**      *      * @return a number normalized in between 0.0 to 1 from any input -inf to inf      */     public static function getSigmoid($  t)     {         return 1 / (1 + pow(M_EULER, -$  t));     }      /**      *      * @return a number equal to square of value mean      */     public static function getMeanSquare($  x, $  mean)     {return pow($  x - $  mean, 2);}      /**      *      * @return a number equal to standard deviation of values of an array      */     public static function getStandardDeviation($  array)     {         if (count($  array) < 2) {             return ConstEQ::NEAR_ZERO_NUMBER;         } else {             return sqrt(array_sum(array_map("ST::getMeanSquare", $  array, array_fill(0, count($  array), (array_sum($  array) / count($  array))))) / (count($  array) - 1));         }     }      /**      *      * @return a number equal to covariance of values of two arrays      */     public static function getCovariance($  valuesA, $  valuesB)     {         // sizing both arrays the same, if different sizes         $  no_keys = min(count($  valuesA), count($  valuesB));         $  valuesA = array_slice($  valuesA, 0, $  no_keys);         $  valuesB = array_slice($  valuesB, 0, $  no_keys);          // if size of arrays is too small         if ($  no_keys < 2) {return ConstEQ::NEAR_ZERO_NUMBER;}          // Use library function if available         if (function_exists('stats_covariance')) {return stats_covariance($  valuesA, $  valuesB);}          $  meanA = array_sum($  valuesA) / $  no_keys;         $  meanB = array_sum($  valuesB) / $  no_keys;         $  add = 0.0;          for ($  pos = 0; $  pos < $  no_keys; $  pos++) {             $  valueA = $  valuesA[$  pos];             if (!is_numeric($  valueA)) {                 trigger_error('Not numerical value in array A at position ' . $  pos . ', value=' . $  valueA, E_USER_WARNING);                 return false;             }              $  valueB = $  valuesB[$  pos];             if (!is_numeric($  valueB)) {                 trigger_error('Not numerical value in array B at position ' . $  pos . ', value=' . $  valueB, E_USER_WARNING);                 return false;             }              $  difA = $  valueA - $  meanA;             $  difB = $  valueB - $  meanB;             $  add += ($  difA * $  difB);         }          return $  add / $  no_keys;     }      /**      *      * @return a number equal to skewness of array values      */     public static function getSkewness($  values)     {         $  numValues = count($  values);         if ($  numValues == 0) {return 0.0;}          // Uses function from php_stats library if available         if (function_exists('stats_skew')) {return stats_skew($  values);}          $  mean = array_sum($  values) / floatval($  numValues);          $  add2 = 0.0;         $  add3 = 0.0;          foreach ($  values as $  value) {             if (!is_numeric($  value)) {return false;}              $  dif = $  value - $  mean;             $  add2 += ($  dif * $  dif);             $  add3 += ($  dif * $  dif * $  dif);          }          $  variance = $  add2 / floatval($  numValues);          if ($  variance == 0) {return ConstEQ::NEAR_ZERO_NUMBER;} else {return ($  add3 / floatval($  numValues)) / pow($  variance, 3 / 2.0);}     }      /**      *      * @return a number equal to kurtosis of array values      */     public static function getKurtosis($  values)     {         $  numValues = count($  values);         if ($  numValues == 0) {return 0.0;}          // Uses function from php_stats library if available         if (function_exists('stats_kurtosis')) {return stats_kurtosis($  values);}          $  mean = array_sum($  values) / floatval($  numValues);         $  add2 = 0.0;         $  add4 = 0.0;          foreach ($  values as $  value) {             if (!is_numeric($  value)) {return false;}             $  dif = $  value - $  mean;             $  dif2 = $  dif * $  dif;             $  add2 += $  dif2;             $  add4 += ($  dif2 * $  dif2);         }          $  variance = $  add2 / floatval($  numValues);         if ($  variance == 0) {return ConstEQ::NEAR_ZERO_NUMBER;} else {return ($  add4 * $  numValues) / ($  add2 * $  add2) - 3.0;}     }      /**      *      * @return a number equal to correlation of two arrays      */     public static function getCorrelation($  arr1, $  arr2)     {         $  correlation = 0;          $  k = ST::sumProductMeanDeviation($  arr1, $  arr2);         $  ssmd1 = ST::sumSquareMeanDeviation($  arr1);         $  ssmd2 = ST::sumSquareMeanDeviation($  arr2);          $  product = $  ssmd1 * $  ssmd2;          $  res = sqrt($  product);         if ($  res == 0) {return ConstEQ::NEAR_ZERO_NUMBER;}         $  correlation = $  k / $  res;          if ($  correlation == 0) {return ConstEQ::NEAR_ZERO_NUMBER;} else {return $  correlation;}     }      /**      *      * @return a number equal to sum of product mean deviation of each array values      */     public static function sumProductMeanDeviation($  arr1, $  arr2)     {         $  sum = 0;         $  num = count($  arr1);          for ($  i = 0; $  i < $  num; $  i++) {$  sum = $  sum + ST::productMeanDeviation($  arr1, $  arr2, $  i);}         return $  sum;     }      /**      *      * @return a number equal to product mean deviation of each array values      */     public static function productMeanDeviation($  arr1, $  arr2, $  item)     {return (ST::meanDeviation($  arr1, $  item) * ST::meanDeviation($  arr2, $  item));}      /**      *      * @return a number equal to sum of square mean deviation of each array values      */     public static function sumSquareMeanDeviation($  arr)     {         $  sum = 0;         $  num = count($  arr);          for ($  i = 0; $  i < $  num; $  i++) {$  sum = $  sum + ST::squareMeanDeviation($  arr, $  i);}         return $  sum;     }      /**      *      * @return a number equal to square mean deviation of each array values      */     public static function squareMeanDeviation($  arr, $  item)     {         return ST::meanDeviation($  arr, $  item) * ST::meanDeviation($  arr, $  item);     }      /**      *      * @return a number equal to sum of mean deviation of each array values      */     public static function sumMeanDeviation($  arr)     {         $  sum = 0;         $  num = count($  arr);          for ($  i = 0; $  i < $  num; $  i++) {$  sum = $  sum + ST::meanDeviation($  arr, $  i);}         return $  sum;     }      /**      *      * @return a number equal to mean deviation of each array values      */     public static function meanDeviation($  arr, $  item)     {         $  average = ST::average($  arr);return $  arr[$  item] - $  average;     }      /**      *      * @return a number equal to mean of array values      */     public static function average($  arr)     {         $  sum = ST::sum($  arr);         $  num = count($  arr);return $  sum / $  num;}      /**      *      * @return a number equal to sum of an array      */     public static function sum($  arr)     {return array_sum($  arr);}      /**      *      * @return an array of coefficients for 7 levels of volatilities      */     public static function getCoefParams($  overall_market_coeff)     {         $  daily_coef = 0.9 + ($  overall_market_coeff / 10);          $  coefs = array(             ConstEQ::LEVEL_VOLATILITY_COEF_1 * $  daily_coef,             ConstEQ::LEVEL_VOLATILITY_COEF_2 * $  daily_coef,             ConstEQ::LEVEL_VOLATILITY_COEF_3 * $  daily_coef,             ConstEQ::LEVEL_VOLATILITY_COEF_4 * $  daily_coef,             ConstEQ::LEVEL_VOLATILITY_COEF_5 * $  daily_coef,             ConstEQ::LEVEL_VOLATILITY_COEF_6 * $  daily_coef,             ConstEQ::LEVEL_VOLATILITY_COEF_7 * $  daily_coef,         );          return $  coefs;     }      /**      * @return a binary true or false for is_numeric testing of an string      */     public static function isNumber($  arr)     {         foreach ($  arr as $  b) {             if (!is_numeric($  b)) {                 return false;             }         }         return true;     }  } 

Should an abstract class implement an interface, as opposed to defining its own abstract methods?

I’m defining a class structure for persisting to our cassandra database, and I’m unsure about using a combination of an abstract class and an interface. I have two concrete classes, one for persisting reports and the other for persisting configurations. They both have separate entity classes defined else where that the entityMapper uses. I have read this post which is very similar, but I don’t think their example really highlights what I want to know.

My structure looks like this:

Interface

public interface CassandraRepository<T> {      void save(T object);      void delete(T object); } 

Abstract class

import com.datastax.driver.core.Session; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.MappingManager;  abstract class AbstractGenericRepository<T> implements CassandraRepository<T> {      private final Session sesion;     Mapper<T> entityMapper;      AbstractGenericRepository(final Session session) {         this.session = session;         final MappingManager manager = new MappingManager(this.session);         this.entityMapper = manager.mapper(getRepositoryClass());     }      protected abstract Class<T> getRepositoryClass(); } 

Configuration class

import com.model.Configuration; import com.datastax.driver.core.Session;  public class ConfigurationRepository extends AbstractGenericRepository<Configuration> {      public ConfigurationRepository(final Session session) {         super(session);     }      @Override     public void delete(final Configuration object) {         this.entityMapper.delete(object);     }      @Override     public void save(final Configuration object) {         this.entityMapper.save(object);     }      @Override     protected Class<Configuration> getRepositoryClass() {         return Configuration.class;     } } 

Report class

import com.model.Report; import com.datastax.driver.core.Session;  public class ReportRepository  extends AbstractGenericRepository<Report> {      ReportRepository(Session session) {         super(session);     }      @Override     public void save(Report object) {         this.entityMapper.save(object);     }      @Override     public void delete(Report object) {         this.entityMapper.delete(object);     }      @Override     protected Class<Report> getRepositoryClass() {         return Report.class;     } } 

My question is: is there a point of having the interface at all? Could I simply define both the save and delete methods as abstract methods in the abstract class itself, and eliminate the interface.

I’ve also realised while typing this up that I could just move both the save and delete implementations into the abstract itself since they do the same thing. But in a case where they each implemented the methods differnetly, is there any benefit to having the interface at all?

Why could I not always use an abstract class over an interface, since it allows you to provide abstract methods that must be implemented in subclasses (like an interface), but then also allows you to defining common code implementations between them (which interfaces do not allow)?

EDIT

In response to the post being tagged as a possible duplicate, the other post doesn’t really clarify anything for me, specifically in the case of if an abstract class should implement an interface, and the pros/cons of doing so

What are some secure methods to share pre-created password? [duplicate]

This question already has an answer here:

  • Sending passwords to someone remotely 12 answers

I am working on something that requires me to create and share AAD(Azure Active Directory) credentials with clients. To give some context, Azure automatically creates a secret and then that secret has to be used to authenticate against the client id. As such, it is not possible for users to create their own secret.

What are the possible secure methods by which I can do this?

Can’t log in to remote unix machine: No supported authentication methods available (server sent: publickey)

I’m trying to connect to my university’s linux machines to do an assignment, but as of today I get this error when trying to login using Putty/WinSCP (no matter what login i use):

No supported authentication methods available (server sent: publickey)

It worked yesterday and the machines are online. What does this error mean and how can I fix it? Most of the questions I’ve seen regarding this error come from people making servers, so their fixes havent really helped me/confused me. I’m not experienced with this kind of stuff at all

generate/generatetoaddress what are this two rpc methods used for?

can anyone explain what are this rpc methods used for:
1.generate
https://bitcoincore.org/en/doc/0.16.3/rpc/generating/generate/
from the introduction of generate mehod:

Mine up to nblocks blocks immediately

but how? bitcoin is hard to mine, how can this method mine nblocks immediately?

generate nblocks ( maxtries )  Mine up to nblocks blocks immediately (before the RPC call returns) to an address in the wallet.  Arguments: 1. nblocks      (numeric, required) How many blocks are generated immediately. 2. maxtries     (numeric, optional) How many iterations to try (default = 1000000).  Result: [ blockhashes ]     (array) hashes of blocks generated  Examples:  Generate 11 blocks > bitcoin-cli generate 11 

2.generatetoaddress
https://bitcoincore.org/en/doc/0.16.3/rpc/generating/generatetoaddress/

the same question as generate method

generatetoaddress nblocks address (maxtries)  Mine blocks immediately to a specified address (before the RPC call returns)  Arguments: 1. nblocks      (numeric, required) How many blocks are generated immediately. 2. address      (string, required) The address to send the newly generated bitcoin to. 3. maxtries     (numeric, optional) How many iterations to try (default = 1000000).  Result: [ blockhashes ]     (array) hashes of blocks generated  Examples:  Generate 11 blocks to myaddress > bitcoin-cli generatetoaddress 11 "myaddress"