Wednesday, 27 April 2022

Build Dynamic Marshal_With in Flask (Python) based on conditions

To create a dynamic marshalling based on condition or parameter type, please follow the instruction below:

# Constants
MARSHELL_WITH_SCHEMAS = {
    "condition_1": Condition1Schema,
    "condition_2": Condition2Schema,
}


# To build dynamic marshalling based on report type
def selective_marshal_with():
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            condition_type = kwargs.get("condition_type", None)

            # Get marshalled with dynamic schema by condition type
            marshal_with_func = marshal_with(MARSHELL_WITH_SCHEMAS.get(condition_type, None))(func)

            return marshal_with_func(*args, **kwargs)

        return wrapper

    return decorator

# Actual class to connect view to URL
class MyViewClass(MethodResource, Resource):
    @doc(description="My View API", tags=["My View List"])
    @use_kwargs(MyQueryParams, location="query")
    @selective_marshal_with()
    @standard_api("My View List")
    def get(self, **kwargs):
        # you get code here....
    
The MyQueryParams can/should be in seperate schema file for e.g. rest/db/schema/my_view_schema.py

class MyQueryParams(Schema):
    """Query parameters for View List API."""

    condition_type = fields.Str(attribute="condition_type", required=True)

Hope it helps!

Friday, 5 March 2021

Count number of PDF file pages in PHP

Below function returns the number of pages count in PHP
function getPageCount(StreamInterface $stream): int
{
        $result = 0;

        $stream->rewind();

        while (! $stream->eof()) {
            $chunk = $stream->read(4096);

            //  looking for root node PDF 1.7+
            $found = \preg_match('/\/Type\s*?\/Pages(?:(?!\/Parent).)*\/Count\s?(?\d+)/', $chunk, $matches);

            if (0 < $found) {
                return (int) $matches['value'];
            }

            //  looking for root node PDF < 1.7
            $found = \preg_match('/\/Count\s?(?\d+)\s?\/Type\s*?\/Pages/', $chunk, $matches);

            if (0 < $found) {
                return (int) $matches['value'];
            }
            
            //  looking for root node PDF 1.7
            // Both regex1 & regex2 should work, but $regex2 is preferred.
            $regex1 = '/(?<=\/Type\s\/Pages\s(.*)\/Count\s)\d*/gs';
            $regex2 = '/\/Type\s*?\/Pages\s.*\/Count\s?(?\d+)/s';
            $found = \preg_match($regex2, $chunk, $matches);
            
            if (0 < $found) {
                return (int) $matches['value'];
            }

            //  looking for /Type/Page
            $found = \preg_match_all('/\/Type\s*?\/Page\s+/', $chunk, $matches);

            if (0 < $found) {
                $result += $found;
            }
        }

        $stream->rewind();

        return $result;
}

Thursday, 3 September 2020

PHP Regex function to extract text between tags for a synopsis or intro text

The following method prepare the synopsis from the body and the second part is for unit tests:

Hope it helps!

Saturday, 11 April 2020

Fix for ng serve --watch is not watching for code changes in Ubuntu

I was running the Angular 8 application on Ubuntu LTS 18.04 on my machine and was having an issue to refresh on code update using  --watch.

Trying to use ng serve and ng build --watch was not watching for code changes and I thought it was something to do with node or angular-cli.
However, I found the solution on Github (https://github.com/angular/angular-cli/issues/8313)
I ran the following on Terminal and apparently, it worked and watching code changes:
echo fs.inotify.max_user_watches=524288 | sudo tee /etc/sysctl.d/40-max-user-watches.conf && sudo sysctl --system

Hope this helps!

Tuesday, 29 October 2019

Angular 7 & Jest & Babel Integration over Jasmine/Karma - AngularSnapshotSerializer.js in the snapshotSerializers option was not found

Steps to integrate of Jest & Babel with Angular 7+:

1. Run the following commands to install:
    # Remove Jesmin/Karma
    npm remove karma karma-chrome-launcher karma-coverage-istanbul-reporter karma-jasmine karma-jasmine-html-reporter
    
    npm uninstall jasmine @types/jasmine
    
    rm ./karma.conf.js ./src/test.ts

    # Install jest    
    npm install --save jest@24.9 @angular-builders/jest@7 @types/jest@24 jest-preset-angular@8 

    # Install babel
    npm install --save-dev babel-jest babel-polyfill
    npm install --save @babel/core @babel/preset-env @babel/preset-flow @babel/preset-typescript    
 

2. On `package.json`, added the following code:
    "scripts": {
      ...
      ...
      "test": "ng test",
      "test:watch": "jest --watch",
      ...
      ...
    }
    ...
    ...   
    "jest": {
      "preset": "jest-preset-angular",
      "setupFilesAfterEnv": [
        "/setupJest.ts"
      ]
    }
 

3. Also, updated the following on the `angular.json`:
    ...
    ... 
    "test": {
       "builder": "@angular-devkit/build-angular:karma",
    ...
    ...
 

Replace with:
    ...
    ... 
    "test": {
       "builder": "@angular-builders/jest:run",
    ...
    ...
 

4. Create the `/setupJest.ts` with below content:
    import 'jest-preset-angular';   
 

5. Create the `/babel.config.js` with below content:
    module.exports = function(api) {

        const presets = [
            '@babel/preset-typescript',
             [
                "@babel/preset-env", {
                    "targets": {
                        "node": "current"
                    }
                }
            ],
            '@babel/preset-flow'
        ];

        return {
            presets,
        };
    };
 


6. And, finally tried running the `ng-test` from a terminal, however, I was stuck with the following error (see picture below):
7. Eventually, managed to fix the issue by adding the file `/src/jest.config.js` with below content:
    module.exports = {
        "transform": {
            "^.+\\.(ts|js|html)$": "ts-jest",
            "^.+\\.[t|j]sx?$": "babel-jest"
        },
        moduleFileExtensions: ['ts', 'html', 'js', 'json'],
        moduleNameMapper: {
            '^src/(.*)$': '/src/$1',
            '^app/(.*)$': '/src/app/$1',
            '^assets/(.*)$': '/src/assets/$1',
            '^environments/(.*)$': '/src/environments/$1',
        },
        transformIgnorePatterns: ['node_modules/(?!@ngrx)'],
        snapshotSerializers: [
            'jest-preset-angular/build/AngularSnapshotSerializer.js',
            'jest-preset-angular/build/HTMLCommentSerializer.js',
        ],
    };
Thereafter, ran `ng test` again and can see the test running thru. I hope it helps!

Friday, 11 October 2019

Construct the dynamic table with specified number of columns on each row as per the size of the data in Angular

The below code is to generate a table with multiple rows with the specified number of columns on each row as per the size of the data array.

Then, on the output, we would be able to generate a table with multiple rows with a specified number of columns.

Monday, 7 October 2019

Check if MySQL Query uses cache or not for most frequent query.


Run the following queries to check if most recent MySQL query uses cache or not.

-- Query 1
SHOW VARIABLES LIKE 'have_query_cache'; 

-- The Output Value should be Yes, if it uses cache.

-- Query 2
SHOW VARIABLES LIKE 'query_cache_size';
-- -- The Output Value should be integer value, if it uses cache.



Refer Link 1 and Link 2 for more detail.

Hope the help!