问:
Error on Displaying Image in Spring Project
I'm sending the resourceAsStream to the front-end and the code works in one project but failed in another

```<code>The failed one shows the error - "The resource identified by this request is only capable
 of generating responses with characteristics not acceptable according to the request
"accept" headers."

return new ResponseEntity<>(byteArray, headers, HttpStatus.OK)
</code>```

Both of them are spring project.

Please let me know why I am getting the above error in one of the project.

Body:
I'm sending the resourceAsStream to the front-end and the code works in one project but failed in another

The failed one shows the error - "The resource identified by this request is only capable
 of generating responses with characteristics not acceptable according to the request
"accept" headers."

return new ResponseEntity<>(byteArray, headers, HttpStatus.OK)

Both of them are spring project.

Please let me know why I am getting the above error in one of the project.


来源: stackexchange

问:
Scipy integration gives wrong values
When I was trying to produce a function, there was a problem :

I wanted to make the function with infinite limit integral

```<code>def integrand(x, eta):
    return eta**2 / (np.exp(np.sqrt(eta**2 + x**2) + 1))

def Iplus(x):
    return integrate.quad(integrand, 0, 1, args=(x))[0]
</code>```

When I input the value x = 0 in to the Iplus function,

it gave me "zero"

But, when I calculated in this way:

```<code>def integrand(eta):
    return (eta**2 / (np.exp(np.sqrt(eta**2)) + 1))
a = integrate.quad(integrand, 0, np.inf)[0]
a
</code>```

a = 1.8030853547393915

It gave me the true answer.

Please help me!

```<code>def integrand(x, eta):
    return eta**2 / (np.exp(np.sqrt(eta**2 + x**2) + 1))

def Iplus(x):
    return integrate.quad(integrand, 0, 1, args=(x))[0]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Scipy integration gives wrong values

Body:
When I was trying to produce a function, there was a problem :

I wanted to make the function with infinite limit integral

def integrand(x, eta):
    return eta**2 / (np.exp(np.sqrt(eta**2 + x**2) + 1))

def Iplus(x):
    return integrate.quad(integrand, 0, 1, args=(x))[0]

When I input the value x = 0 in to the Iplus function,

it gave me "zero"

But, when I calculated in this way:

def integrand(eta):
    return (eta**2 / (np.exp(np.sqrt(eta**2)) + 1))
a = integrate.quad(integrand, 0, np.inf)[0]
a

a = 1.8030853547393915

It gave me the true answer.

Please help me!

def integrand(x, eta):
    return eta**2 / (np.exp(np.sqrt(eta**2 + x**2) + 1))

def Iplus(x):
    return integrate.quad(integrand, 0, 1, args=(x))[0]


问:
Kivy kv. file throws error "Invalid indentation (too many levels)", why?
I'm trying to get this kv. file to run, but it throws the error "Invalid indentation (too many levels)". For the life of me, I don't understand why. Im suspicious that its the way I am nesting the layouts within the kv. file, but I'm not sure. Any help/critique would be appreciated!

.py file:

```<code>from kivy.app import App
import tarot
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout

class selectCard(BoxLayout):

    def __init__(self, *args, **kwargs):
        super(selectCard,self).__init__(*args,**kwargs)
        self.my_text = "Background.png"

    def on_click(self):
        if self.my_text == "Background.png":
            self.my_text = tarot.read().one()
            self.ids.card_image.source = "Cards\\" + self.my_text + ".png"
            print(self.my_text)
        else:
            self.my_text = "Background.png"
            self.ids.card_image.source = "Background.png"
            print(self.my_text)

class layout(FloatLayout):
    pass

class TarotApp(App):
    def build(self):
        return selectCard()

TarotApp().run()
</code>```

.kv file:

```<code>
<layout>
    canvas.before:
        Color:
            rgba: 0, 1, 0, 1
        Rectangle:
            pos: self.pos
            size: self.size

<seletCard>
    layout:
        Button:
            normal: root.my_text
            on_release:  root.on_click()
            background_color: 1,1,1,1
            size_hint: (1,1)
            pos_hint: {'center_x':.5,'center_y':.5}
            Image:
                source: root.my_text
                id: card_image
                pos: self.parent.pos
                size: self.parent.size
                #background_color: self.parent.background_color
                stretch: True
    Button:
        normal: root.my_text
        on_release:  root.on_click()
        background_color: 1,1,1,1
        #size_hint: (1,1)
        pos_hint: {'center_x':.5,'center_y':.5}
        Image:
            source: root.my_text
            id: card_image
            pos: self.parent.pos
            size: self.parent.size
            background_color: self.parent.background_color
            stretch: True
</code>```

I don't think this is an indentation problem. Am I referencing something incorrectly?

Body:
I'm trying to get this kv. file to run, but it throws the error "Invalid indentation (too many levels)". For the life of me, I don't understand why. Im suspicious that its the way I am nesting the layouts within the kv. file, but I'm not sure. Any help/critique would be appreciated!

.py file:

from kivy.app import App
import tarot
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout

class selectCard(BoxLayout):

    def __init__(self, *args, **kwargs):
        super(selectCard,self).__init__(*args,**kwargs)
        self.my_text = "Background.png"

    def on_click(self):
        if self.my_text == "Background.png":
            self.my_text = tarot.read().one()
            self.ids.card_image.source = "Cards\\" + self.my_text + ".png"
            print(self.my_text)
        else:
            self.my_text = "Background.png"
            self.ids.card_image.source = "Background.png"
            print(self.my_text)

class layout(FloatLayout):
    pass

class TarotApp(App):
    def build(self):
        return selectCard()

TarotApp().run()

.kv file:

<layout>
    canvas.before:
        Color:
            rgba: 0, 1, 0, 1
        Rectangle:
            pos: self.pos
            size: self.size

<seletCard>
    layout:
        Button:
            normal: root.my_text
            on_release:  root.on_click()
            background_color: 1,1,1,1
            size_hint: (1,1)
            pos_hint: {'center_x':.5,'center_y':.5}
            Image:
                source: root.my_text
                id: card_image
                pos: self.parent.pos
                size: self.parent.size
                #background_color: self.parent.background_color
                stretch: True
    Button:
        normal: root.my_text
        on_release:  root.on_click()
        background_color: 1,1,1,1
        #size_hint: (1,1)
        pos_hint: {'center_x':.5,'center_y':.5}
        Image:
            source: root.my_text
            id: card_image
            pos: self.parent.pos
            size: self.parent.size
            background_color: self.parent.background_color
            stretch: True

I don't think this is an indentation problem. Am I referencing something incorrectly?


问:
(Angular) Scrolltrigger works in localhost but not after build on server
I am using gsap for the first time in Angular and was trying the Scrolltrigger. In my localhost all works fine with this code:

The boxes faded in nicely but now we come to my problem.

I use "ng build --prod" to generate my project and loaded it on my server.

If I now look on my page, there isn't any animation and I got the following error in console:

Invalid property scrollTrigger set to {trigger: p.readmore-block.fadeIn.ng-tns-c45-3, start: "top bottom", markers: false, scrub: 1, end: "top center"} Missing plugin? gsap.registerPlugin()

Can anyone help me out?


问:
How can we get the text from scrolledtext and create a pdf
I wrote this code but after clicking the generate pdf button it gives blank page pdf as an output with no text at all.

```<code>from tkinter import *
import tkinter as tk
from tkinter.filedialog import asksaveasfile, asksaveasfilename
from reportlab.pdfgen import canvas
from reportlab.lib.styles import ParagraphStyle
from reportlab.platypus import Paragraph
from reportlab.lib.pagesizes import  A4
from tkinter import scrolledtext

my_w = tk.Tk()
my_w.geometry("400x300")
my_w.title("PDF GENERATOR")
b1=tk.Button(text='Generate PDF',command=lambda:gen_pdf())
b1.grid(row=2,column=0,padx=20,pady=10)
infodescr = tk.scrolledtext.ScrolledText(my_w, width=70, height=12,wrap=WORD,font = ('calibre',12))
infodescr.grid(row=1, column=0,   sticky=E+W+N+S,padx=5,pady=5)
infodescr.insert(INSERT,"Hello this is the sample pdf \n you are welcome!")

my_Style = ParagraphStyle('My Para style',fontName="Times-Roman",fontSize=16,
     alignment=0, borderWidth=2,borderColor='#FFFF00',backColor = '#F1F1F1',
                          borderPadding = (20, 20, 20),leading = 20)
width, height = A4
def gen_pdf():
    my_path = asksaveasfilename(filetypes=[('PDF files', '*.pdf')], defaultextension=".pdf")
    if my_path:
        text = infodescr.get("1.0", END)
        text = text.replace('\n', '<BR/>')
        p1 = Paragraph(text, my_Style)
        c = canvas.Canvas(my_path, pagesize=A4)
        p1.wrapOn(c, 300, 50)
        p1.drawOn(c, width - 800, height - 1000)
        c.save()
my_w.mainloop()
</code>```

I have tried the same with entry widget and it works fine with the entered value but for the inserted value it returns blank file with no text.

Body:
I wrote this code but after clicking the generate pdf button it gives blank page pdf as an output with no text at all.

from tkinter import *
import tkinter as tk
from tkinter.filedialog import asksaveasfile, asksaveasfilename
from reportlab.pdfgen import canvas
from reportlab.lib.styles import ParagraphStyle
from reportlab.platypus import Paragraph
from reportlab.lib.pagesizes import  A4
from tkinter import scrolledtext

my_w = tk.Tk()
my_w.geometry("400x300")
my_w.title("PDF GENERATOR")
b1=tk.Button(text='Generate PDF',command=lambda:gen_pdf())
b1.grid(row=2,column=0,padx=20,pady=10)
infodescr = tk.scrolledtext.ScrolledText(my_w, width=70, height=12,wrap=WORD,font = ('calibre',12))
infodescr.grid(row=1, column=0,   sticky=E+W+N+S,padx=5,pady=5)
infodescr.insert(INSERT,"Hello this is the sample pdf \n you are welcome!")

my_Style = ParagraphStyle('My Para style',fontName="Times-Roman",fontSize=16,
     alignment=0, borderWidth=2,borderColor='#FFFF00',backColor = '#F1F1F1',
                          borderPadding = (20, 20, 20),leading = 20)
width, height = A4
def gen_pdf():
    my_path = asksaveasfilename(filetypes=[('PDF files', '*.pdf')], defaultextension=".pdf")
    if my_path:
        text = infodescr.get("1.0", END)
        text = text.replace('\n', '
')
        p1 = Paragraph(text, my_Style)
        c = canvas.Canvas(my_path, pagesize=A4)
        p1.wrapOn(c, 300, 50)
        p1.drawOn(c, width - 800, height - 1000)
        c.save()
my_w.mainloop()

I have tried the same with entry widget and it works fine with the entered value but for the inserted value it returns blank file with no text.


问:
Globbing filenames from file using compgen
I'm simplifying a messy Bash script that synchronizes directories and their contents and files among several machines on a network using rsync.

The script gets file names, directory names, and glob patterns from a sources.txt file with contents like (abridged):

```<code>go/
Pictures/
Videos/
Android/
.AndroidStudio*/
texmf/
.customization/
.local/share/rhythmbox/
.m2/
</code>```

My smplified version of the updated script needs to expand globs within sources.txt and present the result to rsync's --files-from=FILE option.  To do this, I'm using a helper script (expand-globs-in-file.sh), reproduced below (and process substitution):

```<code>#!/bin/bash
if [ -n "$1" ]; then
  cat $1 | tr '\n' '\0' | xargs -i -0 sh -c 'compgen -o bashdefault -G "{}"'
else
  echo "Usage: $0 <filename>"
fi
</code>```

What I am experiencing is that the script doesn't pass through some filenames (most begin with a period) while executing cat sources.txt | tr '\n' '\0' | xargs -i -0 sh -c 'compgen -o bashdefault -G "{}"' on the command line works as expected.

Directory and file names/glob patterns that fail to be passed through:

```<code>.emacs
.gitconfig
.AndroidStudio*/
GPG-KEY-apacifico
network.txt
.jq
</code>```

The following fle and directory names pass through correctly:

```<code>Documents/
Finances/
Downloads/
Development/
.android/
go/
Pictures/
Videos/
.cellphone/
Android/
texmf/
.customization/
.local/share/rhythmbox/
.m2/
useful-scripts/
rpmbuild/
texmf/
</code>```

What am I doing wrong?  I'm suspicious this is a quoting problem, but I don't see it.

Body:
I'm simplifying a messy Bash script that synchronizes directories and their contents and files among several machines on a network using rsync.

The script gets file names, directory names, and glob patterns from a sources.txt file with contents like (abridged):

go/
Pictures/
Videos/
Android/
.AndroidStudio*/
texmf/
.customization/
.local/share/rhythmbox/
.m2/

My smplified version of the updated script needs to expand globs within sources.txt and present the result to rsync's --files-from=FILE option.  To do this, I'm using a helper script (expand-globs-in-file.sh), reproduced below (and process substitution):

#!/bin/bash
if [ -n "$1" ]; then
  cat $1 | tr '\n' '\0' | xargs -i -0 sh -c 'compgen -o bashdefault -G "{}"'
else
  echo "Usage: $0 <filename>"
fi

What I am experiencing is that the script doesn't pass through some filenames (most begin with a period) while executing cat sources.txt | tr '\n' '\0' | xargs -i -0 sh -c 'compgen -o bashdefault -G "{}"' on the command line works as expected.

Directory and file names/glob patterns that fail to be passed through:

.emacs
.gitconfig
.AndroidStudio*/
GPG-KEY-apacifico
network.txt
.jq

The following fle and directory names pass through correctly:

Documents/
Finances/
Downloads/
Development/
.android/
go/
Pictures/
Videos/
.cellphone/
Android/
texmf/
.customization/
.local/share/rhythmbox/
.m2/
useful-scripts/
rpmbuild/
texmf/

What am I doing wrong?  I'm suspicious this is a quoting problem, but I don't see it.


问:
I am using React-Core/RCTWebSocket (= 0.70.1) in react native,Getting issue while closing the Websocket on when the user logOut from the app
Written the code like below for closing the socket on logout

```<code>useEffect(() => {
    EventRegister.addEventListener("Logout", (value) => {
      if (value === true) {
        socket.close();
        socket = null;
      }
    });
  });
</code>```

I am getting the issue like this TypeError: null is not an object (evaluating 'socket.close')
and when I removed the socket (socket = null),then getting socket closing with readyState 2,

I want it should close properly with readyState 3.Image for the error is also attached.

Body:
Written the code like below for closing the socket on logout

useEffect(() => {
    EventRegister.addEventListener("Logout", (value) => {
      if (value === true) {
        socket.close();
        socket = null;
      }
    });
  });

I am getting the issue like this TypeError: null is not an object (evaluating 'socket.close')
and when I removed the socket (socket = null),then getting socket closing with readyState 2,

I want it should close properly with readyState 3.Image for the error is also attached.


问:
How to find whether audio recording is empty or not?
I want to add validation of the save button i.e., check if edit text or recorded audio (one among these two) has been entered by the user or not if both are not entered then the user gets notified that either enter text or record your audio. I have done this code, but it's getting crashed onClick of save button

```<code>
File fileName = new File(finalpath);
Log.e("FileName::",""+fileName);
//   convertfiletobase64(strreminder_txt, strreminder_time, finalpath, finalStrcheckDialy);
if (listfiles.size()==0) {
    listfiles.add(fileName);
} else {
    if (notifiadapeterpos < listfiles.size()) {
        listfiles.set(notifiadapeterpos, fileName);
    } else {
        listfiles.add(fileName);
    }
}
notificationPart = prepareFilePart1(listfiles);

if(mediaRecorder==null&&mediaPlayer==null){
    if (strreminder_txt.isEmpty()){
        Toast.makeText(RegisterMember.this, "Please enter Reminder Text or Record your Reminder!", Toast.LENGTH_SHORT).show();
    }else {
        if (btnsaveReminder.getText().equals("Update")){
            updateReminder(strreminder_txt, strreminder_time, fileName, finalStrcheckDialy,notificationPart);
        }else {
            saveReminder(strreminder_txt, strreminder_time, fileName, finalStrcheckDialy,notificationPart);
        }
    }
}

</code>```

How to resolve this?

Body:
I want to add validation of the save button i.e., check if edit text or recorded audio (one among these two) has been entered by the user or not if both are not entered then the user gets notified that either enter text or record your audio. I have done this code, but it's getting crashed onClick of save button

File fileName = new File(finalpath);
Log.e("FileName::",""+fileName);
//   convertfiletobase64(strreminder_txt, strreminder_time, finalpath, finalStrcheckDialy);
if (listfiles.size()==0) {
    listfiles.add(fileName);
} else {
    if (notifiadapeterpos < listfiles.size()) {
        listfiles.set(notifiadapeterpos, fileName);
    } else {
        listfiles.add(fileName);
    }
}
notificationPart = prepareFilePart1(listfiles);

if(mediaRecorder==null&&mediaPlayer==null){
    if (strreminder_txt.isEmpty()){
        Toast.makeText(RegisterMember.this, "Please enter Reminder Text or Record your Reminder!", Toast.LENGTH_SHORT).show();
    }else {
        if (btnsaveReminder.getText().equals("Update")){
            updateReminder(strreminder_txt, strreminder_time, fileName, finalStrcheckDialy,notificationPart);
        }else {
            saveReminder(strreminder_txt, strreminder_time, fileName, finalStrcheckDialy,notificationPart);
        }
    }
}

How to resolve this?


问:
Launch Chrome with command line switches has no effect
I type these code below on windows cmd.

with  switch --version

```<code>"C:\Program Files\Google\Chrome\Application\chrome.exe" --profile-directory="Default" --version
</code>```

without switch --version

```<code>"C:\Program Files\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1"
</code>```

then type chrome://version/ on browser for each.
In this case you will see all of both with switch --version on command line property.

could i have this reason? Thanks.

Body:
I type these code below on windows cmd.

with  switch --version

"C:\Program Files\Google\Chrome\Application\chrome.exe" --profile-directory="Default" --version

without switch --version

"C:\Program Files\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1"

then type chrome://version/ on browser for each.
In this case you will see all of both with switch --version on command line property.

could i have this reason? Thanks.


问:
Purpose of REQUEST , INCLUDE , FORWARD dispatcher configuration for filter in tomcat and how it works internally
```<code><filter>
        <filter-name>ServerFilter</filter-name>
        <filter-class>com.filter.ServerFilter</filter-class>
</filter>

<filter-mapping>
        <filter-name>ServerFilter</filter-name>
        <url-pattern>*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>FORWARD</dispatcher>
</filter-mapping>
</code>```

i have above configuration for SeverFilter in tomcat web.xml , for some other filters only REQUEST or FORWARD dispatcher are configured. what is the purpose and how it works internally . when i add FORWARD tag all requests are passed through ServerFilter , and when i add INCLUDE tag return null response .

Body:
<filter>
        <filter-name>ServerFilter</filter-name>
        <filter-class>com.filter.ServerFilter</filter-class>
</filter>

<filter-mapping>
        <filter-name>ServerFilter</filter-name>
        <url-pattern>*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>FORWARD</dispatcher>
</filter-mapping>

i have above configuration for SeverFilter in tomcat web.xml , for some other filters only REQUEST or FORWARD dispatcher are configured. what is the purpose and how it works internally . when i add FORWARD tag all requests are passed through ServerFilter , and when i add INCLUDE tag return null response .


问:
How to check location is on or not while app is running
I want to check all the time when the app is running, that location of mobile is on or not.
Because I don't want to let client turn the location off when use my application.
I know how to check GPS is on or not for one time but I don't know how to check that all time.

I have checked and searched a lot but I couldn't find anything useful


问:
Placement of QComboBox inside QTableView
I'm trying to use a QComboBox as a item delegate to update a field in my QTableView. The editor, selection, and model data are all working fine. However, the problem is that when I click on the cell, the QComboBox does not open inside the cell. Instead it opens somewhere outside the main GUI (see attached screenshot). Any ideas how I can fix this beahvior?

I have also added a QSpinBox for column Freq/Qty and they are showing up properly in the cell when I double click for editing.

Note the combo box on the top left of the image.

My code:

```<code>        ...
        hb = QTableView()
        hbm = HierBlocksDataModel()
        hb.setModel(hbm)
        hb.verticalHeader().setDefaultSectionSize(25)
        lbd = LibraryBoxDelegate(hb)
        hb.setItemDelegateForColumn(3, lbd)
        ...

class LibraryBoxDelegate(QStyledItemDelegate):
    def __init__(self, parent, node=None):
        super(LibraryBoxDelegate, self).__init__(parent)
        self.node = node

    def createEditor(self, parent, option, index):

        if self.node is not None:
            cb = QComboBox()
            cb.addItems(list('abc'))
            return cb

    def setEditorData(self, editor, index):
        editor.setCurrentText(index.model().data(index, Qt.DisplayRole))

    def setModelData(self, editor, model, index):
        model.setData(index, editor.currentText(), Qt.EditRole)
</code>```

Body:
I'm trying to use a QComboBox as a item delegate to update a field in my QTableView. The editor, selection, and model data are all working fine. However, the problem is that when I click on the cell, the QComboBox does not open inside the cell. Instead it opens somewhere outside the main GUI (see attached screenshot). Any ideas how I can fix this beahvior?

I have also added a QSpinBox for column Freq/Qty and they are showing up properly in the cell when I double click for editing.

Note the combo box on the top left of the image.

My code:

        ...
        hb = QTableView()
        hbm = HierBlocksDataModel()
        hb.setModel(hbm)
        hb.verticalHeader().setDefaultSectionSize(25)
        lbd = LibraryBoxDelegate(hb)
        hb.setItemDelegateForColumn(3, lbd)
        ...

class LibraryBoxDelegate(QStyledItemDelegate):
    def __init__(self, parent, node=None):
        super(LibraryBoxDelegate, self).__init__(parent)
        self.node = node

    def createEditor(self, parent, option, index):

        if self.node is not None:
            cb = QComboBox()
            cb.addItems(list('abc'))
            return cb

    def setEditorData(self, editor, index):
        editor.setCurrentText(index.model().data(index, Qt.DisplayRole))

    def setModelData(self, editor, model, index):
        model.setData(index, editor.currentText(), Qt.EditRole)


问:
Flutter - Prevent WebViewx video from going fullscreen on ios
Currently using Webviewx from https://pub.dev/packages/webviewx in my Flutter app, but unfortunately I can't seem to figure out how to avoid the player go fullscreen on my iPhone. It works fine on Android, but on ios the video keeps opening up in fullscreen instead of staying inline :(.

```<code>// Automatic FlutterFlow imports
import '../../backend/backend.dart';
import '../../flutter_flow/flutter_flow_theme.dart';
import '../../flutter_flow/flutter_flow_util.dart';
import 'index.dart'; // Imports other custom widgets
import '../actions/index.dart'; // Imports custom actions
import '../../flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom widget code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'package:webviewx/webviewx.dart';

class MuxPlayer extends StatefulWidget {
  const MuxPlayer(
      {Key? key,
      this.width,
      this.height,
      required this.playbackId,
      this.primaryColor})
      : super(key: key);

  final double? width;
  final double? height;
  final String playbackId;
  final String? primaryColor;

  @override
  _MuxPlayerState createState() => _MuxPlayerState();
}

class _MuxPlayerState extends State<MuxPlayer> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primaryColor: Colors.transparent,
      ),
      home: VideoScreen(
        pbId: widget.playbackId,
        primaryColor: widget.primaryColor,
      ),
    );
  }
}

class VideoScreen extends StatelessWidget {
  final String pbId;
  final String? primaryColor;

  const VideoScreen({Key? key, required this.pbId, this.primaryColor})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Html5Player(
        playbackId: pbId,
        primaryColor: primaryColor,
      ),
    );
  }
}

//

class Html5Player extends StatefulWidget {
  const Html5Player({
    this.height = double.maxFinite,
    this.width = double.maxFinite,
    required this.playbackId,
    this.streamType,
    this.videoTitle,
    this.viewerUserId,
    this.primaryColor = 'burlywood',
    this.secondaryColor = '#383838',
    this.muted = false,
    this.crossOrigin = 'anonymous',
    this.startTime,
    Key? key,
  }) : super(key: key);

  ///
  /// `playbackId` is  video play back id from mux.
  ///
  final String playbackId;

  ///
  ///
  ///
  final String? streamType;

  ///
  ///
  final String? videoTitle;

  ///
  ///
  ///
  final String? viewerUserId;

  ///
  ///
  final String? primaryColor;

  ///
  final String? secondaryColor;

  ///
  final bool? muted;

  ///
  final String? crossOrigin;

  ///
  final double? startTime;

  ///
  final double height;

  ///
  final double width;

  @override
  State<Html5Player> createState() => _Html5PlayerState();
}

class _Html5PlayerState extends State<Html5Player> {
  late WebViewXController webviewController;

  late Widget body;

  @override
  void initState() {
    String initialHtmlSource = '''
  <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>Testing Mux Player</title>

  </head>
  <body style="overflow:hidden; margin:0">
    <script src="https://unpkg.com/@mux/mux-player"></script>

    <mux-player
      style="height: 105vh;width: 100vw;--bottom-controls: none;--top-controls:none;--seek-backward-button: none;--seek-forward-button: none;"
      addEventListener(play)
      stream-type= ${widget.streamType}
      playback-id= ${widget.playbackId}
      metadata-video-title=${widget.videoTitle}
      metadata-viewer-user-id= ${widget.viewerUserId}
      primary-color= ${widget.primaryColor}
      secondary-color=${widget.secondaryColor}
      muted='false'
      crossOrigin=${widget.crossOrigin}
      forward-seek-offset="15"
      backward-seek-offset="15"
      start-time=${widget.startTime}
      autoplay="any"
      nohotkeys
      loop
      placeholder='#EE8B60'
      playsinline
    ></mux-player>

  </body>
</html>
  ''';
    body = WebViewX(
      height: widget.height,
      width: widget.width,
      initialContent: initialHtmlSource,
      initialSourceType: SourceType.html,
      onWebViewCreated: (controller) => webviewController = controller,
      initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.alwaysAllow,
      webSpecificParams: WebSpecificParams(webAllowFullscreenContent: false),
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return body;
  }
}

</code>```

Tried figuring out where to place the "allowsInlineMediaPlayback = true" property, but by the life of me I can't figure this one out. I've also tried to understand how to implement the html code in another WebView that facilitates the inline playback a bit better, but since I'm such a beginner this is proving to be extremely difficult and impossible for me to do at the moment. Any help is truly appreciated.

Body:
Currently using Webviewx from https://pub.dev/packages/webviewx in my Flutter app, but unfortunately I can't seem to figure out how to avoid the player go fullscreen on my iPhone. It works fine on Android, but on ios the video keeps opening up in fullscreen instead of staying inline :(.

// Automatic FlutterFlow imports
import '../../backend/backend.dart';
import '../../flutter_flow/flutter_flow_theme.dart';
import '../../flutter_flow/flutter_flow_util.dart';
import 'index.dart'; // Imports other custom widgets
import '../actions/index.dart'; // Imports custom actions
import '../../flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom widget code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'package:webviewx/webviewx.dart';

class MuxPlayer extends StatefulWidget {
  const MuxPlayer(
      {Key? key,
      this.width,
      this.height,
      required this.playbackId,
      this.primaryColor})
      : super(key: key);

  final double? width;
  final double? height;
  final String playbackId;
  final String? primaryColor;

  @override
  _MuxPlayerState createState() => _MuxPlayerState();
}

class _MuxPlayerState extends State<MuxPlayer> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primaryColor: Colors.transparent,
      ),
      home: VideoScreen(
        pbId: widget.playbackId,
        primaryColor: widget.primaryColor,
      ),
    );
  }
}

class VideoScreen extends StatelessWidget {
  final String pbId;
  final String? primaryColor;

  const VideoScreen({Key? key, required this.pbId, this.primaryColor})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Html5Player(
        playbackId: pbId,
        primaryColor: primaryColor,
      ),
    );
  }
}

//

class Html5Player extends StatefulWidget {
  const Html5Player({
    this.height = double.maxFinite,
    this.width = double.maxFinite,
    required this.playbackId,
    this.streamType,
    this.videoTitle,
    this.viewerUserId,
    this.primaryColor = 'burlywood',
    this.secondaryColor = '#383838',
    this.muted = false,
    this.crossOrigin = 'anonymous',
    this.startTime,
    Key? key,
  }) : super(key: key);

  ///
  /// `playbackId` is  video play back id from mux.
  ///
  final String playbackId;

  ///
  ///
  ///
  final String? streamType;

  ///
  ///
  final String? videoTitle;

  ///
  ///
  ///
  final String? viewerUserId;

  ///
  ///
  final String? primaryColor;

  ///
  final String? secondaryColor;

  ///
  final bool? muted;

  ///
  final String? crossOrigin;

  ///
  final double? startTime;

  ///
  final double height;

  ///
  final double width;

  @override
  State<Html5Player> createState() => _Html5PlayerState();
}

class _Html5PlayerState extends State<Html5Player> {
  late WebViewXController webviewController;

  late Widget body;

  @override
  void initState() {
    String initialHtmlSource = '''
  <!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>Testing Mux Player</title>

    <mux-player
      style="height: 105vh;width: 100vw;--bottom-controls: none;--top-controls:none;--seek-backward-button: none;--seek-forward-button: none;"
      addEventListener(play)
      stream-type= ${widget.streamType}
      playback-id= ${widget.playbackId}
      metadata-video-title=${widget.videoTitle}
      metadata-viewer-user-id= ${widget.viewerUserId}
      primary-color= ${widget.primaryColor}
      secondary-color=${widget.secondaryColor}
      muted='false'
      crossOrigin=${widget.crossOrigin}
      forward-seek-offset="15"
      backward-seek-offset="15"
      start-time=${widget.startTime}
      autoplay="any"
      nohotkeys
      loop
      placeholder='#EE8B60'
      playsinline
    ></mux-player>

  ''';
    body = WebViewX(
      height: widget.height,
      width: widget.width,
      initialContent: initialHtmlSource,
      initialSourceType: SourceType.html,
      onWebViewCreated: (controller) => webviewController = controller,
      initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.alwaysAllow,
      webSpecificParams: WebSpecificParams(webAllowFullscreenContent: false),
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return body;
  }
}

Tried figuring out where to place the "allowsInlineMediaPlayback = true" property, but by the life of me I can't figure this one out. I've also tried to understand how to implement the html code in another WebView that facilitates the inline playback a bit better, but since I'm such a beginner this is proving to be extremely difficult and impossible for me to do at the moment. Any help is truly appreciated.


问:
AttributeError: __aenter__ on asynchronous websocket python
I try to resolve this problem about asynchronous WebSocket using python. I don't know why when I used the asynchronous process I get the error log bellow. But my code is totally fine when I didn't used the asynchronous.

error log

```<code>C:\ProgramData\Anaconda3\lib\site-packages\numpy\__init__.py:148: UserWarning: mkl-service package failed to import, therefore Intel(R) MKL initialization ensuring its correct out-of-the box operation under condition when Gnu OpenMP had already been loaded by Python process is not assured. Please install mkl-service package, see http://github.com/IntelPython/mkl-service
  from . import _distributor_init
[2022-12-15 12:51:26,677][root][INFO] - Connected to localhost object_detection mysql database
Error executing job with overrides: []
Traceback (most recent call last):
  File "e:\alfa_beta\etl-python\object_counting\object_counting.py", line 102, in object_counter
  File "e:\alfa_beta\etl-python\object_counting\object_counting.py", line 102, in object_counter
    obj_counting.async_runner()
  File "e:\alfa_beta\etl-python\object_counting\object_counting.py", line 41, in async_runner
    asyncio.run(self.vehicle_async())
  File "C:\ProgramData\Anaconda3\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 647, in run_until_complete
    return future.result()
  File "e:\alfa_beta\etl-python\object_counting\object_counting.py", line 62, in vehicle_async
    async with create_connection(self.ws_connection) as async_ws_connection:
AttributeError: __aenter__

Set the environment variable HYDRA_FULL_ERROR=1 for a complete stack trace.
</code>```

hydra config

```<code>mode: object_counter

# internal database (mysql)
local_db:
  database: object_detection
  enabled: true
  host: localhost
  password: ""
  port: 3306
  user: root
  db_type: mysql

# service camera
service:
  vehichle_counting:
    table: history_vehicles
    ip_cam: 123.23.322.10
    ws_connect: ws://123.23.322.24:324/
    ws_host: 123.23.322.24
    ws_port: 324
    ws_prefix:
      json_data: 3242
      unknown: 42
      video_stream: 0222
</code>```

Main code to run async object_counting.py

```<code>from omegaconf import DictConfig
from pyrootutils import setup_root
from types import SimpleNamespace
from websocket import create_connection, enableTrace
import dill as pickle
import asyncio
import hydra
import json

root = setup_root(
    search_from=__file__,
    indicator=[".git", "pyproject.toml"],
    pythonpath=True,
    dotenv=True,
)

# internal package
import websocket_data as wsd
from src.config.database_config import Database
from src.infra import time_infra as ABTime

# from object_counting import websocket_data as wsd

# TODO multi processing

class ObjectCounting:

    def __init__(self, config: DictConfig, ip_camera: str, ws_connection: str):
        self.config = config
        self.ip_camera = ip_camera
        self.ws_connection = ws_connection  # websocket

    def async_runner(self):
        """
        async_runner will help us to run the asynchronous process in object detection
        for now will runn vehicle_async
        """
        asyncio.run(self.vehicle_async())

    async def vehicle_async(self):
        """
        vehicle_async is the asynchronous process for vehicle detection.
        It will take data from WebSocket with ANPR type and push the license
        plate number with vehicle type of each caught vehicle to MYSQL database
        """
        # database
        self.local_db = Database(
            self.config.local_db.host,
            self.config.local_db.port,
            self.config.local_db.user,
            self.config.local_db.password,
            self.config.local_db.database,
            self.config.local_db.db_type,
        ) if self.config.local_db.enabled else None

        self.push_table = self.config.service.vehichle_counting_cam_1.table

        # enableTrace(True)
        async with create_connection(self.ws_connection) as async_ws_connection:
            while True:
                try:
                    json_data = json.loads(await async_ws_connection.recv(),
                                           object_hook=lambda d: SimpleNamespace(**d))
                    if json_data.type == "anpr":
                        raw_data = wsd.WebsocketData(json_data.type,
                                                 json_data.payload,
                                                 json_data.img)
                        payload_ws = raw_data.payload[0]
                        result_json = payload_ws.resjson
                        image_ws = raw_data.img
                        if result_json != '':
                            print("\ncatch!")
                            print('\nPayload: {}'.format(payload_ws))
                            # push_table = "history_vehicle"
                            response = {"camera_id": 123,
                                        "camera_name": "test_camera",
                                        "plate_number": payload_ws.label,
                                        "vehicle_type": payload_ws.vehicle_type,
                                        "datetime": ABTime.ab_timestamp(),
                                        "image": image_ws,
                                        }
                            self.local_db.push_data(self.push_table, response, self.local_db.db_type)
                            # TODO push data to mysql

                except Exception as e:
                    print("error :", e)

if __name__ == "__main__":

    @hydra.main(config_path=root / "config", config_name="object_counter", version_base=None)
    def object_counter(hydra_config: DictConfig):

        hydra_service = hydra_config.service.vehichle_counting_cam_1
        ip_camera = hydra_service.ip_cam
        ws_connection = hydra_service.ws_connect

        obj_counting = ObjectCounting(hydra_config, ip_camera, ws_connection)
        obj_counting.async_runner()
    object_counter()
</code>```

Object parsing data to convert WebSocket data to python object

```<code>from typing import List

class Box:
    xmin: int
    ymin: int
    xmax: int
    ymax: int

    def __init__(self, xmin: int, ymin: int, xmax: int, ymax: int) -> None:
        self.xmin = xmin
        self.ymin = ymin
        self.xmax = xmax
        self.ymax = ymax

class Candidate:
    score: float
    plate: str

    def __init__(self, score: float, plate: str) -> None:
        self.score = score
        self.plate = plate

class Color:
    color: str
    score: float

    def __init__(self, color: str, score: float) -> None:
        self.color = color
        self.score = score

class ModelMake:
    make: str
    model: str
    score: float

    def __init__(self, make: str, model: str, score: float) -> None:
        self.make = make
        self.model = model
        self.score = score

class Orientation:
    orientation: str
    score: float

    def __init__(self, orientation: str, score: float) -> None:
        self.orientation = orientation
        self.score = score

class Region:
    code: str
    score: float

    def __init__(self, code: str, score: float) -> None:
        self.code = code
        self.score = score

class Vehicle:
    score: float
    type: str
    box: Box

    def __init__(self, score: float, type: str, box: Box) -> None:
        self.score = score
        self.type = type
        self.box = box

class Resjson:
    box: Box
    plate: str
    region: Region
    score: float
    candidates: List[Candidate]
    dscore: float
    vehicle: Vehicle
    model_make: List[ModelMake]
    color: List[Color]
    orientation: List[Orientation]

    def __init__(self, box: Box, plate: str, region: Region, score: float, candidates: List[Candidate], dscore: float, vehicle: Vehicle, model_make: List[ModelMake], color: List[Color], orientation: List[Orientation]) -> None:
        self.box = box
        self.plate = plate
        self.region = region
        self.score = score
        self.candidates = candidates
        self.dscore = dscore
        self.vehicle = vehicle
        self.model_make = model_make
        self.color = color
        self.orientation = orientation

class Payload:
    label: str
    vehicle_type: str
    resjson: Resjson

    def __init__(self, label: str, vehicle_type: str, resjson: Resjson) -> None:
        self.label = label
        self.vehicle_type = vehicle_type
        self.resjson = resjson

class WebsocketData:
    type: str
    payload: List[Payload]
    img: str

    def __init__(self, type: str, payload: List[Payload], img: str) -> None:
        self.type = type
        self.payload = payload
        self.img = img
</code>```

Body:
I try to resolve this problem about asynchronous WebSocket using python. I don't know why when I used the asynchronous process I get the error log bellow. But my code is totally fine when I didn't used the asynchronous.

error log

C:\ProgramData\Anaconda3\lib\site-packages\numpy\__init__.py:148: UserWarning: mkl-service package failed to import, therefore Intel(R) MKL initialization ensuring its correct out-of-the box operation under condition when Gnu OpenMP had already been loaded by Python process is not assured. Please install mkl-service package, see http://github.com/IntelPython/mkl-service
  from . import _distributor_init
[2022-12-15 12:51:26,677][root][INFO] - Connected to localhost object_detection mysql database
Error executing job with overrides: []
Traceback (most recent call last):
  File "e:\alfa_beta\etl-python\object_counting\object_counting.py", line 102, in object_counter
  File "e:\alfa_beta\etl-python\object_counting\object_counting.py", line 102, in object_counter
    obj_counting.async_runner()
  File "e:\alfa_beta\etl-python\object_counting\object_counting.py", line 41, in async_runner
    asyncio.run(self.vehicle_async())
  File "C:\ProgramData\Anaconda3\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 647, in run_until_complete
    return future.result()
  File "e:\alfa_beta\etl-python\object_counting\object_counting.py", line 62, in vehicle_async
    async with create_connection(self.ws_connection) as async_ws_connection:
AttributeError: __aenter__

Set the environment variable HYDRA_FULL_ERROR=1 for a complete stack trace.

hydra config

mode: object_counter

# internal database (mysql)
local_db:
  database: object_detection
  enabled: true
  host: localhost
  password: ""
  port: 3306
  user: root
  db_type: mysql

# service camera
service:
  vehichle_counting:
    table: history_vehicles
    ip_cam: 123.23.322.10
    ws_connect: ws://123.23.322.24:324/
    ws_host: 123.23.322.24
    ws_port: 324
    ws_prefix:
      json_data: 3242
      unknown: 42
      video_stream: 0222

Main code to run async object_counting.py

from omegaconf import DictConfig
from pyrootutils import setup_root
from types import SimpleNamespace
from websocket import create_connection, enableTrace
import dill as pickle
import asyncio
import hydra
import json

root = setup_root(
    search_from=__file__,
    indicator=[".git", "pyproject.toml"],
    pythonpath=True,
    dotenv=True,
)

# internal package
import websocket_data as wsd
from src.config.database_config import Database
from src.infra import time_infra as ABTime

# from object_counting import websocket_data as wsd

# TODO multi processing

class ObjectCounting:

    def __init__(self, config: DictConfig, ip_camera: str, ws_connection: str):
        self.config = config
        self.ip_camera = ip_camera
        self.ws_connection = ws_connection  # websocket

    def async_runner(self):
        """
        async_runner will help us to run the asynchronous process in object detection
        for now will runn vehicle_async
        """
        asyncio.run(self.vehicle_async())

    async def vehicle_async(self):
        """
        vehicle_async is the asynchronous process for vehicle detection.
        It will take data from WebSocket with ANPR type and push the license
        plate number with vehicle type of each caught vehicle to MYSQL database
        """
        # database
        self.local_db = Database(
            self.config.local_db.host,
            self.config.local_db.port,
            self.config.local_db.user,
            self.config.local_db.password,
            self.config.local_db.database,
            self.config.local_db.db_type,
        ) if self.config.local_db.enabled else None

        self.push_table = self.config.service.vehichle_counting_cam_1.table

        # enableTrace(True)
        async with create_connection(self.ws_connection) as async_ws_connection:
            while True:
                try:
                    json_data = json.loads(await async_ws_connection.recv(),
                                           object_hook=lambda d: SimpleNamespace(**d))
                    if json_data.type == "anpr":
                        raw_data = wsd.WebsocketData(json_data.type,
                                                 json_data.payload,
                                                 json_data.img)
                        payload_ws = raw_data.payload[0]
                        result_json = payload_ws.resjson
                        image_ws = raw_data.img
                        if result_json != '':
                            print("\ncatch!")
                            print('\nPayload: {}'.format(payload_ws))
                            # push_table = "history_vehicle"
                            response = {"camera_id": 123,
                                        "camera_name": "test_camera",
                                        "plate_number": payload_ws.label,
                                        "vehicle_type": payload_ws.vehicle_type,
                                        "datetime": ABTime.ab_timestamp(),
                                        "image": image_ws,
                                        }
                            self.local_db.push_data(self.push_table, response, self.local_db.db_type)
                            # TODO push data to mysql

                except Exception as e:
                    print("error :", e)

if __name__ == "__main__":

    @hydra.main(config_path=root / "config", config_name="object_counter", version_base=None)
    def object_counter(hydra_config: DictConfig):

        hydra_service = hydra_config.service.vehichle_counting_cam_1
        ip_camera = hydra_service.ip_cam
        ws_connection = hydra_service.ws_connect

        obj_counting = ObjectCounting(hydra_config, ip_camera, ws_connection)
        obj_counting.async_runner()
    object_counter()

Object parsing data to convert WebSocket data to python object

from typing import List

class Box:
    xmin: int
    ymin: int
    xmax: int
    ymax: int

    def __init__(self, xmin: int, ymin: int, xmax: int, ymax: int) -> None:
        self.xmin = xmin
        self.ymin = ymin
        self.xmax = xmax
        self.ymax = ymax

class Candidate:
    score: float
    plate: str

    def __init__(self, score: float, plate: str) -> None:
        self.score = score
        self.plate = plate

class Color:
    color: str
    score: float

    def __init__(self, color: str, score: float) -> None:
        self.color = color
        self.score = score

class ModelMake:
    make: str
    model: str
    score: float

    def __init__(self, make: str, model: str, score: float) -> None:
        self.make = make
        self.model = model
        self.score = score

class Orientation:
    orientation: str
    score: float

    def __init__(self, orientation: str, score: float) -> None:
        self.orientation = orientation
        self.score = score

class Region:
    code: str
    score: float

    def __init__(self, code: str, score: float) -> None:
        self.code = code
        self.score = score

class Vehicle:
    score: float
    type: str
    box: Box

    def __init__(self, score: float, type: str, box: Box) -> None:
        self.score = score
        self.type = type
        self.box = box

class Resjson:
    box: Box
    plate: str
    region: Region
    score: float
    candidates: List[Candidate]
    dscore: float
    vehicle: Vehicle
    model_make: List[ModelMake]
    color: List[Color]
    orientation: List[Orientation]

    def __init__(self, box: Box, plate: str, region: Region, score: float, candidates: List[Candidate], dscore: float, vehicle: Vehicle, model_make: List[ModelMake], color: List[Color], orientation: List[Orientation]) -> None:
        self.box = box
        self.plate = plate
        self.region = region
        self.score = score
        self.candidates = candidates
        self.dscore = dscore
        self.vehicle = vehicle
        self.model_make = model_make
        self.color = color
        self.orientation = orientation

class Payload:
    label: str
    vehicle_type: str
    resjson: Resjson

    def __init__(self, label: str, vehicle_type: str, resjson: Resjson) -> None:
        self.label = label
        self.vehicle_type = vehicle_type
        self.resjson = resjson

class WebsocketData:
    type: str
    payload: List[Payload]
    img: str

    def __init__(self, type: str, payload: List[Payload], img: str) -> None:
        self.type = type
        self.payload = payload
        self.img = img


问:
telethon: how to fetchall data from database into telethon markup button.text
```<code>@client.on(events.NewMessage(pattern="(?i)/start"))
async def select(event):
sender = await event.get_sender()
SENDER = sender.id
idchat = sender.id
fname = sender.first_name

import datetime
now = datetime.datetime.now()
dt = now.strftime("%Y-%m-%d")

sql = "SELECT noplat FROM tblsolar WHERE tanggal=%s AND idchat_supir=%s;"
crsr.execute(sql, (dt, idchat))
res = crsr.fetchall()
for i in res:
    noplat = i[0]

markup = event.client.build_reply_markup([
    [Button.text(noplat, resize=True, single_use=True)]
])

text = ""
text1 = "Hello, <b>" + fname + "</b>" '\n' "please, choose one below" '\n'
await client.send_message(SENDER, text, parse_mode="HTML")
await client.send_message(SENDER, text1, buttons=markup, parse_mode="HTML")
</code>```

i want created automatic buttons base from database
if my data only 5 the button will created only 5
and if the data have 10 the button will created 10 button

noplat = button.text

can someone make it ? any help thank

Body:
@client.on(events.NewMessage(pattern="(?i)/start"))
async def select(event):
sender = await event.get_sender()
SENDER = sender.id
idchat = sender.id
fname = sender.first_name

import datetime
now = datetime.datetime.now()
dt = now.strftime("%Y-%m-%d")

sql = "SELECT noplat FROM tblsolar WHERE tanggal=%s AND idchat_supir=%s;"
crsr.execute(sql, (dt, idchat))
res = crsr.fetchall()
for i in res:
    noplat = i[0]

markup = event.client.build_reply_markup([
    [Button.text(noplat, resize=True, single_use=True)]
])

text = ""
text1 = "Hello, " + fname + "" '\n' "please, choose one below" '\n'
await client.send_message(SENDER, text, parse_mode="HTML")
await client.send_message(SENDER, text1, buttons=markup, parse_mode="HTML")

i want created automatic buttons base from database
if my data only 5 the button will created only 5
and if the data have 10 the button will created 10 button

noplat = button.text

can someone make it ? any help thank


问:
Output XML with same attribute into multiple rows in CSV file using XSLT
I have XML with same attribute but different values.  Every different value should be output as a row in the CSV output file using XSLT. Below is the XML. For every field that peci:priorValue, I need to output  Prior value and current value in rows in CSV file.

<?xml version='1.0' encoding='UTF-8'?>
<peci:Workers_Effective_Stack xmlns:peci="urn:com.workday/peci">
    <peci:Worker>
        <peci:Effective_Change peci:Sequence="0">
            <peci:Derived_Event_Code>DTA</peci:Derived_Event_Code>
            <peci:Effective_Moment>2022-12-12T00:00:00.000-08:00</peci:Effective_Moment>
            <peci:Entry_Moment>2022-12-14T05:32:34.114-08:00</peci:Entry_Moment>
            <peci:Worker_Status>
                <peci:Status>Active</peci:Status>
                <peci:Active>1</peci:Active>
                <peci:Active_Status_Date>2022-08-01-07:00</peci:Active_Status_Date>
                <peci:Terminated>0</peci:Terminated>
                <peci:Hire_Date>2022-08-01-07:00</peci:Hire_Date>
            </peci:Worker_Status>
            <peci:Compensation peci:isUpdated="1">
                <peci:Position_ID>xyz</peci:Position_ID>
                <peci:Compensation_Grade>Salary</peci:Compensation_Grade>
                <peci:Compensation_Change_Reason peci:priorValue="Change_Location">COLA</peci:Compensation_Change_Reason>
                <peci:Compensation_Summary_in_Annualized_Frequency peci:isUpdated="1">
                    <peci:Total_Base_Pay peci:priorValue="8000">12000</peci:Total_Base_Pay>
                    <peci:Currency>USD</peci:Currency>
                </peci:Compensation_Summary_in_Annualized_Frequency>
                <peci:Compensation_Summary_in_Pay_Group_Frequency>
                    <peci:Frequency>Monthly</peci:Frequency>
                </peci:Compensation_Summary_in_Pay_Group_Frequency>
            </peci:Compensation>
        </peci:Effective_Change>
    </peci:Worker>
</peci:Workers_Effective_Stack>
```
<p>My output should be</p>
```John Doe, Change_Location, COLA
John Doe, 8000, 12000
```
<p>How can this be achieved? I am new to XSLT and so struggling with this.</p>
<p>I am getting an output like this</p>
```John Doe, Change_Location 8000, COLA 12000
```

Body:
I have XML with same attribute but different values.  Every different value should be output as a row in the CSV output file using XSLT. Below is the XML. For every field that peci:priorValue, I need to output  Prior value and current value in rows in CSV file.

<?xml version='1.0' encoding='UTF-8'?>
<peci:Workers_Effective_Stack xmlns:peci="urn:com.workday/peci">
    <peci:Worker>
        <peci:Effective_Change peci:Sequence="0">
            <peci:Derived_Event_Code>DTA</peci:Derived_Event_Code>
            <peci:Effective_Moment>2022-12-12T00:00:00.000-08:00</peci:Effective_Moment>
            <peci:Entry_Moment>2022-12-14T05:32:34.114-08:00</peci:Entry_Moment>
            <peci:Worker_Status>
                <peci:Status>Active</peci:Status>
                <peci:Active>1</peci:Active>
                <peci:Active_Status_Date>2022-08-01-07:00</peci:Active_Status_Date>
                <peci:Terminated>0</peci:Terminated>
                <peci:Hire_Date>2022-08-01-07:00</peci:Hire_Date>
            </peci:Worker_Status>
            <peci:Compensation peci:isUpdated="1">
                <peci:Position_ID>xyz</peci:Position_ID>
                <peci:Compensation_Grade>Salary</peci:Compensation_Grade>
                <peci:Compensation_Change_Reason peci:priorValue="Change_Location">COLA</peci:Compensation_Change_Reason>
                <peci:Compensation_Summary_in_Annualized_Frequency peci:isUpdated="1">
                    <peci:Total_Base_Pay peci:priorValue="8000">12000</peci:Total_Base_Pay>
                    <peci:Currency>USD</peci:Currency>
                </peci:Compensation_Summary_in_Annualized_Frequency>
                <peci:Compensation_Summary_in_Pay_Group_Frequency>
                    <peci:Frequency>Monthly</peci:Frequency>
                </peci:Compensation_Summary_in_Pay_Group_Frequency>
            </peci:Compensation>
        </peci:Effective_Change>
    </peci:Worker>
</peci:Workers_Effective_Stack>

My output should be

John Doe, Change_Location, COLA
John Doe, 8000, 12000

How can this be achieved? I am new to XSLT and so struggling with this.

I am getting an output like this

John Doe, Change_Location 8000, COLA 12000


问:
How to connect and print with Bluetooth printer in Xamarin IOS
I have worked on Xamarin android and in android I am able to print with Bluetooth printer but I am not able to find any solution that work on Xamarin IOS.

Is any dependency services can be used to find near by devices in Xamarin IOS and Print it on any Bluetooth device.


问:
authenticating ldap linux server client with windows server
In our organization we have 3 servers running on aws, one of linux main server with ldap account manager (LAM) configured on it. And other two are (linux client server and windows server).             I've configured linux client server with (LAM) and also able to authenticate (lAM users with linux client server)  but facing issue in authentication of LAM users with windows server ec2 machine. please help me in this regard if community has better solution for it. thanks!!!

i tried different methods just like Microsoft AD domain service but not get result


问:
onProxyReq not called on Create React App project
I created a basic React project using CRA. I'm trying to configure a proxy using setupProxy.js. The proxy works, however all the "on" methods are not being called, such as onProxyReq.

My configration:

```<code>module.exports = {
    webpack: {
        devServer: {
            proxy: {
                '/api': {
                    onProxyReq: function() {
                        console.warn("not reached!!!!");
...
</code>```

Why is this happening? Is it a known recent bug?

Body:
I created a basic React project using CRA. I'm trying to configure a proxy using setupProxy.js. The proxy works, however all the "on" methods are not being called, such as onProxyReq.

My configration:

module.exports = {
    webpack: {
        devServer: {
            proxy: {
                '/api': {
                    onProxyReq: function() {
                        console.warn("not reached!!!!");
...

Why is this happening? Is it a known recent bug?


问:
How to get the camera pose data associated with a frame in UE5?(C++ side)
Where in the UE5 code can the pose data for a particular frame be obtained during rendering?
In C++, take a camera object and use its methods to determine its location. </p>


问:
Calculation from the merged cells
From the table below, I wanted to calculate the average percentage of training. If the status starts with "3" show as 100, "2" show as 50, and "3" show as 0 and then calculate the average. The summary table doesn't include the subjects which are blank (highlighted in grey)

I am able to get the status calculation using the formula "=LET(_classes,FILTER('Content Tracker'!A3:A1048576,'Content Tracker'!A3:A1048576<>""),
_subjects,FILTER('Content Tracker'!B3:B1048576,'Content Tracker'!B3:B1048576<>""),
_trainings,FILTER('Content Tracker'!E3:G1048576,'Content Tracker'!B3:B1048576<>""),
_merge,HSTACK(SCAN(_subjects,_subjects,LAMBDA(x,y,IF(y="",x,y))),_trainings),
_uclasses,UNIQUE(INDEX(_merge,,1)),
_trainingonecomp,MAP(_uclasses,LAMBDA(x,SUM(--(x=INDEX(_merge,,1))*(INDEX(_merge,,2)<>0)IF(ISNUMBER(SEARCH("3",INDEX(_merge,,2))),100,IF(ISNUMBER(SEARCH("2",INDEX(_merge,,2))),50,0))))),
_trainingtwocomp,MAP(_uclasses,LAMBDA(x,SUM(--(x=INDEX(_merge,,1))(INDEX(_merge,,3)<>0)IF(ISNUMBER(SEARCH("3",INDEX(_merge,,3))),100,IF(ISNUMBER(SEARCH("2",INDEX(_merge,,3))),50,0))))),
_trainingthreecomp,MAP(_uclasses,LAMBDA(x,SUM(--(x=INDEX(_merge,,1))(INDEX(_merge,,4)<>0)*IF(ISNUMBER(SEARCH("3",INDEX(_merge,,4))),100,IF(ISNUMBER(SEARCH("2",INDEX(_merge,,2))),50,0))))),
_avg,AVERAGE(_trainingonecomp,_trainingtwocomp,_trainingthreecomp),
_output,VSTACK(HSTACK("classes","subjects","Training 1 Completed","Training 2 Completed","Training 3 Completed","Average"),HSTACK(_classes,_subjects,_trainingonecomp,_trainingtwocomp,_trainingthreecomp,_avg)),
_output)"

This is the output I got:

I am not able to remove the subjects (highlighted in yellow) with blank values in the source files, and the class and average columns throw some errors.

This is the result expected:

Can anyone assist me with this to achieve the expected result?

Title: Calculation from the merged cells


问:
Pandas equivalent of partition by
I have the following dataframe:

```<code>df = pd.DataFrame({'group':['A','A','A','B','B','B'],'value':[1,2,3,4,5,6]})
</code>```

I would like to add a column that will sum all the values for each group. This way each row with group A will have 6 in that column and each row with group B will have 15:

```<code>dfPartition = pd.DataFrame({"group": ['A','A','A','B','B','B'], "value":[1,2,3,4,5,6], "GroupSum": [6,6,6,15,15,15]})
</code>```

In SQL I would do:

```<code>SUM(value) OVER (PARTITION BY group)
</code>```

How would I do it in Pandas?

This is not group by! I need to leave the dataframe as is and add an additional column, with the groupby results

Title: Pandas equivalent of partition by

Body:
I have the following dataframe:

df = pd.DataFrame({'group':['A','A','A','B','B','B'],'value':[1,2,3,4,5,6]})

I would like to add a column that will sum all the values for each group. This way each row with group A will have 6 in that column and each row with group B will have 15:

dfPartition = pd.DataFrame({"group": ['A','A','A','B','B','B'], "value":[1,2,3,4,5,6], "GroupSum": [6,6,6,15,15,15]})

In SQL I would do:

SUM(value) OVER (PARTITION BY group)

How would I do it in Pandas?

This is not group by! I need to leave the dataframe as is and add an additional column, with the groupby results


问:
Mock Servers which can support both GraphQL and REST endpoints?
I'm trying to find some mock servers which can support both graphQL and REST endpoints .
so that when I query, it returns back mock data instead of going to the Graphql / Http  server.

At the moment I found some ways to mock queries , easygraphql-tester  works as a mocker of query or mutation But it specifically for GraphQL endpoints .

Similarly , mock-http-server can be used to mock Http Requests to return specific responses But this is specifically for REST or Http endpoints .

I want to find some way where i can mock both GraphQL and HTTP endpoints at the same time . For Example - if I want to mock queries for GraphQL endpoints i can do that , Also if i want to mock some specific Http Request ,i can do that too using the same tool .

Would appreciate the help if anyone can help me find some mock server to mock both Http and GraphQL endpoints .


问:
How can I pass multiple parameters and create API that gets exactly matched data ( NextJs / Mongoose)
Ive been trying to find a way online how to send more that one parameter in

```<code>const response = await fetch(`/api/citizen/${voterId}`);
</code>```

in the previous, it passed just the id attached to the end of the path. Then, in my api folder, I have folder called "citizen" and sub [voterId].js file.
my [voterId].js file looks like this:

```<code>    export default async (req, res) => {
        const {
            query: { voterId },
            method
        } = req;

        switch (method) {
            case 'GET':
                try {
                    const citizen = await Citizen.find({voterId :voterId});

                    if (!citizen) {
                        return res.status(400).json({ success: false });
                     }

                     res.status(200).json( citizen );
                } catch (error) {
                    res.status(400).json({ success: false });
                }
                break;
            default:
                res.status(400).json({ success: false })
                break;
        }
    }
</code>```

the one parameter query works and retrieves data from the database

I Have tried to create nested folders to reach the [voterId].js file  like this: [fName]/[lName]/[state]/[voterId].js but, i don't know what to change in my [voterId].js file.

I want to to be able to pass multiple params through the path url. and pass them into the function. I am quite new in Mongoose/NextJs routing.

Body:
Ive been trying to find a way online how to send more that one parameter in

const response = await fetch(`/api/citizen/${voterId}`);

in the previous, it passed just the id attached to the end of the path. Then, in my api folder, I have folder called "citizen" and sub [voterId].js file.
my [voterId].js file looks like this:

    export default async (req, res) => {
        const {
            query: { voterId },
            method
        } = req;

        switch (method) {
            case 'GET':
                try {
                    const citizen = await Citizen.find({voterId :voterId});

                    if (!citizen) {
                        return res.status(400).json({ success: false });
                     }

                     res.status(200).json( citizen );
                } catch (error) {
                    res.status(400).json({ success: false });
                }
                break;
            default:
                res.status(400).json({ success: false })
                break;
        }
    }

the one parameter query works and retrieves data from the database

I Have tried to create nested folders to reach the [voterId].js file  like this: [fName]/[lName]/[state]/[voterId].js but, i don't know what to change in my [voterId].js file.

I want to to be able to pass multiple params through the path url. and pass them into the function. I am quite new in Mongoose/NextJs routing.


问:
Facing issue on multilevel according in angular
Facing issue in MultiLevel Accordian is not working properly. Not working properly.
Please find the below code-snippets for refrence.
Angular

```<code><div *ngFor="let item of channel;let i = index;">
  <button class="accordion" (click)="toggleAccordian($event, i)"> {{item["common.ALLTYPES_NAME"]}} </button>
  <div class="panel" hide="!item.isActive">
    <div *ngFor="let child of devices;let i = index;">
      <button class="accordion" (click)="toggleAccordians($event, i)"> {{child["common.ALLTYPES_NAME"]}} </button>
      <div class="panel" hide="!child.isActive">
        <div *ngFor="let childtagGroups of tagGroups;let k = index;">
          <button class="accordion" (click)="toggleAccordians($event, k)">
            {{childtagGroups["common.ALLTYPES_NAME"]}} </button>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

Typescipt

```<code>  toggleAccordian(event, index) {
    const element = event.target;
    element.classList.toggle("active");
    if (this.channel[index].isActive) {
      this.channel[index].isActive = false;
    } else {
      this.Devices(element.outerText);
      this.channel[index].isActive = true;
    }
    const panel = element.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
</code>```

Body:
Facing issue in MultiLevel Accordian is not working properly. Not working properly.
Please find the below code-snippets for refrence.
Angular

  <button class="accordion" (click)="toggleAccordian($event, i)"> {{item["common.ALLTYPES_NAME"]}} </button>

      <button class="accordion" (click)="toggleAccordians($event, i)"> {{child["common.ALLTYPES_NAME"]}} </button>

          <button class="accordion" (click)="toggleAccordians($event, k)">
            {{childtagGroups["common.ALLTYPES_NAME"]}} </button>

Typescipt

  toggleAccordian(event, index) {
    const element = event.target;
    element.classList.toggle("active");
    if (this.channel[index].isActive) {
      this.channel[index].isActive = false;
    } else {
      this.Devices(element.outerText);
      this.channel[index].isActive = true;
    }
    const panel = element.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }


问:
Talend : SOAP fault error while calling a secure webservice in Talend
We are using Talend (Data Integration Platform)in our project.
We are facing an issue calling a secured SOAP webservice through a code routine in Talend.

Here is the error :
Client received SOAP Fault from server: The server was unable to process the request due to an internal error

We tried 2 approaches

Writing the SOAP web service client code directly in the code routine of Talend

Bundle the SOAP client code as an external jar in Talend

Both approaches are failing with above SOAP Fault error.

We have set up KeyStore and TrustStore(JKS) for authentication.
If we run the bundled jar standalone on the Linux machine that hosts Talend, it works fine.
But same jar when packaged inside Talend does not work

If you have any suggestions, Please let us know.


问:
How to decompile very old version VB EXE to Source Code
**Our team has been using a *.exe file developed during window XP or 6 OS timeframe.. I am also not sure which version of Visual Basic (may be VB6), as this code is been written in 2004.

Currently, team is struggling to access it on a virtual XP machine. Unfortunately, the source code was lost. Would it be possible to open the source using any of the VB.Net frame work applications from the *.exe file only

Now I am trying to decompile .exe and generate source code.

Tried Solution:

Installed 32 bit dotpeek and tried but no success.

Also tried through command line "ildsam" but still no success
How do I decompile a .NET EXE into readable C# source code?

Above solution tried on below machine

Dell laptop (Precision 7560) with Windows 10

Visual Studio 2022.

Is anyone tried/faced issue like this.

Is there any way to find out which version of VB from .exe

On which version of

Please let me know your suggestion


问:
Streamlit Database Error (SQL Sever connection)
There wasn't any problem with connecting a SQL Server to Streamlit. But since I have been changed the SQL Server IP address, I am having a trouble with the connection suddenly.

The errors from Streamlit shown below. (I covered up the table name.)

DatabaseError: Execution failed on sql ' SELECT TOP (100) [SEQ] ,[MCNO] ,[STM] ,[PGNM] ,[MATNR] ,[TBFG] ,[GAMNG] ,[SENDFG] ,[CRTM] ,[PGDAT] FROM Table name is confidential WITH(NOLOCK) ': (208, b"Invalid object name 'Table name is confidential'.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n")

Also, I have been used pymssql to connect SQL Server as shown in below.

```<code>class DB:
    def __init__(self, host, port, db, user, pwd) -> None:
        self.conn = None
        self.cursor = None
        self.init(host, port, db, user, pwd)

    def __enter__(self):
        return self

    def execute(self, query):
        self.cursor.execute(query)

    def commit(self):
        self.conn.commit()

    def fetchall(self):
        return self.cursor.fetchall()

    def read_sql(self, query):
        return pd.read_sql(query, self.conn)

    def init(self, host, port, db, user, pwd):
        self.conn = pymssql.connect(
            server=host, database=db, user=user, password=pwd, port=port, charset="utf8"
        )
        self.cursor = self.conn.cursor()

    def close(self):
        self.conn.close()
        self.cursor = None

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()
</code>```

Can anyone give me a help with this problem?

Thank you!

Body:
There wasn't any problem with connecting a SQL Server to Streamlit. But since I have been changed the SQL Server IP address, I am having a trouble with the connection suddenly.

The errors from Streamlit shown below. (I covered up the table name.)

DatabaseError: Execution failed on sql ' SELECT TOP (100) [SEQ] ,[MCNO] ,[STM] ,[PGNM] ,[MATNR] ,[TBFG] ,[GAMNG] ,[SENDFG] ,[CRTM] ,[PGDAT] FROM Table name is confidential WITH(NOLOCK) ': (208, b"Invalid object name 'Table name is confidential'.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n")

Also, I have been used pymssql to connect SQL Server as shown in below.

class DB:
    def __init__(self, host, port, db, user, pwd) -> None:
        self.conn = None
        self.cursor = None
        self.init(host, port, db, user, pwd)

    def __enter__(self):
        return self

    def execute(self, query):
        self.cursor.execute(query)

    def commit(self):
        self.conn.commit()

    def fetchall(self):
        return self.cursor.fetchall()

    def read_sql(self, query):
        return pd.read_sql(query, self.conn)

    def init(self, host, port, db, user, pwd):
        self.conn = pymssql.connect(
            server=host, database=db, user=user, password=pwd, port=port, charset="utf8"
        )
        self.cursor = self.conn.cursor()

    def close(self):
        self.conn.close()
        self.cursor = None

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

Can anyone give me a help with this problem?

Thank you!


问:
How to make rp2040 DynPin usable for Adc with OnesShot read
I am trying to convert from a type erased type to a value type.
I have the following struct that accepts DynPin , which is the type erased type of a rp2040 gpio pin.

```<code>pub struct PhProbe{
  analog_read_pin: DynPin,
}
</code>```

Now using the rp2040 analog to digital converter with OneShot I want to use this pin in the read function (ignore return value). But the read function of the ADC only accepts pins that implement Channel<ADC> which is done using a macro, which as you can see is only implemented for the specific gpios 26-29.

```<code>pub fn read(&mut self, adc: Adc) {
      let reading: u16 = adc.read(&mut <DynPin as Into<FloatingInput>>::into(self.analog_read_pin)).unwrap();
    }
</code>```

The pin is created using the into_floating_input() function and handed to the PhProbe::new() function by making a DynPin using into().

```<code>let ph_pin = pins.gpio26.into_floating_input();
let ph_meter = PhProbe::new(ph_pin.into());
</code>```

I was trying to make a analog input pin (FloatingInput) out of the DynPin, but this doesn't satisfy the bounds Channel<Adc> of OneShot. Is there a a way to use any of the gpio26-29 pins with this or do I need to specify Gpio26 for this?

Body:
I am trying to convert from a type erased type to a value type.
I have the following struct that accepts DynPin , which is the type erased type of a rp2040 gpio pin.

pub struct PhProbe{
  analog_read_pin: DynPin,
}

Now using the rp2040 analog to digital converter with OneShot I want to use this pin in the read function (ignore return value). But the read function of the ADC only accepts pins that implement Channel<ADC> which is done using a macro, which as you can see is only implemented for the specific gpios 26-29.

pub fn read(&mut self, adc: Adc) {
      let reading: u16 = adc.read(&mut <DynPin as Into<FloatingInput>>::into(self.analog_read_pin)).unwrap();
    }

The pin is created using the into_floating_input() function and handed to the PhProbe::new() function by making a DynPin using into().

let ph_pin = pins.gpio26.into_floating_input();
let ph_meter = PhProbe::new(ph_pin.into());

I was trying to make a analog input pin (FloatingInput) out of the DynPin, but this doesn't satisfy the bounds Channel<Adc> of OneShot. Is there a a way to use any of the gpio26-29 pins with this or do I need to specify Gpio26 for this?


问:
How to solve "PRECONDITION_FAILED - delivery acknowledgement on channel 1 timed out. " error in rabbitmq javascript?
After 30 minute I get this error:

```<code>Channel closed by server: 406 (PRECONDITION-FAILED) with message "PRECONDITION_FAILED - delivery acknowledgement on channel 1 timed out. Timeout value used: 1800000 ms. This timeout value can be configured, see consumers doc guide to learn more"
</code>```

I read online that this error is generated because the consumer does not acknowledge the message but I put noAck:false so it should acknowledge the message automatically, also in the queue I can see it has been unacked from  rabbitmq manager. So why am I getting this error? How can I solve this? From what is come from?

this is how my queues look like:

Here is the code for the consumer:

```<code> const channel = await connection.createChannel();
    await channel.assertExchange(exchange, exchangeType, { durable: true });
    const assertedQueue = await channel.assertQueue('', {
      exclusive: true,
    });
    await channel.bindQueue(assertedQueue.queue, exchange, routingKey);
    await channel.consume(assertedQueue.queue, msg => dbOperation(msg, channel), {
      noAck: false, // send always an answer of confirmation back
    });
</code>```

Body:
After 30 minute I get this error:

Channel closed by server: 406 (PRECONDITION-FAILED) with message "PRECONDITION_FAILED - delivery acknowledgement on channel 1 timed out. Timeout value used: 1800000 ms. This timeout value can be configured, see consumers doc guide to learn more"

I read online that this error is generated because the consumer does not acknowledge the message but I put noAck:false so it should acknowledge the message automatically, also in the queue I can see it has been unacked from  rabbitmq manager. So why am I getting this error? How can I solve this? From what is come from?

this is how my queues look like:

Here is the code for the consumer:

 const channel = await connection.createChannel();
    await channel.assertExchange(exchange, exchangeType, { durable: true });
    const assertedQueue = await channel.assertQueue('', {
      exclusive: true,
    });
    await channel.bindQueue(assertedQueue.queue, exchange, routingKey);
    await channel.consume(assertedQueue.queue, msg => dbOperation(msg, channel), {
      noAck: false, // send always an answer of confirmation back
    });


问:
Reshaping TrainX and trainY in LSTM RNN Project
I am working on multivariate time based LSTM RNN Project. Because it is a multivariate, my goal is to train the model with multiple parameters and as an output I want to get predictions for every parameter in the dataset. I will add all the code and information below.

Here is the data set

```<code>Time(sec)   Lat(deg)    Lon(deg)    Alt(m)  Yaw(deg)    Pitch(deg)  Roll(deg)   Vx(m / sec) Vy(m / sec) Vz(m / sec)
0   1.00    42.461525   33.000000   2802.544922 0.000000    0.000000    0.000000    150.000000  0.000000    -0.000000
1   1.02    42.461525   33.000000   2802.544922 0.000000    0.000000    0.000000    150.000000  0.000000    -0.000000
2   1.04    42.461579   33.000000   2802.544922 0.000000    0.000000    0.000000    150.008987  0.000000    -0.000000
3   1.06    42.461579   33.000000   2802.544922 0.000000    0.000000    0.000000    150.008987  0.000000    -0.000000
4   1.08    42.461633   33.000000   2802.544922 0.000000    0.000000    0.000000    150.035843  0.000000    -0.000000
</code>```

and here is the reshaping code for that data set:

```<code>trainX = [] trainY = []

n_future = 1
n_past = 100

 for i in range(n_past, len(df_missile_training_scaled) - n_future +1):
    trainX.append(df_missile_training_scaled[i - n_past:i, 0:df_missile_training_scaled.shape[1]])
    trainY.append(df_missile_training_scaled[i + n_future - 1:i + n_future, 0])
</code>```

with this code i am reshaping the input as I wanted but it only outputs first column "Lat(deg)" because of the shape of the trainY.

```<code>trainX, trainY = np.array(trainX), np.array(trainY)
print('trainX shape == {}.'.format(trainX.shape))
print('trainY shape == {}.'.format(trainY.shape))
</code>```

Outputs;

```<code>trainX shape == (171900, 100, 9).
trainY shape == (171900, 1).
</code>```

My goal is to change it to a shape that after the training, model can predict multiple parameters (columns) on one training.

I tried this code but some how it gives me;

trainY shape == (171900, 1).

Here is the code I tried:

```<code>trainX = []
trainY = []

n_future = 1
n_past = 100

    for i in range(n_past, len(df_missile_training_scaled) - n_future +1):
        trainX.append(df_missile_training_scaled[i - n_past:i, 0:df_missile_training_scaled.shape[1]])
        trainY.append(df_missile_training_scaled[i + n_future:df_missile_training_scaled.shape[1]])
</code>```

My question is how can I do this reshaping properly. And what I'm aiming for can be done for the neural network model?

I hope I was able to explain my question. If there is something I missed or couldn't explain, I can add it. Thanks in advance for reading

Body:
I am working on multivariate time based LSTM RNN Project. Because it is a multivariate, my goal is to train the model with multiple parameters and as an output I want to get predictions for every parameter in the dataset. I will add all the code and information below.

Here is the data set

Time(sec)   Lat(deg)    Lon(deg)    Alt(m)  Yaw(deg)    Pitch(deg)  Roll(deg)   Vx(m / sec) Vy(m / sec) Vz(m / sec)
0   1.00    42.461525   33.000000   2802.544922 0.000000    0.000000    0.000000    150.000000  0.000000    -0.000000
1   1.02    42.461525   33.000000   2802.544922 0.000000    0.000000    0.000000    150.000000  0.000000    -0.000000
2   1.04    42.461579   33.000000   2802.544922 0.000000    0.000000    0.000000    150.008987  0.000000    -0.000000
3   1.06    42.461579   33.000000   2802.544922 0.000000    0.000000    0.000000    150.008987  0.000000    -0.000000
4   1.08    42.461633   33.000000   2802.544922 0.000000    0.000000    0.000000    150.035843  0.000000    -0.000000

and here is the reshaping code for that data set:

trainX = [] trainY = []

n_future = 1
n_past = 100

 for i in range(n_past, len(df_missile_training_scaled) - n_future +1):
    trainX.append(df_missile_training_scaled[i - n_past:i, 0:df_missile_training_scaled.shape[1]])
    trainY.append(df_missile_training_scaled[i + n_future - 1:i + n_future, 0])

with this code i am reshaping the input as I wanted but it only outputs first column "Lat(deg)" because of the shape of the trainY.

trainX, trainY = np.array(trainX), np.array(trainY)
print('trainX shape == {}.'.format(trainX.shape))
print('trainY shape == {}.'.format(trainY.shape))

Outputs;

trainX shape == (171900, 100, 9).
trainY shape == (171900, 1).

My goal is to change it to a shape that after the training, model can predict multiple parameters (columns) on one training.

I tried this code but some how it gives me;

trainY shape == (171900, 1).

Here is the code I tried:

trainX = []
trainY = []

n_future = 1
n_past = 100

    for i in range(n_past, len(df_missile_training_scaled) - n_future +1):
        trainX.append(df_missile_training_scaled[i - n_past:i, 0:df_missile_training_scaled.shape[1]])
        trainY.append(df_missile_training_scaled[i + n_future:df_missile_training_scaled.shape[1]])

My question is how can I do this reshaping properly. And what I'm aiming for can be done for the neural network model?

I hope I was able to explain my question. If there is something I missed or couldn't explain, I can add it. Thanks in advance for reading


问:
Efficient method to get node connectivity in FEM
I have information of element connectivity in problem of finite element method.
For example,
1, 5, 6, 8, 7, 1, 2, 4, 3
The first column is the index of element, and the last 8 columns are the node index which composed entries for element 1.

The goal what I want is node array like as below.
It is an array with all the node indices associated with each node.

```<code>node_arr[1] = [2 3 4 5 6 7 8]
node_arr[2] = [1 3 4 5 6 7 8]
node_arr[3] = [1 2 4 5 6 7 8]
node_arr[4] = [1 2 3 5 6 7 8]
node_arr[5] = [1 2 3 4 6 7 8]
node_arr[6] = [1 2 3 4 5 7 8]
node_arr[7] = [1 2 3 4 5 6 8]
node_arr[8] = [1 2 3 4 5 6 7]
</code>```

So the current state of my code is as below .
1-count the number about how many elements contain that node index

```<code>for loop i  (entire node){
   for loop j  (entire element){
     if (element j has node i is true){
         node_count[i] = node_count[i] + 1;
      }
    }
}
</code>```

2-Allocate node_node_arr to contain target information by using the results of step 1

```<code>node_node_arr = malloc(by using node_count)
</code>```

3-Again, it searches the entire element node index and append the node index related with current node index for composing node_node_array.

```<code>for loop i  (entire node){
   for loop j  (entire element){
     if (element j has node i is true){
        node_node_arr[i] append node indices;
     }
   }
}
</code>```

However this approach is so slow .
If both the number of elements and the number of nodes increase, the calculation time increases tremendously.
I need speed up.
Please help me.

Body:
I have information of element connectivity in problem of finite element method.
For example,
1, 5, 6, 8, 7, 1, 2, 4, 3
The first column is the index of element, and the last 8 columns are the node index which composed entries for element 1.

The goal what I want is node array like as below.
It is an array with all the node indices associated with each node.

node_arr[1] = [2 3 4 5 6 7 8]
node_arr[2] = [1 3 4 5 6 7 8]
node_arr[3] = [1 2 4 5 6 7 8]
node_arr[4] = [1 2 3 5 6 7 8]
node_arr[5] = [1 2 3 4 6 7 8]
node_arr[6] = [1 2 3 4 5 7 8]
node_arr[7] = [1 2 3 4 5 6 8]
node_arr[8] = [1 2 3 4 5 6 7]

So the current state of my code is as below .
1-count the number about how many elements contain that node index

for loop i  (entire node){
   for loop j  (entire element){
     if (element j has node i is true){
         node_count[i] = node_count[i] + 1;
      }
    }
}

2-Allocate node_node_arr to contain target information by using the results of step 1

node_node_arr = malloc(by using node_count)

3-Again, it searches the entire element node index and append the node index related with current node index for composing node_node_array.

for loop i  (entire node){
   for loop j  (entire element){
     if (element j has node i is true){
        node_node_arr[i] append node indices;
     }
   }
}

However this approach is so slow .
If both the number of elements and the number of nodes increase, the calculation time increases tremendously.
I need speed up.
Please help me.


问:
Debian package in Ubuntu
I am using a tool (tagui) to automate the web. The dependency for this are the source file which actually contains the script for the automation, a jdk package, php and python.

Trying to make this as a debian package so that it can be used as an executable file and shared among everyone.

Title: Debian package in Ubuntu


问:
return function/ multiplication (beginner)
I'm trying to multiply the number by itself which I chose but cannot figure this out.

Idea behind it: the number in the "result" is "8" from the tuple and it should multiply by itself.

Code: enter image description here

the regular insertion of a number in the square variable works but cannot figure this out.


Title: Implementation of PreMSIm in R

Body:
I am trying to use this R package on my data:
https://github.com/WangX-Lab/PreMSIm

I generated a normalized counts file similar to example.txt in their example, except I used gene symbol instead of ID for row name.

When I run their sample code:

> library(PreMSIm)
> path = system.file("extdata", "example.txt", package = "PreMSIm", mustWork = TRUE)
> data_pre(path, type = "ID")
            DDX27  EPM2AIP1    HENMT1      LYG1      MLH1       MSH4    NHLRC1     NOL4L      RNLS    RPL22L1      RTF2   SHROOM4     SMAP1    TTC30A    ZSWIM3
Sample1 1.0000000 1.0000000 1.0000000 1.0000000 1.0000000 1.00000000 1.0000000 0.8761449 0.6029301 0.38125416 0.7734447 0.4684460 1.0000000 1.0000000 0.8196170
Sample2 0.2852962 0.7504918 0.9708924 0.8308378 0.9230994 0.29193800 0.6069412 0.2505053 1.0000000 0.32136905 0.0000000 1.0000000 0.7811169 0.5892737 0.8997000
Sample3 0.2925261 0.1905731 0.7926025 0.0000000 0.4826125 0.00000000 0.0628135 0.0000000 0.6856571 0.77711488 0.3534438 0.6395017 0.2431263 0.5991998 0.0000000
Sample4 0.3222120 0.3382536 0.0000000 0.0862332 0.9683453 0.00000000 0.0000000 0.1510892 0.2734307 0.08064167 0.6204359 0.0000000 0.6643792 0.2502177 0.2724272
Sample5 0.0000000 0.4358840 0.9106778 0.3425521 0.5230118 0.64636639 0.4365995 0.5848757 0.5989048 1.00000000 0.5013767 0.8444353 0.0000000 0.8413705 0.7055393
Sample6 0.9668400 0.0000000 0.7920770 0.3549156 0.0000000 0.16837552 0.1753813 1.0000000 0.0000000 0.00000000 1.0000000 0.2707480 0.6189015 0.0000000 1.0000000
Sample7 0.4824578 0.6602128 0.2860993 0.4002768 0.9693666 0.00000000 0.3152340 0.1379430 0.6548660 0.47439889 0.3435690 0.3907255 0.7911855 0.3374053 0.6464399
Sample8 0.7822241 0.7414237 0.4892138 0.2692035 0.7416527 0.08086024 0.5234921 0.6141626 0.7411251 0.53954477 0.3647259 0.4272453 0.7269801 0.6572230 0.4564439
library(PreMSIm)
path = system.file("extdata", "example.txt", package = "PreMSIm", mustWork = TRUE)
input_data = data_pre(path, type = "ID")
msi_pre(input_data)

I get the correct result:

   Sample MSI_status
1 Sample1          0
2 Sample2          0
3 Sample3          1
4 Sample4          0
5 Sample5          1
6 Sample6          0
7 Sample7          0
8 Sample8          0

When I load my file from CSV or excel into R and then try to run mine I get this error:

> X <- read_excel("~/Desktop/Research/PatelMeningioma/SmokerDEG/countpremsim.xlsx")
> input_data = data_pre(X, type = "symbol")
Error in data_pre(X, type = "symbol") :
  'input.path' is missing or incorrect

When I check the function it looks like the input needs to be a character:

> data_pre
function (input.path, type = c("Symbol", "ID"))
{
    if (missing(input.path) || class(input.path) != "character")
        stop("'input.path' is missing or incorrect")
    type <- match.arg(type)
    a <- read.table(input.path, stringsAsFactors = FALSE, header = TRUE,
        row.names = 1, sep = "\t", check.names = FALSE)
    if (TRUE %in% is.na(match(feature[, type], rownames(a)))) {
        if (sum(!is.na(match(feature[, type], rownames(a)))) >=
            5) {
            feature <- feature[!is.na(match(feature[, type],
                rownames(a))), ]
            rownames(feature) <- NULL
        }
        else {
            stop("Some features of the current test set are missing!")
        }
    }
    a <- a[match(feature[, type], rownames(a)), , drop = FALSE]
    if (FALSE %in% complete.cases(a))
        stop("Predictor variables with missing values are presented in the current test set")
    if (dim(a)[2] != 1) {
        a <- apply(t(a), 2, function(x) {
            (x - min(x))/(max(x) - min(x))
        })
        a[is.nan(a)] <- 1
    }
    else {
        a <- t(a)
    }
    if (type == "ID") {
        colnames(a) <- as.character(feature[, "Symbol"])
    }
    return(a)
}
<bytecode: 0x7f82451af3b0>
<environment: namespace:PreMSIm>

So I use this:

> input_data = data_pre(as.character(X), type = "Symbol")

But now I get this error:

Error in file(file, "rt") : invalid 'description' argument

All help is greatly appreciated


问:
Flask multiple routes with single function
initial code:

```<code>@app.route('/word/', defaults={'reqpath': ''})
@app.route('/pdf/', defaults={'reqpath': ''})
@app.route('/word/<path:reqpath>')
@app.route('/pdf/<path:reqpath>')
def my_docs(reqpath):
   if request.path.lower().startswith("/word"):
      localPath = r'D:\WordDocs'
   elif request.path.lower().startswith("/pdf"):
      localPath = r'D:\PdfDocs'

   docsPath = safe_join(localPath, reqpath)
</code>```

rest of the codes:

Hi, when I run the above-written codes, it always runs the (pdf) last route, @app.route('/pdf/<path:reqpath>'), and it gets overwritten in the url from "http://127.0.0.1:5000/word/" to "http://127.0.0.1:5000/pdf/", even if it is changed manually, but if I interchange the order like:

```<code>@app.route('/pdf/', defaults={'reqpath': ''})
@app.route('/word/', defaults={'reqpath': ''})
@app.route('/pdf/<path:reqpath>')
@app.route('/word/<path:reqpath>')

</code>```

then it picks up the word route @app.route('/word/<path:reqpath>') but never runs the pdf route.

I want the url "http://127.0.0.1:5000/pdf/" to pick up the path = r'D:PdfDocs' and "http://127.0.0.1:5000/word/" to pick up the path = r'D:\WordDocs'.

I'm in the process of learning Python (Flask), any help will be appreciated.
thanks

Body:
initial code:

@app.route('/word/', defaults={'reqpath': ''})
@app.route('/pdf/', defaults={'reqpath': ''})
@app.route('/word/<path:reqpath>')
@app.route('/pdf/<path:reqpath>')
def my_docs(reqpath):
   if request.path.lower().startswith("/word"):
      localPath = r'D:\WordDocs'
   elif request.path.lower().startswith("/pdf"):
      localPath = r'D:\PdfDocs'

   docsPath = safe_join(localPath, reqpath)

rest of the codes:

Hi, when I run the above-written codes, it always runs the (pdf) last route, @app.route('/pdf/<path:reqpath>'), and it gets overwritten in the url from "http://127.0.0.1:5000/word/" to "http://127.0.0.1:5000/pdf/", even if it is changed manually, but if I interchange the order like:

@app.route('/pdf/', defaults={'reqpath': ''})
@app.route('/word/', defaults={'reqpath': ''})
@app.route('/pdf/<path:reqpath>')
@app.route('/word/<path:reqpath>')

then it picks up the word route @app.route('/word/<path:reqpath>') but never runs the pdf route.

I want the url "http://127.0.0.1:5000/pdf/" to pick up the path = r'D:PdfDocs' and "http://127.0.0.1:5000/word/" to pick up the path = r'D:\WordDocs'.

I'm in the process of learning Python (Flask), any help will be appreciated.
thanks


问:
Partition small files issue using pyspark
I do have some code works without generating small files in hive, but when I use them in pyspark, I encountered small file issue.

Hi folks, I do use insert overwrite method to get rid of small file issue in orc table like this:

```<code>set hive.exec.dynamic.partition=true
set hive.exec.dynamic.partition.mode=nonstrict;

insert overwrite table {tgt_db}.{tgt_tbl} PARTITION (p_checking_date='{espdate}')
    select
        week_num,
        .....
        .....
    from {stg_db}.{stg_tbl} where p_checking_date='{espdate}'
    order by .... desc

</code>```

It works pretty well in hive but when I use pyspark, it generates lots of small files:

```<code>sql = """

    insert overwrite table {tgt_db}.{tgt_tbl} PARTITION (p_checking_date='{espdate}')
    select
        week_num,
        ........
    from {stg_db}.{stg_tbl} where p_checking_date='{espdate}'
    order by ..... desc
    """.format(tgt_db = tgt_db,
                tgt_tbl = tgt_tbl,
                espdate=espdate,
                stg_db = stg_db,
                stg_tbl = stg_tbl)
    spark.sql(sql)
</code>```

I've also try to set:

```<code>    spark.sql("SET hive.merge.sparkfiles = true")
    spark.sql("SET hive.merge.mapredfiles = true")
    spark.sql("SET hive.merge.tezfiles=true")
    spark.sql("SET hive.merge.mapfiles = true")
    spark.sql("set hive.merge.smallfiles.avgsize = 128000000")
    spark.sql("set hive.merge.size.per.task = 128000000")
</code>```

But it does not work... By the way the CONCATENATE could only concat several small files instead of all.
Could anyone help me? Thank you so much.

Body:
I do have some code works without generating small files in hive, but when I use them in pyspark, I encountered small file issue.

Hi folks, I do use insert overwrite method to get rid of small file issue in orc table like this:

set hive.exec.dynamic.partition=true
set hive.exec.dynamic.partition.mode=nonstrict;

insert overwrite table {tgt_db}.{tgt_tbl} PARTITION (p_checking_date='{espdate}')
    select
        week_num,
        .....
        .....
    from {stg_db}.{stg_tbl} where p_checking_date='{espdate}'
    order by .... desc

It works pretty well in hive but when I use pyspark, it generates lots of small files:

sql = """

    insert overwrite table {tgt_db}.{tgt_tbl} PARTITION (p_checking_date='{espdate}')
    select
        week_num,
        ........
    from {stg_db}.{stg_tbl} where p_checking_date='{espdate}'
    order by ..... desc
    """.format(tgt_db = tgt_db,
                tgt_tbl = tgt_tbl,
                espdate=espdate,
                stg_db = stg_db,
                stg_tbl = stg_tbl)
    spark.sql(sql)

I've also try to set:

    spark.sql("SET hive.merge.sparkfiles = true")
    spark.sql("SET hive.merge.mapredfiles = true")
    spark.sql("SET hive.merge.tezfiles=true")
    spark.sql("SET hive.merge.mapfiles = true")
    spark.sql("set hive.merge.smallfiles.avgsize = 128000000")
    spark.sql("set hive.merge.size.per.task = 128000000")

But it does not work... By the way the CONCATENATE could only concat several small files instead of all.
Could anyone help me? Thank you so much.