Noah Saunders

Noah Saunders

1624508662

CPython Internals: Paperback Now Available!

After almost two years of writing, reviewing, and testing, we’re delighted to announce that CPython Internals: Your Guide to the Python 3 Interpreter is now available in paperback!

Are there certain parts of Python that just seem like magic? Once you see how Python works at the interpreter level, you’ll be able to optimize your applications and fully leverage the power of Python.

In CPython Internals, you’ll unlock the inner workings of the Python language, learn how to compile the Python interpreter from source code, and cover what you’ll need to know to confidently start contributing to CPython yourself!

In this article, you’ll see:

  • How you can take your Python skills to the next level with CPython Internals
  • How other Pythonistas have already been doing it

To skip right to the good stuff and get your hands on the book, click the link below:

Buy on Amazon »

#cpython #python

What is GEEK

Buddha Community

CPython Internals: Paperback Now Available!
Noah Saunders

Noah Saunders

1624508662

CPython Internals: Paperback Now Available!

After almost two years of writing, reviewing, and testing, we’re delighted to announce that CPython Internals: Your Guide to the Python 3 Interpreter is now available in paperback!

Are there certain parts of Python that just seem like magic? Once you see how Python works at the interpreter level, you’ll be able to optimize your applications and fully leverage the power of Python.

In CPython Internals, you’ll unlock the inner workings of the Python language, learn how to compile the Python interpreter from source code, and cover what you’ll need to know to confidently start contributing to CPython yourself!

In this article, you’ll see:

  • How you can take your Python skills to the next level with CPython Internals
  • How other Pythonistas have already been doing it

To skip right to the good stuff and get your hands on the book, click the link below:

Buy on Amazon »

#cpython #python

Riley Lambert

Riley Lambert

1650856507

SQL For Data Science | Learn SQL Database For Data Science

Introduction

Data Science is a most emerging field with numerous job opportunities. We all must have been heard about the topmost Data Science skills. To start with, the easiest, as well as an essential skill that every data science aspirant should acquire, is SQL.

Nowadays, most companies are going towards being data-driven. These data are stored in a database and are managed and processed through a Database Management system. DBMS makes our work so easy and organized. Hence, it is essential to integrate the most popular programming language with the incredible DBMS tool.

SQL is the most widely used programming language while working with databases and supported by various relational database systems, like MySQL, SQL Server, and Oracle. However, the SQL standard has some features that are implemented differently in different database systems. Thus, SQL becomes one of the most important concepts to be learned in this field of Data Science.

data science skills

Image source: KDnuggets

Need of SQL in Data Science

SQL (Structured Query Language) is used for performing various operations on the data stored in the databases like updating records, deleting records, creating and modifying tables, views, etc. SQL is also the standard for the current big data platforms that use SQL as their key API for their relational databases.

Data Science is the all-around study of data. To work with data, we need to extract it from the database. This is where SQL comes into the picture. Relational Database Management is a crucial part of Data Science. A Data Scientist can control, define, manipulate, create, and query the database using SQL commands.

Many modern industries have equipped their products data management with NoSQL technology but, SQL remains the ideal choice for many business intelligence tools and in-office operations.

Many of the Database platforms are modeled after SQL. This is why it has become a standard for many database systems. Modern big data systems like Hadoop, Spark also make use of SQL only for maintaining the relational database systems and processing structured data.

We can say that:

1. A Data Scientist needs SQL to handle structured data. As the structured data is stored in relational databases. Therefore, to query these databases, a data scientist must have a good knowledge of SQL commands.

2.Big Data Platforms like Hadoop and Spark provide an extension for querying using SQL commands for manipulating.

3.SQL is the standard tool to experiment with data through the creation of test environments.

4. To perform analytics operations with the data that is stored in relational databases like Oracle, Microsoft SQL, MySQL, we need SQL.

5. SQL is also an essential tool for data wrangling and preparation. Therefore, while dealing with various Big Data tools, we make use of SQL.

Key elements of SQL for Data Science

Following are the key aspects of SQL which are most useful for Data Science. Every aspiring Data Scientists must know these necessary SQL skills and features.

sql for data science

Introduction to SQL with Python

As we all know that SQL is the most used Database Management Tool and Python is the most popular Data Science Language for its flexibility and wide range of libraries. There are various ways to use SQL with Python. Python provides multiple libraries that are developed and can utilize for this purpose. SQLite, PostgreSQL, and MySQL are examples of these libraries.

Why use SQL with Python

There are many use cases for when Data Scientists want to connect Python to SQL. Data Scientists need to connect a SQL database so that data coming from the web application can be stored. It also helps to communicate between different data sources.

There is no need to switch between different programming languages for data management. It makes Data scientists’ work more convenient. They will be able to use your Python skills to manipulate data stored in a SQL database. They don’t need a CSV file.

MySQL with Python

MySQL is a server-based database management system. One MySQL server can have multiple databases. A MySQL database consist two-step process for creating a database:

1. Make a connection to a MySQL server.

2. Execute separate queries to create the database and process data.

Let’s get started with MySQL with python

First, we will create a connection between the MySQL server and MySQL DB. For this, we will define a function that will establish a connection to the MySQL database server and will return the connection object:

!pip install mysql-connector-python
import mysql.connector
from mysql.connector import Error
def create_connection(host_name, user_name, user_password):
     connection = None
      try:
          connection = mysql.connector.connect(
                 host=host_name,
                 user=user_name,
                 passwd=user_password
            )
            print("Connection to MySQL DB successful")
      except Error as e:
            print(f"The error '{e}' occurred")
       return connection
connection = create_connection("localhost", "root", "")

In the above code, we have defined a function create_connection() that accepts following three parameters:

1. host_name

2. user_name

3. user_password

The mysql.connector is a Python SQL module that contains a method .connect() that is used to connect to a MySQL database server. When the connection is established, the connection object created will be returned to the calling function.

So far the connection is established successfully, now let’s create a database.

#we have created a function to create database that contions two parameters
#connection and query
def create_database(connection, query): #now we are creating an object cursor to execute SQL queries cursor = connection.cursor() try: #query to be executed will be passed in cursor.execute() in string form cursor.execute(query) print("Database created successfully") except Error as e: print(f"The error '{e}' occurred")
#now we are creating a database named example_app
create_database_query = "CREATE DATABASE example_app" create_database(connection, create_database_query)
#now will create database example_app on database server
#and also cretae connection between database and server
def create_connection(host_name, user_name, user_password, db_name): connection = None try: connection = mysql.connector.connect( host=host_name, user=user_name, passwd=user_password, database=db_name ) print("Connection to MySQL DB successful") except Error as e: print(f"The error '{e}' occurred") return connection
#calling the create_connection() and connects to the example_app database. connection = create_connection("localhost", "root", "", "example_app")

SQLite

SQLite is probably the most uncomplicated database we can connect to a Python application since it’s a built-in module we don’t need to install any external Python SQL modules. By default, Python installation contains a Python SQL library named sqlite3 that can be used to interact with an SQLite database.

SQLite is a serverless database. It reads and writes data to a file. That means we don’t even need to install and run an SQLite server to perform database operations like MySQL and PostgreSQL!

Let’s use sqlite3 to connect to an SQLite database in Python:

import sqlite3 from sqlite3 import Error
def create_connection(path): connection = None try: connection = sqlite3.connect(path) print("Connection to SQLite DB successful")
except Error as e: print(f"The error '{e}' occurred") return connection

In the above code, we have imported sqlite3 and the module’s Error class. Then define a function called .create_connection() that will accept the path to the SQLite database. Then .connect() from the sqlite3 module will take the SQLite database path as a parameter. If the database exists at the path specified in .connect, then a connection to the database will be established. Otherwise, a new database is created at the specified path, and then a connection is established.

sqlite3.connect(path) will return a connection object, which was also returned by create_connection(). This connection object will be used to execute SQL queries on an SQLite database. The following line of code will create a connection to the SQLite database:

connection = create_connection("E:\example_app.sqlite")

Once the connection is established we can see the database file is created in the root directory and if we want, we can also change the location of the file.

In this article, we discuss how SQL is essential for Data Science and also how we can work with SQL using python. Thanks for reading. Do let me know your comments and feedback in the comment section.

#sql #datascience #database #programming #developer 

A Simple Flutter API to Manage Rest Api Request Easily

api_manager .A simple flutter API to manage rest api request easily with the help of flutter dio.

Get started

Install

Add dependency

dependencies:
  api_manager: $latest_version

Super simple to use

import 'package:api_manager/api_manager.dart';

void main() async {
 
  ApiResponse response = await ApiManager().request(
    requestType: RequestType.GET,
    route: "your route",
  );
  print(response);
}

Config in a base manager


class ApiRepository {
  
  static final ApiRepository _instance = ApiRepository._internal(); /// singleton api repository
  ApiManager _apiManager;

  factory ApiRepository() {
    return _instance;
  }

  /// base configuration for api manager
  ApiRepository._internal() {
    _apiManager = ApiManager();
    _apiManager.options.baseUrl = BASE_URL; /// EX: BASE_URL = https://google.com/api/v1 
    _apiManager.options.connectTimeout = 100000;
    _apiManager.options.receiveTimeout = 100000;
    _apiManager.enableLogging(responseBody: true, requestBody: false); /// enable api logging EX: response, request, headers etc
    _apiManager.enableAuthTokenCheck(() => "access_token"); /// EX: JWT/PASSPORT auth token store in cache
  }
}

Examples

Suppose we have a response model like this:

class SampleResponse{
  String name;
  int id;

  SampleResponse.fromJson(jsonMap): 
        this.name = jsonMap['name'],
        this.id = jsonMap['id'];
}

and actual api response json structure is:

{
    "data": {
        "name": "md afratul kaoser taohid",
        "id": "id"
    }
}

#Now we Performing a GET request :

 Future<ApiResponse<SampleResponse>> getRequestSample() async =>
      await _apiManager.request<SampleResponse>(
        requestType: RequestType.GET,
        route: 'api_route',
        requestParams: {"userId": 12}, /// add params if required
        isAuthRequired: true, /// by set it to true, this request add a header authorization from this method enableAuthTokenCheck();
        responseBodySerializer: (jsonMap) {
          return SampleResponse.fromJson(jsonMap); /// parse the json response into dart model class
        },
      );

#Now we Performing a POST request :

 Future<ApiResponse<SampleResponse>> postRequestSample() async =>
      await _apiManager.request<SampleResponse>(
        requestType: RequestType.POST,
        route: 'api_route',
        requestBody: {"userId": 12}, /// add POST request body
        isAuthRequired: true, /// by set it to true, this request add a header authorization from this method enableAuthTokenCheck();
        responseBodySerializer: (jsonMap) {
          return SampleResponse.fromJson(jsonMap); /// parse the json response into dart model class
        },
      );

#Now er performing a multipart file upload request :

  Future<ApiResponse<void>> updateProfilePicture(
    String filePath,
  ) async {
    MultipartFile multipartFile =
        await _apiManager.getMultipartFileData(filePath);
    FormData formData = FormData.fromMap({'picture': multipartFile});

    return await _apiManager.request(
      requestType: RequestType.POST,
      isAuthRequired: true,
      requestBody: formData,
      route: 'api_route',
    );
  }

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add api_manager

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


dependencies:
  api_manager: ^0.1.29

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:api_manager/api_manager.dart';

example/example.dart

//void main() async {
//  ApiManager _apiManager = ApiManager();
//  _apiManager.options.baseUrl = $base_url;
//  _apiManager.responseBodyWrapper("data");
//
//  ApiResponse<List<dynamic>> response = await _apiManager.request(
//    requestType: RequestType.GET,
//    route: $route,
//    responseBodySerializer: (jsonMap) {
//      return jsonMap as List;
//    },
//  );
//  print(response);
//} 

Download Details:

Author: afratul-taohid

Source Code: https://github.com/afratul-taohid/api_manager

#flutter  #restapi 

Hunter  Krajcik

Hunter Krajcik

1648208700

Flutter Widgets, Themes Implementing The Current MacOS Design Language

macos_ui

Flutter widgets and themes implementing the current macOS design language.

Content

Contributing

macOS welcomes contributions. Please see CONTRIBUTING.md for more information.

Resources

Layout

MacosWindow

MacosWindow is the basic frame for the macOS layout.

It has a Sidebar on the left and the rest of the window is typically filled out with a MacosScaffold. A scope for the MacosWindow is provided by MacosWindowScope. The sidebar can be toggled with MacosWindowScope.of(context).toggleSidebar(). Please note that you must wrap your MacosScaffold in a Builder widget in order for this to work properly.

MacosScaffold

The MacosScaffold is what you would call a "page".

The scaffold has a TitleBar property and the children property which accepts a ContentArea widget and multiple ResizablePane widgets. To catch navigation or routes below the scaffold, consider wrapping the MacosScaffold in a CupertinoTabView. By doing so, navigation inside the MacosScaffold will be displayed inside the MacosScaffold area instead of covering the entire window. To push a route outside a MacosScaffold wrapped in a CupertinoTabView, use the root navigator Navigator.of(context, rootNavigator: true)

See the documentation for customizations.

Modern window look

A new look for macOS apps was introduced in Big Sur (macOS 11). To match that look in your Flutter app, like our screenshots, your macos/Runner/MainFlutterWindow.swift file should look like this.

import Cocoa
import FlutterMacOS

class MainFlutterWindow: NSWindow {
  override func awakeFromNib() {
    let flutterViewController = FlutterViewController.init()
    let windowFrame = self.frame
    self.contentViewController = flutterViewController
    self.setFrame(windowFrame, display: true)

    if #available(macOS 10.13, *) {
      let customToolbar = NSToolbar()
      customToolbar.showsBaselineSeparator = false
      self.toolbar = customToolbar
    }
    self.titleVisibility = .hidden
    self.titlebarAppearsTransparent = true
    if #available(macOS 11.0, *) {
      self.toolbarStyle = .unified
    }

    self.isMovableByWindowBackground = true
    self.styleMask.insert(NSWindow.StyleMask.fullSizeContentView)

    self.isOpaque = false
    self.backgroundColor = .clear
    let contentView = contentViewController!.view;
    let superView = contentView.superview!;
    let blurView = NSVisualEffectView()
    blurView.frame = superView.bounds
    blurView.autoresizingMask = [.width, .height]
    blurView.blendingMode = NSVisualEffectView.BlendingMode.behindWindow
    if #available(macOS 10.14, *) {
      blurView.material = .underWindowBackground
    }
    superView.replaceSubview(contentView, with: blurView)
    blurView.addSubview(contentView)

    RegisterGeneratedPlugins(registry: flutterViewController)

    super.awakeFromNib()
  }
}

MacosListTile

A widget that aims to approximate the [ListTile] widget found in Flutter's material library.

MacosListTile

Usage:

MacosListTile(
  leading: const Icon(CupertinoIcons.lightbulb),
  title: Text(
    'A robust library of Flutter components for macOS',
    style: MacosTheme.of(context).typography.headline,
  ),
  subtitle: Text(
    'Create native looking macOS applications using Flutter',
    style: MacosTheme.of(context).typography.subheadline.copyWith(
      color: MacosColors.systemGrayColor,
    ),
  ),
),

Icons

MacosIcon

A MacosIcon is identical to a regular Icon in every way with one exception - it respects a MacosTheme. Use it the same way you would a regular icon:

MacosIcon(
  CupertinoIcons.add,
  // color: CupertinoColors.activeBlue.color,
  // size: 20,
),

Buttons

MacosCheckbox

A checkbox is a type of button that lets the user choose between two opposite states, actions, or values. A selected checkbox is considered on when it contains a checkmark and off when it's empty. A checkbox is almost always followed by a title unless it appears in a checklist. Learn more

OffOnMixed
Off CheckboxOn CheckboxMixed Checkbox

Here's an example of how to create a basic checkbox:

bool selected = false;

MacosCheckbox(
  value: selected,
  onChanged: (value) {
    setState(() => selected = value);
  },
)

To make a checkbox in the mixed state, set value to null.

HelpButton

A help button appears within a view and opens app-specific help documentation when clicked. All help buttons are circular, consistently sized buttons that contain a question mark icon. Learn more

HelpButton Example

Here's an example of how to create a help button:

HelpButton(
  onPressed: () {
    print('pressed help button'),
  },
)

You can customize the help button appearance and behaviour using the HelpButtonTheme, but it's not recommended by apple to change help button's appearance.

RadioButton

A radio button is a small, circular button followed by a title. Typically presented in groups of two to five, radio buttons provide the user a set of related but mutually exclusive choices. A radio button’s state is either on (a filled circle) or off (an empty circle). Learn more

RadioButton Preview

Here's an example of how to create a basic radio button:

bool selected = false;

MacosRadioButton(
  value: selected,
  onChanged: (value) {
    setState(() => selected = value);
  },
),

Pop-Up Button

A pop-up button (often referred to as a pop-up menu) is a type of button that, when clicked, displays a menu containing a list of mutually exclusive choices. The menu appears on top of the button. Like other types of menus, a pop-up button’s menu can include separators and symbols like checkmarks. After the menu is revealed, it remains open until the user chooses a menu item, clicks outside of the menu, switches to another app, or quits the app; or until the system displays an alert. Learn more

The type T of the MacosPopupButton is the type of the value that each pop-up menu item represents. All the entries in a given menu must represent values with consistent types. Typically, an enum is used. Each MacosPopupMenuItem in items must be specialized with that same type argument.

The onChanged callback should update a state variable that defines the pop-up menu's value. It should also call State.setState to rebuild the pop-up button with the new value.

When there are menu items that cannot be displayed within the available menu constraints, a caret is shown at the top or bottom of the open menu to signal that there are items that are not currently visible.

The menu can also be navigated with the up/down keys and an item selected with the Return key.

Dark ThemeLight Theme

Here's an example of how to create a basic pop-up button:

String popupValue = 'One';

MacosPopupButton<String>(
  value: popupValue,
  onChanged: (String? newValue) {
    setState(() {
      popupValue = newValue!;
    });
  },
  items: <String>['One', 'Two', 'Three', 'Four']
      .map<MacosPopupMenuItem<String>>((String value) {
    return MacosPopupMenuItem<String>(
      value: value,
      child: Text(value),
    );
  }).toList(),
),

PushButton

A push button appears within a view and initiates an instantaneous app-specific action, such as printing a document or deleting a file. Push buttons contain text—not icons—and often open a separate window, dialog, or app so the user can complete a task. Learn more

Dark ThemeLight Theme

Here's an example of how to create a basic push button:

PushButton(
  child: Text('button'),
  buttonSize: ButtonSize.large,
  onPressed: () {
    print('button pressed');
  },
),

MacosSwitch

A switch is a visual toggle between two mutually exclusive states — on and off. A switch shows that it's on when the accent color is visible and off when the switch appears colorless. Learn more

OnOff

Here's an example of how to create a basic toggle switch:

bool selected = false;

MacosSwitch(
  value: selected,
  onChanged: (value) {
    setState(() => selected = value);
  },
),

Dialogs and Sheets

MacosAlertDialog

Usage:

showMacosAlertDialog(
  context: context,
  builder: (_) => MacosAlertDialog(
    appIcon: FlutterLogo(
      size: 56,
    ),
    title: Text(
      'Alert Dialog with Primary Action',
      style: MacosTheme.of(context).typography.headline,
    ),
    message: Text(
      'This is an alert dialog with a primary action and no secondary action',
      textAlign: TextAlign.center,
      style: MacosTheme.of(context).typography.headline,
    ),
    primaryButton: PushButton(
      buttonSize: ButtonSize.large,
      child: Text('Primary'),
      onPressed: () {},
    ),
  ),
);

MacosSheet

Usage:

showMacosSheet(
  context: context,
  builder: (_) => const MacosuiSheet(),
);

Fields

MacosTextField

A text field is a rectangular area in which the user enters or edits one or more lines of text. A text field can contain plain or styled text.

Here's an example of how to create a basic text field:

MacosTextField(),

Labels

Labels are a short description of what an element on the screen does.

MacosTooltip

Tooltips succinctly describe how to use controls without shifting people’s focus away from the primary interface. Help tags appear when the user positions the pointer over a control for a few seconds. A tooltip remains visible for 10 seconds, or until the pointer moves away from the control.

Tooltip Example

To create a tooltip, wrap any widget on a Tooltip:

MacosTooltip(
  message: 'This is a tooltip',
  child: Text('Hover or long press to show a tooltip'),
),

You can customize the tooltip the way you want using its style property. A tooltip automatically adapts to its environment, responding to touch and pointer events.

Indicators

Progress Indicators

Don’t make people sit around staring at a static screen waiting for your app to load content or perform lengthy data processing operations. Use progress indicators to let people know your app hasn't stalled and to give them some idea of how long they’ll be waiting.

Progress indicators have two distinct styles:

  • Bar indicators, more commonly known as progress bars, show progress in a horizontal bar.
  • Spinning indicators show progress in a circular form, either as a spinner or as a circle that fills in as progress continues.

People don't interact with progress indicators; however, they are often accompanied by a button for canceling the corresponding operation. Learn more

Progress Indicator Example

ProgressCircle

A ProgressCircle can be either determinate or indeterminate.

Determinate Progress CircleIndeterminate Progress Circle

Here's an example of how to create an indeterminate progress circle:

ProgressCircle(
  value: null,
),

You can provide a non-null value to value to make the progress circle determinate.

ProgressBar

A ProgressBar can only be determinate.

Here's an example of how to create a determinate progress bar:

ProgressBar(
  value: 30,
)

Level Indicators

A level indicator graphically represents of a specific value within a range of numeric values. It’s similar to a slider in purpose, but more visual and doesn’t contain a distinct control for selecting a value—clicking and dragging across the level indicator itself to select a value is supported, however. A level indicator can also include tick marks, making it easy for the user to pinpoint a specific value in the range. There are three different level indicator styles, each with a different appearance, for communicating capacity, rating, and relevance.

CapacityIndicator

A capacity indicator illustrates the current level in relation to a finite capacity. Capacity indicators are often used when communicating factors like disk and battery usage. Learn more

ContinuousDiscrete
Continuous CapacityIndicator ExampleDiscrete CapacityIndicator Example
A horizontal translucent track that fills with a colored bar to indicate the current value. Tick marks are often displayed to provide context.A horizontal row of separate, equally sized, rectangular segments. The number of segments matches the total capacity, and the segments fill completely—never partially—with color to indicate the current value.

Here's an example of how to create an interactive continuous capacity indicator:

double value = 30;

CapacityIndicator(
  value: value,
  discrete: false,
  onChanged: (v) {
    setState(() => value = v);
  },
),

You can set discrete to true to make it a discrete capacity indicator.

RatingIndicator

A rating indicator uses a series of horizontally arranged graphical symbols to communicate a ranking level. The default symbol is a star.

RatingIndicator Example

A rating indicator doesn’t display partial symbols—its value is rounded in order to display complete symbols only. Within a rating indicator, symbols are always the same distance apart and don't expand or shrink to fit the control. Learn more

Here's an example of how to create an interactive rating indicator:

double value = 3;

RatingIndicator(
  amount: 5,
  value: value,
  onChanged: (v) {
    setState(() => value = v);
  }
)

RelevanceIndicator

A relevance indicator communicates relevancy using a series of vertical bars. It often appears in a list of search results for reference when sorting and comparing multiple items. Learn more

RelevanceIndicator Example

Here's an example of how to create a relevance indicator:

RelevanceIndicator(
  value: 15,
  amount: 20,
)

Author: GroovinChip
Source Code: https://github.com/GroovinChip/macos_ui 
License: MIT License

#flutter #dart 

Plesk WordPress Toolkit 5.3 is now available for download.

Research, Improvements, Bugfixes
Based on the research performed in December, we have increased the site list loading speed on Plesk. We have also tested the performance of Smart Updates and regular updates to better understand where and how we can improve our product.

As for bugs, the v5.3 release includes a number of customer-requested bugfixes, particularly those that address cloning-related issues.

#wordpress #the plesk wordpress toolkit #now available