问:
How to send a RARP-request using Scapy in Python
I am trying to fetch an ip address of a remote machine B from my machine A using mac address of Machine B. Both A & B  are on same subnet. I am trying to use Scapy library in python and issuing a RARP request.
Below is my code. I am getting 0.0.0.0 as ouput.

```<code>import scapy.all as scapy

def get_ip(mac):
    arp_request=scapy.ARP(op=3, hwdst=mac)
    broadcast = scapy.Ether(dst = 'ff:ff:ff:ff:ff:ff')
    arp_request_broadcast = broadcast / arp_request
    # print('$$$', arp_request_broadcast.show())
    answered_list=scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
    unanswered_list=scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[1]
    response = {'answered_list':answered_list, 'unanswered_list':unanswered_list}
    print('unanswered_list',unanswered_list[0].pdst)
    return response

macB='Mac address of machine B'
obj=get_ip(macB)
print(obj)
</code>```

Output:

```<code>unanswered_list 0.0.0.0
{'answered_list': <Results: TCP:0 UDP:0 ICMP:0 Other:0>, 'unanswered_list': <Unanswered: TCP:0 UDP:0 ICMP:0 Other:1>}
</code>```

Body:
I am trying to fetch an ip address of a remote machine B from my machine A using mac address of Machine B. Both A & B  are on same subnet. I am trying to use Scapy library in python and issuing a RARP request.
Below is my code. I am getting 0.0.0.0 as ouput.

import scapy.all as scapy

def get_ip(mac):
    arp_request=scapy.ARP(op=3, hwdst=mac)
    broadcast = scapy.Ether(dst = 'ff:ff:ff:ff:ff:ff')
    arp_request_broadcast = broadcast / arp_request
    # print('$$$', arp_request_broadcast.show())
    answered_list=scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
    unanswered_list=scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[1]
    response = {'answered_list':answered_list, 'unanswered_list':unanswered_list}
    print('unanswered_list',unanswered_list[0].pdst)
    return response

macB='Mac address of machine B'
obj=get_ip(macB)
print(obj)

Output:

unanswered_list 0.0.0.0
{'answered_list': <Results: TCP:0 UDP:0 ICMP:0 Other:0>, 'unanswered_list': <Unanswered: TCP:0 UDP:0 ICMP:0 Other:1>}


来源: stackexchange

问:
How to "diagram as code" zoomable block diagram in Python, or with another tool Python can interact with?
Is there a package in Python (or JavaSs) that can generate GUI like in the image below? Allowing to:

Generate block diagrams as code

Zoom into\out-of blocks interactively.

There are packages that support "Diagrams as code" in Python (Diagrams, BlockDiag), but These show the entire diagram at once and are not interactive.

I describe below the behavior I want to support.

I want to describe a router that contains components and in turn these
components can contain additional sub components. In the high level of
the diagram (top left corner) I can click on "Router A" and reveal its
contents. I can continue and click on "Protocol 1 Handler" (bottom
left corner) to zoom in again and get the view of the logic inside
that block (Right bottom corner).

In addition, clicking on the arrow will display details about all the
interfaces between the routers (right top corner).

ContentLicense: CC BY-SA 4.0


问:
MERN stack Application Deployment issue
I'm trying to deploy my MERN stack App through render.com, but it's keep getting error like this

Dec 14 10:27:37 PM  > undefined install /opt/render/project/src Dec 14 10:27:37 PM  > npm i && cd client && npm install

and its fail to deployment.

Please help how to fix this, all of my projects are down right now,because heroku have changed their policy.

I did try to update react and node.
Also, I have tried to on heroku but still get same errors..

Title: MERN stack Application Deployment issue


问:
How to create a Barplot with a slider widget using R shiny
I'm trying to create a barplot that varies with time.
I have a dataset called "continental_death_total" which is shown in the image below:

I tried to create the R shiny App but dont know how. This is my rough code:

```<code>library(shiny)
library(ggplot2)

shinyUI(fluidPage(
  # Create a container for the bar plot
  plotOutput("plot", height = "300px"),

  # Create a container for the slider widget
  sliderInput("range", "Date range:",
              min = min(df$date),
              max = max(df$date),
              value = range(df$date))
))

shinyServer(function(input, output) {
  # Load the data into a data frame
  df <- read.csv("data.csv")

  # Generate the bar plot
  output$plot <- renderPlot({
    ggplot(df[df$date >= input$range[1] & df$date <= input$range[2],],
           aes(x = date, y = death_total, fill = continent)) +
      geom_bar(stat = "identity")
  })
})
</code>```

Body:
I'm trying to create a barplot that varies with time.
I have a dataset called "continental_death_total" which is shown in the image below:

I tried to create the R shiny App but dont know how. This is my rough code:

library(shiny)
library(ggplot2)

shinyUI(fluidPage(
  # Create a container for the bar plot
  plotOutput("plot", height = "300px"),

  # Create a container for the slider widget
  sliderInput("range", "Date range:",
              min = min(df$date),
              max = max(df$date),
              value = range(df$date))
))

shinyServer(function(input, output) {
  # Load the data into a data frame
  df <- read.csv("data.csv")

  # Generate the bar plot
  output$plot <- renderPlot({
    ggplot(df[df$date >= input$range[1] & df$date <= input$range[2],],
           aes(x = date, y = death_total, fill = continent)) +
      geom_bar(stat = "identity")
  })
})


问:
Google cloud composer-2 authentication for rest API
I have been trying to use composer-2 apis through REST call. I was using id_token.fetch_id_token to generate token but it is not working for it. Please let me know if there are any ways to authenticate composer-2 apis using SA while making rest api calls from code.</p>


问:
I have to select text and get selection text from textInput and apply style on text for web, ios and android. how to do this?
I am working on a custom text-editor using textInput and custom bold, italic and underline button in tool-bar. I got selection text for web and range of the text for android & ios. Now I don't know how to apply style on selected using bold, italic and underline buttons. So how can I apply?

```<code>const [newSelection, setNewSelection] = useState({
    start: text?.length || 0,
    end: text?.length || 0,
  });

 const onBold = () => {
    if (Platform.OS === "web") {
      const selection = window.getSelection();
       if (selection) {
         const selectedText = selection.toString();
         if (selectedText) {
           alert(selectedText);
         }
       }
    } else {
      alert(newSelection);
    }

 <TextInput
          onChangeText={onChangeText}
          style={[S.textInputStyle, textInputStyle]}
          ref={textInput}
          multiline
          onSelectionChange={(e) => {
            setSelection(e.nativeEvent.selection);
            if (setCursorPosition) setCursorPosition(e.nativeEvent.selection);
            const selection = e.nativeEvent.selection;
            setNewSelection([selection.start, selection.end]);
          }}
          selectTextOnFocus
          autoCapitalize='none'
          autoCorrect={false}
          onFocus={() => {
            setFocused(true);
          }}
          {...props}
        >
          {highlightedText}
        </TextInput>
</code>```

Body:
I am working on a custom text-editor using textInput and custom bold, italic and underline button in tool-bar. I got selection text for web and range of the text for android & ios. Now I don't know how to apply style on selected using bold, italic and underline buttons. So how can I apply?

const [newSelection, setNewSelection] = useState({
    start: text?.length || 0,
    end: text?.length || 0,
  });

 const onBold = () => {
    if (Platform.OS === "web") {
      const selection = window.getSelection();
       if (selection) {
         const selectedText = selection.toString();
         if (selectedText) {
           alert(selectedText);
         }
       }
    } else {
      alert(newSelection);
    }

 <TextInput
          onChangeText={onChangeText}
          style={[S.textInputStyle, textInputStyle]}
          ref={textInput}
          multiline
          onSelectionChange={(e) => {
            setSelection(e.nativeEvent.selection);
            if (setCursorPosition) setCursorPosition(e.nativeEvent.selection);
            const selection = e.nativeEvent.selection;
            setNewSelection([selection.start, selection.end]);
          }}
          selectTextOnFocus
          autoCapitalize='none'
          autoCorrect={false}
          onFocus={() => {
            setFocused(true);
          }}
          {...props}
        >
          {highlightedText}
        </TextInput>


问:
UnidentifiedImageError: cannot identify image file with Pytorch3d on Google Colab
I'm learning Pytorch3d and am trying to load .obj file with texture.
The code is:

```<code>DATA_DIR = "./data"
obj_filename = os.path.join(DATA_DIR, "cow_mesh/cow.obj")
device = torch.device('cuda')
mesh = load_objs_as_meshes([obj_filename], device=device)
</code>```

And indeed I have the texture file at ./data/cow_mesh/cow_texture.png
However, I get the error below.

```<code>UnidentifiedImageError: cannot identify image file <_io.BufferedReader name='data/cow_mesh/cow_texture.png'>
</code>```

Could someone help?

Body:
I'm learning Pytorch3d and am trying to load .obj file with texture.
The code is:

DATA_DIR = "./data"
obj_filename = os.path.join(DATA_DIR, "cow_mesh/cow.obj")
device = torch.device('cuda')
mesh = load_objs_as_meshes([obj_filename], device=device)

And indeed I have the texture file at ./data/cow_mesh/cow_texture.png
However, I get the error below.

UnidentifiedImageError: cannot identify image file <_io.BufferedReader name='data/cow_mesh/cow_texture.png'>

Could someone help?


问:
Animate three card depends on scrolling value
I have three card in horizontal, i just want animate them like this https://www.bluelabellabs.com/work/delve/ (the Result Section)

My JS Code:

```<code>  `window.addEventListener('scroll', () => {
    const cardOne = document.getElementById("box_one")
    const cardTwo = document.getElementById("box_two")
    const cardThree = document.getElementById("box_three")
    const scrollYValue = window.scrollY;

    $(window).scroll(function () {
      if ($(window).scrollTop() > $('body').height() / 2) {
        const cardOne = document.getElementById("box_one")
        const cardTwo = document.getElementById("box_two")
        const cardThree = document.getElementById("box_three")
        const scrollYValue = window.scrollY;

        $(window).scroll(function() {
          var position = $(window).scrollTop();
          var scroll = $(window).scrollTop();
            // console.log(scroll, position);
            if (scroll >= position) {
              console.log("Up");
                cardOne.style.transform = "translate3d(0px, " + -scrollYValue / 200 + "em, 0px)",
                cardTwo.style.transform = "translate3d(0px, " + -scrollYValue / 600 + "em, 0px)",
                cardThree.style.transform = `translateY(${scrollYValue / 30}px)`
              } else if (scroll <= position) {
                console.log("back");
                cardOne.style.transform = "translate3d(0px, " + scrollYValue  + "px, 0px)",
                cardTwo.style.transform = `translateY(${-scrollYValue / 90}px)`
                cardThree.style.transform = `translateY(${-scrollYValue / 30}px)`
            }
            position = scroll;
        });
      }
    });
  })`
</code>```
```<code>
</code>```

Body:
I have three card in horizontal, i just want animate them like this https://www.bluelabellabs.com/work/delve/ (the Result Section)

My JS Code:

  `window.addEventListener('scroll', () => {
    const cardOne = document.getElementById("box_one")
    const cardTwo = document.getElementById("box_two")
    const cardThree = document.getElementById("box_three")
    const scrollYValue = window.scrollY;

    $(window).scroll(function () {
      if ($(window).scrollTop() > $('body').height() / 2) {
        const cardOne = document.getElementById("box_one")
        const cardTwo = document.getElementById("box_two")
        const cardThree = document.getElementById("box_three")
        const scrollYValue = window.scrollY;

        $(window).scroll(function() {
          var position = $(window).scrollTop();
          var scroll = $(window).scrollTop();
            // console.log(scroll, position);
            if (scroll >= position) {
              console.log("Up");
                cardOne.style.transform = "translate3d(0px, " + -scrollYValue / 200 + "em, 0px)",
                cardTwo.style.transform = "translate3d(0px, " + -scrollYValue / 600 + "em, 0px)",
                cardThree.style.transform = `translateY(${scrollYValue / 30}px)`
              } else if (scroll <= position) {
                console.log("back");
                cardOne.style.transform = "translate3d(0px, " + scrollYValue  + "px, 0px)",
                cardTwo.style.transform = `translateY(${-scrollYValue / 90}px)`
                cardThree.style.transform = `translateY(${-scrollYValue / 30}px)`
            }
            position = scroll;
        });
      }
    });
  })`


问:
Why does space appearing between two views when I add scrollView, how can I get rid of that?
space between two views

I also tried android:fillViewport="true" but didn't work


问:
How to use multivariate variables forcast using transformer model of tsai
Please tell me about the tsai model with multivariate variables.

I am trying to create a time series model with multivariate variables using transformer model of tsai.

In the Forecasting section of the document below, it says "univariate or multivariate time series input," but I can only find examples of univariate forecast and not multivariate forecast.
https://timeseriesai.github.io/tsai/#forecasting
When I trained a model with multivariate variables and performed inference, the result was unnatural oscillation.

Please tell me an example of multivariate forecast description.
Or, should I use the following Multivariate Regression instead of Forecasting?
https://timeseriesai.github.io/tsai/#multivariate-regression


问:
Error in loading json with os and pandas package
I want to load a json and I run this source

```<code>b_path = '/home/r/Documents/TTx'
a = os.path.join(base_path, 'Tc.json')
b = json.load(open(a))['data']
</code>```

but I have an error that I attach this error

then I add encoding(utf-8) to open for example

b = json.load(open(a),encoding(utf-8))['data']

but I have error still

How to solve my problem?

Body:
I want to load a json and I run this source

b_path = '/home/r/Documents/TTx'
a = os.path.join(base_path, 'Tc.json')
b = json.load(open(a))['data']

but I have an error that I attach this error

then I add encoding(utf-8) to open for example

b = json.load(open(a),encoding(utf-8))['data']

but I have error still

How to solve my problem?


问:
@Entity classes in external lib and have the option to override it in the current project
I´m currently working to implement a lib ("Share Project") for util classes and also some @Entity classes, which I need in all my other projects to avoid duplicate code implementation.

Some @Entity classes I would like to override in my current project (so I can use other properties etc.).
Unfortunately inside my "Share Project" I have also in some @Entity classes a reference, like:

```<code>@NotNull
@ManyToOne
@JoinColumn(name = "user_fk", nullable = false)
private User user;
</code>```

In my current project I want to override than e.g. this User @Entity class, like:

```<code>@Entity
@Table(name = "user", indexes = { @Index(columnList = "user_id, id_hash") })
public class UserCustom implements Serializable {
</code>```

But my "Share Project" is not aware in the references, that I would like to use my custom User @Entity class.

Here is a visualiation:

I would like to need a generic class for "User" e.g. so my "Share project" is searching in my current project for a @Entity "User". If it´s not found in my project, it will use the @Entity User class from "Share Project".

Any ideas?

Body:
I´m currently working to implement a lib ("Share Project") for util classes and also some @Entity classes, which I need in all my other projects to avoid duplicate code implementation.

Some @Entity classes I would like to override in my current project (so I can use other properties etc.).
Unfortunately inside my "Share Project" I have also in some @Entity classes a reference, like:

@NotNull
@ManyToOne
@JoinColumn(name = "user_fk", nullable = false)
private User user;

In my current project I want to override than e.g. this User @Entity class, like:

@Entity
@Table(name = "user", indexes = { @Index(columnList = "user_id, id_hash") })
public class UserCustom implements Serializable {

But my "Share Project" is not aware in the references, that I would like to use my custom User @Entity class.

Here is a visualiation:

I would like to need a generic class for "User" e.g. so my "Share project" is searching in my current project for a @Entity "User". If it´s not found in my project, it will use the @Entity User class from "Share Project".

Any ideas?


问:
Cookie Consent to Integrate with Angular Website with GDPR policies - FaceBook Analytics and Meta Pixel
Facing issue with meta analytics currently. It works well when i tested with few indian users try to open my website and when they allow analytics to be tracked it works well, but someone from EU countries tries to do the same the FB meta pixel does not analyse the same. My project is in angular and i am using ngx-pixel package to implement the same. We are new to the pixel analytics working and have limited knowlegde over it. Any help would be appreciated.

https://www.npmjs.com/package/ngx-pixel

Need help to track EU users based on the selection in the cookie pop up.


问:
PropertyChanged is null when property is set via object
So I'm doing some example with data binding in C# winforms. And the textbox's text does not change when I update values of the object contains that property, but when I used another textbox to directly change the value of the property then it works well. I found out that when I used another textbox to set value, the "PropertyChanged" has value and when I used object, it's just "null".

Here are my class:

```<code>public WeatherClient() { }
        ~WeatherClient() { }
        public void Dispose() { }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        //other properties
        private float _generationtime_ms;
        public float generationtime_ms
        {
            get => _generationtime_ms;
            set
            {
                _generationtime_ms = value;
                OnPropertyChanged(nameof(this.generationtime_ms));
            }
        }
        public WeatherClient getWeather(string url)
        {
            using (WebClient web = new WebClient())
            {
                url = string.Format(url);
                var json = web.DownloadString(url);
                WeatherClient WeatherInfoRespond = JsonConvert.DeserializeObject<WeatherClient>(json);
                return WeatherInfoRespond;
            }
        }
</code>```

Form.cs:

```<code>        WeatherClient WeatherClient = new WeatherClient();
</code>```
```<code>public Form1()
        {
            InitializeComponent();

            WeatherClient = WeatherClient.getWeather(); //this for avoiding null value of class type variable
            BindingInit();
        }
</code>```

Binding WeatherClient.generationtime_ms with textbox3

```<code>void BindingInit()
        {
            Binding Binding2 = new Binding("Text", WeatherClient, nameof(WeatherClient.generationtime_ms), true, DataSourceUpdateMode.OnPropertyChanged);
            textBox3.DataBindings.Add(Binding2);
        }
</code>```

When I update via instance, it does not binding:

```<code>       private void button1_Click(object sender, EventArgs e)
        {
            WeatherClient = WeatherClient.getWeather();
        }
</code>```

And when I used another textbox to update value, it works:

```<code> private void button1_Click(object sender, EventArgs e)
        {
            WeatherClient.generationtime_ms = Convert.ToInt32(textBox1.Text);
        }

</code>```

Any suggestion would help.
Thank you guys.

Body:
So I'm doing some example with data binding in C# winforms. And the textbox's text does not change when I update values of the object contains that property, but when I used another textbox to directly change the value of the property then it works well. I found out that when I used another textbox to set value, the "PropertyChanged" has value and when I used object, it's just "null".

Here are my class:

public WeatherClient() { }
        ~WeatherClient() { }
        public void Dispose() { }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        //other properties
        private float _generationtime_ms;
        public float generationtime_ms
        {
            get => _generationtime_ms;
            set
            {
                _generationtime_ms = value;
                OnPropertyChanged(nameof(this.generationtime_ms));
            }
        }
        public WeatherClient getWeather(string url)
        {
            using (WebClient web = new WebClient())
            {
                url = string.Format(url);
                var json = web.DownloadString(url);
                WeatherClient WeatherInfoRespond = JsonConvert.DeserializeObject<WeatherClient>(json);
                return WeatherInfoRespond;
            }
        }

Form.cs:

        WeatherClient WeatherClient = new WeatherClient();

public Form1()
        {
            InitializeComponent();

            WeatherClient = WeatherClient.getWeather(); //this for avoiding null value of class type variable
            BindingInit();
        }

Binding WeatherClient.generationtime_ms with textbox3

void BindingInit()
        {
            Binding Binding2 = new Binding("Text", WeatherClient, nameof(WeatherClient.generationtime_ms), true, DataSourceUpdateMode.OnPropertyChanged);
            textBox3.DataBindings.Add(Binding2);
        }

When I update via instance, it does not binding:

       private void button1_Click(object sender, EventArgs e)
        {
            WeatherClient = WeatherClient.getWeather();
        }

And when I used another textbox to update value, it works:

 private void button1_Click(object sender, EventArgs e)
        {
            WeatherClient.generationtime_ms = Convert.ToInt32(textBox1.Text);
        }

Any suggestion would help.
Thank you guys.


问:
How to use DwmRegisterThumbnail with child windows?
I'm 'casting' the screen of window1 to window2 using the WINAPI DwmRegisterThumbnail

but as soon I set the window2 child of another window the image disappears.

After reading the docs I found this mention:

Setting the destination window handle to anything other than a
top-level window type will result in a return value of E_INVALIDARG.

```<code>    HWND dest = (HWND)this->winId();
    HWND source = ...
    hr = DwmRegisterThumbnail(dest, source, &thumbnail_id);
    DWORD err = GetLastError();
    qDebug() << "hr: " << hr;

    if (SUCCEEDED(hr) && NULL != thumbnail_id)
    {
        prop.dwFlags = DWM_TNP_RECTDESTINATION | DWM_TNP_RECTSOURCE | DWM_TNP_OPACITY
            | DWM_TNP_VISIBLE | DWM_TNP_SOURCECLIENTAREAONLY;
        prop.rcSource = { 0, 0, 1200, 600 };
        prop.rcDestination = { 0, 0, 1200, 600 };
        prop.opacity = 255;
        prop.fVisible = TRUE;
        prop.fSourceClientAreaOnly = FALSE;

        hr = DwmUpdateThumbnailProperties(thumbnail_id, &prop);

        qDebug() << "hr: " << hr;
    }
</code>```

I also tried using a QDockWidget but the image is visible only when the widget is not docked to the MainWindow, as soon I dock the widget, the image disappears, sad.

There's something else I could try to be able to 'cast' the image to a child window?

or maybe another winapi I could use?

Body:
I'm 'casting' the screen of window1 to window2 using the WINAPI DwmRegisterThumbnail

but as soon I set the window2 child of another window the image disappears.

After reading the docs I found this mention:

Setting the destination window handle to anything other than a
top-level window type will result in a return value of E_INVALIDARG.

    HWND dest = (HWND)this->winId();
    HWND source = ...
    hr = DwmRegisterThumbnail(dest, source, &thumbnail_id);
    DWORD err = GetLastError();
    qDebug() << "hr: " << hr;

    if (SUCCEEDED(hr) && NULL != thumbnail_id)
    {
        prop.dwFlags = DWM_TNP_RECTDESTINATION | DWM_TNP_RECTSOURCE | DWM_TNP_OPACITY
            | DWM_TNP_VISIBLE | DWM_TNP_SOURCECLIENTAREAONLY;
        prop.rcSource = { 0, 0, 1200, 600 };
        prop.rcDestination = { 0, 0, 1200, 600 };
        prop.opacity = 255;
        prop.fVisible = TRUE;
        prop.fSourceClientAreaOnly = FALSE;

        hr = DwmUpdateThumbnailProperties(thumbnail_id, &prop);

        qDebug() << "hr: " << hr;
    }

I also tried using a QDockWidget but the image is visible only when the widget is not docked to the MainWindow, as soon I dock the widget, the image disappears, sad.

There's something else I could try to be able to 'cast' the image to a child window?

or maybe another winapi I could use?


问:
whenNew in Kotlin unit test & Missing calls inside every block
Specifically asking, is there a Kotlin version for this java statement?

whenNew(myClass.class).withAnyArguments().thenReturn(myObject);

I have looked everywhere and haven't found anything that has worked for me yet.

I have tried:

every { myClass(any(), any()) } returns myObject

To this I get this error - argumentA must be in the form m.n. This tells me that blank arguments are being fed to myClass constructor but this is not my motive. I want this class to always return myObject whenever a constructor is being called, irrespective of the arguments.

I have also tried this:

every { myClass(TEST_A, TEST_B) } returns myObject

Then I get this error - Missing calls inside every { ... } block.

Another key point to add is - this is not the class I am writing the test for. I am writing the test cases for myOtherClass (actually defined in kotlin as an object, see below). Within one of the methods in myOtherClass, myClass is instantiated by feeding a set of arguments to its public constructor.

```<code>object myOtherClass {
   fun mainFunction(a: A, b: B): X {
      val answer = getAnswer(a, b)
      y = convertAnswerToX(answer)
      return y
   }

   private fun getAnswer(a: A, b: B): myClass {
      val a1 = doSomethingToA(a)
      val b1 = doSomethingToB(b)
      return myClass(a1, b1)
   }
}

</code>```

Body:
Specifically asking, is there a Kotlin version for this java statement?

whenNew(myClass.class).withAnyArguments().thenReturn(myObject);

I have looked everywhere and haven't found anything that has worked for me yet.

I have tried:

every { myClass(any(), any()) } returns myObject

To this I get this error - argumentA must be in the form m.n. This tells me that blank arguments are being fed to myClass constructor but this is not my motive. I want this class to always return myObject whenever a constructor is being called, irrespective of the arguments.

I have also tried this:

every { myClass(TEST_A, TEST_B) } returns myObject

Then I get this error - Missing calls inside every { ... } block.

Another key point to add is - this is not the class I am writing the test for. I am writing the test cases for myOtherClass (actually defined in kotlin as an object, see below). Within one of the methods in myOtherClass, myClass is instantiated by feeding a set of arguments to its public constructor.

object myOtherClass {
   fun mainFunction(a: A, b: B): X {
      val answer = getAnswer(a, b)
      y = convertAnswerToX(answer)
      return y
   }

   private fun getAnswer(a: A, b: B): myClass {
      val a1 = doSomethingToA(a)
      val b1 = doSomethingToB(b)
      return myClass(a1, b1)
   }
}


问:
Spark custom Aggregator with multiple columns
I have written a Spark UDAF that takes as input two columns (timestamp and value) and calculates a rate of change via least squares over all data points in a given window. It works perfectly fine, the code is below (shortened to relevant pieces).

UDAF

import com.google.common.collect.ImmutableList;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.expressions.MutableAggregationBuffer;
import org.apache.spark.sql.expressions.UserDefinedAggregateFunction;
import org.apache.spark.sql.types.DataType;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructType;

public class MinimalUDAF extends UserDefinedAggregateFunction {
    @Override
    public StructType inputSchema() {
        return DataTypes.createStructType(ImmutableList.of(
                DataTypes.createStructField("timestamp", DataTypes.LongType, true),
                DataTypes.createStructField("value", DataTypes.DoubleType, true)));
    }

    @Override
    public StructType bufferSchema() {
        return DataTypes.createStructType(ImmutableList.of(
                DataTypes.createStructField("timestamps", DataTypes.createArrayType(DataTypes.LongType), false),
                DataTypes.createStructField("values", DataTypes.createArrayType(DataTypes.DoubleType), false)));
    }

    @Override
    public DataType dataType() {
        return DataTypes.DoubleType;
    }

    @Override
    public void update(final MutableAggregationBuffer buffer, final Row input) {
        final Long timestamp = input.getAs(0);
        final Double value = input.getAs(1);
        // ...
    }

    @Override
    public Object evaluate(final Row buffer) {
        // calculate and return rate of change
    }

    // ...
}
```
<p><strong>Usage</strong></p>
<pre class="lang-java prettyprint-override"><code>@Test
public void testMinimalUDAF() {
    final WindowSpec windowSpec = Window.partitionBy("instrument_id")
            .orderBy("timestamp")
            // look back 24h
            .rangeBetween(-1 * 60 * 60 * 24, Window.currentRow());
    final Dataset<Row> dataset = sparkSession
            .get()
            .createDataFrame(
                    ImmutableList.of(
                            RowFactory.create(1, 1, 1671079600L),
                            RowFactory.create(1, 101, 1671079650L),
                            RowFactory.create(1, 401, 1671079700L),
                            RowFactory.create(2, 50, 1671079630L),
                            RowFactory.create(2, 60, 1671079640L)),
                    StructType.fromDDL("instrument_id INT, value INT, timestamp LONG"))
            .withColumn(
                    "udaf",
                    new MinimalUDAF()
                            .apply(functions.col("timestamp"), functions.col("value"))
                            .over(windowSpec));
    dataset.show(false);
}
</code>```

Result

```<code>+-------------+-----+----------+----+
|instrument_id|value|timestamp |udaf|
+-------------+-----+----------+----+
|1            |1    |1671079600|null|
|1            |101  |1671079650|2.0 |
|1            |401  |1671079700|4.0 |
|2            |50   |1671079630|null|
|2            |60   |1671079640|1.0 |
+-------------+-----+----------+----+
</code>```

As of Spark 3, UDAFs are deprecated and the recommendation is to use the Aggregator interface instead.
I have seen the Java example in the Spark code base / docs but it only uses one column as parameter to the aggregator. I am struggling to adapt this for my case to make it take two columns as arguments.
I tried to use MapType / Struct as the IN class but ran into issues.

Aggregator

import org.apache.spark.sql.Encoder;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.expressions.Aggregator;
import org.apache.spark.sql.types.MapType;

public class MinimalMapAggregator extends Aggregator<MapType, Average, Double> {

    @Override
    public Average reduce(final Average buffer, final MapType data) {
        // ...
    }

    // ...
}
```
<p><strong>Usage</strong></p>
<pre class="lang-java prettyprint-override"><code>@Test
public void testMinimalMapAggregator() {
    sparkSession
            .get()
            .udf()
            .register("myUDAF", functions.udaf(new MinimalMapAggregator(), Encoders.bean(MapType.class)));

    final Dataset<Row> dataset = sparkSession
            .get()
            .createDataFrame(
                    ImmutableList.of(
                            RowFactory.create(1, 1, 1671079600L),
                            RowFactory.create(1, 101, 1671079650L),
                            RowFactory.create(1, 401, 1671079700L),
                            RowFactory.create(2, 50, 1671079630L),
                            RowFactory.create(2, 60, 1671079640L)),
                    StructType.fromDDL("instrument_id INT, value INT, timestamp LONG"))
            .withColumn(
                    "ts_val",
                    functions.map(
                            functions.lit("timestamp"),
                            functions.col("timestamp"),
                            functions.lit("value"),
                            functions.col("value")))
            .withColumn(
                    "udaf", functions.expr("myUDAF(ts_val) over (partition by instrument_id order by timestamp)"));
    dataset.show(false);
}
</code>```

When running this, the data variable in reduce() is just an empty MapType, so I can't get to the column values. I am seeing the same behavior with StructType.

How do I do this properly?
Thanks a lot for your help!

Body:
I have written a Spark UDAF that takes as input two columns (timestamp and value) and calculates a rate of change via least squares over all data points in a given window. It works perfectly fine, the code is below (shortened to relevant pieces).

UDAF

import com.google.common.collect.ImmutableList;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.expressions.MutableAggregationBuffer;
import org.apache.spark.sql.expressions.UserDefinedAggregateFunction;
import org.apache.spark.sql.types.DataType;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructType;

public class MinimalUDAF extends UserDefinedAggregateFunction {
    @Override
    public StructType inputSchema() {
        return DataTypes.createStructType(ImmutableList.of(
                DataTypes.createStructField("timestamp", DataTypes.LongType, true),
                DataTypes.createStructField("value", DataTypes.DoubleType, true)));
    }

    @Override
    public StructType bufferSchema() {
        return DataTypes.createStructType(ImmutableList.of(
                DataTypes.createStructField("timestamps", DataTypes.createArrayType(DataTypes.LongType), false),
                DataTypes.createStructField("values", DataTypes.createArrayType(DataTypes.DoubleType), false)));
    }

    @Override
    public DataType dataType() {
        return DataTypes.DoubleType;
    }

    @Override
    public void update(final MutableAggregationBuffer buffer, final Row input) {
        final Long timestamp = input.getAs(0);
        final Double value = input.getAs(1);
        // ...
    }

    @Override
    public Object evaluate(final Row buffer) {
        // calculate and return rate of change
    }

    // ...
}

Usage

@Test
public void testMinimalUDAF() {
    final WindowSpec windowSpec = Window.partitionBy("instrument_id")
            .orderBy("timestamp")
            // look back 24h
            .rangeBetween(-1 * 60 * 60 * 24, Window.currentRow());
    final Dataset<Row> dataset = sparkSession
            .get()
            .createDataFrame(
                    ImmutableList.of(
                            RowFactory.create(1, 1, 1671079600L),
                            RowFactory.create(1, 101, 1671079650L),
                            RowFactory.create(1, 401, 1671079700L),
                            RowFactory.create(2, 50, 1671079630L),
                            RowFactory.create(2, 60, 1671079640L)),
                    StructType.fromDDL("instrument_id INT, value INT, timestamp LONG"))
            .withColumn(
                    "udaf",
                    new MinimalUDAF()
                            .apply(functions.col("timestamp"), functions.col("value"))
                            .over(windowSpec));
    dataset.show(false);
}

Result

+-------------+-----+----------+----+
|instrument_id|value|timestamp |udaf|
+-------------+-----+----------+----+
|1            |1    |1671079600|null|
|1            |101  |1671079650|2.0 |
|1            |401  |1671079700|4.0 |
|2            |50   |1671079630|null|
|2            |60   |1671079640|1.0 |
+-------------+-----+----------+----+

As of Spark 3, UDAFs are deprecated and the recommendation is to use the Aggregator interface instead.
I have seen the Java example in the Spark code base / docs but it only uses one column as parameter to the aggregator. I am struggling to adapt this for my case to make it take two columns as arguments.
I tried to use MapType / Struct as the IN class but ran into issues.

Aggregator

import org.apache.spark.sql.Encoder;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.expressions.Aggregator;
import org.apache.spark.sql.types.MapType;

public class MinimalMapAggregator extends Aggregator<MapType, Average, Double> {

    @Override
    public Average reduce(final Average buffer, final MapType data) {
        // ...
    }

    // ...
}

Usage

@Test
public void testMinimalMapAggregator() {
    sparkSession
            .get()
            .udf()
            .register("myUDAF", functions.udaf(new MinimalMapAggregator(), Encoders.bean(MapType.class)));

    final Dataset<Row> dataset = sparkSession
            .get()
            .createDataFrame(
                    ImmutableList.of(
                            RowFactory.create(1, 1, 1671079600L),
                            RowFactory.create(1, 101, 1671079650L),
                            RowFactory.create(1, 401, 1671079700L),
                            RowFactory.create(2, 50, 1671079630L),
                            RowFactory.create(2, 60, 1671079640L)),
                    StructType.fromDDL("instrument_id INT, value INT, timestamp LONG"))
            .withColumn(
                    "ts_val",
                    functions.map(
                            functions.lit("timestamp"),
                            functions.col("timestamp"),
                            functions.lit("value"),
                            functions.col("value")))
            .withColumn(
                    "udaf", functions.expr("myUDAF(ts_val) over (partition by instrument_id order by timestamp)"));
    dataset.show(false);
}

When running this, the data variable in reduce() is just an empty MapType, so I can't get to the column values. I am seeing the same behavior with StructType.

How do I do this properly?
Thanks a lot for your help!


问:
Error in "p1"/"p2" : non-numeric argument to binary operator
```<code>nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
p1 <- ggplot(nc) +
  geom_sf(linewidth = 0.5) +
  ggtitle("Old default")

p2 <- ggplot(nc) +
  geom_sf() +
  ggtitle("New default")

p1/p2
</code>```

Error in p1/p2 : non-numeric argument to binary operator

Not running. What should I do?
What should I fix?

I have no idea...

..

Body:
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
p1 <- ggplot(nc) +
  geom_sf(linewidth = 0.5) +
  ggtitle("Old default")

p2 <- ggplot(nc) +
  geom_sf() +
  ggtitle("New default")

p1/p2

Error in p1/p2 : non-numeric argument to binary operator

Not running. What should I do?
What should I fix?

I have no idea...

..


问:
OBJLoader gives error when trying to load high poly models
I made a OBJFILELoader but when i try to load a high poly model it gives me a empty string error
I Checked the file and it seems to be totally fine Im not really sure if the problem is with the code or with the model because it dosent work on any high poly model
The Empty string error is at Vector3f vertex = new Vector3f(Float.parseFloat(currentLine[1]) (Line 45)
`

```<code>public static ModelData loadOBJ(String objFileName) {
        FileReader isr = null;
        File objFile = new File(RES_LOC + objFileName + ".obj");
        try {
            isr = new FileReader(objFile);
        } catch (FileNotFoundException e) {
            System.err.println("File not found in res; don't use any extention");
        }
        BufferedReader reader = new BufferedReader(isr);
        String line;
        List<Vertex> vertices = new ArrayList<Vertex>();
        List<Vector2f> textures = new ArrayList<Vector2f>();
        List<Vector3f> normals = new ArrayList<Vector3f>();
        List<Integer> indices = new ArrayList<Integer>();
        try {
            while (true) {
                line = reader.readLine();
                if (line.startsWith("v ")) {
                    String[] currentLine = line.split(" ");
                                        System.out.println(currentLine[1]);
                                        System.out.println("^");
                    Vector3f vertex = new Vector3f((float) Float.valueOf(currentLine[1]),
                            (float) Float.valueOf(currentLine[2]),
                            (float) Float.valueOf(currentLine[3]));
                    Vertex newVertex = new Vertex(vertices.size(), vertex);
                    vertices.add(newVertex);

                } else if (line.startsWith("vt ")) {
                    String[] currentLine = line.split(" ");
                    Vector2f texture = new Vector2f((float) Float.valueOf(currentLine[1]),
                            (float) Float.valueOf(currentLine[2]));
                    textures.add(texture);
                } else if (line.startsWith("vn ")) {
                    String[] currentLine = line.split(" ");
                    Vector3f normal = new Vector3f((float) Float.valueOf(currentLine[1]),
                            (float) Float.valueOf(currentLine[2]),
                            (float) Float.valueOf(currentLine[3]));
                    normals.add(normal);
                } else if (line.startsWith("f ")) {
                    break;
                }
            }
            while (line != null && line.startsWith("f ")) {
                String[] currentLine = line.split(" ");
                String[] vertex1 = currentLine[1].split("/");
                String[] vertex2 = currentLine[2].split("/");
                String[] vertex3 = currentLine[3].split("/");
                processVertex(vertex1, vertices, indices);
                processVertex(vertex2, vertices, indices);
                processVertex(vertex3, vertices, indices);
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            System.err.println("Error reading the file");
        }
        removeUnusedVertices(vertices);
        float[] verticesArray = new float[vertices.size() * 3];
        float[] texturesArray = new float[vertices.size() * 2];
        float[] normalsArray = new float[vertices.size() * 3];
        float furthest = convertDataToArrays(vertices, textures, normals, verticesArray,
                texturesArray, normalsArray);
        int[] indicesArray = convertIndicesListToArray(indices);
        ModelData data = new ModelData(verticesArray, texturesArray, normalsArray, indicesArray,
                furthest);
        return data;
    }
</code>```

`

I checked the file its totally fine
I checked the String its also fine
I tried using other models And it seems to work as long as they are not high poly

Body:
I made a OBJFILELoader but when i try to load a high poly model it gives me a empty string error
I Checked the file and it seems to be totally fine Im not really sure if the problem is with the code or with the model because it dosent work on any high poly model
The Empty string error is at Vector3f vertex = new Vector3f(Float.parseFloat(currentLine[1]) (Line 45)
`

public static ModelData loadOBJ(String objFileName) {
        FileReader isr = null;
        File objFile = new File(RES_LOC + objFileName + ".obj");
        try {
            isr = new FileReader(objFile);
        } catch (FileNotFoundException e) {
            System.err.println("File not found in res; don't use any extention");
        }
        BufferedReader reader = new BufferedReader(isr);
        String line;
        List<Vertex> vertices = new ArrayList<Vertex>();
        List<Vector2f> textures = new ArrayList<Vector2f>();
        List<Vector3f> normals = new ArrayList<Vector3f>();
        List<Integer> indices = new ArrayList<Integer>();
        try {
            while (true) {
                line = reader.readLine();
                if (line.startsWith("v ")) {
                    String[] currentLine = line.split(" ");
                                        System.out.println(currentLine[1]);
                                        System.out.println("^");
                    Vector3f vertex = new Vector3f((float) Float.valueOf(currentLine[1]),
                            (float) Float.valueOf(currentLine[2]),
                            (float) Float.valueOf(currentLine[3]));
                    Vertex newVertex = new Vertex(vertices.size(), vertex);
                    vertices.add(newVertex);

                } else if (line.startsWith("vt ")) {
                    String[] currentLine = line.split(" ");
                    Vector2f texture = new Vector2f((float) Float.valueOf(currentLine[1]),
                            (float) Float.valueOf(currentLine[2]));
                    textures.add(texture);
                } else if (line.startsWith("vn ")) {
                    String[] currentLine = line.split(" ");
                    Vector3f normal = new Vector3f((float) Float.valueOf(currentLine[1]),
                            (float) Float.valueOf(currentLine[2]),
                            (float) Float.valueOf(currentLine[3]));
                    normals.add(normal);
                } else if (line.startsWith("f ")) {
                    break;
                }
            }
            while (line != null && line.startsWith("f ")) {
                String[] currentLine = line.split(" ");
                String[] vertex1 = currentLine[1].split("/");
                String[] vertex2 = currentLine[2].split("/");
                String[] vertex3 = currentLine[3].split("/");
                processVertex(vertex1, vertices, indices);
                processVertex(vertex2, vertices, indices);
                processVertex(vertex3, vertices, indices);
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            System.err.println("Error reading the file");
        }
        removeUnusedVertices(vertices);
        float[] verticesArray = new float[vertices.size() * 3];
        float[] texturesArray = new float[vertices.size() * 2];
        float[] normalsArray = new float[vertices.size() * 3];
        float furthest = convertDataToArrays(vertices, textures, normals, verticesArray,
                texturesArray, normalsArray);
        int[] indicesArray = convertIndicesListToArray(indices);
        ModelData data = new ModelData(verticesArray, texturesArray, normalsArray, indicesArray,
                furthest);
        return data;
    }

`

I checked the file its totally fine
I checked the String its also fine
I tried using other models And it seems to work as long as they are not high poly


问:
next js redirects not working in production page
```<code>const withPlugins = require("next-compose-plugins")

const withBundleAnalyzer = require("@next/bundle-analyzer")({
  enabled: process.env.ANALYZE === "true",
})

/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  reactStrictMode: true,
  async redirects() {
    return [
      {
        source: "/",
        destination: "/schedule/calendar",
        permanent: false,
      },
    ]
  },
  exportPathMap: async function () {
    return {
      "/": { page: "/schedule/calendar" },
    }
  },
}

const withTM = require("next-transpile-modules")([
  "@fullcalendar/common",
  "@fullcalendar/daygrid",
  "@fullcalendar/interaction",
  "@fullcalendar/react",
  "@fullcalendar/timegrid",
])

module.exports = withPlugins([[withBundleAnalyzer({ nextConfig, target: "serverless" })], [withTM]], nextConfig)
</code>```

This is my next.config.js file. In development page this working well, but in production page when i enter root page like 'example.com' show the /schedule/calendar page. Also i try to enter 'example.com/schedule/calendar' show the error This XML file does not appear to have any style information associated with it. I check aws s3 buckets i can't see schedule.html. How can i solve this problem

Body:
const withPlugins = require("next-compose-plugins")

const withBundleAnalyzer = require("@next/bundle-analyzer")({
  enabled: process.env.ANALYZE === "true",
})

/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  reactStrictMode: true,
  async redirects() {
    return [
      {
        source: "/",
        destination: "/schedule/calendar",
        permanent: false,
      },
    ]
  },
  exportPathMap: async function () {
    return {
      "/": { page: "/schedule/calendar" },
    }
  },
}

const withTM = require("next-transpile-modules")([
  "@fullcalendar/common",
  "@fullcalendar/daygrid",
  "@fullcalendar/interaction",
  "@fullcalendar/react",
  "@fullcalendar/timegrid",
])

module.exports = withPlugins([[withBundleAnalyzer({ nextConfig, target: "serverless" })], [withTM]], nextConfig)

This is my next.config.js file. In development page this working well, but in production page when i enter root page like 'example.com' show the /schedule/calendar page. Also i try to enter 'example.com/schedule/calendar' show the error This XML file does not appear to have any style information associated with it. I check aws s3 buckets i can't see schedule.html. How can i solve this problem


问:
How to use gohook to bind right and other buttons?

package main

import (
    "fmt"

    hook "github.com/robotn/gohook"
)

func main() {

    // out: alt-q
    hook.Register(hook.KeyDown, []string{"alt", "q"}, func(e hook.Event) {
        fmt.Println("alt-q")
    })

    // out: no output
    hook.Register(hook.KeyDown, []string{"up"}, func(e hook.Event) {
        fmt.Println("up")
    })

    // out: no output
    hook.Register(hook.KeyHold, []string{"left"}, func(e hook.Event) {
        fmt.Println("left")
    })

    // out: no output
    hook.Register(hook.KeyUp, []string{"down"}, func(e hook.Event) {
        fmt.Println("down")
    })

    s := hook.Start()
    <-hook.Process(s)
}
```
<p>I didn't find the relevant instructions, how to use it?</p>
<p>=================================================</p>
<p>I'm sure there is nothing wrong with the keyboard, the following code prints out the keys normally</p>
<pre class="lang-golang prettyprint-override"><code>hook.Register(hook.KeyUp, []string{}, func(e hook.Event) {
    fmt.Println(e)
})
</code>```

Thank you for your attention.

Body:
package main

import (
    "fmt"

    hook "github.com/robotn/gohook"
)

func main() {

    // out: alt-q
    hook.Register(hook.KeyDown, []string{"alt", "q"}, func(e hook.Event) {
        fmt.Println("alt-q")
    })

    // out: no output
    hook.Register(hook.KeyDown, []string{"up"}, func(e hook.Event) {
        fmt.Println("up")
    })

    // out: no output
    hook.Register(hook.KeyHold, []string{"left"}, func(e hook.Event) {
        fmt.Println("left")
    })

    // out: no output
    hook.Register(hook.KeyUp, []string{"down"}, func(e hook.Event) {
        fmt.Println("down")
    })

    s := hook.Start()
    <-hook.Process(s)
}

I didn't find the relevant instructions, how to use it?

=================================================

I'm sure there is nothing wrong with the keyboard, the following code prints out the keys normally

hook.Register(hook.KeyUp, []string{}, func(e hook.Event) {
    fmt.Println(e)
})

Thank you for your attention.


问:
pandas 'replace' function from string to integers
pandas has a 'replace' function that allows to replace one value with another, but it seems to me not the best option if I have a column with numbers that are represented as strings and I want to convert to integers, is there a better way to do it? ('replac'e will only work for the whole dataframe...)

df.replace('0', int(0)) is too long to implement. is there something more specific?


问:
Twitter OAuth CORS error while redirecting user for authentication from server
I am trying to build an application for my users so that they can log in to my website using Twitter and they can manage their Twitter account from the website itself.
I have created a full 3-legged authentication flow and other managing API calls at my server (some server url) when I call authentication API from the browser it works fine.
But now I want to use a webpage for my users so that they can log in and manage their accounts from that website (a website URL different that server url). So I am trying to create a flow like this:

User will click to log in on my website.

Website will send a login request to my server with the user credentials so that I can verify the

user and its request at my server first.

Then the server will redirect the user to the authentication page of Twitter.

But this is not working, I am getting a CORS error in the console, I attached a screenshot for reference.

Thank you.
Error I am getting in console

I have tried whitelisting server and website URL in twitter developer console.
I know the flow may work if I return the authentication url from server to frontend and navigate user to that url, this may get rid of CORS, but I want to know whether this can be achieved by directly redirecting user to authentication URL from server?


问:
while sending array from android to server 1st element sets at server side 0 value but in android it sets correct value what is the solution
server data

android data

I am passing arraylist of srid of all element and post to server using volley request.enter image description here

here is the code

```<code>public class AttendenceShowStdList extends AppCompatActivity {

    ActivityAttendenceShowStdListBinding AttendenceShowStdList;

    ArrayList<AttStdListModel> userlist = new ArrayList<>();
    ArrayList<AllStdListsrIdAdmIdModel> list= new ArrayList<>();
    ArrayList<AllStdListModel> stdlist = new ArrayList<>();

    AttStdListAdapter adapter;
    private DatePickerDialog datePickerDialog;
    private String date,clid,sectionId,yrId,instId,usid,usType,attdate;

    SharedPreferences sharedPreferences_teach;//staff shareprefferece for profile fetch

    private static final String SHARED_PREF_NAME_TEACH="myprefteach";
    private static final String Key_USID_TEACH = "techusid";
    private static final String Key_INSTID_TEACH = "techinstid";
    private static final String Key_USTYPE_TEACH = "techustype";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AttendenceShowStdList= ActivityAttendenceShowStdListBinding.inflate(getLayoutInflater());
        setContentView(AttendenceShowStdList.getRoot());

        sharedPreferences_teach =getSharedPreferences(SHARED_PREF_NAME_TEACH, Context.MODE_PRIVATE);
        instId=sharedPreferences_teach.getString(Key_INSTID_TEACH,null);
        usid=sharedPreferences_teach.getString(Key_USID_TEACH,null);
        usType=sharedPreferences_teach.getString(Key_USTYPE_TEACH,null);

        //getting data from TakeAttendenceAdapter cardview
        clid=getIntent().getExtras().getString("ClassId");
        sectionId=getIntent().getExtras().getString("sectionId");
        Log.d("cliddd",clid);
        yrId=getIntent().getExtras().getString("YearId");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        date = sdf.format(new Date());
        Log.d("dttt",date);

        userlist = (ArrayList<AttStdListModel>) getModel(false);
        adapter = new AttStdListAdapter(this,userlist);
        AttendenceShowStdList.rvstdlist.setAdapter(adapter);
        AttendenceShowStdList.rvstdlist.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

//        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
//        recyclerView.setHasFixedSize(true);

        getData();

        //toolbar
        setSupportActionBar(AttendenceShowStdList.toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        AttendenceShowStdList.submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                submitAttendence();

//                Intent intent = new Intent(AttendenceShowStdList.this,SubmitAttendenceActivity.class);
//                startActivity(intent);
            }
        });

    }
    private List<AttStdListModel> getModel(boolean isSelect){
        List<AttStdListModel> list = new ArrayList<>();
        for(int i = 0; i < list.size(); i++){

            AttStdListModel model = new AttStdListModel();
            model.setSelected(isSelect);
//            model.setStud_name(String.valueOf(list.get(i)));
            model.setAdmi_id(String.valueOf(list.get(i)));
            list.add(model);
        }
        return list;
    }

    private void getData() {
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        String url1="https://comzent.in/wonderschoolerp/apis/teacher/get_studteachers_att.php";

        StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onResponse(String response) {

                //  Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
                try {

                    JSONObject respObj = new JSONObject(response);

                    JSONArray jsonArray5=respObj.getJSONArray("studatt_details");

                    Log.d("std details",jsonArray5.toString());
                    for(int i=0;i<jsonArray5.length();i++){
                        JSONObject jsonObject=jsonArray5.getJSONObject(i);
                        String sr_id=jsonObject.optString("sr_id");
                        String admi_id=jsonObject.optString("admi_id");
                        String stud_name=jsonObject.optString("stud_name");
                        String stud_phone=jsonObject.optString("stud_phone");
                        String stud_email=jsonObject.optString("stud_email");
                        String attd_status=jsonObject.optString("attd_status");
                        String attd_reason=jsonObject.optString("attd_reason");

                        userlist.add(new AttStdListModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
                                attd_status,attd_reason));
                        Log.d("s", String.valueOf(userlist));
                        list.add(new AllStdListsrIdAdmIdModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
                                attd_status,attd_reason));

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapter=new AttStdListAdapter(getApplicationContext(),userlist);
                AttendenceShowStdList.rvstdlist.setAdapter(adapter);
                adapter.notifyDataSetChanged();

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {

                Map<String, String> params = new HashMap<String, String>();

                params.put("get_studattd","1");
                params.put("us_id",usid);
                params.put("inst_id",instId);
                params.put("class_id",clid);
                params.put("sec_id",sectionId);
                params.put("ay_id",yrId);
                params.put("stud_attend_date",date);

                return params;
            }
        };

        queue.add(request);
    }

    //submit attendence

    private void submitAttendence() {
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        String url1="https://comzent.in/wonderschoolerp/apis/teacher/take_studteacher_att.php";

        StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                //  Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
                try {

                    JSONObject respObj = new JSONObject(response);
                    String msg=respObj.getString("message");
                    Toast.makeText(AttendenceShowStdList.this, msg, Toast.LENGTH_LONG).show();
                    Log.d("response msg",msg);
                    if(msg.equals("Attendance Generated Successfully..!")){
                        finish();

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_LONG).show();
                Log.d("error msg", String.valueOf(error));

            }
        }) {
            @Override
            protected Map<String, String> getParams() {

                Map<String, String> params = new HashMap<String, String>();

                ArrayList<String> allstdsrid = new ArrayList<String>();

                for(int i=0; i < list.size(); i++) {

                    allstdsrid.add(String.valueOf(list.get(i).getSr_id()));

                }
                params.put("sr_id", String.valueOf(allstdsrid));
                Log.d("params", String.valueOf(params));

                Log.d("allstudentsrid", String.valueOf(allstdsrid));

                ArrayList<String> allstdadmid = new ArrayList<String>();
                for(int i=0; i < list.size(); i++) {

                        allstdadmid.add(list.get(i).getAdmi_id());
                        params.put("admission_id", String.valueOf(allstdadmid));
                }
                Log.d("allstudentsadmid", String.valueOf(allstdadmid));

                ///selected student list
                ArrayList<String> attstd = new ArrayList<String>();
                for (int i = 0; i < AttStdListAdapter.userlist.size(); i++) {
                    if (AttStdListAdapter.userlist.get(i).getSelected()) {
                        attstd.add(AttStdListAdapter.userlist.get(i).getAdmi_id());
                    }
                }

                params.put("student_attend_submit","1");
                params.put("class_id",clid);
                params.put("sec_id",sectionId);
                params.put("ay_id",yrId);
                params.put("att_status", String.valueOf(attstd));
                Log.d("params", String.valueOf(params));
                params.put("stud_attend_date",date);
                params.put("inst_id",instId);
                params.put("us_id",usid);
                params.put("us_type",usType);

                return params;
            }
        };

        queue.add(request);
    }

    //toolbar back to home
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        if(item.getItemId()==android.R.id.home){

            finish();
        }
        return super.onOptionsItemSelected(item);
    }

}
</code>```

After  submitting attendance, values of array of srid and admid retrive at server correctly ,problem is that only first record's srid and admid sets to '0' value.There is no problem when same Api is fetch on postman.

Body:
server data

android data

I am passing arraylist of srid of all element and post to server using volley request.enter image description here

here is the code

public class AttendenceShowStdList extends AppCompatActivity {

    ActivityAttendenceShowStdListBinding AttendenceShowStdList;

    ArrayList<AttStdListModel> userlist = new ArrayList<>();
    ArrayList<AllStdListsrIdAdmIdModel> list= new ArrayList<>();
    ArrayList<AllStdListModel> stdlist = new ArrayList<>();

    AttStdListAdapter adapter;
    private DatePickerDialog datePickerDialog;
    private String date,clid,sectionId,yrId,instId,usid,usType,attdate;

    SharedPreferences sharedPreferences_teach;//staff shareprefferece for profile fetch

    private static final String SHARED_PREF_NAME_TEACH="myprefteach";
    private static final String Key_USID_TEACH = "techusid";
    private static final String Key_INSTID_TEACH = "techinstid";
    private static final String Key_USTYPE_TEACH = "techustype";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AttendenceShowStdList= ActivityAttendenceShowStdListBinding.inflate(getLayoutInflater());
        setContentView(AttendenceShowStdList.getRoot());

        sharedPreferences_teach =getSharedPreferences(SHARED_PREF_NAME_TEACH, Context.MODE_PRIVATE);
        instId=sharedPreferences_teach.getString(Key_INSTID_TEACH,null);
        usid=sharedPreferences_teach.getString(Key_USID_TEACH,null);
        usType=sharedPreferences_teach.getString(Key_USTYPE_TEACH,null);

        //getting data from TakeAttendenceAdapter cardview
        clid=getIntent().getExtras().getString("ClassId");
        sectionId=getIntent().getExtras().getString("sectionId");
        Log.d("cliddd",clid);
        yrId=getIntent().getExtras().getString("YearId");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        date = sdf.format(new Date());
        Log.d("dttt",date);

        userlist = (ArrayList<AttStdListModel>) getModel(false);
        adapter = new AttStdListAdapter(this,userlist);
        AttendenceShowStdList.rvstdlist.setAdapter(adapter);
        AttendenceShowStdList.rvstdlist.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

//        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
//        recyclerView.setHasFixedSize(true);

        getData();

        //toolbar
        setSupportActionBar(AttendenceShowStdList.toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        AttendenceShowStdList.submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                submitAttendence();

//                Intent intent = new Intent(AttendenceShowStdList.this,SubmitAttendenceActivity.class);
//                startActivity(intent);
            }
        });

    }
    private List<AttStdListModel> getModel(boolean isSelect){
        List<AttStdListModel> list = new ArrayList<>();
        for(int i = 0; i < list.size(); i++){

            AttStdListModel model = new AttStdListModel();
            model.setSelected(isSelect);
//            model.setStud_name(String.valueOf(list.get(i)));
            model.setAdmi_id(String.valueOf(list.get(i)));
            list.add(model);
        }
        return list;
    }

    private void getData() {
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        String url1="https://comzent.in/wonderschoolerp/apis/teacher/get_studteachers_att.php";

        StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onResponse(String response) {

                //  Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
                try {

                    JSONObject respObj = new JSONObject(response);

                    JSONArray jsonArray5=respObj.getJSONArray("studatt_details");

                    Log.d("std details",jsonArray5.toString());
                    for(int i=0;i<jsonArray5.length();i++){
                        JSONObject jsonObject=jsonArray5.getJSONObject(i);
                        String sr_id=jsonObject.optString("sr_id");
                        String admi_id=jsonObject.optString("admi_id");
                        String stud_name=jsonObject.optString("stud_name");
                        String stud_phone=jsonObject.optString("stud_phone");
                        String stud_email=jsonObject.optString("stud_email");
                        String attd_status=jsonObject.optString("attd_status");
                        String attd_reason=jsonObject.optString("attd_reason");

                        userlist.add(new AttStdListModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
                                attd_status,attd_reason));
                        Log.d("s", String.valueOf(userlist));
                        list.add(new AllStdListsrIdAdmIdModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
                                attd_status,attd_reason));

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapter=new AttStdListAdapter(getApplicationContext(),userlist);
                AttendenceShowStdList.rvstdlist.setAdapter(adapter);
                adapter.notifyDataSetChanged();

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {

                Map<String, String> params = new HashMap<String, String>();

                params.put("get_studattd","1");
                params.put("us_id",usid);
                params.put("inst_id",instId);
                params.put("class_id",clid);
                params.put("sec_id",sectionId);
                params.put("ay_id",yrId);
                params.put("stud_attend_date",date);

                return params;
            }
        };

        queue.add(request);
    }

    //submit attendence

    private void submitAttendence() {
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        String url1="https://comzent.in/wonderschoolerp/apis/teacher/take_studteacher_att.php";

        StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                //  Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
                try {

                    JSONObject respObj = new JSONObject(response);
                    String msg=respObj.getString("message");
                    Toast.makeText(AttendenceShowStdList.this, msg, Toast.LENGTH_LONG).show();
                    Log.d("response msg",msg);
                    if(msg.equals("Attendance Generated Successfully..!")){
                        finish();

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_LONG).show();
                Log.d("error msg", String.valueOf(error));

            }
        }) {
            @Override
            protected Map<String, String> getParams() {

                Map<String, String> params = new HashMap<String, String>();

                ArrayList<String> allstdsrid = new ArrayList<String>();

                for(int i=0; i < list.size(); i++) {

                    allstdsrid.add(String.valueOf(list.get(i).getSr_id()));

                }
                params.put("sr_id", String.valueOf(allstdsrid));
                Log.d("params", String.valueOf(params));

                Log.d("allstudentsrid", String.valueOf(allstdsrid));

                ArrayList<String> allstdadmid = new ArrayList<String>();
                for(int i=0; i < list.size(); i++) {

                        allstdadmid.add(list.get(i).getAdmi_id());
                        params.put("admission_id", String.valueOf(allstdadmid));
                }
                Log.d("allstudentsadmid", String.valueOf(allstdadmid));

                ///selected student list
                ArrayList<String> attstd = new ArrayList<String>();
                for (int i = 0; i < AttStdListAdapter.userlist.size(); i++) {
                    if (AttStdListAdapter.userlist.get(i).getSelected()) {
                        attstd.add(AttStdListAdapter.userlist.get(i).getAdmi_id());
                    }
                }

                params.put("student_attend_submit","1");
                params.put("class_id",clid);
                params.put("sec_id",sectionId);
                params.put("ay_id",yrId);
                params.put("att_status", String.valueOf(attstd));
                Log.d("params", String.valueOf(params));
                params.put("stud_attend_date",date);
                params.put("inst_id",instId);
                params.put("us_id",usid);
                params.put("us_type",usType);

                return params;
            }
        };

        queue.add(request);
    }

    //toolbar back to home
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        if(item.getItemId()==android.R.id.home){

            finish();
        }
        return super.onOptionsItemSelected(item);
    }

}

After  submitting attendance, values of array of srid and admid retrive at server correctly ,problem is that only first record's srid and admid sets to '0' value.There is no problem when same Api is fetch on postman.


问:
How to get all the active users (currently logged in) in .NET Core Identity
I would like to show a table with user name, Email and current active status. Does Microsoft.AspNetCore.Identity.EntityFrameworkCore have such a function to check if a user is active or not?

Controller Code:

```<code>   [Authorize]
   public class UserController : Controller
   {
       private readonly UserManager<IdentityUser> _userManager;
       public UserController(UserManager<IdentityUser> userManager)
       {
           _userManager = userManager;
       }
       public IActionResult Index()
       {
           var users = _userManager.Users.ToList();
           return View(users);
       }
   }
</code>```

View Code:

```<code>        @foreach(var user in Model){
              <tr>
                  <td> @user.UserName </td>
                  <td> @user.Email </td>
                  <td> Currently I dont know </td>
              </tr>
         }
</code>```

Body:
I would like to show a table with user name, Email and current active status. Does Microsoft.AspNetCore.Identity.EntityFrameworkCore have such a function to check if a user is active or not?

Controller Code:

   [Authorize]
   public class UserController : Controller
   {
       private readonly UserManager<IdentityUser> _userManager;
       public UserController(UserManager<IdentityUser> userManager)
       {
           _userManager = userManager;
       }
       public IActionResult Index()
       {
           var users = _userManager.Users.ToList();
           return View(users);
       }
   }

View Code:

        @foreach(var user in Model){

                   @user.UserName
                   @user.Email
                   Currently I dont know

         }


问:
Feathersjs with tsconfig-path not working while running with ts-node-dev
```<code>  "scripts": {
    "dev": "ts-node-dev --no-notify -r tsconfig-paths/register src/index.ts",
  },
</code>```

Getting following error

```<code>[INFO] 12:12:54 ts-node-dev ver. 2.0.0 (using ts-node ver. 10.9.1, typescript ver. 4.9.4)
TypeError: Cannot read property 'getEnv' of undefined
    at Function.<anonymous> (/home/lap068/lectures/ln-sso/node_modules/@feathersjs/configuration/src/index.ts:44:29)
    at Function.configure (/home/lap068/lectures/ln-sso/node_modules/@feathersjs/feathers/lib/application.js:59:8)
    at Object.<anonymous> (/home/lap068/lectures/ln-sso/src/app.ts:25:5)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Module._compile (/home/lap068/lectures/ln-sso/node_modules/source-map-support/source-map-support.js:568:25)
    at Module.m._compile (/tmp/ts-node-dev-hook-9561096062855228.js:69:33)
    at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at require.extensions..jsx.require.extensions..js (/tmp/ts-node-dev-hook-9561096062855228.js:114:20)
    at require.extensions.<computed> (/tmp/ts-node-dev-hook-9561096062855228.js:71:20)
    at Object.nodeDevHook [as .ts] (/home/lap068/lectures/ln-sso/node_modules/ts-node-dev/lib/hook.js:63:13)
[ERROR] 12:13:10 TypeError: Cannot read property 'getEnv' of undefined
(node:326169) UnhandledPromiseRejectionWarning: Error: The client is closed
    at Commander._RedisClient_sendCommand (/home/lap068/lectures/ln-sso/node_modules/@redis/client/dist/lib/client/index.js:440:31)
    at Commander.SELECT (/home/lap068/lectures/ln-sso/node_modules/@redis/client/dist/lib/client/index.js:216:99)
    at Object.<anonymous> (/home/lap068/lectures/ln-sso/src/redis.ts:9:19)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Module._compile (/home/lap068/lectures/ln-sso/node_modules/source-map-support/source-map-support.js:568:25)
    at Module.m._compile (/tmp/ts-node-dev-hook-9561096062855228.js:69:33)
    at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at require.extensions..jsx.require.extensions..js (/tmp/ts-node-dev-hook-9561096062855228.js:114:20)
    at require.extensions.<computed> (/tmp/ts-node-dev-hook-9561096062855228.js:71:20)
    at Object.nodeDevHook [as .ts] (/home/lap068/lectures/ln-sso/node_modules/ts-node-dev/lib/hook.js:63:13)
</code>```

I have tried https://medium.com/@fmoessle/typescript-paths-with-ts-node-ts-node-dev-and-jest-671deacf6428

Body:
  "scripts": {
    "dev": "ts-node-dev --no-notify -r tsconfig-paths/register src/index.ts",
  },

Getting following error

[INFO] 12:12:54 ts-node-dev ver. 2.0.0 (using ts-node ver. 10.9.1, typescript ver. 4.9.4)
TypeError: Cannot read property 'getEnv' of undefined
    at Function.<anonymous> (/home/lap068/lectures/ln-sso/node_modules/@feathersjs/configuration/src/index.ts:44:29)
    at Function.configure (/home/lap068/lectures/ln-sso/node_modules/@feathersjs/feathers/lib/application.js:59:8)
    at Object.<anonymous> (/home/lap068/lectures/ln-sso/src/app.ts:25:5)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Module._compile (/home/lap068/lectures/ln-sso/node_modules/source-map-support/source-map-support.js:568:25)
    at Module.m._compile (/tmp/ts-node-dev-hook-9561096062855228.js:69:33)
    at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at require.extensions..jsx.require.extensions..js (/tmp/ts-node-dev-hook-9561096062855228.js:114:20)
    at require.extensions.<computed> (/tmp/ts-node-dev-hook-9561096062855228.js:71:20)
    at Object.nodeDevHook [as .ts] (/home/lap068/lectures/ln-sso/node_modules/ts-node-dev/lib/hook.js:63:13)
[ERROR] 12:13:10 TypeError: Cannot read property 'getEnv' of undefined
(node:326169) UnhandledPromiseRejectionWarning: Error: The client is closed
    at Commander._RedisClient_sendCommand (/home/lap068/lectures/ln-sso/node_modules/@redis/client/dist/lib/client/index.js:440:31)
    at Commander.SELECT (/home/lap068/lectures/ln-sso/node_modules/@redis/client/dist/lib/client/index.js:216:99)
    at Object.<anonymous> (/home/lap068/lectures/ln-sso/src/redis.ts:9:19)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Module._compile (/home/lap068/lectures/ln-sso/node_modules/source-map-support/source-map-support.js:568:25)
    at Module.m._compile (/tmp/ts-node-dev-hook-9561096062855228.js:69:33)
    at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at require.extensions..jsx.require.extensions..js (/tmp/ts-node-dev-hook-9561096062855228.js:114:20)
    at require.extensions.<computed> (/tmp/ts-node-dev-hook-9561096062855228.js:71:20)
    at Object.nodeDevHook [as .ts] (/home/lap068/lectures/ln-sso/node_modules/ts-node-dev/lib/hook.js:63:13)

I have tried https://medium.com/@fmoessle/typescript-paths-with-ts-node-ts-node-dev-and-jest-671deacf6428


问:
Calculate Daily/Monthly Energy consumption in SQL Server
I have a SQL Server table Energy_CC with two columns: time [int] (Epoch time) and E_CC14 [float]. Every 30 minutes, the total amount of my energy (kWh) is appended to the data table - something like this:

time
E_CC14

1670990400
5469.00223

1670992200
5469.02791

1670994000
5469.056295

1670995800
5469.082706

1670997600
5469.10558

1670999400
5469.128534

I tried this SQL statement:

```<code>SELECT
    MONTH(DATEADD(SS, i.time, '1970-01-01')),
    i.E_CC14 AS mwh,
    iprev.E_CC14 AS prevmwh,
    (i.E_CC14 - iprev.E_CC14) AS diff
FROM
    Energy_CC i
LEFT OUTER JOIN
    Energy_CC iprev ON MONTH(iprev.time) = MONTH(i.time) - MONTH(DATEADD(month, -1, i.time))
                    AND DAY(iprev.time) = 1
WHERE
    DAY(i.time) = 1
GROUP BY
    MONTH(i.time), i.E_CC14, iprev.E_CC14;
</code>```

I expect the result for monthly like this :

time
E_CC14

DECEMBER-22
10223

Any help would be greatly appreciated.

Body:
I have a SQL Server table Energy_CC with two columns: time [int] (Epoch time) and E_CC14 [float]. Every 30 minutes, the total amount of my energy (kWh) is appended to the data table - something like this:

time
E_CC14

1670990400
5469.00223

1670992200
5469.02791

1670994000
5469.056295

1670995800
5469.082706

1670997600
5469.10558

1670999400
5469.128534

I tried this SQL statement:

SELECT
    MONTH(DATEADD(SS, i.time, '1970-01-01')),
    i.E_CC14 AS mwh,
    iprev.E_CC14 AS prevmwh,
    (i.E_CC14 - iprev.E_CC14) AS diff
FROM
    Energy_CC i
LEFT OUTER JOIN
    Energy_CC iprev ON MONTH(iprev.time) = MONTH(i.time) - MONTH(DATEADD(month, -1, i.time))
                    AND DAY(iprev.time) = 1
WHERE
    DAY(i.time) = 1
GROUP BY
    MONTH(i.time), i.E_CC14, iprev.E_CC14;

I expect the result for monthly like this :

time
E_CC14

DECEMBER-22
10223

Any help would be greatly appreciated.


问:
Show a Smarty custom variable in plain text
I'm modifying the modal tpl to display a message that shows the difference that is left to have a free shipping.

I know how to display the message but I can't show the variable I've created in the text. And I've doubts that I'm creating well the variable.

I have to show the difference between the subtotal and 150 €

I've tried:

```<code><div class="col-md-7">
    <div class="cart-content pt-3">
        {if $cart.products_count > 1}
        <p class="cart-products-count">
        {l s='There are %products_count% items in your cart.' sprintf=['%products_count%' => $cart.products_count] d='Shop.Theme.Checkout'}
        </p>
        {else}
        <p class="cart-products-count">
            {l s='There is %product_count% item in your cart.' sprintf=['%product_count%' =>$cart.products_count] d='Shop.Theme.Checkout'}
        </p>
        {/if}
        <p>
            <strong>{l s='Total products:' d='Shop.Theme.Checkout'}</strong> {$cart.subtotals.products.value}
        </p>
        {hook h='displayCartAjaxInfo'}
        <div class="cart-content-btn">
            <a href="{$cart_url}" class="btn btn-primary btn-block btn-lg mb-2">{l s='Proceed to checkout' d='Shop.Theme.Actions'}</a>
            <button type="button" class="btn btn-secondary btn-block" data-dismiss="modal">{l s='Continue shopping' d='Shop.Theme.Actions'}</button>
        </div>
        <div class="remember-vip">
            <br>
            {assign var="diferencia" value=$cart.subtotals.products.value-150.00}
            Le faltan $diferencia para disponer de envío gratuito.
        </div>
    </div>
</div>
</code>```

This is how the code looks now:
Current result

Body:
I'm modifying the modal tpl to display a message that shows the difference that is left to have a free shipping.

I know how to display the message but I can't show the variable I've created in the text. And I've doubts that I'm creating well the variable.

I have to show the difference between the subtotal and 150 €

I've tried:

        {if $cart.products_count > 1}

        {l s='There are %products_count% items in your cart.' sprintf=['%products_count%' => $cart.products_count] d='Shop.Theme.Checkout'}

        {else}

            {l s='There is %product_count% item in your cart.' sprintf=['%product_count%' =>$cart.products_count] d='Shop.Theme.Checkout'}

        {/if}

            {l s='Total products:' d='Shop.Theme.Checkout'} {$cart.subtotals.products.value}

        {hook h='displayCartAjaxInfo'}

            {l s='Proceed to checkout' d='Shop.Theme.Actions'}
            <button type="button" class="btn btn-secondary btn-block" data-dismiss="modal">{l s='Continue shopping' d='Shop.Theme.Actions'}</button>

            {assign var="diferencia" value=$cart.subtotals.products.value-150.00}
            Le faltan $diferencia para disponer de envío gratuito.

This is how the code looks now:
Current result


问:
Got an "INTERNAL ERROR" with getTaskClient(application,siteKey) method on Android app
according to the docs,I create the instance of recaptchaTasksClient with given method getTaskClient(application,siteKey),but I got this exception message "INTERNAL_ERROR",I don't know where goes wrong ,there is no further details about this error.

So I wanna know how this happens.Is there a solution to solve this?


问:
Visual Studio high CPU usage
I've got problem with Visual Studio 2010 Ultimate edition. My cpu usage peaks top after search on entire solution or undoing pending changes and doesn't go down until I turn off VS. Does somebody have similar experience?</p>

ContentLicense: CC BY-SA 3.0

Title: Visual Studio high CPU usage


问:
Component is being re created everytime when called as a component instead of render prop
I have this component -

```<code>type Props = {
  count: number;
};

const NewComponent = ({ count }: Props) => {
  const renderCount = useRef(0);

  renderCount.current++;

  return <div>Render Count - {renderCount.current}</div>;
};

</code>```

I'm rendering it inside another component in 2 ways-

As render function

Directly as component

```<code>function App() {
  const [count, setCount] = useState(0);

  const Body = useCallback(() => <NewComponent count={count} />, [count]);

  const renderBody = useCallback(() => <NewComponent count={count} />, [count]);

  return (
    <div className="App">
      {renderBody()}
      <h1>Hello CodeSandbox</h1>
      <Body />
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={() => setCount((prevCount) => prevCount + 1)}>
        Count - {count}
      </button>
    </div>
  );
}
</code>```

Now, to see number of re-renders, when I click the button, render count of Body always remains as 1 behaving as if the component is re-created everytime instead of re-rendering. Why is this behaving like this?

Body:
I have this component -

type Props = {
  count: number;
};

const NewComponent = ({ count }: Props) => {
  const renderCount = useRef(0);

  renderCount.current++;

  return
Render Count - {renderCount.current}
;
};

I'm rendering it inside another component in 2 ways-

As render function

Directly as component

function App() {
  const [count, setCount] = useState(0);

  const Body = useCallback(() => <NewComponent count={count} />, [count]);

  const renderBody = useCallback(() => <NewComponent count={count} />, [count]);

  return (

      {renderBody()}

Hello CodeSandbox

Start editing to see some magic happen!

      <button onClick={() => setCount((prevCount) => prevCount + 1)}>
        Count - {count}
      </button>

  );
}

Now, to see number of re-renders, when I click the button, render count of Body always remains as 1 behaving as if the component is re-created everytime instead of re-rendering. Why is this behaving like this?


问:
Angular 15 components when trying to use OnInit:"Class is using Angular features but is not decorated. Please add an explicit Angular decorator"
I set up angular 15 and the components seem to have issues with using lifecycle hooks eg OnInit, giving 'Class is using angular features but is not decorated. Please add an explicit Angular decorator' error.

code sample
Component code:

```<code> import { Component, OnInit } from '@angular/core';

@Component({
 selector: 'app-nav',
 templateUrl: './nav.component.html',
 styleUrls: ['./nav.component.css']
 })
export  class NavComponent implements OnInit {

  ngOnInit(): void {
    throw new Error('Method not implemented.');
  }

 }
</code>```

packages:

```<code>  {
  "name": "new",
 "version": "0.0.0",
 "scripts": {
 "ng": "ng",
 "start": "ng serve",
 "build": "ng build",
 "watch": "ng build --watch --configuration development",
 "test": "ng test"
 },
 "private": true,
 "dependencies": {
 "@angular/animations": "^15.0.0",
 "@angular/common": "^15.0.0",
 "@angular/compiler": "^15.0.0",
 "@angular/core": "^15.0.3",
 "@angular/forms": "^15.0.0",
 "@angular/platform-browser": "^15.0.0",
 "@angular/platform-browser-dynamic": "^15.0.0",
 "@angular/router": "^15.0.0",
 "rxjs": "~7.5.0",
 "tslib": "^2.3.0",
 "zone.js": "~0.12.0"
  },
  "devDependencies": {
 "@angular-devkit/build-angular": "^15.0.0",
 "@angular/cli": "~15.0.0",
  "@angular/compiler-cli": "^15.0.0",
  "@types/jasmine": "~4.3.0",
  "jasmine-core": "~4.5.0",
  "karma": "~6.4.0",
  "karma-chrome-launcher": "~3.1.0",
  "karma-coverage": "~2.2.0",
  "karma-jasmine": "~5.1.0",
  "karma-jasmine-html-reporter": "~2.0.0",
  "typescript": "~4.8.2"
   }
 }
</code>```

I tried update and downgrading @angular/core and typescript
If I install typescript version less than 4.8 the error disappear but  ng serve need typescript version from 4.8.2 upwards to run

the error occurs after ngcc finished to run

Body:
I set up angular 15 and the components seem to have issues with using lifecycle hooks eg OnInit, giving 'Class is using angular features but is not decorated. Please add an explicit Angular decorator' error.

code sample
Component code:

 import { Component, OnInit } from '@angular/core';

@Component({
 selector: 'app-nav',
 templateUrl: './nav.component.html',
 styleUrls: ['./nav.component.css']
 })
export  class NavComponent implements OnInit {

  ngOnInit(): void {
    throw new Error('Method not implemented.');
  }

 }

packages:

  {
  "name": "new",
 "version": "0.0.0",
 "scripts": {
 "ng": "ng",
 "start": "ng serve",
 "build": "ng build",
 "watch": "ng build --watch --configuration development",
 "test": "ng test"
 },
 "private": true,
 "dependencies": {
 "@angular/animations": "^15.0.0",
 "@angular/common": "^15.0.0",
 "@angular/compiler": "^15.0.0",
 "@angular/core": "^15.0.3",
 "@angular/forms": "^15.0.0",
 "@angular/platform-browser": "^15.0.0",
 "@angular/platform-browser-dynamic": "^15.0.0",
 "@angular/router": "^15.0.0",
 "rxjs": "~7.5.0",
 "tslib": "^2.3.0",
 "zone.js": "~0.12.0"
  },
  "devDependencies": {
 "@angular-devkit/build-angular": "^15.0.0",
 "@angular/cli": "~15.0.0",
  "@angular/compiler-cli": "^15.0.0",
  "@types/jasmine": "~4.3.0",
  "jasmine-core": "~4.5.0",
  "karma": "~6.4.0",
  "karma-chrome-launcher": "~3.1.0",
  "karma-coverage": "~2.2.0",
  "karma-jasmine": "~5.1.0",
  "karma-jasmine-html-reporter": "~2.0.0",
  "typescript": "~4.8.2"
   }
 }

I tried update and downgrading @angular/core and typescript
If I install typescript version less than 4.8 the error disappear but  ng serve need typescript version from 4.8.2 upwards to run

the error occurs after ngcc finished to run


问:
how to make the parent element perfectly wrap the child element with respect of child border-radius?
im trying to make react js component called "GBorder" which provide gradient border for the child element but the problem is when the child have border radius something like 100px the GBorder will not have a border radius of 100px without knowing before hand that the child have 100px of border radius enter image description here as you see in this pic the aqua color circle is the child element with border radius the parent element which is the gray color don't perfectly wrap the child element, i want a solution without using javascript just css

i did tried multiple css border tricks and i did search on stackoverflow for solution with no luck


问:
How to I get img src in python?
I am attempting to get img src value with this code,
but can not find mistakes by myself.
Could anyone kindly check my codes and let me know the correct one?

I have thousands of url list which has to get img src

url list is xlsx, txt

```<code>from selenium import webdriver
from bs4 import BeautifulSoup
import openpyxl

driver=webdriver.Chrome("chromedriver")
req=driver.page_source

soup=BeautifulSoup(req, "html.parser")

thumbnails=soup.select_one("#container > div.content > div.dc_content > div > div:nth-child(2) > ul:nth-child(2) > li > div.item_con2 > table > tbody > tr > td > img")["src"]
print(thumbnails)

wb=openpyxl.load_workbook("150list.xlsx")
sheet=wb.active

i=1
while not sheet.cell(row=i,column=1).value is None:

driver.get(str(sheet.cell(row=i,column=1).value)
</code>```

Title: How to I get img src in python?

Body:
I am attempting to get img src value with this code,
but can not find mistakes by myself.
Could anyone kindly check my codes and let me know the correct one?

I have thousands of url list which has to get img src

url list is xlsx, txt

from selenium import webdriver
from bs4 import BeautifulSoup
import openpyxl

driver=webdriver.Chrome("chromedriver")
req=driver.page_source

soup=BeautifulSoup(req, "html.parser")

thumbnails=soup.select_one("#container > div.content > div.dc_content > div > div:nth-child(2) > ul:nth-child(2) > li > div.item_con2 > table > tbody > tr > td > img")["src"]
print(thumbnails)

wb=openpyxl.load_workbook("150list.xlsx")
sheet=wb.active

i=1
while not sheet.cell(row=i,column=1).value is None:

driver.get(str(sheet.cell(row=i,column=1).value)


问:
jenkins sidebar, how to make long text wrap?
our jobs in jenkins have long names, thus when they start to be built, the side bar will become too wide, and the main window can hardly be seen. Is there a neat solution to make the job names wrapped, so that the sidebar can be shrinked to a proper size?