mardi 2 juillet 2019

Pytest, using fixtures as instances of class in prolog method setup_method

I've started using unitest infrastructure that based on pytest for adding additional test class (see below TestMyStuff)

It seems that if I add the fixtures xi and yi as inputs of method setup_method it refer to them as functions from fixtures.py, but adding them to each of the test functions, they get their return value of classX and classY respectively rather then the function value.

Both test methods share identical code block which require xi and yi, and also an additional per-test unique code. I wish to take the common code and add it to test_method but for that I need that xi and yi as instances of classX and classY which the fixtures method returns, and not the methods themselves from fixtures.py

In brief, is there any way to share some pre-built fixtures between all class functions (both the test methods and the prolog method) ?

test_xy.py

from fixtures import *

class TestMyStuff
    def setup_method(self, test_method, xi, yi):
        # here xi and yi are functions :-(
        self.x = classX.makeX()
        self.y = classY.makeY()


    def test_X(self, xi, yi):
        # here xi and yi are instances of classX and classY
        # do shared stuff with xi and yi
        # do unique stuff with xi and yi

    def test_Y(self, xi,yi):
        # here xi and yi are instances of classX and classY
        # do shared stuff with xi and yi
        # do other stuff with xi and yi

fixtures.py

from classY import classY
from classX import classX


@pytest.fixture()
def xi(request):
    ...
    return classX(request.var1, request.var2, request.var3)
    #classX is implemented on different file called classX.py

@pytest.fixture()
def yi(request, xi)
    ...
    return classY(request.var1, xi) 

lundi 1 juillet 2019

How to move files found with pattern and move to another subdirectory in unix

I have this:

.
├── dirA
│   └── ProdA
│       ├── Brief
│       │   └── Form.xlsx
│       ├── Results
│       └── Studies
└── dirB
    └── BrandB
        └── ProdB
            ├── Brief
            │   └── Form.xlsx
            └── Results

and i want this:

.
├── dirA
│   └── ProdA
│       ├── Brief
│       ├── Results
│       └── Studies
│           └── Form.xlsx
└── dirB
    └── BrandB
        └── ProdB
            ├── Brief
            └── Results
            └── Studies  
                └── Form.xslx         

So basically i have to find files Form.xlsx and move it from subdirectory Brief to subdirectory Studies (create it if it does not exists), both at the same level.

when i do:

find . -name '*.xlsx' -exec mv '{}' ../Studies ';'

I got:

.
├── dirA
│   └── ProdA
│       ├── Brief
│       ├── Results
│       └── Studies
└── dirB
    └── BrandB
        └── ProdB
            ├── Brief
            └── Results

What's the purpose of making the class which instantiates all other classes and subsystems

After looking at many open source projects i have noticed that many of them use the same idea for initialization and deinitialization of the whole system. Many of them have one specific class (likely it's a singletone) which loads resources, instantiates all other classes, subsystems, connects them to each other and prepares the objects structure which is used during run-time. Why not to do that in main()? Which idea is behind this approach, is that some high-level programming pattern which has a lot of advantages?

Conditional pattern on input text in angularjs

I need to validate input type only in some cases with regex pattern. But when that fields is hidden , whole form isn't valid so I can't proceed. Is there a way that I can make pattern conditional

<input type="text" class="form-control" name="FileName" id="FileName" ng-model="FileName" ng-required="fileModalMode=='Rename' || fileModalMode=='Create'" pattern="^(\w+\.?)*\w+$">

So something like

<input type="text" class="form-control" name="FileName" id="FileName" ng-model="FileName" ng-required="fileModalMode=='Rename' || fileModalMode=='Create'" ng-pattern="fileModalMode=='Rename' || fileModalMode=='Create' ? '^(\w+\.?)*\w+$'">

What is the best to write common code to call

I'm calling alerts, view's colours, spinners and components properties from Shared class. Is it ok. What is the best way to write common code.

Ex: My shared class code is...

import UIKit

class SharedClass: NSObject {

static let sharedInstance = SharedClass()

    var spinner = UIActivityIndicatorView()

//Show activity indicator
func activityIndicator() {

    DispatchQueue.main.async {
        if let window = UIApplication.shared.keyWindow {//Conditionally unwrap it instead of force unwrap

  //                let window = UIApplication.shared.keyWindow! //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
            self.transparentView = UIView()
            self.transparentView?.frame = CGRect(x: 0, y: 0, width: window.frame.width, height: window.frame.height)
            self.transparentView?.backgroundColor = UIColor.black.withAlphaComponent(0.4)
            window.addSubview(self.transparentView!)

            if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
                //                    self.spinner = UIActivityIndicatorView(style: .whiteLarge)
                self.spinner = UIActivityIndicatorView(style: .whiteLarge)
                self.spinner.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
            } else {
                //                    self.spinner = UIActivityIndicatorView(style: .white)
                self.spinner = UIActivityIndicatorView(style: .white)
                self.spinner.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
            }
            self.spinner.center = window.center
            self.transparentView?.addSubview(self.spinner)
            self.spinner.startAnimating()

            DispatchQueue.main.asyncAfter(deadline: .now() + 40.0) {//Stop spinner after 40 Sec's
                self.stopActivityIndicator()
            }
        }
    }
}

//Stop activity indicator
func stopActivityIndicator() {
    DispatchQueue.main.async {
        self.spinner.stopAnimating()
        self.spinner.removeFromSuperview()
        self.transparentView?.removeFromSuperview()//Some times getting error here
    }
}

 //Email validation
func isValidEmail(email: String) -> Bool {
    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
    var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)
    if valid {
        valid = !email.contains("Invalid email id")
    }
    return valid
}

//Mobile number validation
func isValidPhone(phone: String) -> Bool {
    let phoneRegex = "^((0091)|(\\+91)|0?)[6789]{1}\\d{9}$"; // @"^((0091)|(\\+91)|0?)[6789]{1}\\d{9}$"        "^[0-9]{6,14}$"
    let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phone)
    return valid
}

 private override init() {

}

}

//Alert function
extension UIViewController {
    func showAlert(title: String, msg: String) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
}

//Set TF shadow in login VC
extension UITextField {
    func TFProperties() {
        layer.shadowColor = UIColor(red: 199/255, green: 217/255, blue: 223/255, alpha: 1.0).cgColor
        layer.shadowOpacity = 1
        layer.shadowOffset = CGSize.zero
        layer.shadowRadius = 5
        layer.borderColor = UIColor(red: 199/255, green: 217/255, blue: 223/255, alpha: 1.0).cgColor
        layer.borderWidth = 1
        layer.cornerRadius = 4
    }
}

//Set View shadow in OTPVerify VC
extension UIView {
func subViewShadow() {
    layer.shadowColor = UIColor.white.cgColor
    layer.shadowOpacity = 1
    layer.shadowOffset = CGSize.zero
    layer.shadowRadius = 3
    layer.borderColor = UIColor.gray.cgColor
    layer.borderWidth = 1
    layer.cornerRadius = 4
}
func viewShadow() {
    layer.shadowColor = UIColor.gray.cgColor
    layer.shadowOpacity = 1
    layer.shadowOffset = CGSize.zero
    layer.shadowRadius = 3
}
func collectionViewCellBorder() {
    layer.cornerRadius = 5
    layer.borderColor = UIColor UIColor.gray.cgColor
    layer.borderWidth = 1.0
}
}

Wich Patterns are good to used with a Graph SGBD in Express?

Hello I am developping a REST API and I chose to use Angular in Front-end, Express in Back-end, and Neo4J in DBMS.

I want to know which pattern would be the best to implement the back-end... I know the Repository pattern, but I don't think it is appropriate with an Graph DBMS.

Could you please tell me which pattern would you use and why ? Thank's

C++ Good-Practice of Classes Designs

I made a small software, for image processing, that does some small and basics edits. I wrote this code in C++, by not checking any good practice of C++ Designs. At the beginning, my point was just made some code work. Those are the classes with methods and attributes:

MasterPH.h

class MasterPH
{
public:
    cv::Mat img;
    cv::Mat tmp;
    cv::Mat original;

    cv::Mat hist_Mat_r;
    cv::Mat hist_Mat_g;
    cv::Mat hist_Mat_b;

    int exposure_val = 0;
    int red_val = 0;
    int green_val = 0;
    int blue_val = 0;
    double contrast_val = 0;

    int hue = 0;
    int luminance = 0;
    int saturation = 0;
};

imgprocessing.h

class ImgProcessing
{
public:
    ImgProcessing();

    void processMaster(cv::Mat& img, cv::Mat& tmp, int brightness, int red, int green, int blue, double contrast);
    void processHLS(cv::Mat& img, cv::Mat& tmp, int hue, int luminance, int saturation);
    void black_n_white(cv::Mat& img, cv::Mat& tmp);
    void sepia(cv::Mat& img, cv::Mat& tmp);
};

ImgHandling.h

class ImgHandling
{
public:
    ImgHandling();

    void imgLoad(cv::Mat& img, cv::Mat& tmp, cv::Mat& original, QString& path);
    void imgSave(QString& path, cv::Mat& img);

    void calculateHist(cv::Mat& img, cv::Mat& hist_Mat, int color);
};

imgdistortions.h

class ImgDistortions
{
public:
    ImgDistortions();


    void rotate(cv::Mat& img, cv::Mat& tmp, int angle);
    void flipH(cv::Mat& img, cv::Mat& tmp);
    void flipV(cv::Mat& img, cv::Mat& tmp);
};

imgconvolution.h

class ImgConvolution
{
public:
    ImgConvolution();

    void applyKernel(); // To implement still
};

Plus a class containing all the buttons & sliders, that just call these functions.

So now I need some advice on how I can step from this kind of Procedural-Code, to a more Object Oriented one, via using all the possible Good Practice design of C ++.

I'm new to C++, so I'm still learning on how I can apply polymorphism etc...