fabiochiu/medium-articles huggingface dataset:
Using Groups in Tableau
By: Michel Burnett
Tags: Data Visualization, Tableau, Tableau Public, Big Data, Data Visualisation

A quick tutorial on grouping data in Tableau Public.

Using groups in Tableau can be an easy way to clean and differentiate your data. For example you may have data coming from different countries and you’d like to group countries to their respective continents. With groups you can divide fields however you’d like and increase the readability of your visualization.

For this example I’ll be using a public dataset found here: https://catalogue.data.govt.nz/dataset/effects-of-covid-19-on-trade/resource/6d411b54-3ab4-4aeb-981d-b41df81afbfa. This is data of COVID-19’s effect on international trade. There are several different countries and regions included. I’ll be grouping these as “Western” or “Eastern”. To begin we will go into the data source shelf and click the arrow on the side of the “Country” field. There will be a drop down menu where you can select “Create” and then select “Group…”.

You should now see a group creation window with all the countries (or respective data from your field) and be able to select and group them together. Once you’ve made your selections for a group, you can click on “group” and you will be prompted to name that group. Make sure to hold ctrl or command when selecting multiples.

Once you are satisfied with your grouping you can click “ok” and Tableau will create a new calculated field with your groups. In this example I’ve dragged and dropped the new calculated field “Country (group)” onto the axis of the “Country” table to get an elegantly divided and descriptive table.

Grouping in Tableau can be very handy when working with “messy” data or larger fields with lots of rows that could use some separation.
Dataviz #5 : La Nintendo Switch, un succès commercial
By: Mickaël Andrieu
Tags: Data Visualization, Data Science, Weekly, Tableau

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.
Connecting Tableau to Oracle Cloud
By: Michelle Kolbe Hardwick
Tags: Tableau, Oracle Cloud

I wanted to connect my Tableau desktop client to an Automous Database that I setup in the Free Tier of Oracle Cloud. Unfortunately, it was not as easy as these instructions from Tableau made it sound: https://kb.tableau.com/articles/howto/Connecting-to-Oracle-in-Tableau-Desktop-using-Oracle-Wallet

Here’s how I got it to work on my windows machine. Hopefully this helps someone else that’s struggling. And as a disclaimer, I’m unsure if all of these steps are needed but this what eventually worked for me after trial and error.

Download the Oracle Instant Client. Install it to a folder on your C drive. I put this in C:\oracle\instant_client_19_8. In that folder, create a new folder called “owm” and then another folder called “wallets”. (I read somewhere that these folders are needed but now I can’t recall what source told me to do this.) Unzip your Oracle Wallet to this new wallets folder. Run the ewallet.p12 file in this wallets folder. This is the Certificate Import Wizard. Edit the sqlnet.ora file to change the DIRECTORY to the path of where you unzipped the wallet. Mine looks like this:

WALLET_LOCATION = (SOURCE = (METHOD = file) (METHOD_DATA = (DIRECTORY=”C:\oracle\instantclient_19_8\owm\wallets”)))

SSL_SERVER_DN_MATCH=yes

7. Open the Environment Variables window in Windows from System Properties.

8. Edit the PATH variable to add the path to your instant client download.

C:\oracle\instantclient_19_8\

9. Add a new Environment Variable for TNS_ADMIN pointed to:

C:\oracle\instantclient_19_8\owm\wallets\

10. Add a new Environment Variable for ORACLE_HOME pointed to:

C:\oracle\instantclient_19_8

11. Now open Tableau.

12. For connecting to data, choose the Oracle option under To a Server.

13. Enter a name from your tnsnames.ora file for the Server name. Then enter your database username and password.

13. That’s it! This should connect successfully in Tableau using a tns connection.

Note: my Oracle Cloud free tier database is setup to the following for the Access Type. I did not see a difference in being able to connect when I changed to allow specific IP addresses via the Access Control List.
Weekly Dose of Data Analyst#7 — Who are the top political donors in each state of Australian and overall
By: Common Man
Tags: Data Visualization, Tableau, Political Donations, Australian Politics, Data Analysis

This post is about finding out who/which company make the largest political donation from FY 1998 to FY 2019 in Australia.

Notice:

In the disclosed political donation records, there are donations which are not registered with any states. In this dataset, they named as “NOT REGISTERED”.

Summary

Overall, in Australia, from 1998 to 2019, Mineralogy Pty Ltd takes the top position in the political donation chart. It has donated almost 100 million Australian dollars. Queensland Nickel Pty Ltd came in second, it has donated around 22.5 million. Combining these two donation amount together (since these two companies are owned by the same person Clive Palmer), his companies has made more than 10 times of donation made by the company in the third place (Cormack Foundation Pty Ltd). Although, whether he has spent all these money is unclear, as most likely these donation has gone to his own party.

Not surprisingly, QLD, ACT,NSW and VIC are the states received the most political donation.

For ACT,

These are the top three companies/individual made the most political donation.

Pratt Holdings P/L ($7 million) ANZ Banking Group Limited ($3.5 million) Sugolena Pty Limited ($3.4 million)

For QLD,

Other than the top three companies owned by Clive Palmer, these are the top three companies/individual made the most political donation

JJ Richards & Sons Pty Ltd ($0.76 million) Springfield Land Corporation ($0.64 million) Palmer, Clive Frederick as Individual (0.52 million)

For NSW,

These are the top three companies/individual made the most political donation

Clubs NSW ($2.2 million) Manildra Group ($1.6 million) Australian Hotels Association (N.S.W.) ($1.58 million)

For VIC,

These are the top three companies/individual made the most political donation

Cormack Foundation Pty Ltd ($9.37 million) Australian Hotels & Hospitality Association Inc. ($2.86 million) Electrical Trades Union of Australia — Victorian Branch ($2.79 million)

As always, I have made an interactive Tableau workbook for you to play with. Please click this link to access it. You can change states and financial year to find out which company/individual has made the most political donation in the state and time you are interested.

Data Source:

https://transparency.aec.gov.au/Download
Python or Tableau for Data Visualization?
By: Hantao Lin
Tags: Data Visualization, Tableau, Python, Data Science

Insights:

Both software are great at visualizing the dataset, but I prefer using Tableau for data visualization after trying it, here are the reasons:

Tableau is User-frienldy

Tableau is user-friendly to illustrated graphs compare to Python. Tableau exhibits a drag and place style and you don’t need to be an expert in coding to plot the dataset. Here’s an example:

Objective: Make a geo gragh and color different status

Python:

Source: Hantao Lin, via: Github

Tableau:

Source:Hantao Lin

From the above comparison, it is CLEAR that Tableau is much easier to use. It took me 30 seconds to plot the graph whereas for Python, not only did I have to think hard about the code I also need to pray that it will work. (Maybe this is not the case for much more experienced Python programmer)

Tableau is Interactive

If ONLY using matplotlib and seaborn in python compared to Tableau, then I can conclude that Tableau is much more interactive. Here’s an example:

Objective: Overview of Transcation Type

Python:

Tableau:

Source: Hantao Lin

From the illustration above, you can see that one of the feature Tableau provides is pinpoint at a certain section of your plot and see more information from that section(I listed out the percentage and count total, but that information are normally hidden unless pinpointed). Whereas in python, the graph is flat and you are only presented with the information labeled.
Tableau Desktop Specialist 합격후기
By: Jeongyeon, Irene
Tags: Data Visualization, Tableau, Tableau Desktop

자료

문제유형_개념문제 1. color gradient is used for which of the following

a. Discrete measure

b. Continuous measure

c. Both continuous and discrete

d. None of the above
Tableau: Quick Tip: Latest Date and Value in a Calculated Field.
By: Julian Doublesin
Tags: Data Visualization, Tableau, Tips And Tricks, Level Of Detail

Part of a series of short articles about those little annoying Tableau issues a developer faces daily for which short and sweet solutions are hard to find without digging deep.

The Problem

You need to get the latest date and value associated with that date from your dataset in a calculated field?

The Solution

Level of Detail Calculation

Quite simply all you have to do is create a calculated field consisting of a LOD: Level of Detail calculation.

The calculation above returns the most upper Maximum value if the date for that value is equal to the maximum date at the partition level defined in the LOD: Code.

There you have it! A very simple solution, short and sweet answer to one of the most common daily issues faced by Tableau developers.

More articles like this are going to be published aimed at providing simple, short and sweet answers to help you solve problems without going through never-ending threads.
Dashboard Wars: Excel vs. Tableau
By: Firdos Vohra
Tags: Data Visualization, Data Analytics, Excel, Tableau, Dashboard

Data visualization is an important aspect of data analysis. Microsoft Excel and Tableau are two frequented go-to options for interactive dashboards. Let’s break down some of the pros and cons of each.

Excel has really come a long way within the past decade with its data visualization options. Not sure where to start the process? One really cool feature is ‘Quick Analysis’. Simply select the entire data set and a button will automatically show up on the bottom right-hand side which will guide you through several options, including different charts and sparklines. For fewer, more targeted options, chart recommendations are also available under the ‘Insert’ tab, which will only recommend the most useful chart types for the selected data set. Pivot chart slicers are an amazing tool that seems to be directly competing with Tableau filters. The only drawback is you need to create a pivot table first, a hurdle which many beginner Excel users need to overcome. An even bigger hurdle is creating a geographically mapped dashboard. It takes more than twice as long as Tableau and you really have to know what you’re doing. Another drawback is that you are stuck with the version and features of Excel you originally purchased.

The ease of use is why Tableau has been leading the data visualization game for so long. Tableau’s easy-peasy drag and drop tools let users try out different styles immediately. The software is also supported by a large online community. For beginner data visualizers, the community is an excellent source of information, support, and creative ideas. However, the downside with Tableau is the lack of privacy of data, since the free version is an online public platform visible to all. The paid version is only available as a subscription-based model and will cost you a pretty penny, eliminating most individual users. Of course, one benefit of subscription-based models is that you always have the latest version and features of the software.

Ultimately both Excel and Tableau can perform many of the same functions, but the tradeoffs are cost, privacy, and ease of use. Depending on where your values lie, you can take your pick.
Connect Tableau to a community web data connector
By: Michel Burnett
Tags: Data Visualization, Tableau, Tableau Public, Data Visualisation

A quick tutorial on how to access data over http through web data connectors on Tableau.

Web data connectors can be versatile tools to let you connect to many different possible data sources across the web. Lots of popular websites give access to free APIs that can be convenient to connect to from Tableau rather than perhaps having to download all the website’s data and hosting it locally to run your analytics on.

Several of the community WDCs

For this tutorial we’ll be using a web data connector provided by Tableau on their community github page: https://tableau.github.io/webdataconnector/community/. As you can see there are many web data connectors readily available to the community, some connectors are made to be compatible with generic file types and parameters while others are more specific connectors for popular websites such as Instagram. Most of these connectors will be pretty straightforward to access, some may require social media authentication or parameter information. For this example I’ll be using the connector for “Confirmed Exoplanets” by “ZooGorilla”.

Webpage for the ExoPlanet WDC

Following these links brings you to the actual web data connector pages. Copy the url at the top and we will connect to this ExoPlanet database from Tableau. Open Tableau and under “To a server” in the “Connect” shelf, click on “Web data connector” as the data connection type. This will open a browser window. Paste the url copied from the previous step into this browser and click “Get Confirmed ExoPlanets” (there will be a similar type of activation on other connectors as well).

Connecting to WDC on Tableau

You should now be connected to your data source and be able to access it as you would any other data source on Tableau. You might not find a compatible web data connector for the website you want to connect to but Tableau also has several tutorials on building your own custom web data connector for specific websites or data connections that you can’t find a connector to. Here’s one on their official YouTube page: https://www.youtube.com/watch?v=jtGzBq4hw2s.
From one chart to a whole story
By: Herman M.
Tags: Data Visualization, Tableau, Data, Udacity

Where we start from …

The graph I needed to improve was the following

The dataset used was relatively small (categories, countries, prices and years were the only variables). So telling a story starting from such a small dataset was a bit tricky for me.

The graph, as you can see, is a classic linechart and answers one question: How did the average price of books vary compared to the average price of all other items around the decade 2010 in Europe?

By manipulating the data I noted a few limitations to this graph:

It offers only one angle of view: that of the evolution of book prices compared to other goods.

Since we are talking about Europe, we can wonder if the evolution has been the same in all countries.

Are there any abnormal or particular trajectories that it would be interesting to analyze?

Was the price variability the same in all countries?

All these questions remain unanswered.

In the same way, the datasets could have been enriched with a few variables such as GDP, the size of the population of each country, or even the average standard of living or purchasing power of the population.

These data would have allowed a better understanding of the evolution of book prices in certain countries and perhaps identify correlations.

Ingredients of the story

The story types

To make a data story, you have to start by choosing the type of story you want to tell. A small analysis of the datasets allowed me to make a mix of several types of data story:

Change over time: To follow the trajectory of average book prices over time.

Hierarchy drill down: Two levels of analysis namely Europe and then the countries taken separately

Once I had defined the type of story, it was time to set the storyline. That was the easy part for me. I chose to tell a story about the evolution of average book prices in Europe and the analysis of the trajectories taken by different countries.

The selected visuals

I chose to build the story from two types of graphics:

Line chart or Timeline Chart: Since it’s about telling a story over a certain period, this chart makes perfect sense. It is best suited for trend-based visualizations of data over time.

Scatter plot: This chart is primarily used for correlation and distribution analysis. It is also used to show the data distribution or clustering trends and help spot anomalies or outliers. I decided to use it to identify particular trajectories.

The whole story

Now that the stage is set, the whole story can be told. Below I give you a snapshot of the story, you can find the whole data story here.

Once upon a time …

During the decade 2010, the average price of books has evolved at the same pace as that of other goods in Europe.

However, not all countries have followed the same trajectory. The trajectories followed by some countries are indeed completely different from the rest.

These countries are at the origin of the high variability of the average price of books at the European level.

The data story ends with a dashboard that allows anyone to examine the data and perhaps find some interesting insights.
Tableau Desktop Specialist— Part 1
By: Sanchit Sharma
Tags: Extract, Tableau, Tde, Tableau Training

A live connection means that when your Tableau view refreshes it will use the latest version of data.

An extract supports large datasets, faster than live connection, helps improve performance and it provides offline access to your data.

If the above comparison did not already sell you the benefits of Tableau Data Extracts (TDEs) then let me take you through some use cases.

Blending a data source with aggregated extract from the same data source can help you filter and slice the data to compare aggregations of the subset to the entire data.

To create “double aggregates” , creating a pre-aggregated extract would allow you to calculate the aggregate of an aggregate.

Save meta data properties in a .tds

TDS stands for Tableau Data Source

Data source files store the information necessary to connect to the data source such as the server name and port, as well as changes you have made to data such as changing the default formatting and adding calculated field.

Keep these simple best practices while using extracts:

Use full refreshes when possible.

Fully refresh incremental refreshes extracts at regular intervals to maximize performance.

Extracts should be published to data servers to avoid redundant extracts in tableau server.

Hide unused column before creating an extract to increase speed of creation and save space.

Learn more about extracts —

Why use Tableau Data Extracts by Gordon Rose

Extract your data by Tableau
UI Tip: list overflow and ‘+ others’
By: Cody Lindsay Gordon
Tags: Design Patterns, Design, UX, Design Thinking, UI

Let’s say you have a list of 6 objects (or breads):

Baguette Sourdough Potato bread Brioche Bagel Banana bread

Now let’s say you have a UI that lists out those breads:

Baguette, Sourdough, Potato bread, Brioche, Bagel, Banana bread

But that list might be variable and have any number of bread in it. So in your UI you might stipulate that it shows up to 4 breads and then appends a count of any remaining:

Baguette, Sourdough, Potato bread, Brioche, + 2 other breads

This works nicely — we now have a more predictable list size. But what about the case where we have 5 breads? It would look like this:

Baguette, Sourdough, Potato bread, Brioche, + 1 other bread

That’s not great — we are taking up space saying there is ‘1 other bread’ when we could instead just say what that last bread is. Let’s modify our rules:

When there are 5 or less, list them all

When there are 6 or more, list 4 and append a count of the remaining

For 5 breads that would return:

Baguette, Sourdough, Potato bread, Brioche, Bagel

For 6 breads that would return:

Baguette, Sourdough, Potato bread, Brioche, + 2 other breads

Now we never have the case of ‘+1 other’. As a bonus, you also don’t have to worry about singular vs plural states of the appended count, because it is always 2 or more.

🥯 🍞 🥖 🥨 🥐 🫓
Unit Of Work Pattern Nedir ?
Tags: Generic Programming, Design Patterns, Unitofwork, Tutorial

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Architecture Learnings #6, Design Patterns — Builder vs Decorator and the Pizza Problem
By: Hitesh Das
Tags: Design Patterns, Architecture Components, Interview Questions, Best Practices

Image by Michal Jarmoluk from Pixabay

One of the common design questions in Software Engineering interviews is the Pizza problem. i.e Building the software for a pizza shop who has a wide variety of pizza and wants to prepare different types, e.g Veg Pizza, Non-veg Pizza, Flat Bread, Pepperoni Pizza with Extra Cheese 😋, put add on toppings on it.

Hungry??? So am I… please wait for some more time.

Let’s now see the different approaches to solve this design problem.

Traditionally, for pizza problem, Builder Pattern is most commonly used. However, there are some examples using Decorator Pattern as well. Both the approaches are correct but there is difference in use case which we will discuss in detail in this article.
모던 C++ : 스마트 포인터와 객체 생성
Tags: Design Patterns, Cpp, Smart Pointer, Software Development

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Understanding the Builder Design Pattern
By: Carlos Caballero
Tags: Builder Pattern, JavaScript, Typescript, Design Patterns, Programming

Example 2: Creating Video Game Heroes

You've now seen the classic theoretical example so you understand the responsibilities of each of the classes in the pattern. Now, here’s another example where we identify each of these classes with a specific problem.

Our problem is the representation of different heroes or characters in a video game. We’ll focus on the classic WoW (World of Warcraft) game, in which the heroes are divided into two races: Humans and Orcs. Each of these heroes can have armor , weapon s or different skills depending on whether the hero is a human or orc.

In the event that the builder pattern is not applied, it causes a constructor to be defined in the Hero class with a long list of parameters ( race , armor , skills , etc), which in turn causes logic to be defined in the constructor to decide whether the armor is human or orc. So, with this initial solution, the problem is coupled since any change in the business logic would mean having to rewrite quite a few pieces of code, with hardly any possibility of reuse.

So, the first thing we have to do is stop and think about how the builder pattern helps us solve this problem. So, we focus on showing the UML diagram that solves this problem and we begin to implement it.

Builder pattern applied to the Hero creation problem of a video game.

In this example, we follow the same order as in the previous example and we start with the model or object that we want to build flexibly.

The Hero class defines the race , armor , weapon and skills properties. All these attributes could be objects but to keep this example simple we’ve left them as character strings.

The HeroBuilder interface defines methods for specific builders. Let’s observe look at how the Hero object is configured, little by little, with setArmor , setWeapon , and setSkills . Finally, we have the build method that finishes the configuration of the object and extracts the Hero object.

Once the builder is defined (as an abstract class or interface) we must build the two specific builders that our problem requires: HumanHeroBuilder and OrcHeroBuilder . In the demo code we have completed with a different string according to each builder. It’s important to note that the build method of each of the builders returns the built object ( Hero ) and resets the state of the object, so it can build another one.

The last element of the pattern is the Hero-Director class that allows you to store configurations repeated throughout the code. In our example, we created three Hero creation setups. For example, the createHero method builds a complete hero — that is, it assigns armor, abilities, and weapons. We also create a hero without any equipment with the createHeroBasic method. Finally, to illustrate another configuration, the createHeroWithArmor method is defined, which returns a hero for whom only the armor has been assigned.
React: you remove the PROPS!
Tags: JavaScript, React, Store, Clean Code, Design Patterns

In my experience the big problem I had by switching to REACT is that it does not propose a global pattern to manage the business logic.

I have reviewed code where data and callbacks have passed to an infinite series of components.

Any modification was a pain, especially to move a component out of its hierarchy.

REDUX is very interesting but too verbose for my style.

REACT provides “native” tools:

PROVIDER and REDUCER

but, in my opinion, they are too basic to use them directly.

So… I wrote a “utility” (NOT a “library”) served in several projects

very very light.

https://gitlab.com/priolo22/iistore

Basic example:

Create STORE

export default {

state: {

value: "init value",

},

getters: {

getUppercase: (state) => state.value.toUpperCase(),

},

actions: {

fetch: async (state, payload, store) => {

//const {response} = await ajax.get(`my_server`)

//store.setValue(response)

}

},

mutators: {

setValue: (state, value) => ({ value }),

},

}

Create PROVIDER

import React from "react";

import ReactDOM from "react-dom";

import App from "./App";



import { MultiStoreProvider, setupStore } from '@priolo/iistore';

import myStore from "./myStore"

setupStore({ myStore })



const rootElement = document.getElementById("root");

ReactDOM.render(

<MultiStoreProvider>

<App />

</MultiStoreProvider>,

rootElement

);

Use STORE

import { useStore } from "@priolo/iistore";

import React from "react";



export default function App() {



const { state, setValue, getUppercase } = useStore("myStore")



return (<div>

<h1>{state.value}</h1><h2>{getUppercase()}</h2>

<input onChange={(e)=>setValue(e.target.value)} />

</div>);

}

[online]

Hope it’s useful, I’m a huge fan of VUEX which I got my inspiration from

Bye!
Belajar Design Pattern Part 2 — Factory Method
Tags: Design Pattern, Python, Factory Method Pattern

Which is more difficult, coding or counting? Not both of them, the difficult one is sharing your knowledge to people without asking the payment.
How to Create a Thread-Safe Singleton Class in Python
By: Jordan Gillard
Tags: Python, Coding, Software Development, Design Patterns, Singleton

In this article, I’m going to show you how to make a thread-safe Singleton class in Python. I am writing this article because most examples online of a Singleton in Python are either atrocious or not thread safe. Here’s the final code, because you’re probably here for a quick answer so you can solve your current task:

import threading





class Singleton:

_instance = None

_lock = threading.Lock()



def __new__(cls, *args, **kwargs):

if not cls._instance:

with cls._lock:

# another thread could have created the instance

# before we acquired the lock. So check that the

# instance is still nonexistent.

if not cls._instance:

cls._instance = super(Singleton, cls).__new__(cls)

return cls._instance

*I apologize for the 2 space indents — I want to keep lines from being wrapped.

Explanation

Whats the deal with Python’s __new__ dunder method?

__new__ is called whenever Python instantiates a new object of a class. Normally, __new__ goes to the super of the class, which is Object , and instantiates a new object which is then passed to __init__ with whatever args were passed to __new__ . We intercept this method, and tell it to create one and only one class instance (i.e. the Singleton). This class object is then passed to the __init__ method as it normally would be.

Whats the deal with the Lock ?

This is a good question. threading.Lock is a class implementing primitive lock objects. It allows the thread running our code to be the only thread accessing the code within the lock’s context manager, so long as it holds the lock. This means that no other threads can run the code within the with cls._lock block at the same time as the thread which has the lock.

Whats the deal with the two cls._instance checks?

We check that the cls._instance is None before we acquire the lock. There is an edge case where cls._instance is None in this thread while another thread is about to call cls._instance = super(Singleton, cls).__new__(cls) . In this edge case, two class objects are created, thus breaking the Singleton property of our class.

Why not wrap the entire body of the __new__ method in the Lock context manager and avoid the second if not cls._instance check, like this?

class Singleton:

_instance = None

_lock = threading.Lock()



def __new__(cls, *args, **kwargs):

with cls._lock:

# another thread could have created the instance

# before we acquired the lock. So check that the

# instance is still nonexistent.

if not cls._instance:

cls._instance = super(Singleton, cls).__new__(cls)

return cls._instance

This would work, and at first glance is seems better because of the reduction in lines of code. The problem, however, is that acquiring locks is an expensive operation. Having a class/method which acquires locks when it does not need to can lead to slow code which is hard to pin down. Only acquire locks when it’s necessary.
Useful Design Patterns
By: Ahmad Berahman
Tags: Programmer, Golang, Thinking, Design Patterns, Structure

Design Patterns have a role of an eye-catching picture to me and whenever I want to write a piece of code I’ll stay in front of this picture and while I enjoy of this beautifulness, I think how can I transfer this beauty to my code.

What will we learn from design patterns? You know you don’t want to reinvent the wheel, so you look to Design Patterns
FastAPI Microservice Patterns: Local Development Environment
By: Florian Kromer
Tags: Python, Skaffold, Fastapi, Design Patterns, Microservices

FastAPI Microservice Patterns: Local Development Environment

Source code example repository

The series post’s will reference source code examples in the Github repository fastapi-microservice-patterns. Usually each sub directory contains an exemplary implementation of one or several patterns and is executable. The only exception is the directory hello-fastapi which shows how a minimal dockerized FastAPI service looks like and which can be executed using docker. The purpose of this directory is to make it easier to figure out which files need to be added for running services in with the skaffold setup.

Local development environment

First one needs to setup the development environment which allows the execution of the examples. The setup is suitable for local development as well and consists of Skaffold, Docker (for building container images), kubectl (for deploying images), minikube (Kubernetes distribution suitable for for running on local developer machines). The advantage of this setup is that the examples are easy to follow and allow migrating own projects based on the example skeleton into production environments comparably easily. One migration step required is to migrate from kubectl to a deployment tool which allows easier configuration, which implies easier maintenance, etc. like e.g. Helm. There is Kustomize as well but as others suggest I’d suggest to use Helm. However using Helm straight away would have added complexity to the examples which distract from the relevant things w.r.t. the pattern implementation. For an introduction to Skaffold refer to e.g. Intro to Skaffold for easy Kubernetes development.

Setup of the local development environment and run examples

To run the examples on a local machine the following steps are needed:

Skaffolded FastAPI

The source code repository hello-skaffold contains a minimal FastAPI service. The functionality is as minimalist as in the dockerized FastAPI service with the difference that a service based on this skeleton may be developed way faster than with a workflow based on docker or docker-compose. To run the example change into the sub directory hello-skaffold and execute minikube start followed by skaffold dev --port-forward .

The post series content
Design Patterns: Fácil implementação de alguns padrões de projetos em JavaScript com Typescript.
By: Guilherme Henrique De Melo
Tags: Development, Equals, JavaScript, Typescript, Design Patterns

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Belajar Design Pattern Part 1 — Builder
Tags: Design Patterns, Builder Pattern, Python

Which is more difficult, coding or counting? Not both of them, the difficult one is sharing your knowledge to people without asking the payment.
DesignLab Learning Log 12/12
By: Stacy Li
Tags: Ux Learning, Responsive Design, Typesetting, Design Patterns

#responsive design##typesetting#

What did I do today:

A. Attended group crits

B. Finished 1/3 of cap 1 case study

C. Finished part 1 of webflow tutorial

D. finish analysis of the user research for cap 2

New tools discovered today:

Type scale — a helpful resource that generates ratio-based type stacks

gloomaps — awesome site map tool.

New resources discovered today:

the responsive — a website that shows you responsive designs across different screen sizes; provides a quick way to see how some sites have translated their design patterns across viewports

mobbin — app design patterns and inspirations

New tricks learned today:

Use google chrome inspect feature to check the size of elements on Any website — tutorial.

Refresher of design guidelines

Daily Reading

My friends say Spotify SUX, so I took a look at its UX

reachability of UI elements on mobile

mind the defects of the hamburger menu — understand what features your user really need, and make it clear and obvious

The Non-Designer’s Design Book
5 Sites For UI Design Patterns That I’m Following And Why You Should Too
By: Yao Chen
Tags: Design Thinking, UI Design, Product Design, Design Patterns

Photo credit: Daniel Korpai

Most of the time, when we are trying to solve a problem, the chances of that solutions of similar problems is already out there is high. Instead of spending days or weeks to design a solution from scratch, we can look for a design that solves a problem that has been solved inside a different application before. That’s a design pattern to us.

What are User Interface (UI) design patterns?

User interface (UI) design patterns are reusable/recurring components which designers use to solve common problems in user interface design. For example, the breadcrumbs design pattern lets users retrace their steps. Designers can apply them to a broad range of cases, but must adapt each to the specific context of use. — Interaction Design Foundation

Here is a list of my 5 favorite sites to find design patterns.

1. UI Patterns

This is my go-to site. UI Patterns makes it easy to find patterns that you like and to group them together once you’ve decided that something is useful. They also have a bunch of interesting articles on UI design patterns which can help extend the way you approach using patterns in your designs.

2. Pattern Browser

Pattern Browser lets you quickly switch between UI patterns in your browser window. There aren’t as many patterns here as on some of the bigger sites but it’s still a good resource that worth looking.

3. Elements of Design

Elements of Design is a collection of UI components that highlight best practices for particular design patterns from leading websites around the world. You will find some useful groupings of design elements.

4. UI Scraps

UI Scraps is a collection of good, bad and noteworthy user interface designs found by Jason Robb. It looks at interface design as a whole and then tinkers with the patterns used.

5. User Interface Engineering

User Interface Engineering is a heavy resource that can meet a lot of your UI needs and it offers more than UI patterns.

Hope this list is helpful to you. What’s your favourite place to find UI patterns?
ADAPTER PATTERN -PHP
By: Uğur Müslim
Tags: Adapter Pattern, Coding, Oop, PHP, Design Patterns

You can find the patterns I write in other languages but I am writing the language on the end of the title to inform you which language will be there for examples.

You use every pattern I wrote in your frameworks without knowing it. After learning these concepts, overall knowledge of these framework architectures will be better. Today I’ll write about Adapter Pattern.

The name will give you a hint. Adapters are like converters. You use plug adapters in UK right if you are traveling from another country right?

Let’s go with an example;

You have a chef and an owen. All we gonna do is turning on that owen, we will not go further.

interface OwenInterface

{

public function turnOn();



public function checkLeakage();



}



class Owen implements OwenInterface

{

public function turnOn()

{

var_dump('Turn the gas on');

}



public function checkLeakage()

{

var_dump('Check if there is gas leakage');

}

}

We created an interface and a class. In this class we are turning the owen on and checking for gas leakage. 2 days later you heard that a new electric owen will be used. So will you change functions and names. Or will you put two or more extra functions to Owen class. No, forget them there is a better way.

interface ElectricOwenInterface

{

public function pressOnButton();



public function checkResistance();



}



class ElectricOwen implements ElectricOwenInterface

{

public function pressButton()

{

var_dump('Press on button');

}



public function checkResistance()

{

var_dump('Check the electrical resistance');

}

}

We created an ElectricOwen class also. We have got two seperate classes and different functions. How can we bind them?

class ElectricOwenAdapter implements OwenInterface

{



/**

* @var ElectricOwenInterface

*/

private $electricOwen;



public function __construct(ElectricOwenInterface $electricOwen)

{

$this->electricOwen = $electricOwen;

}



public function turnOn()

{

$this->electricOwen->pressOnButton();

}



public function checkLeakage()

{

$this->electricOwen->checkResistance();

}

}

As you see this adapter class implements our old and beloved OwenInterface, therefore uses the same functions but in these functions it is integrating our ElectricOwen class’ functions. So we can do something like this;

class Chef {

public function cook(OwenInterface $owen){

$owen->turnOn();

$owen->checkLeakage();

}

}



(new Chef)->cook(new ElectricOwenAdapter(new ElectricOwen));

And what will we have?

string(15) “Press on button”

string(31) “Check the electrical resistance”

But if we use it without adapter we ill just use our old owen class;

(new Chef)->cook(new Owen()); string(15) "Turn the gas on"

string(29) "Check if there is gas leakage"

As you see Adapter Pattern is pretty useful. Without changing function names and the grand logic you can integrate new classes to your system. All the patterns are trying to solve a problem and ease developer’s pain but adapter pattern make it in a really smooth way I think.

As always I‘ll put a link if you want to watch a video.
DRY in Test
Tags: Code Refactoring, Unit Testing, Design Patterns

AAA(Arrange-Act-Assert) Pattern於撰寫測試時經常出現，在寫一個測試案例需要準備測試所需的環境和測試資料，也就是Arrange階段。在此階段經常會需要建立待測物件所需的dependency，如果每個測試案例都經常需要相同的物件，我們可以簡單地透過Factory Method Pattern來避免程式碼重複(DRY, Don’t Repeat Yourself)．如果參數需要做微調則可以利用OOP的Method Overload來達成，在有預設值的情況下想要微調特定參數，如IP位址、裝置名稱，如下所示：

public class DeviceTests {

... private DeviceInfo CreateDeviceInfo() {

return new DeviceInfo(Guid.NewGuid(), IP, NAME, STATE);

} private DeviceInfo CreateDeviceInfo(string ip) {

return new DeviceInfo(Guid.NewGuid(), ip, NAME, STATE);

} private DeviceInfo CreateDeviceInfo(string name) {

return new DeviceInfo(Guid.NewGuid(), IP, name, STATE);

}

}

這樣在Arrage階段建立新的DeviceInfo時可以直接呼叫CreateDeviceInfo()，除此之外，還可以避免將DeviceInfo定義為Field，將測試資料定義在Field不僅會導致日後測試難以維護，可讀性也相當差，且缺乏彈性．如果遇到上面情況需要微調就只能在Test Case中重新new新的DeviceInfo，使用Factory Method使得每個測試更加獨立，不共用Field，在Arrage階段呼叫Factory Method取得新的DeviceInfo還可以讓語意更加明確．

但是，可以看到此程式碼產生了Duplicated Code的情形，因為DeviceInfo是Data Object會有許多資料，測試時因情況需要，微調時就會出現多個函式之間有點像又有點不像的情況．要解決這個問題我們可以透過Builder Pattern來進行封裝，由於每個欄位都有預設值，因此我命名為DefaultBuilder，如下所示：

public class DefaultDeviceInfoBuilder {

private Guid id;

private string ip;

private string name;

private bool state; public DefaultDeviceInfoBuilder() {

id = Guid.NewGuid();

ip = "192.168.0.100";

name = "Default Name";

state = false;

} public DefaultDeviceInfoBuilder SetIp(string ip) {

this.ip = ip;

return this;

}



public DefaultDeviceInfoBuilder SetName(string name) {

this.name = name;

return this;

}



public DeviceInfo Build() {

return new DeviceInfo(id, ip, name, state);

}

} public class DeviceTests {

private DeviceInfo CreateDeviceInfo(string ip) {

return new DefaultDeviceInfoBuilder()

.SetIp(ip)

.Build();

}

}

這樣在建立DeviceInfo時可以避免不必要的重複，也不會對於DeviceInfo的constructor過度依賴，導致constructor改變時測試需要大量的修改，影響範圍太廣等問題．

如果DeviceInfo只在相同Test Class中使用，CreateDeviceInfo() Factory Method放在相同class中就夠了．但如果DeviceInfo也被其他幾個Test Class使用到，就不好在其他測試中也重新定義相同的Factory Method，因為也會違反DRY原則，因此必須將其獨立出Factory Class，如下所示：

public class DefaultDeviceInfoFactory {

public DeviceInfo Create() {

return new DefaultDeviceInfoBuilder().Build();

} public DeviceInfo Create(string ip) {

return new DefaultDeviceInfoBuilder()

.SetIp(ip)

.Build;

}

...

}

可以先定義多個Test Class都需要的Factory Method就好，如果只有一個Test Class需要使用，可以先定義在自己的類別中，等有重複情況時再抽取出來．

結論：測試也需要DRY，把Builder當作特殊微調使用，而Factory Class中的函式則是經常被使用的，可以讓測試更乾淨、更好維護．

參考：

[1] https://reflectoring.io/objectmother-fluent-builder/?fbclid=IwAR2iBT9QiHN0NERycV-2x-6a7PUomvkyBb-rySBFi99vxt0o5CTMbVv-Oqc

[2] https://www.amazon.com/Practical-Object-Oriented-Design-Ruby-Addison-Wesley/dp/0321721330
Business Delegate Design Pattern
By: Daniel Liu
Tags: Java, Design Patterns, Programming, Backend, Backend Development

Overview

The business delegate is used to separate the business side and presentation side. The business side is made up of 4 parts:

Client — The presentation code to display the data

Business Delegate — Provides access to the business service methods which the client uses

LookUp Service — Responsible to get relative business implementation and provides business object access to business delegate object

Business Service — The concrete class implements the business service interface to provide business implementation logic

Photo by Charles Forerunner on Unsplash

Implementation

BusinessService.java

public interface BusinessService {

public void doSomething();

}

The business interface that the concrete class implements

ServiceOne.java

public class ServiceOne implements BusinessService {

@Override

public void doSomething() {

System.out.println("Something One!");

}

}

ServiceOne.java

public class ServiceTwo implements BusinessService {

@Override

public void doSomething() {

System.out.println("Something Two!");

}

}

The concrete business service that implements the business interface.

LookUp.java

public class LookUp {

public BusinessService getBusinessService(String serviceType){

if(serviceType.equalsIgnoreCase("one")){

return new ServiceOne();

}

else {

return new ServiceTwo();

}

}

}

LookUp service provides the concrete business service based on the string provided.

BusinessDelegate.java

public class BusinessDelegate {

private LookUp lookupService = new LookUp();

private BusinessService businessService;

private String serviceType;



public void setServiceType(String serviceType){

this.serviceType = serviceType;

}



public void doTask(){

businessService = lookupService.getBusinessService(serviceType);

businessService.doSomething();

}

}

The business delegate is what the client uses to access the business service. The client can change which service to use based on the service type.

Client.java

public class Client {

BusinessDelegate businessDelegate;



public Client(BusinessDelegate businessDelegate){

this.businessDelegate = businessDelegate;

}



public void doTask(){

businessService.doTask();

}

}

Demo.java

public class Demo {

public static void main(String[] args) {

BusinessDelegate businessDelegate = new BusinessDelegate();

businessDelegate.setServiceType("one");



Client client = new Client(businessDelegate);

client.doTask();



businessDelegate.setServiceType("two");

client.doTask();

}

} >> Something One!

>> Something Two!

Conclusion

The business delegate design pattern was more popular in the early days with Enterprise Java Beans(EJB). Now with the popularity of Spring and dependency inject this design pattern has lost a lot of significance. But when it is used it reduces coupling with the business and client side and it hides the implementation of the business service. However, it adds an extra layer so it increase the effort needed to maintain the code.
Adding/ Removing Mirrors into my personal space
By: Zainab Alkhamis
Tags: Feng Shui Tips, Positive Energy, Mirror, Interior Design Tips, Design Patterns

Growing up, you definitely had a lot of mirrors in your house. The biggest mirrors you had to look at were presumably meant for the bathroom and maybe the dining room. That said, now we know that mirrors can do so much more to shape the interior of our houses or office space etc. The look, sound and overall presence of your home can be enormously affected by high-quality glass mirrors. How are they willing to do that? It’s commonly known that mirrors brighten, and widen any room if placed properly.

Since we have been all quarantined, we all had the urge to redecorate, and be creative in our space since we’re spending more time behind these walls. I was redecorating my bedroom, which I haven’t done in over ten years. I wanted to do some research on mirrors, and see how much can they define the space? does it make any difference? Is having too many mirrors a good thing? Does size matter? Is the location important? I have found that mirrors optimize natural light when positioned in the correct direction especially if the room or space you’re decorating has a window. If you’re looking into adding/removing mirrors for your bedroom, according to Feng shiu, adding a mirror into the bedroom can improve the quality of sleep. It’s believed that it cultivates the energy in the room, and destress. But, it’s important not to add the mirror opposite to the bed.

If the room doesn’t have a window, for example, a main entry, then adding mirrors will expand the space, give a sense of luxury, and doesn’t hurt to check yourself out before you head out to set those affirmations one more time. Essentially, if you want to double the amount of good energy radiating from something you can add a mirror, like on top of a fireplace, or in front of a dinning room dinner table.

However these are the positions that shouldn’t be considered for a mirror, they are areas where the person should be focused in what they’re doing for example, in front of a staircase, kitchen, in front of your study/work desk, and in front of the bed.

Recollect where you’ve seen major mirrors lately. Within offices, salons, and even wellness centers, you have undoubtedly seen large mirrors. For a common intention, both of these locations add mirrors to create a sharp, professional appearance. Mirrors that have been professionally framed, and mounted will give even the most informal of rooms a touch of class.

Hope my thoughts can get you to research more into adding mirrors, and investing in a bulk purchase of mirrors.