Hunter  Krajcik

Hunter Krajcik

1653223680

Xcontext: Predictable Static Extension Methods on BuildContext

xcontext

This simple package adds static extension methods and getters to the BuildContext context object from the widgets, material, and cupertino libraries.

xcontext makes it easy for you to add static extensions methods and getters to your context from Flutter's widgets, material, and cupertino libraries. You have total control over which methods and getters you want to add to your context, with all the type safety guarantees Dart provides, while keeping your code concise and clean.

Important links

About this package

This package is an experiment to get rid of the SomeClass.of(context).someMethod calls in a codebase. The package also simplifies other function calls that require the context to be passed in.

Using the package will hopefully make your code easier to type, read and understand.

I wrote the package in a way that is easy to customize to your needs and selectively add or hide extensions.

If you like the .of static methods, please feel free to continue using it!

Usage

// Add all methods and getters to BuildContext
import 'package:xcontext/xcontext.dart';

BuildContext context;
// then...
context.navigator.pushNamed('/other');
context.scaffold;
context.mediaQuery.platformBrightness;
context.theme;
context.dividerTheme;
context.cupertinoLocalizations;
context.cupertinoTheme;
context.showCupertinoDialog(builder: b, useRootNavigator: true); // Don't forget to define the builder.
context.showTimePicker(initialTime: TimeOfDay.now());

If you prefer to be even more concise, use the "tiny" version:

// tiny_xcontext uses shorter names and does not add all getters
import 'package:xcontext/tiny_xcontext.dart';

BuildContext context;
// then...
context.nav.pushNamed('/other');
context.scaf;
context.mq.platformBrightness;
context.theme; // Not all getters are shortened. Theme is short enough already
// context.dividerTheme; // Not all getters are available in "tiny" mode
context.cupL10n;
context.cuptheme;
context.showCupDialog(builder: builder, useRootNavigator: true); // Don't forget to define the builder.
context.showTP(initialTime: TimeOfDay.now());

The libraries of this package

// Add all methods and getters to BuildContext
import 'package:xcontext/xcontext.dart';

// Alternatively, if you want to extend only from some libraries:
import 'package:xcontext/cupertino.dart';
import 'package:xcontext/material.dart';
import 'package:xcontext/widgets.dart';

// Add some methods and getters to BuildContext, some are shortened
import 'package:xcontext/tiny_xcontext.dart';

// Alternatively, if you want to extend only from some libraries with the short version
import 'package:xcontext/tiny_cupertino.dart';
import 'package:xcontext/tiny_material.dart';
import 'package:xcontext/tiny_widgets.dart';

See all libraries: xcontext, cupertino, material, widgets, tiny_xcontext, tiny_cupertino, tiny_material, tiny_widgets

From Navigator.of(context) to context.navigator

The xcontext package lets you access Something.of(context).someMethod directly on the context as context.something.someMethod. It adds all the .of static methods from the official widgets, material, and cupertino libraries' return value as getters.

So after you imported 'package:xcontext/xcontext.dart', you will be able to write:

import 'package:xcontext/xcontext.dart';

class Example extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Instead of Theme.of(context), just write: 
    final theme = context.theme;
    // ...and use the theme as usual:
    print('Current brightness is ${theme.brightness}');
    return RaisedButton(
      onPressed: () {
        // Instead of Navigator.of(context), use context.navigator
        context.navigator.pushNamed('/other');
      },
      child: Text('Navigator push'),
    );
  }
}

In case the .of static method accepts extra parameters, those values are exposed in a different getter, such as:

// Navigator.of(context, rootNavigator: true)
context.rootNavigator;
// Theme.of(this, shadowThemeOnly: true);
context.shadowTheme;

Show this, show that!

All showXYZ (date and time pickers, modal bottom sheet, about dialog) methods are added, as well, so now you can write:

import 'package:xcontext/xcontext.dart';

context.showAboutDialog(
  applicationName: 'xcontext example app',
  applicationIcon: FlutterLogo(),
  applicationLegalese: 'Copyright 2020',
  applicationVersion: '1.2.3',
  children: [
    Text('Thank you for using this package!'),
    Text('❤️'),
  ],
);

hide/show

While the extensions might improve the discoverability, seeing tens of extra methods popping up in your IDE whenever you type "context." can be annoying. For this reason, every getter and method is added as a separate extension, so you can hide or show them as you like.

/*** hide ***/
// If one or more extensions annoy you, hide them.
import 'package:xcontext/material.dart' hide XContextNavigationRailTheme;

/*** show ***/
// If you only need some extensions, show them, and hide all others.
// Only show context.navigator and context.rootNavigator
import 'package:xcontext/widgets.dart' show XContextNavigator, XContextRootNavigator;

export only what you need

You might conclude that, while using some extensions from the package is great, the other extensions are less great, so you want see only a subset of the extensions everywhere.

Just create a new your_favorite_extensions.dart file , export the extensions you like, and import this file in the rest of your codebase to stay consistent.

// your_favorite_extensions.dart
export 'package:xcontext/xcontext.dart'
    show XContextShowGeneralDialog,  // context.showGeneralDialog
         XContextNavigator, // context.navigator
         XContextRootNavigator, // context.rootNavigator
         XContextScaffold,  // context.scaffold
         XContextMediaQuery; // context.mediaQuery

// You may even write your own context extensions here.
// Some other file...
import 'package:your_awesome_app/your_favorite_extensions.dart';

The tiny variation

This package also has a tiny variation of the extensions. The tiny version is great is you prefer brevity. 'package:xcontext/tiny_xcontext.dart' does not include all the possible getters and methods, and some getters were renamed so that you can write less code while keeping everything straightforward:

import 'package:xcontext/tiny_xcontext.dart';

// then...
context.nav.pop();
final isLight = context.mq.platformBrightness == Brightness.light;

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add xcontext

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  xcontext: ^1.0.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:xcontext/xcontext.dart';

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:xcontext/xcontext.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('xcontext'),
        ),
        body: Example(),
      ),
    );
  }
}

class Example extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final TextDirection textDirection = context.textDirection;
    print('Text direction: $textDirection}');
    return Wrap(
      children: [
        for (final button in [
          ElevatedButton(
            onPressed: () {
              context.showDatePicker(
                initialDate: DateTime.now(),
                firstDate: DateTime.now(),
                lastDate: DateTime.now().add(Duration(days: 7)),
              );
            },
            child: Text('Date picker'),
          ),
          ElevatedButton(
            onPressed: () {
              context.navigator
                  .push(MaterialPageRoute(builder: (_) => ExampleRoute()));
            },
            child: Text('Navigator push'),
          ),
          ElevatedButton(
            onPressed: () {
              context.showModalBottomSheet(
                builder: (_) => BottomSheet(
                  builder: (_) => Padding(
                    padding: const EdgeInsets.all(28.0),
                    child: Popper(),
                  ),
                  onClosing: () {},
                ),
              );
            },
            child: Text('Show Modal Bottom Sheet'),
          ),
          ElevatedButton(
            onPressed: () {
              final time = context.showTimePicker(initialTime: TimeOfDay.now());
              print('selected time is $time');
            },
            child: Text('Show Time Picker'),
          ),
          ElevatedButton(
            onPressed: () {
              context.showAboutDialog(
                applicationName: 'xcontext example app',
                applicationIcon: FlutterLogo(),
                applicationLegalese: 'Copyright 2020',
                applicationVersion: '1.2.3',
                children: [
                  Text('Thank you for using this package!'),
                  Text('❤️'),
                ],
              );
            },
            child: Text('Show About Dialog'),
          ),
        ])
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            child: button,
          )
      ],
    );
  }
}

class ExampleRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Popper(),
      ),
    );
  }
}

class Popper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        context.navigator.pop();
      },
      child: Text('pop!'),
    );
  }
}

Author: Dartsidedev
Source Code: https://github.com/dartsidedev/xcontext 
License: BSD-3-Clause license

#dart #flutter #extensions 

What is GEEK

Buddha Community

Xcontext: Predictable Static Extension Methods on BuildContext
Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Hunter  Krajcik

Hunter Krajcik

1653223680

Xcontext: Predictable Static Extension Methods on BuildContext

xcontext

This simple package adds static extension methods and getters to the BuildContext context object from the widgets, material, and cupertino libraries.

xcontext makes it easy for you to add static extensions methods and getters to your context from Flutter's widgets, material, and cupertino libraries. You have total control over which methods and getters you want to add to your context, with all the type safety guarantees Dart provides, while keeping your code concise and clean.

Important links

About this package

This package is an experiment to get rid of the SomeClass.of(context).someMethod calls in a codebase. The package also simplifies other function calls that require the context to be passed in.

Using the package will hopefully make your code easier to type, read and understand.

I wrote the package in a way that is easy to customize to your needs and selectively add or hide extensions.

If you like the .of static methods, please feel free to continue using it!

Usage

// Add all methods and getters to BuildContext
import 'package:xcontext/xcontext.dart';

BuildContext context;
// then...
context.navigator.pushNamed('/other');
context.scaffold;
context.mediaQuery.platformBrightness;
context.theme;
context.dividerTheme;
context.cupertinoLocalizations;
context.cupertinoTheme;
context.showCupertinoDialog(builder: b, useRootNavigator: true); // Don't forget to define the builder.
context.showTimePicker(initialTime: TimeOfDay.now());

If you prefer to be even more concise, use the "tiny" version:

// tiny_xcontext uses shorter names and does not add all getters
import 'package:xcontext/tiny_xcontext.dart';

BuildContext context;
// then...
context.nav.pushNamed('/other');
context.scaf;
context.mq.platformBrightness;
context.theme; // Not all getters are shortened. Theme is short enough already
// context.dividerTheme; // Not all getters are available in "tiny" mode
context.cupL10n;
context.cuptheme;
context.showCupDialog(builder: builder, useRootNavigator: true); // Don't forget to define the builder.
context.showTP(initialTime: TimeOfDay.now());

The libraries of this package

// Add all methods and getters to BuildContext
import 'package:xcontext/xcontext.dart';

// Alternatively, if you want to extend only from some libraries:
import 'package:xcontext/cupertino.dart';
import 'package:xcontext/material.dart';
import 'package:xcontext/widgets.dart';

// Add some methods and getters to BuildContext, some are shortened
import 'package:xcontext/tiny_xcontext.dart';

// Alternatively, if you want to extend only from some libraries with the short version
import 'package:xcontext/tiny_cupertino.dart';
import 'package:xcontext/tiny_material.dart';
import 'package:xcontext/tiny_widgets.dart';

See all libraries: xcontext, cupertino, material, widgets, tiny_xcontext, tiny_cupertino, tiny_material, tiny_widgets

From Navigator.of(context) to context.navigator

The xcontext package lets you access Something.of(context).someMethod directly on the context as context.something.someMethod. It adds all the .of static methods from the official widgets, material, and cupertino libraries' return value as getters.

So after you imported 'package:xcontext/xcontext.dart', you will be able to write:

import 'package:xcontext/xcontext.dart';

class Example extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Instead of Theme.of(context), just write: 
    final theme = context.theme;
    // ...and use the theme as usual:
    print('Current brightness is ${theme.brightness}');
    return RaisedButton(
      onPressed: () {
        // Instead of Navigator.of(context), use context.navigator
        context.navigator.pushNamed('/other');
      },
      child: Text('Navigator push'),
    );
  }
}

In case the .of static method accepts extra parameters, those values are exposed in a different getter, such as:

// Navigator.of(context, rootNavigator: true)
context.rootNavigator;
// Theme.of(this, shadowThemeOnly: true);
context.shadowTheme;

Show this, show that!

All showXYZ (date and time pickers, modal bottom sheet, about dialog) methods are added, as well, so now you can write:

import 'package:xcontext/xcontext.dart';

context.showAboutDialog(
  applicationName: 'xcontext example app',
  applicationIcon: FlutterLogo(),
  applicationLegalese: 'Copyright 2020',
  applicationVersion: '1.2.3',
  children: [
    Text('Thank you for using this package!'),
    Text('❤️'),
  ],
);

hide/show

While the extensions might improve the discoverability, seeing tens of extra methods popping up in your IDE whenever you type "context." can be annoying. For this reason, every getter and method is added as a separate extension, so you can hide or show them as you like.

/*** hide ***/
// If one or more extensions annoy you, hide them.
import 'package:xcontext/material.dart' hide XContextNavigationRailTheme;

/*** show ***/
// If you only need some extensions, show them, and hide all others.
// Only show context.navigator and context.rootNavigator
import 'package:xcontext/widgets.dart' show XContextNavigator, XContextRootNavigator;

export only what you need

You might conclude that, while using some extensions from the package is great, the other extensions are less great, so you want see only a subset of the extensions everywhere.

Just create a new your_favorite_extensions.dart file , export the extensions you like, and import this file in the rest of your codebase to stay consistent.

// your_favorite_extensions.dart
export 'package:xcontext/xcontext.dart'
    show XContextShowGeneralDialog,  // context.showGeneralDialog
         XContextNavigator, // context.navigator
         XContextRootNavigator, // context.rootNavigator
         XContextScaffold,  // context.scaffold
         XContextMediaQuery; // context.mediaQuery

// You may even write your own context extensions here.
// Some other file...
import 'package:your_awesome_app/your_favorite_extensions.dart';

The tiny variation

This package also has a tiny variation of the extensions. The tiny version is great is you prefer brevity. 'package:xcontext/tiny_xcontext.dart' does not include all the possible getters and methods, and some getters were renamed so that you can write less code while keeping everything straightforward:

import 'package:xcontext/tiny_xcontext.dart';

// then...
context.nav.pop();
final isLight = context.mq.platformBrightness == Brightness.light;

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add xcontext

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  xcontext: ^1.0.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:xcontext/xcontext.dart';

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:xcontext/xcontext.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('xcontext'),
        ),
        body: Example(),
      ),
    );
  }
}

class Example extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final TextDirection textDirection = context.textDirection;
    print('Text direction: $textDirection}');
    return Wrap(
      children: [
        for (final button in [
          ElevatedButton(
            onPressed: () {
              context.showDatePicker(
                initialDate: DateTime.now(),
                firstDate: DateTime.now(),
                lastDate: DateTime.now().add(Duration(days: 7)),
              );
            },
            child: Text('Date picker'),
          ),
          ElevatedButton(
            onPressed: () {
              context.navigator
                  .push(MaterialPageRoute(builder: (_) => ExampleRoute()));
            },
            child: Text('Navigator push'),
          ),
          ElevatedButton(
            onPressed: () {
              context.showModalBottomSheet(
                builder: (_) => BottomSheet(
                  builder: (_) => Padding(
                    padding: const EdgeInsets.all(28.0),
                    child: Popper(),
                  ),
                  onClosing: () {},
                ),
              );
            },
            child: Text('Show Modal Bottom Sheet'),
          ),
          ElevatedButton(
            onPressed: () {
              final time = context.showTimePicker(initialTime: TimeOfDay.now());
              print('selected time is $time');
            },
            child: Text('Show Time Picker'),
          ),
          ElevatedButton(
            onPressed: () {
              context.showAboutDialog(
                applicationName: 'xcontext example app',
                applicationIcon: FlutterLogo(),
                applicationLegalese: 'Copyright 2020',
                applicationVersion: '1.2.3',
                children: [
                  Text('Thank you for using this package!'),
                  Text('❤️'),
                ],
              );
            },
            child: Text('Show About Dialog'),
          ),
        ])
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            child: button,
          )
      ],
    );
  }
}

class ExampleRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Popper(),
      ),
    );
  }
}

class Popper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        context.navigator.pop();
      },
      child: Text('pop!'),
    );
  }
}

Author: Dartsidedev
Source Code: https://github.com/dartsidedev/xcontext 
License: BSD-3-Clause license

#dart #flutter #extensions 

Joseph  Murray

Joseph Murray

1621537320

What is a Static Method & Static Keyword in Java?

Introduction

Java is also considered as an extended version of c++, and java has removed a few of the new features and added a few unique features. We don’t need to do any work for clearing space for unreferenced objects because garbage collector in java does the hard work for you.

Java also has few cool features like platform independence, architecture-neutral, portability, multi-threaded execution, etc.

And the one feature which attracts the most is the static keyword.

So what is a static keyword?

#full stack development #java #static keyword java #static method in java

Ian  Robinson

Ian Robinson

1623223443

Predictive Modeling in Data Science

Predictive modeling is an integral tool used in the data science world — learn the five primary predictive models and how to use them properly.

Predictive modeling in data science is used to answer the question “What is going to happen in the future, based on known past behaviors?” Modeling is an essential part of data science, and it is mainly divided into predictive and preventive modeling. Predictive modeling, also known as predictive analytics, is the process of using data and statistical algorithms to predict outcomes with data models. Anything from sports outcomes, television ratings to technological advances, and corporate economies can be predicted using these models.

Top 5 Predictive Models

  1. Classification Model: It is the simplest of all predictive analytics models. It puts data in categories based on its historical data. Classification models are best to answer “yes or no” types of questions.
  2. Clustering Model: This model groups data points into separate groups, based on similar behavior.
  3. **Forecast Model: **One of the most widely used predictive analytics models. It deals with metric value prediction, and this model can be applied wherever historical numerical data is available.
  4. Outliers Model: This model, as the name suggests, is oriented around exceptional data entries within a dataset. It can identify exceptional figures either by themselves or in concurrence with other numbers and categories.
  5. Time Series Model: This predictive model consists of a series of data points captured, using time as the input limit. It uses the data from previous years to develop a numerical metric and predicts the next three to six weeks of data using that metric.

#big data #data science #predictive analytics #predictive analysis #predictive modeling #predictive models

Extension method in C# | C# static extension method | C# Bangla Tutorial | Advanced C#

https://youtu.be/bdvgEnKRe5o

#oop in c# #object oriented programming #object oriented concept in c# #learn oop concept #advance c# #extension method in c#