Friday, October 15, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Table content showing only when i comment a line that is not executing/ Vue 3

Posted: 15 Oct 2021 09:38 AM PDT

I have a table that only shows its content if i remove a line of code inside a method.

I'm trying to remove a table row, but even if the code that removes the row is not executed, the table won't show its content until i remove that line or if the component gets hot-reloaded.

Here is my html template:

    <table class="table table-dark table-hover">        <thead>          <tr>            <th v-for="header in headers" :key="header">              {{ header }}            </th>            <th>Acciones</th>          </tr>        </thead>        <tbody>          <tr v-for="(data, index) in tableContent" :key="data.id">            <td v-for="value in data" :key="value">              {{ value }}            </td>            <td>              <div class="action-buttons">                <button class="btn btn-warning">Editar</button>                <button                  class="btn btn-primary"                  @click="deleteRow(data.id, index)"                >                  Eliminar                </button>              </div>            </td>          </tr>        </tbody>      </table>    

And my js code:

import { ref } from "vue";  export default {    name: "DataTable",    props: {      headers: Array,      content: Array,      apiUrl: String,    },    setup(props) {      const tableContent = ref(props.content);        const deleteRow = async (id, rowIdx) => {        try {          console.log(props.apiUrl, id, rowIdx);          tableContent.value.splice(tableContent.value.indexOf(id), 1); /*<------ this is the line*/        } catch (error) {          console.error(error);        }      };      return {        tableContent,        deleteRow,      };    },  };    

If that js line is commented or deleted, the table shows its content as normally it does, but if the line is uncommented it just won't show the content.

If i hot-reload the component with the line uncommented, the table will show its content but If i reload the page, the table content won't get rendered

How to do a join bewteen tables with a conditional statement

Posted: 15 Oct 2021 09:38 AM PDT

I have two tables. I do not have a direct field to join. But, what I want to do, is to take everything in Table1, and join it with a field that is "in" a field in Table2. I know this will result in multiple connections between rows in Table2 to Table1, but that is okay. Let me give a for instance..

Please have some patience. I know there is a way to make a query to do this, but I have not done that before. But, I can give sample data, and what I want to do with it.

Table1(SN, Customer) Table2(SNRange, OrderNum, Line Item)

Table1[12, Bob, 13, Bob, 14, Bob, 54, Bill, 55, Bruno, 56, Bruno, 100, Sylvia] Table2[12,13, WO234, 1, 14, WO234, 2, 54, WO300, 1, 55,56, WO532, 1]

Result:(SN, Customer, WONum, LineNum) [12, Bob, WO234, 1, 13, Bob, WO234, 1, 14, Bob, WO234, 2, 54, Bill, WO300, 1, 55, Bruno, WO532, 1, 56, Bruno, WO532, 2, 100, Sylvia, NULL, NULL]

My very uneducated guess would be:

'''SELECT * From Table1 INNER JOIN SN ON Table1.SN in Table2.SNRange'''

I think this defines the situation, and loose logic on how to do it. I need some format help. SNRange is a string with commas separating the numbers. I know my formatting is horrible, but I'm not very deep in SQL, but I have needed to do some complex things.

Thank you!! Rod

How do I downlaod a package from debian.org website on raspberry pi?

Posted: 15 Oct 2021 09:38 AM PDT

The package in question

I tried doing sudo apt install python3-pyqt5.qtbluetooth which gave the error E: Unable to locate package python3-pyqt5.qtbluetooth

Getting TRANSACTION_OVERSIZE error when submitting a transaction on the Hedera network

Posted: 15 Oct 2021 09:38 AM PDT

For Hedera File Service (HFS), I read that the file size limit is 1MB but each transaction is only limited to 6Kb.

The documentation says that we can use FileAppend to add the additional contents so - Does this mean that if I do want to upload a 1MB file, I'd have to do it in increments of 6Kb size transactions?

Right now I'm getting a TRANSACTION_OVERSIZE error

How can I make a main that call every method in my program [Python]

Posted: 15 Oct 2021 09:37 AM PDT

I just started learning methods in python and I was asked to create a "main" that would call all the 12 "methods" in my program. I did it in a way that worked, but I think it shouldn't.

# Input:      Prompt the User for it's: first name, last name, age, annual salary, and number of siblings.  # Processing: Calculate Age into: months, weeks, days, hours, minutes, and weekly salary.  # Output:     Display what was prompted and processed.    # Methods  def promptFirstName ():      firstName = input ("Enter your first name: ")      return firstName  def promptLastName ():      lastName = input ("Enter your last name: ")      return lastName  def promptAgeYear ():      ageYear = int(input ("Enter your age: "))      return ageYear  def promptSiblings ():      siblings = input ("Enter the amount of sibling that you have: ")      return siblings  def promptSalaryYear ():      salaryYear = float(input ("Enter your annual salary: "))      return salaryYear    def calculateAgeMonth (ageYear):      ageMonth = ageYear * 12      return ageMonth  def calculateAgeWeek (ageYear):      ageWeek = ageYear * 52      return ageWeek  def calculateAgeDay (ageYear):      ageDay = ageYear * 365      return ageDay  def calculateAgeHour (ageYear):      ageHour = ageYear * 8760      return ageHour  def calculateAgeMinute (ageYear):      ageMinute = ageYear * 525600      return ageMinute  def calculateSarayWeek (salaryYear):      salaryWeek = salaryYear / 52      return salaryWeek    def displayOutput (firstName, lastName, ageYear, siblings, ageMonth, ageWeek, ageDay, ageHour, ageMinute, salaryYear, salaryWeek):      outputDisplay = print("\nHello",firstName,"!\nYou are",ageYear,"years old.\nYou have",siblings,"brothers/sisters.\nThis is:\n\t1.",format(ageMonth,",d"),"months.\n\t2.",format(ageWeek,",d"),"weeks.\n\t3.",format(ageDay,",d"),"days.\n\t4.",format(ageHour,",d"),"hours.\n\t5.",format(ageMinute,",d"),"minutes\nYou make: $"+format(salaryYear,",.2f"),"per year,\nwhich is",format(salaryWeek,",.2f"),"per week.\nBye",firstName,lastName,"!")    # It's not beautiful but works ¯\_(ツ)_/¯      return outputDisplay    def mainDisplay():      firstName   = promptFirstName   ()      lastName    = promptLastName    ()      ageYear     = promptAgeYear     ()      siblings    = promptSiblings    ()      salaryYear  = promptSalaryYear  ()      ageMonth    = calculateAgeMonth(ageYear)      ageWeek     = calculateAgeWeek(ageYear)      ageDay      = calculateAgeDay(ageYear)      ageHour     = calculateAgeHour(ageYear)      ageMinute   = calculateAgeMinute(ageYear)      salaryWeek  = calculateSarayWeek(salaryYear)      outputDisplay = displayOutput(firstName, lastName, ageYear, siblings, ageMonth, ageWeek, ageDay, ageHour, ageMinute, salaryYear, salaryWeek)      return mainDisplay    # I feel like this shouldn't work...    # Output  mainDisplay = mainDisplay()  

If anyone could check if I'm doing something wrong it would help me a lot.

Using product flavors with multiple firebase apps

Posted: 15 Oct 2021 09:37 AM PDT

I have a development and a production firebase console, each with an android app. I am trying to connect my development environment to the development google-services.json and the production one to the other google-services.json.

I placed the respective google-servies.json files in app/src/dev/ and app/src/prod/

To my understanding, app/build.gradle requires

android {      ...      flavorDimensions "default"      productFlavors {          dev {              applicationIdSuffix '.dev'              resValue "string", "build_config_package", "com.myapp"          }          prod {              resValue "string", "build_config_package", "com.myapp"          }      }      ...  }  

The development firebase's appId is com.myapp.dev and the production one is just com.myapp

When I run react-native run-android --variant=prodDebug everything works fine, but if I run react-native run-android --variant=devDebug it still connects to the production firebase.

How can I get them to reliably switch between consoles based on my variant?

Testing Component That Fetches Data With React Testing Library

Posted: 15 Oct 2021 09:37 AM PDT

I have a component that does some very basic fetching of data. Once this data is fetched, users can interact and click on the items in a list. When an item is clicked, it is displayed at the top of the component with a description as the "active item".

I'd like to test the click functionality by making sure that an item can be set to active, and also removed from being active. However, I am not sure how to do this, since it relies on data from an API. Any ideas?

Component Code

interface Item {    title: string;    description: string;  }    const Home: NextPage = () => {    const [items, setItems] = useState<Item[]>([]);    const [activeItem, setActiveItem] = useState<Item | null>(null);      const fetchItems = async () => {      try {        const res = await axios.get<Item[]>('http://localhost:3090/api/items');        setItems(res.data);      } catch (error) {        console.log(error);      }    };      const handleActiveItem = (item: Item) => {      if (activeItem?.title === item.title) {        setActiveItem(null);      } else {        setActiveItem(item);      }    };      useEffect(() => {      fetchItems();    }, []);      return (      <div>        {activeItem && (          <div data-testid="active-item">            <h1>{activeItem.title}</h1>            <p>{activeItem.description}</p>          </div>        )}          <ul>          {items.map((item: Item) => (            <li key={item.title} onClick={() => handleActiveItem(item)}>              {item.title}            </li>          ))}        </ul>      </div>    );  };    

Test Code

describe('Home', () => {    it('matches snapshot', () => {      const tree = renderer.create(<Home />).toJSON();      expect(tree).toMatchSnapshot();    });      render(<Home />);      it('Initially there is no active item', () => {      const activeItem = screen.queryByTestId('active-item');      expect(activeItem).not.toBeInTheDocument();    });      it('When an item is clicked in the list, it becomes the active item', () => {      //    });      it('If there is an active item and it is clicked in the list, active item is emptied', () => {      //    });  });  

Reshaping a coordinate list

Posted: 15 Oct 2021 09:37 AM PDT

I have 3xN dimensional array containing coordinates ([x1,x2,...xN],[y1,y2,...yN],[z1,z2,...zN]), I need to reshape it into a Nx3 dimensional array of coordinates ([x1,y1,z1],[x2,y2,z2],...,[xN,yN,zN]). I've tried the following:

n=int(1e7)  x=np.linspace(0,1,n)  y=np.linspace(0,1,n)  z=np.linspace(0,1,n)  pos=np.array([x,y,z])    newpos=np.array(list(zip(pos[0],pos[1],pos[2])))  

The problem with the code above is that it's to slow for it's purposes. Not only, when using n=1e7 the code runs into a memory error. Is there any other way to achieve the desired purpose?

Can anybody explain to me how this sorted work?

Posted: 15 Oct 2021 09:38 AM PDT

I found this edabit challenge (link to challenge):

Create a function that takes a list of numbers lst, a string s and return a list of numbers as per the following rules:

"Asc" returns a sorted list in ascending order. "Des" returns a sorted list in descending order. "None" returns a list without any modification.

Some person Evgeny SH propose this solution:

def asc_des_none(lst, s):      return sorted(lst, reverse=s == 'Des') if s else lst  

Can you explain me how sorted(...) part works? Thanks in advance!

How do I round my labels to two decimal places in this code

Posted: 15 Oct 2021 09:37 AM PDT

Can someone please help me with this code below? I want the labels to only show two decimal places.

CODE:

//@version=4  study("Previous Candle High and Low", shorttitle = "Previous. H/L", overlay=true , precision = 2)    patternLabelPosLow = low[1] - abs(atr(30) * 0.6)  patternLabelPosHigh = high[1] + abs(atr(30) * 0.6)    l1 = label.new(bar_index[1], patternLabelPosHigh, text=tostring(high[1]), style=label.style_label_right, color = color.black, textcolor=color.white)  l2 = label.new(bar_index[1], patternLabelPosLow, text=tostring(low[1]), style=label.style_label_right, color = color.black, textcolor=color.white)    label.delete(l1[1])  label.delete(l2[1])  

Bulk insert data into empty (but existing) records with SQL

Posted: 15 Oct 2021 09:37 AM PDT

The first table columns (A to G) are already filled with data for each row/record, but the columns H to K have no data in it yet. So I have to add data for these columns, for each individual row in the table (1 to 285, whatever the number is). Columns A to G should remain unaltered!

What SQL query do I use to insert data into existing but empty records? Without overwriting any columns, other than H to K?

I am looking for something that does this:

INSERT INTO `table` (`record_id`, `colA`, `colB`, `colC`, `colD`, `colE`, `colF`, `colG`, `colH`, `colI`, `colJ`, `colK`)    VALUES      (`auto-increment 1`, `dont-change A`, `dont-change B`, `dont-change C`, `dont-change D`, `dont-change E`, `dont-change F`, `dont-change G`, `new-value H`, `new-value I`, `new-value J`, `new-value K`),      (`auto-increment 2`, `dont-change A`, `dont-change B`, `dont-change C`, `dont-change D`, `dont-change E`, `dont-change F`, `dont-change G`, `new-value H`, `new-value I`, `new-value J`, `new-value K`),      (`auto-increment 3`, `dont-change A`, `dont-change B`, `dont-change C`, `dont-change D`, `dont-change E`, `dont-change F`, `dont-change G`, `new-value H`, `new-value I`, `new-value J`, `new-value K`),  

All the way to row 285:

    (`auto-increment 285`, `dont-change A`, `dont-change B`, `dont-change C`, `dont-change D`, `dont-change E`, `dont-change F`, `dont-change G`, `new-value H`, `new-value I`, `new-value J`, `new-value K`),  

Use native CSS min/max functions with LESS

Posted: 15 Oct 2021 09:38 AM PDT

I want to use the min() CSS function with a stylesheet written in LESS. However, LESS has its own min and max functions that precompute values (making it impossible to mix-and-match units). How do I get it so the output CSS has the min/max functions as I wrote them?

Here is the style in the LESS file, which should also be the expected output.

canvas {      background: white;      width: min(95vh, 95vw);      height: min(95vh, 95vw);  }  

I am using lessc 3.13.1, which produces the following error:

ArgumentError: error evaluating function `min`: incompatible types in <snipped> on line 49, column 12:  48     background: white;  49     width: min(95vh, 95vw);  50     height: min(95vh, 95vw);  

Can i add two elements at once in a list comprehension?

Posted: 15 Oct 2021 09:38 AM PDT

The output i want:

[[(1,1)], [(2,2)], [(2,2)], [(4,4)], [(3,3)], [(6,6)]]  

This is the code that does not work:

mylist = [[[(x,x)], [(x*2,x*2)]] for x in range(1, 4)]  

I know i could use:

mylist = []  [mylist.extend([[(x,x)], [(x*2,x*2)]]) for x in range(1, 4)]  

But is there a way to write this in one line?

Why JScrollpane won't be added to JTextArea

Posted: 15 Oct 2021 09:37 AM PDT

I've tried everything(that I mostly found from stack overflow), but I still can't understand why the JScrollpane won't be added to JTextArea:

import java.awt.*;  import java.awt.event.*;  import java.io.*;  import javax.swing.*;    //---------------------------------------  class MyFrame extends JFrame { // creating class name is 'Myframe' extending from 'JFrame' class      MenuBar bar;      Menu menu1, menu2, format_menu, font_size, theme;      MenuItem new_item1, item2, item3, item4, item5, item6, item7, item8;      MenuItem dracula, queen, dawn, light;      MenuItem size_8, size_12, size_16, size_20, size_24, size_28;        JTextArea jTextArea;      String text;        MyFrame() {          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);          setTitle("Untitled - CodePad");            // this is for shortcut keys          MenuShortcut menuShortcut_new_item1 = new MenuShortcut(KeyEvent.VK_N);          MenuShortcut menuShortcut_item2 = new MenuShortcut(KeyEvent.VK_O);          MenuShortcut menuShortcut_item3 = new MenuShortcut(KeyEvent.VK_S);          MenuShortcut menuShortcut_item4 = new MenuShortcut(KeyEvent.VK_X);            MenuShortcut menuShortcut_item5 = new MenuShortcut(KeyEvent.VK_C);          MenuShortcut menuShortcut_item6 = new MenuShortcut(KeyEvent.VK_V);          MenuShortcut menuShortcut_item7 = new MenuShortcut(KeyEvent.VK_T);          MenuShortcut menuShortcut_item8 = new MenuShortcut(KeyEvent.VK_A);          // -------------------------------------------          // setting icon          Image icon = Toolkit.getDefaultToolkit().getImage(".//res//icon.png");          setIconImage(icon);            //            bar = new MenuBar(); // creating object of menubar and giving it reference            menu1 = new Menu("File");// creating object of menu as 'File' and giving it reference          menu2 = new Menu("Edit");// creating object of menu as 'Edit' and giving it reference            format_menu = new Menu("Format");// creating object of menu as 'Format' and giving it reference          font_size = new Menu("Font Size");// creating object of menu as 'Font Size' and giving it reference          theme = new Menu("Theme");// creating object of menu as 'Theme' and giving it reference            //// creating object of MenuItem and giving it reference,and Passing arguments          //// 'label','menushortcut'          new_item1 = new MenuItem("New", menuShortcut_new_item1);          item2 = new MenuItem("Open", menuShortcut_item2);          item3 = new MenuItem("Save", menuShortcut_item3);          item4 = new MenuItem("Exit", menuShortcut_item4);            item5 = new MenuItem("Copy", menuShortcut_item5);          item6 = new MenuItem("Paste", menuShortcut_item6);          item7 = new MenuItem("Cut", menuShortcut_item7);          item8 = new MenuItem("Select All", menuShortcut_item8);            // ------------------done--------------            // creating menuItem for font size menu          size_8 = new MenuItem("8");          size_12 = new MenuItem("12");          size_16 = new MenuItem("16");          size_20 = new MenuItem("20");          size_24 = new MenuItem("24");          size_28 = new MenuItem("28");          // -------------------done-------------------          // creating menuItem for theme menu          dracula = new MenuItem("Dracula");          queen = new MenuItem("Queen");          dawn = new MenuItem("Dawn");          light = new MenuItem("Light");            // creating menuItem for theme menu            // adding new_item1,2,3,4 to menu1 ,that is new,open,save,exit          menu1.add(new_item1);          menu1.add(item2);          menu1.add(item3);          menu1.add(item4);            // ------------------Done-------------------            // adding item5,6,7,8 to menu2 ,that is copy,paste,cut,and select all          menu2.add(item5);          menu2.add(item6);          menu2.add(item7);          menu2.add(item8);          // -------done---------------------------------------------------------            format_menu.add(font_size);// adding font_size menu to format menu so it becomes submenu            // adding MenuItems to font_size menu          font_size.add(size_8);          font_size.add(size_12);          font_size.add(size_16);          font_size.add(size_20);          font_size.add(size_24);          font_size.add(size_28);          // ---------done------------------------            // adding MenuItem to theme Menu-------          theme.add(dracula);          theme.add(queen);          theme.add(dawn);          theme.add(light);          // ---------done------------------------            jTextArea = new JTextArea();// adding jTextArea          jTextArea.setLineWrap(true);          JScrollPane scroll = new JScrollPane(jTextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,                  ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);          add(scroll);            // adding menus to bar          bar.add(menu1);          bar.add(menu2);          bar.add(format_menu);          bar.add(theme);            setMenuBar(bar); // settingmenubar as bar          add(jTextArea);// adding text area            // declaring some colors using rgb            Color dracula_Color = new Color(39, 40, 34);          Color green_Color = new Color(166, 226, 41);          Color orange_Color = new Color(219, 84, 34);          Color queen_Color = new Color(174, 129, 219);            // setting default foreground color of jTextArea and setting font          jTextArea.setForeground(Color.BLUE);          jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 15));            // setting size and location and visibility          setSize(1000, 600);          setLocationRelativeTo(null);          setVisible(true);            item2.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  FileDialog dialog = new FileDialog(new Frame(), "Open", FileDialog.LOAD); // this will load the                                                                                            // fileDialog                  dialog.setVisible(true);// this will make dialog visible                  String path = dialog.getDirectory() + dialog.getFile(); // this will select the path of selected file                                                                          // and put it into 'path'                  setTitle(dialog.getFile() + " - CodePad");// this will set Title to selected file name and -CodePad                    try {                      FileInputStream fi = new FileInputStream(path);                      byte b[] = new byte[fi.available()];                      fi.read(b);                      String str = new String(b); // this will store b in str                      jTextArea.setText(str);// this will display text in 'str' in jTextArea                      fi.close();// this will close fi                    } catch (Exception e) {                        System.out.println("Something went Wrong :(");                  }              }          });            new_item1.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  setTitle("Untitled - CodePad");                  jTextArea.setText(" ");              }          });            item3.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  FileDialog dialog = new FileDialog(new Frame(), "Save ", FileDialog.SAVE);                  dialog.setVisible(true);                  String path = dialog.getDirectory() + dialog.getFile();                  setTitle(dialog.getFile() + "- CodePad");                    try {                        FileWriter fw = new FileWriter(path);                      fw.write(jTextArea.getText());                      fw.close();                    } catch (Exception e) {                        System.out.println("Something went Wrong :(");                  }              }          });          item4.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  // setVisible(false);//this will make frame invisible                  System.exit(0);              }          });            item5.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  text = jTextArea.getSelectedText();// this will store selected text in to variable 'text'              }          });            item6.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  jTextArea.insert(text, jTextArea.getCaretPosition()); // this will insert the text present in 'text'                                                                        // variable at the carret position              }          });            item7.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  text = jTextArea.getSelectedText(); // this will copy the selected text                  jTextArea.replaceRange("", jTextArea.getSelectionStart(), jTextArea.getSelectionEnd()); // this will put                                                                                                          // ""                                                                                                          // to selected                                                                                                          // text              }          });            item8.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  jTextArea.selectAll(); // this will select all the text in jTextArea              }          });            // ------------------------------------------------------------------------            // --------------------------------------------------------------------------            size_8.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 8)); // this will change the size of text in                                                                              // jTextArea to 8              }          });          size_12.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 12));// this will change the size of text in                                                                              // jTextArea to 12              }          });          size_16.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 16));// this will change the size of text in                                                                              // jTextArea to 16              }          });          size_20.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));// this will change the size of text in                                                                              // jTextArea to 20              }          });          size_24.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 24));// this will change the size of text in                                                                              // jTextArea to 24              }          });          size_28.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 28));// this will change the size of text in                                                                              // jTextArea to 28              }          });            // --------------------------------------------------------------------------          dracula.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                    jTextArea.setBackground(dracula_Color);// this will backgound to dracula                  jTextArea.setForeground(green_Color);// this will set foregrounf to green              }          });          queen.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                    jTextArea.setBackground(dracula_Color);                  jTextArea.setForeground(queen_Color);              }          });          dawn.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  jTextArea.setBackground(Color.WHITE);                  jTextArea.setForeground(orange_Color);              }          });          light.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent event) {                  jTextArea.setBackground(Color.WHITE);                  jTextArea.setForeground(Color.BLUE);              }          });          // --------------------------------------------------------------------------      }    }    // ---------------------------------------    public class CodePad_updated {      public static void main(String[] args) {          new MyFrame();// object      }  }  

raw text to array python

Posted: 15 Oct 2021 09:37 AM PDT

import numpy as np  import re  def read_process_OD():      OD = np.zeros([24, 24])      lines=[]      with open('Network_OD.txt','r') as f:          lines=f.readlines()      origin=[]      for line in lines:          if line.startswith('Origin')==True:              pass          else:              origin.append(re.split(pattern=[':;'],string=lines))  

#raw text is shown like this: #Origin 1

1 : 0.0; 2 : 100.0; 3 : 100.0; 4 : 500.0; 5 : ###200.0;

MongoDB return sub document as an array

Posted: 15 Oct 2021 09:38 AM PDT

I have a query on mongoose

const result = await modelProfile.findOne(      {        _id: profileId,      },      { 'payItems.ACId': 1 }    );  

profile sample is

{      "firstName": "ABC",      "lastName": "DEF",      "payItems": [         {          "ACId": {              "$oid": "6168825c5d0edbc0b61615db"          },          "balance": 0,          "rate": 0      }, {          "ACId": {              "$oid": "6168825c5d0edbc0b61615dc"          },          "balance": 1,          "rate": 2      }]  }  

when I ran it, it returns the following results that is correct:

{ payItems:      [       { ACId: ObjectId("6168825c5d0edbc0b61615db") },       { ACId: ObjectId("6168825c5d0edbc0b61615dc") }      ]   }  

That is correct, is there any way that I can MongoDB that I would like to return it "without keys" something like this (array of Ids)?

 [        ObjectId("6168825c5d0edbc0b61615db"),      ObjectId("6168825c5d0edbc0b61615dc")   ]  

Xcode 13 doesn't show quick help when option click defined property on left

Posted: 15 Oct 2021 09:37 AM PDT

A quick question. I use to see the inferred type by option click the property or object on the left of a statement. After upgrade to Xcode 13, for instance, when I option click on below text property, there is no quick help popping up. Do u guys meet this same issue? Just Google it, no clue found.

let text = "Have a nice day"  

Quick help is only shown when I option-click on an iOS built-in property, function, etc. It doesn't appear for custom defined things.

For code below, when I optional click on viewDidLoad or addSubview , I could get quick help menu popped up. But without luck for tableView, which is a user defined stuff.

private lazy var tableView: UITableView = {      let table = UITableView()      table.register(UITableViewCell.self, forCellReuseIdentifier: "cell")      return table  }()    override func viewDidLoad() {      super.viewDidLoad()      view.addSubview(tableView)      tableView.frame = view.bounds  }  

Python Crash Course 2nd Edition exercise 12-4

Posted: 15 Oct 2021 09:38 AM PDT

Have 3 files. rocket_game.py, rocket.py, settings.py. Contents of rocket.py. Key "Up" arrow does nothing. Key "Down" arrow moves the ship up. If I change the last line to "self.y += self.settings.ship_speed", down arrow moves the ship down. But why won't the game hook the up arrow?

def update(self):      """Update the ship's position based on the moving flag."""        if self.moving_right and self.rect.right < self.screen_rect.right:          self.x += self.settings.ship_speed      elif self.moving_left and self.rect.left > 0:          self.x -= self.settings.ship_speed      if self.moving_up and self.rect.top < self.screen_rect.top:          self.y += self.settings.ship_speed      elif self.moving_down and self.rect.bottom > 0:          self.y -= self.settings.ship_speed  

Key "Up" arrow does nothing. Key "Down" arrow moves the ship up. If I change self.y += self.settings.ship_speed, down arrow moves the ship up, I understand I why. But why doesn't the up arrow?

If I print the events, it sees me pressing the up arrow, but the rocket does not move.

The OTHER issue, the top and bottom boundaries don't seem to exist.

The bottom left corner of the screen is described as being coordinates 0, 0 respectively. I did try setting the bottom boundary as 0, but the ship still flies below the screen. Left and right boundaries work fine. New to python programming, and I tried reading pygame API for rect but it doesn't seem to have the reference that I need. It does list top and bottom rather than up and down. I have tried multiple ways in both the rocket_game.py and rocket.py.

No error messages, and the ultimate goal was to add the ability to move up and down, move left and right, while within the screen_rect borders.

Plotting lambda function

Posted: 15 Oct 2021 09:39 AM PDT

I am trying to plot a function which is defined via a lambda. I always get the error message:

x and y must have the same first dimension but have shapes (20,) and (1,)  

But I have no idea why.

import numpy as np  import matplotlib.pyplot as plt    x = np.linspace(-4,8,20)  print(x)  fx = lambda x: x - 10 * np.exp(-1/10*((x-2)**2))   plt.plot(x, fx)  plt.show()  

AngularJS Form validation transition to valid when some elements are not even touched yet

Posted: 15 Oct 2021 09:38 AM PDT

enter image description here

I have a save button that is only enabled when all form data is provided and the form is valid. I don't understand why bandwidth options are not selected and the form become valid. myForm.$valid transition to true ... it should stay as false

<button id="save-create-account-modal" type="submit" class="btn btn-success"      ng-disabled="!myForm.$valid || $ctrl.disableButton" ng-click="$ctrl.accessPointSave($ctrl.accessPoint)">      Save  </button>  

Bandwidth select menu

<div class="col-xs-3">      <div class="form-group" ng-class="{ 'has-error': myForm.uplink.$touched && myForm.uplink.$invalid }">          <label for="uplink" class="required">              <translate>GENERAL.UPLINK.value</translate>          </label>          <select id="edit-service-plan-uplink-select" class="form-control" name="uplink"              ng-model="$ctrl.accessPoint.uplink"              ng-options="bandwidth.value as bandwidth.option for bandwidth in $ctrl.uplinks" required>          </select>      </div>        <span class="message error" ng-messages="myForm.uplink.$error" ng-if="myForm.uplink.$touched">          <p ng-message="required">              <translate>GENERAL.FORM_VALIDATIONS.REQUIRED_FIELD.value</translate>          </p>      </span>  </div>    <div class="col-xs-3">      <div class="form-group"          ng-class="{ 'has-error': myForm.downlink.$touched && myForm.downlink.$invalid }">          <label for="downlink" class="required">              <translate>GENERAL.DOWNLINK.value</translate>          </label>          <select id="edit-service-plan-downlink-select" class="form-control" name="downlink"              ng-model="$ctrl.accessPoint.downlink"              ng-options="bandwidth.value as bandwidth.option for bandwidth in $ctrl.downlinks" required>          </select>      </div>        <span class="message error" ng-messages="myForm.downlink.$error" ng-if="myForm.downlink.$touched">          <p ng-message="required">              <translate>GENERAL.FORM_VALIDATIONS.REQUIRED_FIELD.value</translate>          </p>      </span>  </div>  

How can debug this further?


Updated

I also tried to add required in the same line as my <select> tags

still not working as expected

Getting empty response from gRPC call

Posted: 15 Oct 2021 09:37 AM PDT

I have a simple gRPC server and client. The server and client are working fine (I assume since I am getting a response and no error). However the response is empty which I have no idea why.

Here is the proto message.proto

syntax = "proto3";    message Msg {      int32 timeStamp = 1;      string text = 2;      string sender = 3;  }    message Empty {}    service MsgService{      rpc AllMessages (Empty) returns (MsgList) {}  }    message MsgList {      repeated Msg msgs = 1;  }  

and server.js

const grpc = require('@grpc/grpc-js');  const PROTO_PATH = "./message.proto";  const protoLoader = require('@grpc/proto-loader');    const options = {      keepCase: true,      longs: String,      enums: String,      defaults: true,      oneofs: true  }    const packageDefinition = protoLoader.loadSync(PROTO_PATH, options);  const msgProto = grpc.loadPackageDefinition(packageDefinition);    const server = new grpc.Server();  let savedMessages = [      { timeStamp: 1, text: "lorem", sender: "alex" },      { timeStamp: 2, text: "ipsum", sender: "bob" },      { timeStamp: 3, text: "dolor", sender: "alex" },      { timeStamp: 4, text: "net", sender: "bob" }  ];    server.addService(msgProto.MsgService.service, {      AllMessages: (_, callback) => {          callback(null, savedMessages);      }  })    server.bindAsync("127.0.0.1:50051", grpc.ServerCredentials.createInsecure(), (err, port) => {      if (err) {          console.log(err);      }      console.log(port);      server.start();      console.log("Server running at 127.0.0.1:50051");  })  

and client.js

const grpc = require('@grpc/grpc-js');  const protoLoader = require('@grpc/proto-loader');  const PROTO_PATH = "./message.proto";    const options = {      keepCase: true,      longs: String,      enums: String,      defaults: true,      oneofs: true,  };    var packageDefinition = protoLoader.loadSync(PROTO_PATH, options);    const MsgService = grpc.loadPackageDefinition(packageDefinition).MsgService;    const client = new MsgService(      "localhost:50051",      grpc.credentials.createInsecure()  );    client.AllMessages({}, (err, msg) => {      // console.log(err);      if (err) throw err;      console.log(msg);      // console.log(msg);  })  

and the repsonse I am getting

{ msgs: [] }  

If it helps , I was following this blog post https://daily.dev/blog/build-a-grpc-service-in-nodejs

Thanks in advance.

Can we add css classes on Shopify?

Posted: 15 Oct 2021 09:38 AM PDT

I working on Shopify website by editing. And new css files needed to be added. Created style.css file in assets and connected in theme.liquid file as

{{ 'style.css' | asset_url | stylesheet_tag }}.   

I want to know can we add new css classes? If so how can we do it?

Correct way to trigger radio button handler with jQuery

Posted: 15 Oct 2021 09:37 AM PDT

I have two radio buttons. Depending on which one is checked, I want to show or hide a <div> on the page. So I created this handler.

$(function () {      $('input[name="Search.LatestOnly"]').on('change', function () {          if ($(this).val() == 'true')              $('#date-section').hide(400);          else              $('#date-section').show(400);      });  });  

This works fine. But I want to set the <div> visibility to the correct state when the page loads, so I added this line:

$('input[name="Search.LatestOnly"]:checked').trigger();  

This produces run-time errors that aren't meaningful to me.

jQuery.Deferred exception: Cannot convert undefined or null to object TypeError: Cannot convert undefined or null to object at hasOwnProperty () at Object.trigger (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:70619) at HTMLInputElement. (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:72108) at Function.each (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:2976) at S.fn.init.each (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:1454) at S.fn.init.trigger (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:72084) at HTMLDocument. (https://localhost:44377/Data/Search:206:58) at e (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:30005) at t (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:30307) undefined S.Deferred.exceptionHook @ jquery.min.js:2 t @ jquery.min.js:2 setTimeout (async) (anonymous) @ jquery.min.js:2 c @ jquery.min.js:2 fireWith @ jquery.min.js:2 fire @ jquery.min.js:2 c @ jquery.min.js:2 fireWith @ jquery.min.js:2 ready @ jquery.min.js:2 B @ jquery.min.js:2 jquery.min.js:2

Uncaught TypeError: Cannot convert undefined or null to object at hasOwnProperty () at Object.trigger (jquery.min.js:2) at HTMLInputElement. (jquery.min.js:2) at Function.each (jquery.min.js:2) at S.fn.init.each (jquery.min.js:2) at S.fn.init.trigger (jquery.min.js:2) at HTMLDocument. (Search:206) at e (jquery.min.js:2) at t (jquery.min.js:2)

Can anyone tell me how to initialize my HTML so that the <div> is hidden or displayed once the page is loaded?

What's the best way to get top nth values from Dictionary?

Posted: 15 Oct 2021 09:37 AM PDT

I am trying to get the top n values from a dictionary. The part that is making it not easy for me is that if there are multiple values of the same rank, I need to keep all of them. For example, if a dictionary looks like:

Dictionary<string, int> dict = new Dictionary<string, int>();  dict.Add("AAA", 91);  dict.Add("BBB", 97);  dict.Add("CCC", 98);  dict.Add("DDD", 92);  dict.Add("EEE", 97);  dict.Add("FFF", 100);  

and if I want Top 3, I need to get

dict.Add("BBB", 97);  dict.Add("CCC", 98);  dict.Add("EEE", 97);  dict.Add("FFF", 100);  

because BBB and EEE have the same rank. I first sorted the dictionary by the rank, and tried Take() but it only took one of the two.

/* Does not work */  var dictSorted = dict.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value).Take(3);    /* The below only prints       FFF = 100      CCC = 98      BBB = 97        but not        EEE = 97  */  foreach(KeyValuePair kvp in dictSorted){      Console.WriteLine(kvp.Key + " = " + kvp.Value);  }  

Is there a good way to achieve this?

SQLAlchemy - Eager load subquery as column for an ORM class

Posted: 15 Oct 2021 09:37 AM PDT

I have two tables. One is mapped as an ORM class like so:

from typing import Union  from dataclasses import dataclass  from api.models import db, SerializerMixin    @dataclass  class Company(db.Model, SerializerMixin):      __tablename__ = "Company"      company_id: int = db.Column(db.Integer, primary_key = True)      name: str = db.Column(db.String(50), nullable = False, unique = True)      primary_contact: Union[int, None] = db.Column(db.Integer, db.ForeignKey("User.user_id"))      website: Union[str, None] = db.Column(db.Text)  

The second one is written as just a plain SQL table (wrote it this way since I don't plan to query from this table directly, only used for JOINS and COUNTS):

user_company_table = db.Table("UserCompany",      db.Column("user_id", db.Integer, db.ForeignKey("User.user_id"), primary_key = True, unique = True),      db.Column("company_id", db.Integer, db.ForeignKey("Company.company_id"), primary_key = True),      db.Column("assigned", db.DateTime, server_default = text("CURRENT_TIMESTAMP"), onupdate = datetime.utcnow),      db.Column("approved", db.Boolean, nullable = False, default = False)  )  

I need to fetch all columns from Company while at the same time getting a COUNT of all users who have approved = true and are assigned to one specific company. The resulting SQL would look like this:

SELECT Company.company_id, Company.name, Company.primary_contact, Company.website, (SELECT COUNT(1) FROM UserCompany WHERE approved = true and company_id = Company.company_id) AS user_count FROM Company;  

This should give me this sample result: enter image description here

So user_count is a result set from a subquery that was appended to the Company table. How would I go about adding a user_count property to the Company class that eager loads this subquery and attaches the result as a column whenever I run Company.query.all()?

Notes: using Flask 2.0+, Flask-SQLAlchemy, Python 3.9 (that explains the @dataclass and the type hints in the Model properties)

BASH: My variable's value is not displaying correctly inside a loop

Posted: 15 Oct 2021 09:38 AM PDT

In the function below, I'm using JQ to parse the JSON data and get the httpOperations key/value pair.

#!/usr/bin/env bash  function batch_post() {    SETTINGS_INPUT=$1 #! Variable that holds the argument value    n=0    :> "${SETTINGS_INPUT}"_req.tmp #! This will just create an empty file        while read setting    do      # Get parameters that need to go in the batch put/post request      url=$(echo $setting | ./jq -r '.url')      body=$(echo $setting | ./jq -r '.response.body')        # Get the request method      method=$(cat settings.json | ./jq --arg URL ${url} '.settings[] | select(.pathPattern==$URL|tostring).httpOperations[] | select(.method == "PUT" or .method == "POST").method')               # Save individual requests to be added to the batch request      let n=n+1    done <<< $(cat ${SETTINGS_INPUT} | ./jq -c '.')      # Format individual requests in the expected batch json format    cat "${SETTINGS_INPUT}"_req.tmp | ./jq -n '.requests |= [inputs]' > "${SETTINGS_LIST}"_batch_post_put_req    # TODO: Validate this has the correct format and PUT/POST according to the settings    cat "${SETTINGS_LIST}"_batch_post_put_req        #! DO NOT execute API call with put/post request  }  

and I'm passing a JSON file as my argument to this function, below is the content of the JSON file. Please note that this is not the full JSON data that I'm actually using.

   {    "settings" : [ {      "key" : "AccountingRules",      "description" : "Accounting Rules settings",      "context" : "Entity",      "pathPattern" : "/accounting-rules",      "httpOperations" : [ {        "method" : "GET",        "url" : "/settings/accounting-rules",        "parameters" : [ ],        "responseType" : {          "$ref" : "#/definitions/AccountingRules",          "definitions" : {            "AccountingRules" : {              "additionalProperties" : false,              "type" : "object",              "properties" : {                "allowRevenueScheduleNegativeAmounts" : {                  "type" : "boolean"                },                "allowBlankAccountingCodes" : {                  "type" : "boolean"                },                "allowCreationInClosedPeriod" : {                  "type" : "boolean"                },                "allowUsageInClosedPeriod" : {                  "type" : "boolean"                },                "differentCurrencies" : {                  "type" : "boolean"                }              }            }          }        }      }, {        "method" : "PUT",        "url" : "/settings/accounting-rules",        "parameters" : [ ],        "requestType" : {          "$ref" : "#/definitions/AccountingRules",          "definitions" : {            "AccountingRules" : {              "additionalProperties" : false,              "type" : "object",              "properties" : {                "allowRevenueScheduleNegativeAmounts" : {                  "type" : "boolean"                },                "allowBlankAccountingCodes" : {                  "type" : "boolean"                },                "allowCreationInClosedPeriod" : {                  "type" : "boolean"                },                "allowUsageInClosedPeriod" : {                  "type" : "boolean"                },                "differentCurrencies" : {                  "type" : "boolean"                }              }            }          }        },        "responseType" : {          "$ref" : "#/definitions/AccountingRules",          "definitions" : {            "AccountingRules" : {              "additionalProperties" : false,              "type" : "object",              "properties" : {                "allowRevenueScheduleNegativeAmounts" : {                  "type" : "boolean"                },                "allowBlankAccountingCodes" : {                  "type" : "boolean"                },                "allowCreationInClosedPeriod" : {                  "type" : "boolean"                },                "allowUsageInClosedPeriod" : {                  "type" : "boolean"                },                "differentCurrencies" : {                  "type" : "boolean"                }              }            }          }        }      } ]    }, {      "key" : "AgingBuckets",      "description" : "Aging Buckets",      "context" : "Entity",      "pathPattern" : "/aging-buckets",      "httpOperations" : [ {        "method" : "GET",        "url" : "/settings/aging-buckets",        "parameters" : [ ],        "responseType" : {          "$ref" : "#/definitions/AgingBucket",          "definitions" : {            "Bucket" : {              "additionalProperties" : false,              "type" : "object",              "properties" : {                "name" : {                  "type" : "string",                  "maxLength" : 100                },                "fromDaysPastDue" : {                  "type" : "integer"                },                "toDaysPastDue" : {                  "type" : "integer"                }              },              "required" : [ "name" ]            },            "AgingBucket" : {              "additionalProperties" : false,              "type" : "object",              "properties" : {                "includeNegativeInvoice" : {                  "type" : "boolean"                },                "buckets" : {                  "type" : "array",                  "items" : {                    "$ref" : "#/definitions/Bucket"                  }                }              }            }          }        }      } ]  }  ]}  

And whenever I'm displaying the output for my variable named "method", the output that's being returned is stacked on top of one another. To give you an example, the issue looks like this when displaying the $method value.

Display method below  "PUT"  "POST"  "PUT"  "POST"  "PUT"  "POST"  "PUT"  "POST"  "PUT"  "POST"  "PUT"  "POST"  "PUT"  "PUT"  "POST"  "PUT"  "POST"  "POST"  "PUT"  "POST"  Done displaying method  

Wherein I'm expecting the output to be just a single "PUT" or "POST" only. Also, the thing I observed that's kind of weird for me is that this issue will show up when I try to display my variable executing "$ echo ${method}" command but when I remove the curly braces it sometimes works fine.

EEG data preprocessing with mne python

Posted: 15 Oct 2021 09:37 AM PDT

I have Physiological EEG emotion dataset named "Deap". I want to analyze and visualize the data through MNE but it has its own format.

How can I load my personal data for pre-processing, data format is (.dat)?

Deny CreateBucket in S3 unless AES256 Encryption Checked

Posted: 15 Oct 2021 09:37 AM PDT

I have been trying for the better part of a day. I am, as an administrator, attempting to require users to check the "Automatically encrypt objects when they are stored in S3" button (AES256) when creating their S3 buckets. I've tried about everything can think of. So far, I have only gotten 2 separate results.

As a test user, I am either allowed to create buckets (with or without checking encryption), or I am denied (with or without checking encryption).

The last effort has resulted in the following policy being applied to the test user, in which case I am denied creating a bucket whether or not I check the encryption box

{      "Version": "2012-10-17",      "Statement": [          {              "Sid": "VisualEditor0",              "Effect": "Deny",              "Action": [                  "s3:CreateBucket"              ],              "Resource": "*",              "Condition": {                  "StringNotEquals": {                      "s3:x-amz-content-sha256": "AES256"                  },                  "Null": {                      "s3:x-amz-content-sha256": true                  }              }       ]    }    

I have combined the above policy with S3AllowFullAccess, with other custom policies allowing access, but I simply cannot get it to work.

Any help is appreciated

How do you change the icon of the `wwwroot` folder in a .NET Core project?

Posted: 15 Oct 2021 09:37 AM PDT

In Visual Studio 2017, when I want to create an ASP.NET Core Web Application from scratch using either one of these standard .NET Core project templates:

  • Console App (.NET Core)
  • Class Library (.NET Core)

These project templates; obviously would not include the wwwroot folder. So, when I add the folder to my project it will look like (and behave like) a standard folder:

.NET Core Console App

When you create it using the ASP.NET Core Web Application project template, the wwwroot folder looks like this:

ASP.NET Core Web Application

Question - Appearance (Icon)

How do you change the icon of the wwwroot folder to look like the one found in the ASP.NET Core Web Application project template?


Additional Question - Behavior (Copying Files to Output Directory)
In the standard .NET Core project, I would have to add this to my .csproj file:

<ItemGroup>    <Content Include="wwwroot\**" CopyToOutputDirectory="PreserveNewest" />  </ItemGroup>  

so that it copies all my files from the wwwroot folder to the output directory similar to the ASP.NET Core Web Application project. I looked in the ASP.NET Core Web Application's .csproj file and didn't see anything like that.

I'm assuming the answer to the main question will also provide the answer for this one, as the project templates are obviously different. I can't seem to find the resources online to help me manually edit this myself.

Thanks in advance.

Managed Debugging Assistant 'FatalExecutionEngineError'

Posted: 15 Oct 2021 09:38 AM PDT

I'm getting below error:

Managed Debugging Assistant 'FatalExecutionEngineError' has detected a problem in 'C:\Users\App\App.exe'. Additional Information: The runtime has encountered a fatal error. The address of the error was at 0xf5b029e1, on thread 0x72bc. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

I get the above error when i execute this statement while debugging.

 LoggerHandler.Info("Executed " & iterations.ToString & " iterations on " & max_processors & " cores in " & Format((Now() - time).TotalSeconds, "0.0") & " seconds.")  

No comments:

Post a Comment