jeudi 4 août 2022

How to restrict available parent functions child class users can call

I have a StringIntTable based on a HashMap<String, Integer>.
It's with a single purpose: to produce as a perfect min hash for distinct Strings (each String will have a unique int associated).
Implementation is simple as demonstrated in the code, by extending HashMap<String, Integer> and a special put method to produce unique integer for each String. In the end the class will have a String -> int hash mapping and I can easily query the hash value given a String by stringIntTable.get("stringValue").

However, my concern is that it will work only if callers are only calling the special put(final String string) method to add values in. If they call parent HashMap functions like put(K key, V value) or putAll, it would beat the purpose.
Therefore, I'm wondering if there's a way for me to restrict StringIntTable users to only call the put method but not other similar HashMap functions to put new values in?

public class StringIntTable extends HashMap<String, Integer> {
    public int put(final String string) {
        return super.computeIfAbsent(string, v -> super.size() + 1);
    }
}

One way I can think of, is to use the adapter pattern.
The drawback being that I'll have to provide functions like lookup() and size(), which are readily available if using previous implementation.

public class StringIntTable {
    private final HashMap<String> stringLookup = new HashMap<>();

    public int put(final String string) {
        return stringLookup.computeIfAbsent(string, v -> stringLookup.size() + 1);
    }

    // Have to write more functions

    public int lookup(final String string) {
        return stringLookup.get(string);
    }

    public int size() {
        return stringLookup.size();
    }

    ...
}

Feedback on current iteration of React code

I am looking for feedback regarding this React code I am writing. I previously posted when I first started out on this and I have since iterated on it and tried to implement best practices. I am learning a lot and I cannot help, but feel that my current code is clunky. In what ways can I improve the design?

I am having a hard time figuring out what needs to be a component, what needs to be a function, and what can just be a value (even then whether it should be state). I also feel like I am misusing variable scope, but I can't put my finger on how. One specific thing I cannot resolve is ESlint is highlighting mostly everything in my file with this error "Function component is not a function declaration". Any and all feedback is appreciated. Thank you!

/* eslint-disable react/prop-types */
/* eslint-disable no-underscore-dangle */
import axios from 'axios';
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { GetWishes, InsertWish } from './apis';

// Main component, acts a wrapper for the entire screen content
const Wishlist = () => {
  const [loading, setLoading] = useState('initial');
  const [listOfWishes, setListOfWishes] = useState('default');

  // Passed down to update the main list state
  function updateListOfWishes(list) {
    setListOfWishes([...list]);
  }

  // Sorting lists dynamically
  function dynamicSort(property) {
    let sortOrder = 1;
    let newprop = '';
    if (property[0] === '-') {
      sortOrder = -1;
      newprop = property.substr(1);
    }
    return (a, b) => {
      let result = 0;
      if ((a[newprop] < b[newprop])) {
        result = -1;
      } else if (a[newprop] > b[newprop]) {
        result = 1;
      }
      return result * sortOrder;
    };
  }

  // Get all items from DB, this is main list
  async function GetWishesList() {
    try {
      const apiresp = await GetWishes();
      apiresp.sort(dynamicSort('-source'));
      const goodlist = apiresp.map((item) => ({ ...item, isReadOnly: true, show: true }));

      setListOfWishes(goodlist);
      setLoading('false');
    } catch (e) {
      console.log(`Error in Wishlist.GetWishesList: ${e.message}`);
    }
  }

  // Only once, get items and set loading state
  useEffect(() => {
    setLoading('true');
    GetWishesList();
  }, []);

  if (loading === 'initial') {
    return <h2 className="content">Initializing...</h2>;
  }

  if (loading === 'true') {
    return <h2 className="content">Loading...</h2>;
  }

  // Return header and content, pass down function for deep state update
  return (
    <div className="contentwrapper">
      <WishlistHeader fullList={listOfWishes} updateListOfWishes={updateListOfWishes} />
      <WishTable fullList={listOfWishes} updateListOfWishes={updateListOfWishes} />
    </div>
  );
}

// Header component
const WishlistHeader = (props) => {
  const [filter, setFilter] = useState('all');

  let list = props.fullList;

  // Get length of current filtered list
  function getShowCount(list) {
    return list.filter((item) => item.show === true).length;
  }

  // Update shown list items when filter changes
  const HandleFilterChange = (e) => {
    const { fullList, updateListOfWishes } = props;
    const { value } = e.target;

    for (let i = fullList.length - 1; i >= 0; i -= 1) {
      fullList[i].isReadOnly = true;
      fullList[i].show = true;
      if (value !== 'all' && fullList[i].category !== value) {
        fullList[i].show = false;
      }
    }

    setFilter(value);

    const newlist = fullList.map(i => {
      return { ...i };

    });

    updateListOfWishes(newlist);
  }


  // Return header component content
  return (
    <div className="contentBanner">
      <h1 className="wishTitle">
        Wishes:
        {' '}
        {getShowCount(list)}
      </h1>
      <label htmlFor="category">
        <p className="bannerFilter">Category</p>
        <select id="category" name="category" value={filter} onChange={(e) => HandleFilterChange(e)}>
          <option value="all">All</option>
          <option value="default">Default</option>
          <option value="camping">Camping</option>
          <option value="hendrix">Hendrix</option>
          <option value="decor">Decor</option>
        </select>
      </label>
    </div>
  );
}

// Component to show list of items
function WishTable(props) {
  const rows = [];
  let { fullList, updateListOfWishes } = props;

  if (fullList === null) {
    console.log('currentList is null');
  } else {
    fullList.forEach(function (item) {
      rows.push(
        <div key={item._id} >
          <WishRow item={item} currentList={fullList} updateListOfWishes={updateListOfWishes} />
        </div>)
    })
  }

  return (
    <div className="content">
      {rows}
    </div>
  );
};

// Individual row render for each item
const WishRow = (props) => {
  let item = props.item;
  let prevItem = useRef(item);

  // Store unedited item in case of cancel, mark not read only
  const handleEdit = () => {
    let { item, currentList, updateListOfWishes } = props;
    prevItem.current = { ...item };
    const newlist = currentList.map(i => {
      if (i._id === item._id) {
        return { ...i, isReadOnly: false }
      }

      return { ...i };
    });
    updateListOfWishes(newlist);
  };

  // Send item to DB
  async function insertWish(item) {
    try {
      await InsertWish(item);
    } catch (e) {
      console.log(`Error in wishlist.insertWish: ${e.message}`);
    }
  };

  // Send current item info to DB and mark read only
  const handleSubmit = () => {
    let { item, currentList, updateListOfWishes } = props;
    insertWish(item);
    const newlist = currentList.map(i => {
      if (i._id === item._id) {
        return { ...i, isReadOnly: true };
      }
      return { ...i };
    });
    updateListOfWishes(newlist);
  };

  // Return content for submit button
  function Submit(item) {
    if (!item.isReadOnly) {
      return (
        <span>
          <button className="typicalbutton" type="button" onClick={() => handleSubmit(item)}>
            Submit
          </button>
        </span>

      );
    }
    return null;
  };

  // Return content for edit button
  function ShowEdit(item) {
    if (item.source === 'manual') {
      return (
        <span  >
          <button className="typicalbutton righthand" type="button" onClick={() => handleEdit(item, props.currentList)}>
            Edit
          </button>
        </span>
      );
    }
    return null;
  };


  // Revert to unedited item and mark read only
  const handleCancel = () => {
    let { item, currentList, updateListOfWishes } = props;
    const newlist = currentList.map(i => {
      if (i._id === item._id) {
        return { ...prevItem.current, isReadOnly: true }
      }
      return { ...i };
    });
    updateListOfWishes(newlist);
  };

  // Return content for cancel button
  function Cancel(item) {

    if (!item.isReadOnly) {
      return (
        <span>
          <button className="typicalbutton" type="button" onClick={(e) => handleCancel(e, prevItem, item)}>
            Cancel
          </button>
        </span>
      );
    }
    return null;
  };

  // Update item when fields edited
  const handleChange = (e) => {
    let { item, currentList, updateListOfWishes } = props;
    const { name, value } = e.target;
    item[name] = value;
    const newlist = currentList.map(i => {
      return { ...i };
    });
    updateListOfWishes(newlist);
  };

  // Update item for category change
  const handleCategoryChange = (e) => {
    const { value } = e.target;
    let { item, currentList, updateListOfWishes } = props;
    item.category = value;
    const newlist = currentList.map(i => {
      return { ...i };
    });
    updateListOfWishes(newlist);
  };

  // Open url in new tab  
  const openInTab = (url) => {
    const newWindow = window.open(url, '_blank', 'noopener,noreferrer');
    if (newWindow) newWindow.opener = null;
  };

  // Get the url from backend
  async function getUrl(link) {
    const toflask = `/go_outside_flask/${link}`;
    const tempurl = await axios.get(toflask);
    const newurl = tempurl.data;
    return newurl;
  }

  // Get the url from backend and go to it in new tab
  const goToLink = async (link) => {
    let taburl = '';
    try {
      taburl = await getUrl(link);
      return openInTab(taburl);
    } catch (e) {
      console.log(`Error getting url from link: ${link} ${e.message}`);
      return window.location.href;
    }
  };

  // Row content, if read only show just fields, if not read only then show different buttons and editable fields
  return (
    <div >
      {item.show ? (
        <div className="wish">
          <div className="wishatt">
            {
              item.isReadOnly ? (
                <div>
                  <span className="wishatt capital">
                    Category:
                    {item.category}
                  </span>
                  {ShowEdit(item)}
                  <div className="wishatt">
                    Item Name:
                    {item.name}
                  </div>
                  <div className="wishatt">
                    Description:
                    {item.description}
                  </div>
                  <div className="wishatt">
                    Cost:
                    {item.cost}
                  </div>
                  <span>Link: </span>
                  {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
                  <a className="wishatt" href="#" onClick={(e) => goToLink(item.link)}>{item.link}</a>
                  <div className="wishatt">
                    Quantity:
                    {item.quantity}
                  </div>
                </div>
              )
                : (
                  <span>
                    <label htmlFor="category">
                      Category:
                      <select name="category" onChange={(e) => handleCategoryChange(e, item)} value={item.category}>
                        <option value="default">Default</option>
                        <option value="camping">Camping</option>
                        <option value="hendrix">Hendrix</option>
                        <option value="decor">Decor</option>
                      </select>
                    </label>
                    <span className="righthandSection">
                      {Submit(item)}
                      {Cancel(item)}
                    </span>
                    <div>
                      <div>
                        <label htmlFor="name">
                          Item Name:
                        </label>
                        <input className="wishatt" name="name" placeholder="Name" onChange={(e) => handleChange(e, item)} value={item.name} />
                      </div>
                      <div>
                        <label htmlFor="description">
                          Description:
                        </label>
                        <input className="wishatt" name="description" placeholder="Description" onChange={(e) => handleChange(e, item)} value={item.description} />
                      </div>
                      <div>
                        <label htmlFor="cost">
                          Cost:
                        </label>
                        <input className="wishatt" name="cost" placeholder="Cost" onChange={(e) => handleChange(e, item)} value={item.cost} />
                      </div>
                      <div>
                        <label htmlFor="link">
                          Link:
                        </label>
                        <input className="wishatt" name="link" placeholder="Link" onChange={(e) => handleChange(e, item)} value={item.link} />
                      </div>
                      <div>
                        <label htmlFor="quantity">
                          Quantity:
                        </label>
                        <input className="wishatt" name="quantity" placeholder="Quantity" onChange={(e) => handleChange(e, item)} value={item.quantity} />
                      </div>
                      <div className="wishatt">
                        Wishlist:
                        {item.wishlist}
                      </div>
                    </div>
                  </span>
                )
            }
          </div>
        </div>
      ) : null}
    </div>
  )
}

export default Wishlist;

Removing duplicated functions in two classes in Kotlin

I have wrote the following code in Kotlin:

class ProxyiOSUIElementWrapper(val app: SIMIAppUIElementProtocol) : IAppUIElement {

    override fun tap() {
        app.tap()
    }

    override fun elementWithTestId(testId: String): IAppUIElement {
        return ProxyiOSUIElementWrapper(app.elementWithTestIdTestId(testId))
    }

    override fun table(withId: String): IAppUIElement {
        return ProxyiOSUIElementWrapper(app.tableWithId(withId))
    }

    override fun cell(withId: String): IAppUIElement {
        return ProxyiOSUIElementWrapper(app.cellWithId(withId))
    }

    override fun waitForExistence(timeout: Double) {
        app.waitForExistenceTimeout(timeout)
    }

    override fun hasText(text: String, timeout: Double) {
        app.hasTextText(text, timeout)
    }

    override fun getText(timeout: Double): String {
        return app.getTextTimeout(timeout)
    }

    override val debugDescription: String
        get() = app.debugDescription
}

class ProxyiOSAppWrapper : IAppWrapper {

    private val app = ConcreteAppWrapper(AppSetup.identifier)

    override var identifier: String = app.identifier

    override fun launch(arguments: Map<String, String>) {
        app.launchArguments(arguments as Map<Any?, *>)
    }

    override fun tap() {
        app.tap()
    }

    override fun elementWithTestId(testId: String): IAppUIElement {
        return ProxyiOSUIElementWrapper(app.elementWithTestIdTestId(testId))
    }

    override fun table(withId: String): IAppUIElement {
        return ProxyiOSUIElementWrapper(app.tableWithId(withId))
    }

    override fun cell(withId: String): IAppUIElement {
        return ProxyiOSUIElementWrapper(app.cellWithId(withId))
    }

    override fun waitForExistence(timeout: Double) {
        app.waitForExistenceTimeout(timeout)
    }

    override fun hasText(text: String, timeout: Double) {
        app.hasTextText(text, timeout)
    }

    override fun getText(timeout: Double): String {
        return app.getTextTimeout(timeout)
    }

    override val debugDescription: String
        get() = app.debugDescription
}

actual object AppSingleton {
    actual var app: IAppWrapper = ProxyiOSAppWrapper()
}

As you can see, there are functions that are being repeated, for example table, cell etc. How can I make it DRY? I want to take out these functions out of the classes and only write then once, but since both classes have to conform interfaces, I cannot do that. I tried creating one class that would inherit from both interfaces, but then there is a problem with constructors as one Proxy class takes an argument and the other does not.

mercredi 3 août 2022

Importing multiple with some pattern in their names in R

We need to create a list, importing several XLSX files. These files have a pattern in their names, each one has the same first characters, but different numbers based on dates:

Opca202201
Opca202202
etc

Problm is: these files have multiple sheets, and the the name and the position of the sheet we need changes from file to file. They does have a pattern in the sheet name, such as:

Dados08777
Dados65423
etc

The word Dados always remain in the sheet.

We tried to use lapply(), pattern() and read.xlsx(), but we don't know how to find the exact sheet.

setwd("H:/Bases/Teste")
file.list <- list.files(pattern='*')
df.list <- lapply(file.list, read_excel)
df = bind_rows(df.list)

Could someone help us?

Is it bad practice for a Decorator Class to change the state of the innermost wrapped object

Normally by definition the Decorator Pattern attaches new behaviour to an object by using a chain of decorators on the decorated class. The pattern exploits the chain of decorators to the main decorated class to transform incoming and outgoing data to the decorated class.

Although there is a reference in every decorator class to the immediate successor there is no reference to the actual decorated class object (innermost class). So, there is no easy way that a decorator class could access or modify the decorated class's state (innermost class) unless this information is transferred in the chain of decorators (which is not very convinient). This weird to me because the decorator pattern is considered the dynamic alternative of inheritance which allows this to happen. The subclasses can access and modify the state of the parent classes ( if they are not private ) however in the decorator pattern description this is not conviniently provided.

So the question is : Is it bad practice for a decorator to access the data in the innermost class in the chain ( decorated class )?

How can I take a sample from CDF and then calculate manually chi-squared statistic?

I am not good at R. I have a problem that I must solve it in R. I have two CDFs. One of them is for my original data and another is for rgamma. now I should take a random sample from these CDFs and calculate the chi-squared statistic manually to identify p-value and GOF. I do not allow to use the chi-squre package and I must do everything manually. is there anyone to help me, please? here is my data:

x<- sort(d1)
CDFx<- ecdf(x)
d2<- rgamma(length(x),0.25436673129,0.00001157445)
y<- sort(d2)
CDFy<- ecdf(y)

How to wrap first element child from render function of React functional component?

How i can wrap child element/s from render function in React component? For example, i have component:

React functional component:

const Component = () => (
  <div>
    <p>Some p element</p>
  </div>
)

and i want to wrap only <p> element with something else. I want this result after wrapping:

Component after wrapping:

const Component = () => (
  <div>
    <Wrapper>
      <p>Some p element</p>
    </Wrapper>
  </div>
)

How can i do it? Thx