kandi background
Explore Kits

diagrams | : art : Diagram as Code for prototyping cloud system | Architecture library

 by   mingrammer Python Version: v0.21.1 License: MIT

 by   mingrammer Python Version: v0.21.1 License: MIT

Download this library from

kandi X-RAY | diagrams Summary

diagrams is a Python library typically used in Architecture, Docker applications. diagrams has no bugs, it has no vulnerabilities, it has a Permissive License and it has high support. However diagrams build file is not available. You can download it from GitHub.
Diagrams lets you draw the cloud system architecture in Python code. It was born for prototyping a new system architecture design without any design tools. You can also describe or visualize the existing system architecture as well. Diagrams currently supports main major providers including: AWS, Azure, GCP, Kubernetes, Alibaba Cloud, Oracle Cloud etc... It also supports On-Premise nodes, SaaS and major Programming frameworks and languages. Diagram as Code also allows you to track the architecture diagram changes in any version control system. NOTE: It does not control any actual cloud resources nor does it generate cloud formation or terraform code. It is just for drawing the cloud system architecture diagrams.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • diagrams has a highly active ecosystem.
  • It has 16552 star(s) with 969 fork(s). There are 272 watchers for this library.
  • There were 2 major release(s) in the last 12 months.
  • There are 190 open issues and 145 have been closed. On average issues are closed in 20 days. There are 66 open pull requests and 0 closed requests.
  • It has a negative sentiment in the developer community.
  • The latest version of diagrams is v0.21.1
diagrams Support
Best in #Architecture
Average in #Architecture
diagrams Support
Best in #Architecture
Average in #Architecture

quality kandi Quality

  • diagrams has 0 bugs and 0 code smells.
diagrams Quality
Best in #Architecture
Average in #Architecture
diagrams Quality
Best in #Architecture
Average in #Architecture

securitySecurity

  • diagrams has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • diagrams code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
diagrams Security
Best in #Architecture
Average in #Architecture
diagrams Security
Best in #Architecture
Average in #Architecture

license License

  • diagrams is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
diagrams License
Best in #Architecture
Average in #Architecture
diagrams License
Best in #Architecture
Average in #Architecture

buildReuse

  • diagrams releases are available to install and integrate.
  • diagrams has no build file. You will be need to create the build yourself to build the component from source.
  • Installation instructions, examples and code snippets are available.
  • diagrams saves you 2043 person hours of effort in developing the same functionality from scratch.
  • It has 5624 lines of code, 120 functions and 220 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
diagrams Reuse
Best in #Architecture
Average in #Architecture
diagrams Reuse
Best in #Architecture
Average in #Architecture
Top functions reviewed by kandi - BETA

kandi has reviewed diagrams and discovered the below as its top functions. This is intended to give you an instant insight into diagrams implemented functionality, and help decide if they suit your requirements.

  • Initialize graph .
  • Generate the apidoc for the given pvd .
  • Generate documentation for the given PVD .
  • Connect two nodes .
  • Generate class .
  • Convert SVG to PNG .
  • Clean file name .
  • Clean png files .
  • Round PNG files .
  • Convert SVG to PNG .

diagrams Key Features

:art: Diagram as Code for prototyping cloud system architectures

Getting Started

copy iconCopydownload iconDownload
# using pip (pip3)
$ pip install diagrams

# using pipenv
$ pipenv install diagrams

# using poetry
$ poetry add diagrams

Plot Venn diagram from a boolean set notation in Python

copy iconCopydownload iconDownload
/usr/local/lib/python3.7/dist-packages/matplotlib_venn/_common.py in get_patch_by_id(self, id)
     29            A region id is a string '10', '01' or '11' for 2-circle diagram or a
     30            string like '001', '010', etc, for 3-circle diagram.'''
---> 31         return self.patches[self.id2idx[id]]
     32 
     33     def get_label_by_id(self, id):

KeyError: '000
from matplotlib import pyplot as plt
from matplotlib_venn import venn3, venn3_circles
from itertools import product

def list_regions(formula):
    
    for x in product([False, True], repeat=3):
        if eval(formula, {}, dict(zip('ABC', x))):
            yield ''.join(str(int(x_i)) for x_i in x)

def plot_diagram(formula):
    plt.figure(figsize=(6,6))
    v = venn3(subsets=[1]*7,
              set_colors=['white']*3,
              subset_label_formatter=lambda x: '')
    c = venn3_circles(subsets=[1]*7, linestyle='solid')
    for region in list_regions(formula):
      if region!='000':
        v.get_patch_by_id(region).set_color('black')
    plt.show()

plot_diagram('not B')
plot_diagram('A or (not B)')
-----------------------
/usr/local/lib/python3.7/dist-packages/matplotlib_venn/_common.py in get_patch_by_id(self, id)
     29            A region id is a string '10', '01' or '11' for 2-circle diagram or a
     30            string like '001', '010', etc, for 3-circle diagram.'''
---> 31         return self.patches[self.id2idx[id]]
     32 
     33     def get_label_by_id(self, id):

KeyError: '000
from matplotlib import pyplot as plt
from matplotlib_venn import venn3, venn3_circles
from itertools import product

def list_regions(formula):
    
    for x in product([False, True], repeat=3):
        if eval(formula, {}, dict(zip('ABC', x))):
            yield ''.join(str(int(x_i)) for x_i in x)

def plot_diagram(formula):
    plt.figure(figsize=(6,6))
    v = venn3(subsets=[1]*7,
              set_colors=['white']*3,
              subset_label_formatter=lambda x: '')
    c = venn3_circles(subsets=[1]*7, linestyle='solid')
    for region in list_regions(formula):
      if region!='000':
        v.get_patch_by_id(region).set_color('black')
    plt.show()

plot_diagram('not B')
plot_diagram('A or (not B)')
-----------------------
/usr/local/lib/python3.7/dist-packages/matplotlib_venn/_common.py in get_patch_by_id(self, id)
     29            A region id is a string '10', '01' or '11' for 2-circle diagram or a
     30            string like '001', '010', etc, for 3-circle diagram.'''
---> 31         return self.patches[self.id2idx[id]]
     32 
     33     def get_label_by_id(self, id):

KeyError: '000
from matplotlib import pyplot as plt
from matplotlib_venn import venn3, venn3_circles
from itertools import product

def list_regions(formula):
    
    for x in product([False, True], repeat=3):
        if eval(formula, {}, dict(zip('ABC', x))):
            yield ''.join(str(int(x_i)) for x_i in x)

def plot_diagram(formula):
    plt.figure(figsize=(6,6))
    v = venn3(subsets=[1]*7,
              set_colors=['white']*3,
              subset_label_formatter=lambda x: '')
    c = venn3_circles(subsets=[1]*7, linestyle='solid')
    for region in list_regions(formula):
      if region!='000':
        v.get_patch_by_id(region).set_color('black')
    plt.show()

plot_diagram('not B')
plot_diagram('A or (not B)')
-----------------------
/usr/local/lib/python3.7/dist-packages/matplotlib_venn/_common.py in get_patch_by_id(self, id)
     29            A region id is a string '10', '01' or '11' for 2-circle diagram or a
     30            string like '001', '010', etc, for 3-circle diagram.'''
---> 31         return self.patches[self.id2idx[id]]
     32 
     33     def get_label_by_id(self, id):

KeyError: '000
from matplotlib import pyplot as plt
from matplotlib_venn import venn3, venn3_circles
from itertools import product

def list_regions(formula):
    
    for x in product([False, True], repeat=3):
        if eval(formula, {}, dict(zip('ABC', x))):
            yield ''.join(str(int(x_i)) for x_i in x)

def plot_diagram(formula):
    plt.figure(figsize=(6,6))
    v = venn3(subsets=[1]*7,
              set_colors=['white']*3,
              subset_label_formatter=lambda x: '')
    c = venn3_circles(subsets=[1]*7, linestyle='solid')
    for region in list_regions(formula):
      if region!='000':
        v.get_patch_by_id(region).set_color('black')
    plt.show()

plot_diagram('not B')
plot_diagram('A or (not B)')
-----------------------
from matplotlib import pyplot as plt
from matplotlib_venn import venn3, venn3_circles

def list_regions(formula):
    from itertools import product    
    for x in product([False, True], repeat=3):
        if eval(formula, {}, dict(zip('ABC', x))):
            yield ''.join(str(int(x_i)) for x_i in x)

def plot_diagram(formula):
    f = plt.figure(figsize=(6,6))
    v = venn3(alpha=1.0,
              subsets=[1]*7,
              set_colors=['white']*3,
              subset_label_formatter=lambda x: '')
    c = venn3_circles(subsets=[1]*7, linestyle='solid')
    for region in list_regions(formula):
      if region == '000':
        f.gca().set_facecolor('grey')
      else:
        v.get_patch_by_id(region).set_color('grey')
    plt.annotate('U', (-0.657, 0.557)); plt.axis('on')
    plt.show()

ggplot2: Projecting points or distribution on a non-orthogonal (eg, -45 degree) axis

copy iconCopydownload iconDownload
(my_hist <- df %>%
    mutate(gain = final - initial) %>% # gain would be better name
    ggplot(aes(gain)) +
    geom_density())
a <- ggplot_build(my_hist)
rot = pi * 3/4
diag_hist <- tibble(
  x = a[["data"]][[1]][["x"]],
  y = a[["data"]][[1]][["y"]]
) %>%
  # squish
  mutate(y = y*0.2) %>%
  # rotate 135 deg CCW
  mutate(xy = x*cos(rot) - y*sin(rot),
         dens = x*sin(rot) + y*cos(rot)) %>%
  # slide
  mutate(xy = xy - 0.7,  #  magic number based on plot range below
         dens = dens - 0.7)
ggplot(df, aes(x = initial, y = final, color = group)) +
  geom_point() + 
  geom_smooth(method = "lm", formula  =  y~x) +
  stat_ellipse(size = 1.2) +
  geom_abline(slope  =  1, color = "black", size = 1.2) +
  coord_fixed(clip = "off", 
              xlim = c(-0.7,1.6),
              ylim = c(-0.7,1.6), 
              expand = expansion(0)) +
  annotate("segment", x = -1.4, xend = 0, y = 0, yend = -1.4) +
  annotate("path", x = diag_hist$xy, y = diag_hist$dens) +
  theme_bw() +
  theme(legend.position = c(.15, .85), 
        plot.margin = unit(c(.1,.1,2,2), "cm")) 
-----------------------
(my_hist <- df %>%
    mutate(gain = final - initial) %>% # gain would be better name
    ggplot(aes(gain)) +
    geom_density())
a <- ggplot_build(my_hist)
rot = pi * 3/4
diag_hist <- tibble(
  x = a[["data"]][[1]][["x"]],
  y = a[["data"]][[1]][["y"]]
) %>%
  # squish
  mutate(y = y*0.2) %>%
  # rotate 135 deg CCW
  mutate(xy = x*cos(rot) - y*sin(rot),
         dens = x*sin(rot) + y*cos(rot)) %>%
  # slide
  mutate(xy = xy - 0.7,  #  magic number based on plot range below
         dens = dens - 0.7)
ggplot(df, aes(x = initial, y = final, color = group)) +
  geom_point() + 
  geom_smooth(method = "lm", formula  =  y~x) +
  stat_ellipse(size = 1.2) +
  geom_abline(slope  =  1, color = "black", size = 1.2) +
  coord_fixed(clip = "off", 
              xlim = c(-0.7,1.6),
              ylim = c(-0.7,1.6), 
              expand = expansion(0)) +
  annotate("segment", x = -1.4, xend = 0, y = 0, yend = -1.4) +
  annotate("path", x = diag_hist$xy, y = diag_hist$dens) +
  theme_bw() +
  theme(legend.position = c(.15, .85), 
        plot.margin = unit(c(.1,.1,2,2), "cm")) 
-----------------------
(my_hist <- df %>%
    mutate(gain = final - initial) %>% # gain would be better name
    ggplot(aes(gain)) +
    geom_density())
a <- ggplot_build(my_hist)
rot = pi * 3/4
diag_hist <- tibble(
  x = a[["data"]][[1]][["x"]],
  y = a[["data"]][[1]][["y"]]
) %>%
  # squish
  mutate(y = y*0.2) %>%
  # rotate 135 deg CCW
  mutate(xy = x*cos(rot) - y*sin(rot),
         dens = x*sin(rot) + y*cos(rot)) %>%
  # slide
  mutate(xy = xy - 0.7,  #  magic number based on plot range below
         dens = dens - 0.7)
ggplot(df, aes(x = initial, y = final, color = group)) +
  geom_point() + 
  geom_smooth(method = "lm", formula  =  y~x) +
  stat_ellipse(size = 1.2) +
  geom_abline(slope  =  1, color = "black", size = 1.2) +
  coord_fixed(clip = "off", 
              xlim = c(-0.7,1.6),
              ylim = c(-0.7,1.6), 
              expand = expansion(0)) +
  annotate("segment", x = -1.4, xend = 0, y = 0, yend = -1.4) +
  annotate("path", x = diag_hist$xy, y = diag_hist$dens) +
  theme_bw() +
  theme(legend.position = c(.15, .85), 
        plot.margin = unit(c(.1,.1,2,2), "cm")) 

Adjust mermaid diagram white space in Azure devops wiki

copy iconCopydownload iconDownload
::: mermaid
graph TD
%%{init: {"flowchart": { "useMaxWidth": false } }}%%
A[Author sends a review to the customer success email] -->|Dynamics 365 creates a review case based on the Knowledge Base Article Review Template| B[[Automation]]
B --> D[D365 creates a review case based on the Knowledge Base Article Review Template]
B --> E[D365 places the review article in the Article Review Queue]
D -->F[Dynamics 365 creates a review case based on the Knowledge Base Article Review Template]
E -->F[A customer success agent assigns themself as the owner for the article]
F -->G[[D365 sends a notification of the new owner to the TDT email]]
G -->H[In Madcap Central, the Flare author reassigns article review from the cus success email to the assigned Owner for the review case]
H -->I[Agent completes review in Madcap Central and submit it to Flare Author]
I -->J[Agent closes the review case in D365]
J -->K[Flare author receives notification of returned review via Madcap Central email]
K -->L[Flare author implements changes in Flare and accepts the file]
L -->M[Flare author synchronizes project with source control]
:::

How are Haskell Monad laws derived from Monoid laws?

copy iconCopydownload iconDownload
(x >>= y) = join (fmap y x)
return a >>= k = k a
join (fmap k (return a)) = k a
join (return (k a)) = k a
m >>= return = m
join (fmap return m) = m
-----------------------
(x >>= y) = join (fmap y x)
return a >>= k = k a
join (fmap k (return a)) = k a
join (return (k a)) = k a
m >>= return = m
join (fmap return m) = m
-----------------------
(x >>= y) = join (fmap y x)
return a >>= k = k a
join (fmap k (return a)) = k a
join (return (k a)) = k a
m >>= return = m
join (fmap return m) = m
-----------------------
(x >>= y) = join (fmap y x)
return a >>= k = k a
join (fmap k (return a)) = k a
join (return (k a)) = k a
m >>= return = m
join (fmap return m) = m
-----------------------
(x >>= y) = join (fmap y x)
return a >>= k = k a
join (fmap k (return a)) = k a
join (return (k a)) = k a
m >>= return = m
join (fmap return m) = m
-----------------------
(x >>= y) = join (fmap y x)
return a >>= k = k a
join (fmap k (return a)) = k a
join (return (k a)) = k a
m >>= return = m
join (fmap return m) = m

plotly sankey graph data formatting

copy iconCopydownload iconDownload
import pandas as pd
import numpy as np
import plotly.graph_objects as go

links = [
    {'source': 'start', 'target': 'A', 'value': 2},
    {'source': 'A', 'target': 'B', 'value': 1},
    {'source': 'A', 'target':'C', 'value':.5}

]

df = pd.DataFrame(links)
nodes = np.unique(df[["source","target"]], axis=None)
nodes = pd.Series(index=nodes, data=range(len(nodes)))

go.Figure(
    go.Sankey(
        node={"label": nodes.index},
        link={
            "source": nodes.loc[df["source"]],
            "target": nodes.loc[df["target"]],
            "value": df["value"],
        },
    )
)

How to Download pdf using python selenium in google colab

copy iconCopydownload iconDownload
!pip install selenium
!apt-get update # to update ubuntu to correctly run apt install
!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin
import sys
sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('chromedriver',chrome_options=chrome_options)
from google.colab import drive
drive.mount('/content/gdrive')
response = requests.get(link)
path = "gdrive/My Drive/" + "filename" + ".pdf"
with open(path, "wb") as file:
  file.write(response.content)
-----------------------
!pip install selenium
!apt-get update # to update ubuntu to correctly run apt install
!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin
import sys
sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('chromedriver',chrome_options=chrome_options)
from google.colab import drive
drive.mount('/content/gdrive')
response = requests.get(link)
path = "gdrive/My Drive/" + "filename" + ".pdf"
with open(path, "wb") as file:
  file.write(response.content)
-----------------------
!pip install selenium
!apt-get update # to update ubuntu to correctly run apt install
!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin
import sys
sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('chromedriver',chrome_options=chrome_options)
from google.colab import drive
drive.mount('/content/gdrive')
response = requests.get(link)
path = "gdrive/My Drive/" + "filename" + ".pdf"
with open(path, "wb") as file:
  file.write(response.content)

How to calculate the Precedence Matrix in Python?

copy iconCopydownload iconDownload
class PrecedenceDiagram():
    def __init__(self, mode = 'relative'):
        # {<str> origin : { <str> destination: <int> frequency, ... } }
        self.graph = dict()
        self.flow_amount = 0
        self.mode = mode
    
    def update(self, origin, destination):
        '''
        increment frequency if origin exists and destination is in
        origin else instantiate origin/destination appropriately
        '''
        if origin in self.graph:
            if destination in self.graph[origin]:
                self.graph[origin][destination] += 1
            else:
                self.graph[origin][destination] = 1
        else:
            self.graph[origin] = dict()
            self.graph[origin][destination] = 1
        self.flow_amount += 1

    def display_precedence(self):
        '''
        display flow frequency
        '''
        print('O','D','f')
        for node, edges in self.graph.items():
            for edge, weight in edges.items():
                if self.mode == 'absolute':
                    print(node, edge, weight)
                elif self.mode == 'relative':
                    print(node, edge, weight/ self.flow_amount)
        print('-'*16)


pm = PrecedenceDiagram(mode='relative')
pm.update('a', 'b')
pm.update('b', 'c')
pm.update('a', 'b')
pm.update('a', 'b')
pm.update('a', 'd')
pm.update('a', 'e')
pm.update('e', 'a')
pm.update('a', 'n')
pm.update('a', 'b')
pm.update('a', 'b')
pm.update('a', 'b')
pm.display_precedence()
pm.mode = 'absolute'
pm.display_precedence()
-----------------------
import pandas as pd
import pm4py

df = pm4py.format_dataframe(pd.read_csv('https://raw.githubusercontent.com/pm4py/pm4py-core/release/notebooks/data/running_example.csv', sep=';'), case_id='case_id',activity_key='activity', timestamp_key='timestamp')
from pm4py.objects.conversion.log import converter as log_converter
log = log_converter.apply(df)
d = pm4py.discover_dfg(log)[0]
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
df.rename(columns={"index" : "Antecedent,Consequent", 0 : "Count"}, inplace=True)
df['Antecedent'], df['Consequent'] = zip(*df["Antecedent,Consequent"])
-----------------------
import pandas as pd
import pm4py

df = pm4py.format_dataframe(pd.read_csv('https://raw.githubusercontent.com/pm4py/pm4py-core/release/notebooks/data/running_example.csv', sep=';'), case_id='case_id',activity_key='activity', timestamp_key='timestamp')
from pm4py.objects.conversion.log import converter as log_converter
log = log_converter.apply(df)
d = pm4py.discover_dfg(log)[0]
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
df.rename(columns={"index" : "Antecedent,Consequent", 0 : "Count"}, inplace=True)
df['Antecedent'], df['Consequent'] = zip(*df["Antecedent,Consequent"])
-----------------------
import pandas as pd
import pm4py

df = pm4py.format_dataframe(pd.read_csv('https://raw.githubusercontent.com/pm4py/pm4py-core/release/notebooks/data/running_example.csv', sep=';'), case_id='case_id',activity_key='activity', timestamp_key='timestamp')
from pm4py.objects.conversion.log import converter as log_converter
log = log_converter.apply(df)
d = pm4py.discover_dfg(log)[0]
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
df.rename(columns={"index" : "Antecedent,Consequent", 0 : "Count"}, inplace=True)
df['Antecedent'], df['Consequent'] = zip(*df["Antecedent,Consequent"])
-----------------------
import pandas as pd
import pm4py

df = pm4py.format_dataframe(pd.read_csv('https://raw.githubusercontent.com/pm4py/pm4py-core/release/notebooks/data/running_example.csv', sep=';'), case_id='case_id',activity_key='activity', timestamp_key='timestamp')
from pm4py.objects.conversion.log import converter as log_converter
log = log_converter.apply(df)
d = pm4py.discover_dfg(log)[0]
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
df.rename(columns={"index" : "Antecedent,Consequent", 0 : "Count"}, inplace=True)
df['Antecedent'], df['Consequent'] = zip(*df["Antecedent,Consequent"])

In R, how to display value on the links/paths of Sankey Graph?

copy iconCopydownload iconDownload
library(htmlwidgets)
library(networkD3)

nodes <- 
  data.frame(
    name = c("Node A", "Node B", "Node C", "Node D")
  )

links <- 
  data.frame(
    source = c(0, 0, 1, 2),
    target = c(1, 2, 3, 3),
    value = c(10, 20, 30, 40)
  )

p <- sankeyNetwork(Links = links, Nodes = nodes,
                   Source = "source", Target = "target",
                   Value = "value", NodeID = "name",
                   fontSize= 20, nodeWidth = 30)

htmlwidgets::onRender(p, '
  function(el) { 
    var nodeWidth = this.sankey.nodeWidth();
    var links = this.sankey.links();
        
    links.forEach((d, i) => {
      var startX = d.source.x + nodeWidth;
      var endX = d.target.x;
      
      var startY = d.source.y + d.sy + d.dy / 2;
      var endY = d.target.y + d.ty + d.dy / 2;
      
      d3.select(el).select("svg g")
        .append("text")
        .attr("text-anchor", "middle")
        .attr("alignment-baseline", "middle")
        .attr("x", startX + ((endX - startX) / 2))
        .attr("y", startY + ((endY - startY) / 2))
        .text(d.value);
    })
  }
')

RXJS Show accumulated result within a timerange

copy iconCopydownload iconDownload
stream$.pipe(
  mergeMap((value) => {
    const add$ = of({ type: 'ENTER', value });
    const remove$ = of({ type: 'EXIT', value }).pipe(delay(60e3));
    return merge(add$, remove$);
  }),
  scan((state, { type, value }) => {
    switch (type) {
      case 'ENTER':
        return { ...state, [value]: (state[value] || 0) + 1 };
      case 'EXIT':
        return { ...state, [value]: state[value] - 1 };
      default:
        return state;
    }
  }, {})
);
-----------------------
//  accumulator$ is the Observable that emits the values accumulated in the last minute
// source$ is the source Observable
const accumulator$ = source$.pipe(
  // first thing we add to each element notified by source$ the timestamp of when it is notified
  map((d) => ({ val: d, ts: Date.now() })),
  // then we use the scan operator to emit a new accumulator everytime a new
  // value is received from upstream
  scan((acc, val) => {
    const now = val.ts;
    // only the values which are not older than xxx time, in this case xxx is
    // 1000 milliseconds
    acc = acc.filter((o) => now - o.ts < 1000);
    // the last value received is added to the accumulator
    acc.push(val);
    return acc;
  }, []),
  map((accArray) =>
    // in this last transformation we transform the array in an object which contains
    // the occurrences of each value in the last minute using the reduce method
    // of javascript Array, not to be confused with the reduce operator of rxJs
    accArray.reduce((accObj, el) => {
      if (!accObj[el.val]) {
        accObj[el.val] = 0;
      }
      accObj[el.val] = accObj[el.val] + 1;
      return accObj;
    }, {})
  )
);

Jest fails with 'self is not defined' when importing react-diagrams

copy iconCopydownload iconDownload
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
};
{
  "name": "jest-test",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "jest": "^26.6.3",
    "ts-jest": "^26.5.2"
  },
  "scripts": {
    "test": "jest"
  },
  "dependencies": {
    "@emotion/react": "^11.1.5",
    "@emotion/styled": "^11.3.0",
    "@projectstorm/react-canvas-core": "^6.5.2",
    "@projectstorm/react-diagrams": "^6.5.2",
    "@projectstorm/react-diagrams-routing": "^6.5.2",
    "closest": "^0.0.1",
    "dagre": "^0.8.5",
    "pathfinding": "^0.4.18",
    "paths-js": "^0.4.11",
    "react": "^17.0.2",
    "resize-observer-polyfill": "^1.5.1"
  }
}
-----------------------
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
};
{
  "name": "jest-test",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "jest": "^26.6.3",
    "ts-jest": "^26.5.2"
  },
  "scripts": {
    "test": "jest"
  },
  "dependencies": {
    "@emotion/react": "^11.1.5",
    "@emotion/styled": "^11.3.0",
    "@projectstorm/react-canvas-core": "^6.5.2",
    "@projectstorm/react-diagrams": "^6.5.2",
    "@projectstorm/react-diagrams-routing": "^6.5.2",
    "closest": "^0.0.1",
    "dagre": "^0.8.5",
    "pathfinding": "^0.4.18",
    "paths-js": "^0.4.11",
    "react": "^17.0.2",
    "resize-observer-polyfill": "^1.5.1"
  }
}

Community Discussions

Trending Discussions on diagrams
  • saveWidget works interactively, but no file saved when using buildVignette
  • Big O Understand Quadratic n(n+1)/2 diagram
  • Plot Venn diagram from a boolean set notation in Python
  • ggplot2: Projecting points or distribution on a non-orthogonal (eg, -45 degree) axis
  • What does composition mean in the composition vs inheritance debate?
  • Independent Thread Scheduling since Volta
  • How to represent communication protocol in UML?
  • Adjust mermaid diagram white space in Azure devops wiki
  • Including a create message inside a combined fragment in sequence diagram
  • Does UML shared aggregation imply absence of cycles?
Trending Discussions on diagrams

QUESTION

saveWidget works interactively, but no file saved when using buildVignette

Asked 2022-Apr-11 at 17:06

When I run the following code interactively, the expected testFig.html is produced and functions correctly.

suppressPackageStartupMessages(library("plotly"))
suppressPackageStartupMessages(library("htmlwidgets"))

  DF <- data.frame(
  x <- rnorm(50),
  y <- rnorm(50),
  z <- rnorm(50))

  fig <- plot_ly(
    name = "data", DF, x = ~x, y = ~y, z = ~z,
    marker = list(size = 2.0)) %>% add_markers()
  saveWidget(partial_bundle(fig), "testFig.html", knitrOptions = list(results = "show"))

However, if the above code is placed in a vignette, and buildVignette is used, testFig.html is not produced and hence there is a placeholder in the vignette saying file not found. No errors or warnings are emitted. The vignette code is appended below. Save it as Vignette.Rmd and then do buildVignette("Vignette.Rmd") to see the result.

This is a minimal example of a larger project that worked fine about 5 weeks ago but has recently started acting as described above. I've checked against older versions of R and the packages in use and get the same behavior. As a result I am totally stumped.

---
title:  "Test Vignette"
date:  "`r Sys.Date()`"
output:
    bookdown::html_document2:
      toc: yes
      toc_depth: 2
      fig_caption: yes
      number_sections: false
vignette: >
    %\VignetteIndexEntry{Vignette}
    %\VignetteEngine{knitr::rmarkdown}
    %\VignetteEncoding{UTF-8}
pkgdown:
  as_is: true
---

```{r SetUp, echo = FALSE, eval = TRUE, results = "hide"}
# R options & configuration:
set.seed(13)
suppressPackageStartupMessages(library("knitr"))
suppressPackageStartupMessages(library("plotly"))
suppressPackageStartupMessages(library("htmlwidgets"))

# Stuff specifically for knitr:
opts_chunk$set(eval = TRUE, echo = FALSE)
```

**Test Vignette**

Trying to troubleshoot a problem with interactive diagrams not being included.

```{r testFig, results = "show"}

if (!is_latex_output()) {
  DF <- data.frame(
  x <- rnorm(50),
  y <- rnorm(50),
  z <- rnorm(50))

  fig <- plot_ly(
    name = "data", DF, x = ~x, y = ~y, z = ~z,
    marker = list(size = 2.0)) %>%
    add_markers()
  saveWidget(partial_bundle(fig), "testFig.html", knitrOptions = list(results = "show"))
  include_url("testFig.html")
}
> sessionInfo()
R version 4.2.0 alpha (2022-04-05 r82100)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Monterey 12.3.1

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] htmlwidgets_1.5.4 plotly_4.10.0     ggplot2_3.3.5     knitr_1.38       

loaded via a namespace (and not attached):
 [1] magrittr_2.0.3    tidyselect_1.1.2  munsell_0.5.0     viridisLite_0.4.0 colorspace_2.0-3 
 [6] R6_2.5.1          rlang_1.0.2       fastmap_1.1.0     fansi_1.0.3       httr_1.4.2       
[11] dplyr_1.0.8       tools_4.2.0       grid_4.2.0        data.table_1.14.2 gtable_0.3.0     
[16] xfun_0.30         utf8_1.2.2        cli_3.2.0         withr_2.5.0       htmltools_0.5.2  
[21] ellipsis_0.3.2    lazyeval_0.2.2    digest_0.6.29     tibble_3.1.6      lifecycle_1.0.1  
[26] crayon_1.5.1      tidyr_1.2.0       purrr_0.3.4       vctrs_0.4.0       glue_1.6.2       
[31] compiler_4.2.0    pillar_1.7.0      generics_0.1.2    scales_1.1.1      jsonlite_1.8.0   
[36] pkgconfig_2.0.3  

ANSWER

Answered 2022-Apr-11 at 17:06

As noted in the comments to the question, the solution to the question asked is to put the file produced in a folder in the vignette directory. This protects the necessary files from being deleted when using buildVignette. However, this approach does not work when building and checking a package. I will ask a separate question on that.

Source https://stackoverflow.com/questions/71788938

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install diagrams

It requires Python 3.6 or higher, check your Python version first. It uses Graphviz to render the diagram, so you need to install Graphviz to use diagrams. After installing graphviz (or already have it), install the diagrams. macOS users can download the Graphviz via brew install graphviz if you're using Homebrew.

Support

To contribute to diagram, check out contribution guidelines. Let me know if you are using diagrams! I'll add you in showcase page. (I'm working on it!) :).

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Reuse Pre-built Kits with diagrams
Compare Architecture Libraries with Permissive License
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.