问:
How to plot bar graph from a line graph?
I am working as an intern for data analysis. The experiment is to put 4 mice under observation for 3 days, and draw behavioural analysis. I am supposed to analyse the total distance travelled by 4 mice in 3 days, and plot a bar graph for it. I am working with a system called Live Mouse Tracker. The inventors of this system have given codes on GitHub for making plots. But they are all trajectory, line and scatter plots.

I have the following code which gives me a line graph for total distance travelled. I tried many things but I am unable to get a bar plot out of it. Please help me!

```<code>import sys
sys.path.insert(1, "../")

import sqlite3
from lmtanalysis.Animal import *
import matplotlib.pyplot as plt
from lmtanalysis.Event import *
from lmtanalysis.Measure import *
import lmtanalysis
from tkinter.filedialog import askopenfilename
from tabulate import tabulate
from collections import Counter
import collections
import xlsxwriter
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

import os
from lmtanalysis.FileUtil import getFilesToProcess
from lmtanalysis.Util import convert_to_d_h_m_s, getMinTMaxTAndFileNameInput

def frameToTimeTicker(x, pos):

  vals= convert_to_d_h_m_s( x )
  return "D{0} - {1:02d}:{2:02d}".format( int(vals[0])+1, int(vals[1]), int(vals[2]) )
print("Code launched.")
saveFile = "figTimeLineActivity"
 #Choose the files to process
files = getFilesToProcess()

tmin, tmax, text_file = getMinTMaxTAndFileNameInput()

for file in files:
   print(file)
   expName = os.path.basename(file)[:-7]
   print( expName )

   connection = sqlite3.connect( file )

   pool = AnimalPool( )
   pool.loadAnimals( connection )

   pool.loadDetection( start = tmin, end = tmax, lightLoad=True)

   #Load the timeline of the nest4 event over all individuals
   print( "Loading all nest4 for file " + file )
   nest4TimeLine = {}
   nest4TimeLine["all"] = EventTimeLine( connection, "Nest4", minFrame=tmin, maxFrame=tmax )

   #Load the timeline of the nest3 event over all individuals
   print( "Loading all nest3 for file " + file )
   nest3TimeLine = {}
   nest3TimeLine["all"] = EventTimeLine( connection, "Nest3", minFrame=tmin, maxFrame=tmax )

   print("loading night events for file " + file)
   nightTimeLine = EventTimeLine( connection, "night" , minFrame=tmin, maxFrame=tmax )

 ''' build the plot '''
   ymax=200
   ymin=-30
   fig, ax = plt.subplots( 1,1 , figsize=(16, 4 ) )
   ax = plt.gca() # get current axis
   ax.set_xlabel("time")
   ax.set_xlim([0, tmax])
   ax.set_ylim([ymin, ymax])

  #set x axis
   formatter = matplotlib.ticker.FuncFormatter( frameToTimeTicker )
   ax.xaxis.set_major_formatter(formatter)
   ax.tick_params(labelsize=6 )
   ax.xaxis.set_major_locator(ticker.MultipleLocator( 30 * 60 * 60 * 12 ))
   ax.xaxis.set_minor_locator(ticker.MultipleLocator( 30 * 60 * 60 ))

#draw the rectangles for the nights
   for nightEvent in nightTimeLine.getEventList():
       ax.axvspan( nightEvent.startFrame, nightEvent.endFrame, alpha=0.1, color='black')
       ax.text( nightEvent.startFrame+(nightEvent.endFrame-nightEvent.startFrame)/2 , 0.90*ymax , "dark phase" ,fontsize=6, ha='center')

 #plot the distance traveled per timeBin min time bin
   timeBin = 10
   dt = {}
   totalDistance = {}

   for animal in pool.animalDictionnary.keys():
       print ( pool.animalDictionnary[animal].RFID )
       dt[animal] = [x/100 for x in pool.animalDictionnary[animal].getDistancePerBin(binFrameSize = timeBin*oneMinute, maxFrame = tmax )]
       totalDistance[animal] = pool.animalDictionnary[animal].getDistance(tmin=tmin, tmax=tmax)

   nTimeBins = len(dt[1])
   print(nTimeBins)

   abs = [10*oneMinute]
   for t in range(1, nTimeBins):
       x = abs[t-1] + timeBin*oneMinute
       abs.append(x)

   #print(abs)
   print(len(abs))

   text_file.write( "{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( "file", "rfid", "genotype", "user1", "tmin", "tmax", "totalDistance" ) )

   for animal in pool.animalDictionnary.keys():
       #print(dt[animal])
       ax.plot( abs, dt[animal], color = getAnimalColor(animal), linewidth=0.6 )

    #prepare data to be written in a txt file, with tab separating columns
       line =""
       line+= str ( file )+ "\t"
       line+= str ( pool.animalDictionnary[animal].RFID )+ "\t"
       line+= str ( pool.animalDictionnary[animal].genotype )+ "\t"
       line+= str ( pool.animalDictionnary[animal].user1 )+ "\t"
       line+= str ( tmin )+ "\t"
       line+= str ( tmax )+ "\t"
       line+= str ( totalDistance[animal]/100 )+ "\t"

       for val in dt[animal]:
           line+= str( val )+ "\t"

       text_file.write( line )
       text_file.write( "\n" )

   text_file.close()

#Print the name and genotype of the animals on the graph, with the corresponding colors and the total distance traveled over the experiment
   legendHeight = 0.6*ymax
   for animal in pool.animalDictionnary.keys():
       print ( pool.animalDictionnary[animal].RFID )
       ax.text(30*60*60, legendHeight, "{} {} ({} m)".format(pool.animalDictionnary[animal].RFID[5:], pool.animalDictionnary[animal].genotype, round(totalDistance[animal]/100)), color=getAnimalColor(animal), fontsize=5 )
       legendHeight += 12

   yLabels=[]
   line = -20
   yTickList = []
   addThickness=0

   fig.suptitle("Activity time line {}".format( expName ))
   ax.spines['right'].set_visible(False)
   ax.spines['top'].set_visible(False)

#draw the nest4 time line
   yLabels.append("nest4")
   lineData = []

   for eventList in nest4TimeLine["all"].eventList:
       lineData.append( ( eventList.startFrame-addThickness , eventList.duration()+addThickness ))

   ax.broken_barh( lineData , ( line-4, 4 ), facecolors = "black" )
   yTickList.append(line)

   line+=10

#draw the nest3 time line
   yLabels.append("nest3")
   addThickness=0
   lineData = []

   for eventList in nest3TimeLine["all"].eventList:
       lineData.append( ( eventList.startFrame-addThickness , eventList.duration()+addThickness ))

   ax.broken_barh( lineData , ( line-4, 4 ), facecolors = "black" )
   yTickList.append(line)

   line+=10

#draw the y axis
   yLab=[0, 40, 80, 120, 160, 200]
   for i in yLab:
       yTickList.append(i)
       yLabels.append(i)

   ax.set_yticks( yTickList )
   ax.set_yticklabels( yLabels )

   plt.tight_layout()
   print ("Saving figure...")
   figureFileName = "FigActivityTimeLine_{}.pdf".format( expName )
   print( "Saving figure to ", figureFileName )
   fig.savefig( figureFileName ,dpi=100)
   plt.show()
   plt.close( fig )
</code>```
```<code></code>```

Body:
I am working as an intern for data analysis. The experiment is to put 4 mice under observation for 3 days, and draw behavioural analysis. I am supposed to analyse the total distance travelled by 4 mice in 3 days, and plot a bar graph for it. I am working with a system called Live Mouse Tracker. The inventors of this system have given codes on GitHub for making plots. But they are all trajectory, line and scatter plots.

I have the following code which gives me a line graph for total distance travelled. I tried many things but I am unable to get a bar plot out of it. Please help me!

import sys
sys.path.insert(1, "../")

import sqlite3
from lmtanalysis.Animal import *
import matplotlib.pyplot as plt
from lmtanalysis.Event import *
from lmtanalysis.Measure import *
import lmtanalysis
from tkinter.filedialog import askopenfilename
from tabulate import tabulate
from collections import Counter
import collections
import xlsxwriter
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

import os
from lmtanalysis.FileUtil import getFilesToProcess
from lmtanalysis.Util import convert_to_d_h_m_s, getMinTMaxTAndFileNameInput

def frameToTimeTicker(x, pos):

  vals= convert_to_d_h_m_s( x )
  return "D{0} - {1:02d}:{2:02d}".format( int(vals[0])+1, int(vals[1]), int(vals[2]) )
print("Code launched.")
saveFile = "figTimeLineActivity"
 #Choose the files to process
files = getFilesToProcess()

tmin, tmax, text_file = getMinTMaxTAndFileNameInput()

for file in files:
   print(file)
   expName = os.path.basename(file)[:-7]
   print( expName )

   connection = sqlite3.connect( file )

   pool = AnimalPool( )
   pool.loadAnimals( connection )

   pool.loadDetection( start = tmin, end = tmax, lightLoad=True)

   #Load the timeline of the nest4 event over all individuals
   print( "Loading all nest4 for file " + file )
   nest4TimeLine = {}
   nest4TimeLine["all"] = EventTimeLine( connection, "Nest4", minFrame=tmin, maxFrame=tmax )

   #Load the timeline of the nest3 event over all individuals
   print( "Loading all nest3 for file " + file )
   nest3TimeLine = {}
   nest3TimeLine["all"] = EventTimeLine( connection, "Nest3", minFrame=tmin, maxFrame=tmax )

   print("loading night events for file " + file)
   nightTimeLine = EventTimeLine( connection, "night" , minFrame=tmin, maxFrame=tmax )

 ''' build the plot '''
   ymax=200
   ymin=-30
   fig, ax = plt.subplots( 1,1 , figsize=(16, 4 ) )
   ax = plt.gca() # get current axis
   ax.set_xlabel("time")
   ax.set_xlim([0, tmax])
   ax.set_ylim([ymin, ymax])

  #set x axis
   formatter = matplotlib.ticker.FuncFormatter( frameToTimeTicker )
   ax.xaxis.set_major_formatter(formatter)
   ax.tick_params(labelsize=6 )
   ax.xaxis.set_major_locator(ticker.MultipleLocator( 30 * 60 * 60 * 12 ))
   ax.xaxis.set_minor_locator(ticker.MultipleLocator( 30 * 60 * 60 ))

#draw the rectangles for the nights
   for nightEvent in nightTimeLine.getEventList():
       ax.axvspan( nightEvent.startFrame, nightEvent.endFrame, alpha=0.1, color='black')
       ax.text( nightEvent.startFrame+(nightEvent.endFrame-nightEvent.startFrame)/2 , 0.90*ymax , "dark phase" ,fontsize=6, ha='center')

 #plot the distance traveled per timeBin min time bin
   timeBin = 10
   dt = {}
   totalDistance = {}

   for animal in pool.animalDictionnary.keys():
       print ( pool.animalDictionnary[animal].RFID )
       dt[animal] = [x/100 for x in pool.animalDictionnary[animal].getDistancePerBin(binFrameSize = timeBin*oneMinute, maxFrame = tmax )]
       totalDistance[animal] = pool.animalDictionnary[animal].getDistance(tmin=tmin, tmax=tmax)

   nTimeBins = len(dt[1])
   print(nTimeBins)

   abs = [10*oneMinute]
   for t in range(1, nTimeBins):
       x = abs[t-1] + timeBin*oneMinute
       abs.append(x)

   #print(abs)
   print(len(abs))

   text_file.write( "{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( "file", "rfid", "genotype", "user1", "tmin", "tmax", "totalDistance" ) )

   for animal in pool.animalDictionnary.keys():
       #print(dt[animal])
       ax.plot( abs, dt[animal], color = getAnimalColor(animal), linewidth=0.6 )

    #prepare data to be written in a txt file, with tab separating columns
       line =""
       line+= str ( file )+ "\t"
       line+= str ( pool.animalDictionnary[animal].RFID )+ "\t"
       line+= str ( pool.animalDictionnary[animal].genotype )+ "\t"
       line+= str ( pool.animalDictionnary[animal].user1 )+ "\t"
       line+= str ( tmin )+ "\t"
       line+= str ( tmax )+ "\t"
       line+= str ( totalDistance[animal]/100 )+ "\t"

       for val in dt[animal]:
           line+= str( val )+ "\t"

       text_file.write( line )
       text_file.write( "\n" )

   text_file.close()

#Print the name and genotype of the animals on the graph, with the corresponding colors and the total distance traveled over the experiment
   legendHeight = 0.6*ymax
   for animal in pool.animalDictionnary.keys():
       print ( pool.animalDictionnary[animal].RFID )
       ax.text(30*60*60, legendHeight, "{} {} ({} m)".format(pool.animalDictionnary[animal].RFID[5:], pool.animalDictionnary[animal].genotype, round(totalDistance[animal]/100)), color=getAnimalColor(animal), fontsize=5 )
       legendHeight += 12

   yLabels=[]
   line = -20
   yTickList = []
   addThickness=0

   fig.suptitle("Activity time line {}".format( expName ))
   ax.spines['right'].set_visible(False)
   ax.spines['top'].set_visible(False)

#draw the nest4 time line
   yLabels.append("nest4")
   lineData = []

   for eventList in nest4TimeLine["all"].eventList:
       lineData.append( ( eventList.startFrame-addThickness , eventList.duration()+addThickness ))

   ax.broken_barh( lineData , ( line-4, 4 ), facecolors = "black" )
   yTickList.append(line)

   line+=10

#draw the nest3 time line
   yLabels.append("nest3")
   addThickness=0
   lineData = []

   for eventList in nest3TimeLine["all"].eventList:
       lineData.append( ( eventList.startFrame-addThickness , eventList.duration()+addThickness ))

   ax.broken_barh( lineData , ( line-4, 4 ), facecolors = "black" )
   yTickList.append(line)

   line+=10

#draw the y axis
   yLab=[0, 40, 80, 120, 160, 200]
   for i in yLab:
       yTickList.append(i)
       yLabels.append(i)

   ax.set_yticks( yTickList )
   ax.set_yticklabels( yLabels )

   plt.tight_layout()
   print ("Saving figure...")
   figureFileName = "FigActivityTimeLine_{}.pdf".format( expName )
   print( "Saving figure to ", figureFileName )
   fig.savefig( figureFileName ,dpi=100)
   plt.show()
   plt.close( fig )


来源: stackexchange

问:
EventWaitHandle access denied .NET Standard 2.0
I am using a global EventWaitHandle to implement an inter-process handshake for a named pipe. The server (running as service with admin priviliges) opens the EventWaitHandle while the client checks for the open handle before connecting to the named pipe.

Using both with the same priviliges, its fine. Running the server as admin and client normal results in:
System.UnauthorizedAccessException: Access to the path 'Global\DEMO_CONNECTION_OPEN_HANDLE' is denied.

I am using .NET Standard 2.0. Hence, simple solutions such as EventHandleRights are not available. Is there any way to set access rights (e.g. while creating the handle) or elevate the client code for the EventWaitHandle only?

Example code server:

```<code>var handshakeHandle = new EventWaitHandle(false, EventResetMode.ManualReset,
    String.Format(@"Global\{0}", $"{ConnectionName.ToUpper()}_CONNECTION_OPEN_HANDLE"));

CreateServerPipe(ConnectionName);

handshakeHandle.Set();
await serverStream.WaitForConnectionAsync();
handshakeHandle.Reset();

</code>```

Example code client:

```<code>// Results in Exception:
var handshakeHandle = EventWaitHandle.OpenExisting(
    String.Format(@"Global\{0}", $"{ConnectionName.ToUpper()}_CONNECTION_OPEN_HANDLE"));

CreateClientPipe(ConnectionName);

if (!handshakeHandle.WaitOne(millisecondsTimeout))
    throw new TimeoutException($"Cannot access within timeout.");

clientStream.Connect(millisecondsTimeout);
</code>```

Any hint is much appreciated!

Edit: Any recommendation for a different approach than EventWaitHandle to implement an inter-process handshake is welcome.

ContentLicense: CC BY-SA 4.0

Body:
I am using a global EventWaitHandle to implement an inter-process handshake for a named pipe. The server (running as service with admin priviliges) opens the EventWaitHandle while the client checks for the open handle before connecting to the named pipe.

Using both with the same priviliges, its fine. Running the server as admin and client normal results in:
System.UnauthorizedAccessException: Access to the path 'Global\DEMO_CONNECTION_OPEN_HANDLE' is denied.

I am using .NET Standard 2.0. Hence, simple solutions such as EventHandleRights are not available. Is there any way to set access rights (e.g. while creating the handle) or elevate the client code for the EventWaitHandle only?

Example code server:

var handshakeHandle = new EventWaitHandle(false, EventResetMode.ManualReset,
    String.Format(@"Global\{0}", $"{ConnectionName.ToUpper()}_CONNECTION_OPEN_HANDLE"));

CreateServerPipe(ConnectionName);

handshakeHandle.Set();
await serverStream.WaitForConnectionAsync();
handshakeHandle.Reset();

Example code client:

// Results in Exception:
var handshakeHandle = EventWaitHandle.OpenExisting(
    String.Format(@"Global\{0}", $"{ConnectionName.ToUpper()}_CONNECTION_OPEN_HANDLE"));

CreateClientPipe(ConnectionName);

if (!handshakeHandle.WaitOne(millisecondsTimeout))
    throw new TimeoutException($"Cannot access within timeout.");

clientStream.Connect(millisecondsTimeout);

Any hint is much appreciated!

Edit: Any recommendation for a different approach than EventWaitHandle to implement an inter-process handshake is welcome.


问:
Mocked function is called twice, should be called once
I'm testing a functional component. In one scenario a mocked function is called twice, does anyone know why? When I comment the useEffect hooks it works fine and gets called once, but there is no code related to that on the useEffect.

Here is my test:

```<code>   it('sends correct payload when user deletes a comment', async () => {
      const spy = jest.spyOn(CommentsService, 'deleteComment').mockImplementation(mockDeleteComment);
      const { container } = render(
        withProvider(queryClient, <GeneralParametersSections {...generalParametersProps} />),
      );
      const commentsSection = container.querySelector('.comments-section')!;
      const comments = commentsSection.querySelectorAll('.comment-item');
      expect(comments).toHaveLength(1);
      expect(comments[0].textContent).toContain(commentsMock[0].content);

      const firstCommentDeleteButton = comments[0].querySelector('.comment-item-actions .fa-trash')!;

      await fireEvent.click(firstCommentDeleteButton);

      expect(mockDeleteComment).toHaveBeenCalledTimes(1);
      expect(mockDeleteComment).toHaveBeenCalledWith('/general_parameters_page_comments');

      spy.mockRestore();
    });

</code>```

I've received 2 in expect(mockDeleteComment).toHaveBeenCalledTimes(1);

Body:
I'm testing a functional component. In one scenario a mocked function is called twice, does anyone know why? When I comment the useEffect hooks it works fine and gets called once, but there is no code related to that on the useEffect.

Here is my test:

   it('sends correct payload when user deletes a comment', async () => {
      const spy = jest.spyOn(CommentsService, 'deleteComment').mockImplementation(mockDeleteComment);
      const { container } = render(
        withProvider(queryClient, <GeneralParametersSections {...generalParametersProps} />),
      );
      const commentsSection = container.querySelector('.comments-section')!;
      const comments = commentsSection.querySelectorAll('.comment-item');
      expect(comments).toHaveLength(1);
      expect(comments[0].textContent).toContain(commentsMock[0].content);

      const firstCommentDeleteButton = comments[0].querySelector('.comment-item-actions .fa-trash')!;

      await fireEvent.click(firstCommentDeleteButton);

      expect(mockDeleteComment).toHaveBeenCalledTimes(1);
      expect(mockDeleteComment).toHaveBeenCalledWith('/general_parameters_page_comments');

      spy.mockRestore();
    });

I've received 2 in expect(mockDeleteComment).toHaveBeenCalledTimes(1);


问:
How to stop column auto jumping text on size change
The problem is simple.
I generate a bunch of inline-block DIV things with a fixed with of 345px.
They are all in another DIV that has column-width:345px; so that resizing will generate whatever number of columns fits on the screen and the elements all list down the columns nicely.

The problem is, on mouse over each of these elements expands increasing in height (new contend is added below it).
So, when you get to the bottom of the column block, you have the issue of the bottom line expanding and then jumping to the top of the next column where it can’t be seen.

All searches seem to just land me on a page about break-inside, but that just stops the element from splitting between 2 columns. The issue I have is its jumping to the next.
It’s obvious why but how can we get around this in css? Iv not found any option that lets you list content in a column format top to bottom, top to bottom, only left to right.

Example:

line 1

line 2

<div...

```


问:
How to reuse existing module global installations in virtual environments using pipenv?
Recently I have been struggling with storage issues. I discovered that virtual environments are part of the problem.

I have to pipenv install --dev ipython for each virtual environment, and often also pipenv install many big libraries. I was trying to understand if I could keep in the environment a version of one module installed globally that can be reused in many virtual environments.

The aim would be to have the module in the pipfile but use the module installed globally, and install it only if the module installed globally differs from the module listed in the pipfile.


问:
How to tokenize German words using tf.keras.preprocessing.text.Tokenizer
Suppse we have a deutsch sentence like this: "Ich hab gewonnen!". How can we tokenize the sentence to unique words as we do in english sentences with text.Tokenizer? I mustn't use other libraries like Spacy. Can anyone give ideas? I'm looking for something, like an arguement for Tokenizer.</p>


问:
Cannot resolve symbol 'OAuth2AuthenticationToken'
My Configure java file GoogleOAuth2SuccessHandler:

```<code>package ru.connor.shopping_app.config;

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import ru.connor.shopping_app.repository.RoleRepository;
import ru.connor.shopping_app.repository.UserRepository;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@RequiredArgsConstructor
public class GoogleOAuth2SuccessHandler implements AuthenticationSuccessHandler {
    private final RoleRepository roleRepository;
    private final UserRepository userRepository;

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) authentication;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {

    }

}
</code>```

I added the following dependencies:

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-oauth2-client</artifactId>
    <version>5.7.3</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    <version>2.7.5</version>
</dependency>
</code>```

But for some reason, the compiler gives the following error:
Cannot resolve symbol 'OAuth2AuthenticationToken'

I don't understand what the problem is.

Body:
My Configure java file GoogleOAuth2SuccessHandler:

package ru.connor.shopping_app.config;

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import ru.connor.shopping_app.repository.RoleRepository;
import ru.connor.shopping_app.repository.UserRepository;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@RequiredArgsConstructor
public class GoogleOAuth2SuccessHandler implements AuthenticationSuccessHandler {
    private final RoleRepository roleRepository;
    private final UserRepository userRepository;

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) authentication;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {

    }

}

I added the following dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-oauth2-client</artifactId>
    <version>5.7.3</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    <version>2.7.5</version>
</dependency>

But for some reason, the compiler gives the following error:
Cannot resolve symbol 'OAuth2AuthenticationToken'

I don't understand what the problem is.


问:
How to send API post request for download pdf using url in react?
I have user data in a table and wanted to make a post request to a specific url to download in PDF format. Basically, it should return me an ID and with that, I can send get request which generates a pdf document. Here is what I am trying to do:

```<code>const handleSubmit = async (e) => {
    e.preventDefault();
    axios({
      method: 'post',
      url: `${API_PATH}pdf/generate`,
      data: service
    })
    .then((res) => console.log("response",res))
    .catch((err) => console.log(["APIGet error:", err]));
  };

</code>```

service is a data with array of objects. For now response is 400 bad request not sure where I am doing wrong at. Please help!

Body:
I have user data in a table and wanted to make a post request to a specific url to download in PDF format. Basically, it should return me an ID and with that, I can send get request which generates a pdf document. Here is what I am trying to do:

const handleSubmit = async (e) => {
    e.preventDefault();
    axios({
      method: 'post',
      url: `${API_PATH}pdf/generate`,
      data: service
    })
    .then((res) => console.log("response",res))
    .catch((err) => console.log(["APIGet error:", err]));
  };

service is a data with array of objects. For now response is 400 bad request not sure where I am doing wrong at. Please help!


问:
Want to read a .pfx file and want to write on multiple pages of pdf file able to write it only one page
Want to read a .pfx file and want to write on multiple pages of pdf file able to write it only one page.
I am sharing my code below i have itext library reading and detaching the .pfx in the pdf.
The Output what I get is it writing the digital signature in the first page of the document, but my requirement is to write it on all pdf pages.From My analysis the The sign is dispatched after calling

```<code>MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, MakeSignature.CryptoStandard.CMS);
</code>```

Exception in thread "main" com.itextpdf.text.DocumentException: com.itextpdf.text.DocumentException: Document already pre closed.

it is the exception what I am getting while looping the pages.

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package digitalsigning;

/**
 *
 * @author srivardhan.vasudevan
 */
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.Enumeration;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.layout.Document;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.ExternalSignature;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.itextpdf.text.pdf.security.PrivateKeySignature;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Digitalsigning{
public static void main(String[] args) throws FileNotFoundException, GeneralSecurityException, IOException, DocumentException {
    KeyStore ks;
    PrivateKey pk = null;
    Certificate[] chain=null;
        String signedFileName = "D:/PDF/new.pdfSigned.pdf";
    String inputPdfName = "D:/PDF/nameddestinations.pdf";
       File newfile = new File(inputPdfName);

    PdfReader reader = null;
    PdfStamper stamper = null;
    try {
        if(true){
         java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
         String digiPCred = "llmsprod"; // PDF password
         ks = KeyStore.getInstance("pkcs12");
         byte[] array = Files.readAllBytes(Paths.get("D:\\Pfxname\\llmsprod.pfx"));

             InputStream is = new ByteArrayInputStream(array);
             ks.load(is, digiPCred.toCharArray());
     //      ks.load(new FileInputStream("D:\\Pfxname"), digiPCred.toCharArray());

         String alias = "abbb";
         Enumeration<String> aliases = ks.aliases();
         while (aliases.hasMoreElements()) {
             alias = aliases.nextElement();
             pk = (PrivateKey) ks.getKey(alias, digiPCred.toCharArray());
                if (pk != null) {
                    break;
                    }
            }
             chain = ks.getCertificateChain(alias);
        }
                    reader = new PdfReader(inputPdfName);
            try {
            OutputStream os = new FileOutputStream(signedFileName);
            stamper = PdfStamper.createSignature(reader, os, '\0', null, false);

        }
          catch(Exception e){
              e.printStackTrace();
          }
            PdfSignatureAppearance appearance = null;
            try {
                if (stamper != null) {
                    appearance = stamper.getSignatureAppearance();
                }
            } catch (NullPointerException ex) {
                ex.printStackTrace();
            }
          int top = 100;
          int pages = reader.getNumberOfPages();

          for (int i = 1; i <= pages; i++) {

            appearance.setVisibleSignature(new com.itextpdf.text.Rectangle(0, 1, 300, 109), 1, "sig");

        String algorithm = "SHA384";
        /*switch (4) {
        case 1:
            algorithm = "RIPEMD160";
            break;
        case 2:
            algorithm = "SHA1";
            break;
        case 3:
            algorithm = "SHA256";
            break;
        case 4:
            algorithm = "SHA384";
            break;
        case 5:
            algorithm = "SHA512";
            break;

        }*/

ExternalDigest digest = new BouncyCastleDigest();
ExternalSignature es = new PrivateKeySignature(pk, algorithm, "BC");
MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, MakeSignature.CryptoStandard.CMS);

        }

        }catch (GeneralSecurityException ex) {
         //OMSLayoutLogger.printErr(ex.toString(), ex);
            throw new GeneralSecurityException(ex);
        } catch (IOException ex) {
        if (ex.toString().contains("BadPaddingException")) {
        //OMSLayoutLogger.printErr("*****************************Password incorrect***************************", ex);
        } else if (ex.toString().contains("FileNotFoundException")) {
        //OMSLayoutLogger.printErr("*******************.PFX file or PDF not found**************************", ex);
        } else {
        //OMSLayoutLogger.printErr(ex.toString()+"Digital Signature Exception", ex);
        }
            throw new IOException(ex);
    } catch (DocumentException ex) {
        //OMSLayoutLogger.printErr(ex.toString()+"Digital Signature Exception", ex);
            throw new DocumentException(ex);
        }
    finally{
        if(reader != null) {
            reader.close();
        }
    try {
    }catch (Exception e) {
        throw e;
    }
    }
    }
}
</code>```

Body:
Want to read a .pfx file and want to write on multiple pages of pdf file able to write it only one page.
I am sharing my code below i have itext library reading and detaching the .pfx in the pdf.
The Output what I get is it writing the digital signature in the first page of the document, but my requirement is to write it on all pdf pages.From My analysis the The sign is dispatched after calling

MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, MakeSignature.CryptoStandard.CMS);

Exception in thread "main" com.itextpdf.text.DocumentException: com.itextpdf.text.DocumentException: Document already pre closed.

it is the exception what I am getting while looping the pages.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package digitalsigning;

/**
 *
 * @author srivardhan.vasudevan
 */
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.Enumeration;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.layout.Document;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.ExternalSignature;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.itextpdf.text.pdf.security.PrivateKeySignature;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Digitalsigning{
public static void main(String[] args) throws FileNotFoundException, GeneralSecurityException, IOException, DocumentException {
    KeyStore ks;
    PrivateKey pk = null;
    Certificate[] chain=null;
        String signedFileName = "D:/PDF/new.pdfSigned.pdf";
    String inputPdfName = "D:/PDF/nameddestinations.pdf";
       File newfile = new File(inputPdfName);

    PdfReader reader = null;
    PdfStamper stamper = null;
    try {
        if(true){
         java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
         String digiPCred = "llmsprod"; // PDF password
         ks = KeyStore.getInstance("pkcs12");
         byte[] array = Files.readAllBytes(Paths.get("D:\\Pfxname\\llmsprod.pfx"));

             InputStream is = new ByteArrayInputStream(array);
             ks.load(is, digiPCred.toCharArray());
     //      ks.load(new FileInputStream("D:\\Pfxname"), digiPCred.toCharArray());

         String alias = "abbb";
         Enumeration<String> aliases = ks.aliases();
         while (aliases.hasMoreElements()) {
             alias = aliases.nextElement();
             pk = (PrivateKey) ks.getKey(alias, digiPCred.toCharArray());
                if (pk != null) {
                    break;
                    }
            }
             chain = ks.getCertificateChain(alias);
        }
                    reader = new PdfReader(inputPdfName);
            try {
            OutputStream os = new FileOutputStream(signedFileName);
            stamper = PdfStamper.createSignature(reader, os, '\0', null, false);

        }
          catch(Exception e){
              e.printStackTrace();
          }
            PdfSignatureAppearance appearance = null;
            try {
                if (stamper != null) {
                    appearance = stamper.getSignatureAppearance();
                }
            } catch (NullPointerException ex) {
                ex.printStackTrace();
            }
          int top = 100;
          int pages = reader.getNumberOfPages();

          for (int i = 1; i <= pages; i++) {

            appearance.setVisibleSignature(new com.itextpdf.text.Rectangle(0, 1, 300, 109), 1, "sig");

        String algorithm = "SHA384";
        /*switch (4) {
        case 1:
            algorithm = "RIPEMD160";
            break;
        case 2:
            algorithm = "SHA1";
            break;
        case 3:
            algorithm = "SHA256";
            break;
        case 4:
            algorithm = "SHA384";
            break;
        case 5:
            algorithm = "SHA512";
            break;

        }*/

ExternalDigest digest = new BouncyCastleDigest();
ExternalSignature es = new PrivateKeySignature(pk, algorithm, "BC");
MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, MakeSignature.CryptoStandard.CMS);

        }

        }catch (GeneralSecurityException ex) {
         //OMSLayoutLogger.printErr(ex.toString(), ex);
            throw new GeneralSecurityException(ex);
        } catch (IOException ex) {
        if (ex.toString().contains("BadPaddingException")) {
        //OMSLayoutLogger.printErr("*****************************Password incorrect***************************", ex);
        } else if (ex.toString().contains("FileNotFoundException")) {
        //OMSLayoutLogger.printErr("*******************.PFX file or PDF not found**************************", ex);
        } else {
        //OMSLayoutLogger.printErr(ex.toString()+"Digital Signature Exception", ex);
        }
            throw new IOException(ex);
    } catch (DocumentException ex) {
        //OMSLayoutLogger.printErr(ex.toString()+"Digital Signature Exception", ex);
            throw new DocumentException(ex);
        }
    finally{
        if(reader != null) {
            reader.close();
        }
    try {
    }catch (Exception e) {
        throw e;
    }
    }
    }
}


问:
Is is possible to record voice from the microphone in Decentraland?
I am trying to catch the voice from micrpphone in Decentraland  but not able to do it but I am able to convert any mp3 to text.
If Some has work on decentraland  for capturing the voice from microphone.

1.Is is possible to record voice from the microphone in Decentraland ?
2. Is there some alternative way to achieve this like using a nodejs library that integrates with the Decentraland SDK ?

I am expecting to resolve this above issue


问:
Getting error about PyQt5 when using Virtual Environment on Ubuntu
I'm building a project with PyQt5 and I've changed my operating system Windows to Ubuntu. On Windows, everything was going perfect with virtual environments but since i changed my OS and tried to launch my first qt app, i'm getting the error down below.

Additionally, it works clearly without Virtual Env.

First of all, I've created my virtual environment with python3-venv module.
Then, i activated the environment and install PyQt5 with pip.

Then I just tried run the project.

python3 main.py

Output:

`qt.qpa.plugin: Could not find the Qt platform plugin "xcb" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Canceled (core dumped)`


问:
Laravel 8 signature pad won't appear in hostinger
Help me pls;< Can someone tell me why the signature pad only appears in localhost and not when deployed online i'm using hostinger.  https://www.itsolutionstuff.com/post/laravel-signature-pad-example-tutorialexample.html i'm using the code from here.

or someone master at laravel can recommend me what to use in laravel 8, i am needing signature pad and if submitted in form turn into image. someone have idea? :<

here is the code:

```<code><head>
    <title>Laravel Signature Pad Tutorial Example - ItSolutionStuff.com </title>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css">

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/south-street/jquery-ui.css" rel="stylesheet">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script type="text/javascript" src="http://keith-wood.name/js/jquery.signature.js"></script>

    <link rel="stylesheet" type="text/css" href="http://keith-wood.name/css/jquery.signature.css">

    <style>
        .kbw-signature { width: 100%; height: 200px;}
        #sig canvas{
            width: 100% !important;
            height: auto;
        }
    </style>

</head>
<body class="bg-dark">
<div class="container">
   <div class="row">
       <div class="col-md-6 offset-md-3 mt-5">
           <div class="card">
               <div class="card-header">
                   <h5>Laravel Signature Pad Tutorial Example - ItSolutionStuff.com </h5>
               </div>
               <div class="card-body">
                    @if ($message = Session::get('success'))
                        <div class="alert alert-success  alert-dismissible">
                            <button type="button" class="close" data-dismiss="alert">×</button>
                            <strong>{{ $message }}</strong>
                        </div>
                    @endif
                    <form method="POST" action="{{ route('signaturepad.upload') }}">
                        @csrf
                        <div class="col-md-12">
                            <label class="" for="">Signature:</label>
                            <br/>
                            <div id="sig" ></div>
                            <br/>
                            <button id="clear" class="btn btn-danger btn-sm">Clear Signature</button>
                            <textarea id="signature64" name="signed" style="display: none"></textarea>
                        </div>
                        <br/>
                        <button class="btn btn-success">Save</button>
                    </form>
               </div>
           </div>
       </div>
   </div>
</div>
<script type="text/javascript">
    var sig = $('#sig').signature({syncField: '#signature64', syncFormat: 'PNG'});
    $('#clear').click(function(e) {
        e.preventDefault();
        sig.signature('clear');
        $("#signature64").val('');
    });
</script>
</body>
</html>```
```

Body:
Help me pls;< Can someone tell me why the signature pad only appears in localhost and not when deployed online i'm using hostinger.  https://www.itsolutionstuff.com/post/laravel-signature-pad-example-tutorialexample.html i'm using the code from here.

or someone master at laravel can recommend me what to use in laravel 8, i am needing signature pad and if submitted in form turn into image. someone have idea? :<

here is the code:

    <title>Laravel Signature Pad Tutorial Example - ItSolutionStuff.com </title>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css">

    <link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/south-street/jquery-ui.css" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="http://keith-wood.name/css/jquery.signature.css">

Laravel Signature Pad Tutorial Example - ItSolutionStuff.com

                    @if ($message = Session::get('success'))

                            <button type="button" class="close" data-dismiss="alert">×</button>
                            {{ $message }}

                    @endif
                    <form method="POST" action="{{ route('signaturepad.upload') }}">
                        @csrf

                            Signature:

                            <button id="clear" class="btn btn-danger btn-sm">Clear Signature</button>
                            <textarea id="signature64" name="signed" style="display: none"></textarea>

                        <button class="btn btn-success">Save</button>
                    </form>

```


问:
selenium-standalone-chrome throws error when driver is trying to connect
My goal is to run Selenium in a docker. The problem is that it refused to connect although selenium-standalone-chrome works fine and I can hit http://127.0.0.1:4444 in my own browser.

The culrpit:

```<code>chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--disable-notifications")
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Remote(
    command_executor='http://127.0.0.1:4444/wd/hub',
    options=chrome_options
)
</code>```

The error

```<code>Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/bin/flask", line 8, in <module>
    sys.exit(main())
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/cli.py", line 1047, in main
    cli.main()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 1055, in main
    rv = self.invoke(ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 1657, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 760, in invoke
    return __callback(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/decorators.py", line 84, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 760, in invoke
    return __callback(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/cli.py", line 911, in run_command
    raise e from None
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/cli.py", line 897, in run_command
    app = info.load_app()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/cli.py", line 308, in load_app
    app = locate_app(import_name, name)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/cli.py", line 218, in locate_app
    __import__(module_name)
  File "/Volumes/T7Touch/Learn/p2---final-project-ftds-016-rmt-group-001/scraping-2/deployment/app.py", line 2, in <module>
    from util.scrapeutil import get_db
  File "/Volumes/T7Touch/Learn/p2---final-project-ftds-016-rmt-group-001/scraping-2/deployment/util/scrapeutil.py", line 22, in <module>
    driver = webdriver.Remote(
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/selenium/webdriver/remote/webdriver.py", line 272, in __init__
    self.start_session(capabilities, browser_profile)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/selenium/webdriver/remote/webdriver.py", line 364, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/selenium/webdriver/remote/webdriver.py", line 429, in execute
    self.error_handler.check_response(response)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/selenium/webdriver/remote/errorhandler.py", line 243, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: Could not start a new session. Error while creating session with the driver service. Stopping driver service: Could not start a new session. Response code 500. Message: unknown error: Chrome failed to start: crashed.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Host info: host: '07a1292de76f', ip: '172.17.0.2'
Build info: version: '4.7.1', revision: 'c6795baf1a3'
System info: os.name: 'Linux', os.arch: 'amd64', os.version: '5.10.124-linuxkit', java.version: '11.0.17'
Driver info: driver.version: unknown
Build info: version: '4.7.1', revision: 'c6795baf1a3'
System info: os.name: 'Linux', os.arch: 'amd64', os.version: '5.10.124-linuxkit', java.version: '11.0.17'
Driver info: driver.version: unknown
Stacktrace:
    at org.openqa.selenium.grid.node.config.DriverServiceSessionFactory.apply (DriverServiceSessionFactory.java:202)
    at org.openqa.selenium.grid.node.config.DriverServiceSessionFactory.apply (DriverServiceSessionFactory.java:69)
    at org.openqa.selenium.grid.node.local.SessionSlot.apply (SessionSlot.java:147)
    at org.openqa.selenium.grid.node.local.LocalNode.newSession (LocalNode.java:379)
    at org.openqa.selenium.grid.distributor.local.LocalDistributor.startSession (LocalDistributor.java:645)
    at org.openqa.selenium.grid.distributor.local.LocalDistributor.newSession (LocalDistributor.java:564)
    at org.openqa.selenium.grid.distributor.local.LocalDistributor$NewSessionRunnable.handleNewSessionRequest (LocalDistributor.java:818)
    at org.openqa.selenium.grid.distributor.local.LocalDistributor$NewSessionRunnable.lambda$run$1 (LocalDistributor.java:779)
    at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1128)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:628)
    at java.lang.Thread.run (Thread.java:829)
</code>```

Edit: I use Mac M1. So I should use docker run -d -p 4444:4444 --shm-size="2g" seleniarm/standalone-chromium instead of docker run -d -p 4444:4444 --shm-size="2g" seleniarm/standalone-chromium

Body:
My goal is to run Selenium in a docker. The problem is that it refused to connect although selenium-standalone-chrome works fine and I can hit http://127.0.0.1:4444 in my own browser.

The culrpit:

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--disable-notifications")
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Remote(
    command_executor='http://127.0.0.1:4444/wd/hub',
    options=chrome_options
)

The error

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/bin/flask", line 8, in <module>
    sys.exit(main())
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/cli.py", line 1047, in main
    cli.main()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 1055, in main
    rv = self.invoke(ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 1657, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 760, in invoke
    return __callback(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/decorators.py", line 84, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 760, in invoke
    return __callback(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/cli.py", line 911, in run_command
    raise e from None
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/cli.py", line 897, in run_command
    app = info.load_app()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/cli.py", line 308, in load_app
    app = locate_app(import_name, name)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/cli.py", line 218, in locate_app
    __import__(module_name)
  File "/Volumes/T7Touch/Learn/p2---final-project-ftds-016-rmt-group-001/scraping-2/deployment/app.py", line 2, in <module>
    from util.scrapeutil import get_db
  File "/Volumes/T7Touch/Learn/p2---final-project-ftds-016-rmt-group-001/scraping-2/deployment/util/scrapeutil.py", line 22, in <module>
    driver = webdriver.Remote(
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/selenium/webdriver/remote/webdriver.py", line 272, in __init__
    self.start_session(capabilities, browser_profile)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/selenium/webdriver/remote/webdriver.py", line 364, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/selenium/webdriver/remote/webdriver.py", line 429, in execute
    self.error_handler.check_response(response)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/selenium/webdriver/remote/errorhandler.py", line 243, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: Could not start a new session. Error while creating session with the driver service. Stopping driver service: Could not start a new session. Response code 500. Message: unknown error: Chrome failed to start: crashed.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Host info: host: '07a1292de76f', ip: '172.17.0.2'
Build info: version: '4.7.1', revision: 'c6795baf1a3'
System info: os.name: 'Linux', os.arch: 'amd64', os.version: '5.10.124-linuxkit', java.version: '11.0.17'
Driver info: driver.version: unknown
Build info: version: '4.7.1', revision: 'c6795baf1a3'
System info: os.name: 'Linux', os.arch: 'amd64', os.version: '5.10.124-linuxkit', java.version: '11.0.17'
Driver info: driver.version: unknown
Stacktrace:
    at org.openqa.selenium.grid.node.config.DriverServiceSessionFactory.apply (DriverServiceSessionFactory.java:202)
    at org.openqa.selenium.grid.node.config.DriverServiceSessionFactory.apply (DriverServiceSessionFactory.java:69)
    at org.openqa.selenium.grid.node.local.SessionSlot.apply (SessionSlot.java:147)
    at org.openqa.selenium.grid.node.local.LocalNode.newSession (LocalNode.java:379)
    at org.openqa.selenium.grid.distributor.local.LocalDistributor.startSession (LocalDistributor.java:645)
    at org.openqa.selenium.grid.distributor.local.LocalDistributor.newSession (LocalDistributor.java:564)
    at org.openqa.selenium.grid.distributor.local.LocalDistributor$NewSessionRunnable.handleNewSessionRequest (LocalDistributor.java:818)
    at org.openqa.selenium.grid.distributor.local.LocalDistributor$NewSessionRunnable.lambda$run$1 (LocalDistributor.java:779)
    at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1128)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:628)
    at java.lang.Thread.run (Thread.java:829)

Edit: I use Mac M1. So I should use docker run -d -p 4444:4444 --shm-size="2g" seleniarm/standalone-chromium instead of docker run -d -p 4444:4444 --shm-size="2g" seleniarm/standalone-chromium


问:
Firebase Analytics for Web: Clean up screen tracking in funnels
I'm using Firebase Analytics in a React Native app (running on iOS, Android, web). I'm trying to build a funnel - but when building a funnel I'm getting multiple screen events (on web).

Currently I'm trying to disable page_views like this:

```<code>gtag('config', MEASUREMENT_ID, {
  anonymize_ip: true,
  send_page_view: false,
})
</code>```

and I'm sending my events like this:

```<code>const app = initializeApp(firebaseConfig)
const webAnalytics = getAnalytics(app)

logEvent(webAnalytics, 'screen_view', {
  firebase_screen: currentRouteName,
  firebase_screen_class: currentRouteName,
})
</code>```

From what I can see only one request is sent for each screen view, and it includes both the firebase_* params as well as page_title and page_location. But in the funnel (see screenshot) it gives me duplicates. I want to get completely rid of the "page title"-based in the funnel since they mess up the funnel.

I'm not sure if I need to (1) do something more to prevent page_title from being sent altogether or (2) can do something else to prevent the funnel from duplicating this. Any ideas?

Body:
I'm using Firebase Analytics in a React Native app (running on iOS, Android, web). I'm trying to build a funnel - but when building a funnel I'm getting multiple screen events (on web).

Currently I'm trying to disable page_views like this:

gtag('config', MEASUREMENT_ID, {
  anonymize_ip: true,
  send_page_view: false,
})

and I'm sending my events like this:

const app = initializeApp(firebaseConfig)
const webAnalytics = getAnalytics(app)

logEvent(webAnalytics, 'screen_view', {
  firebase_screen: currentRouteName,
  firebase_screen_class: currentRouteName,
})

From what I can see only one request is sent for each screen view, and it includes both the firebase_* params as well as page_title and page_location. But in the funnel (see screenshot) it gives me duplicates. I want to get completely rid of the "page title"-based in the funnel since they mess up the funnel.

I'm not sure if I need to (1) do something more to prevent page_title from being sent altogether or (2) can do something else to prevent the funnel from duplicating this. Any ideas?


问:
Difference in Adobe Analytics Data from Reporting API and Data Warehousing API 1.4
I am working on Adobe Analytics API 1.4 but I am getting different results when I am making API calls from reporting API and data warehousing API. Please refer to the screenshot I have used dummy data to explain the difference between those API calls. I have taken into consideration the Github Link for getting started as well as fetching data. I am not sure what am I missing or if is it an expected result.</p>


问:
SAML Callback from Onelogin not redirecting
Trying to implement a basic saml authentication with nodejs using passport-saml locally with the code below, and managed to get to Onelogin's login page when I hit localhost:8080, however, after login, it does not redirect me to http://localhost:8080/login/callback as I would expect.

Not sure if its something I misconfigured, or missed out, but I have the callback url on both the saml.Strategy configuration in code as well as my onelogin app page, and trying a few different things on my code so didn't work. Would be great to get some help on this!

```<code>const samlStrategy = new saml.Strategy(
    {
        callbackUrl: "http://localhost:8080/login/callback",
        entryPoint: <SLO Endpoint (HTTP)>,
        issuer: 'my-app',
        cert: fs.readFileSync("./certs/onelogin.pem", "utf8")
    },
        function(profile, done) {
        return done(null, profile);
    }
);

app.route("/login").get(passport.authenticate(samlStrategy));
app.route("/login/callback").post(samlCallback(passport));
</code>```

Body:
Trying to implement a basic saml authentication with nodejs using passport-saml locally with the code below, and managed to get to Onelogin's login page when I hit localhost:8080, however, after login, it does not redirect me to http://localhost:8080/login/callback as I would expect.

Not sure if its something I misconfigured, or missed out, but I have the callback url on both the saml.Strategy configuration in code as well as my onelogin app page, and trying a few different things on my code so didn't work. Would be great to get some help on this!

const samlStrategy = new saml.Strategy(
    {
        callbackUrl: "http://localhost:8080/login/callback",
        entryPoint: <SLO Endpoint (HTTP)>,
        issuer: 'my-app',
        cert: fs.readFileSync("./certs/onelogin.pem", "utf8")
    },
        function(profile, done) {
        return done(null, profile);
    }
);

app.route("/login").get(passport.authenticate(samlStrategy));
app.route("/login/callback").post(samlCallback(passport));


Title: How to open a PFA csv file

Body:
A client gave me a file in CSV format and called that PFA. I want to open a PFA file, but I got something like the one below.
I would appreciate it if I get help from you.

df=pd.read_csv( '/home/mikaeil/Downloads/ccd4b28d-4340-4e4f-a3b4-e2de3a2de142.csv')

The result is like below:

0   f71069a5840386c6ece104de3f2bafc3ecb1ff37f1bc64...   99406be6f8f8044366aef3271ac4109d0538df39276e9e...   cb3e421b1d1c2c3448f323268f972ee3b2a54cc1021bf4...   3a14097e562c77b201d23978b706f07e52133506bf5902...   dc937b59892604f5a86ac96936cd7ff09e25f18ae6b758...   dc937b59892604f5a86ac96936cd7ff09e25f18ae6b758...   dc937b59892604f5a86ac96936cd7ff09e25f18ae6b758...   8ce86a6ae65d3692e7305e2c58ac62eebd97d3d943e093...   8ce86a6ae65d3692e7305e2c58ac62eebd97d3d943e093...   e15274dcfe2d0cb541e8aa23fef7aaaa116bfcbc937d35...   ...     8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e...   8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   c22cd1ea7268eed0a17f08b05559b6f7939040cf707d5a...   a416ea84421fa7e1351582da48235bac88380a337ec5cb...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   52ebab80b30e4922e932f30f2dd0de3a66dfccdc96c921...   1.0
1   f7e645ca1739c318ae12efa6767cf1e7f38accd55c238c...   9b2d5b4678781e53038e91ea5324530a03f27dc1d0e5f6...   9b2d5b4678781e53038e91ea5324530a03f27dc1d0e5f6...   9b2d5b4678781e53038e91ea5324530a03f27dc1d0e5f6...   dc937b59892604f5a86ac96936cd7ff09e25f18ae6b758...   dc937b59892604f5a86ac96936cd7ff09e25f18ae6b758...   dc937b59892604f5a86ac96936cd7ff09e25f18ae6b758...   8ce86a6ae65d3692e7305e2c58ac62eebd97d3d943e093...   8ce86a6ae65d3692e7305e2c58ac62eebd97d3d943e093...   b690285b6e60662df771bc7a6b6ee1cb13f799e3d902ec...   ...     8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e...   8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   26c9a96ce053a14dd88a71a4830c9cbed7e1fed7e3f3f8...   1.0
2   7a2987f600f343f47c4bd9c1bb704db28517da1e814f95...   ca9f6563c7614c5ef5f033c9aaa1aa21611412da771a91...   27e1c95e64999f594001f3b8fada27406bb96ae8adfded...   78df16cdd1a174c6372267773cf96fc1e7bbcc40a0e935...   9b2d5b4678781e53038e91ea5324530a03f27dc1d0e5f6...   9b2d5b4678781e53038e91ea5324530a03f27dc1d0e5f6...   eb1e33e8a81b697b75855af6bfcdbcbf7cbbde9f94962c...   8ce86a6ae65d3692e7305e2c58ac62eebd97d3d943e093...   8ce86a6ae65d3692e7305e2c58ac62eebd97d3d943e093...   8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e...   ...     8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e...   8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   8ab31b5afaea56114427e1f01b81d001b079a0f59539f6...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e...   648e5bca018ffe4b6db96361d9b1a5245ee72d27e49269...   1.0
3   e1eb1c05e9cd661690a5eca2566f93ff0a6146bd91025b...   9b2d5b4678781e53038e91ea5324530a03f27dc1d0e5f6...   4e07408562bedb8b60ce05c1decfe3ad16b72230967de0...   be683e560cde64bff281f929cab1c6588dc9b7057d3cbf...   dc937b59892604f5a86ac96936cd7ff09e25f18ae6b758...   dc937b59892604f5a86ac96936cd7ff09e25f18ae6b758...   dc937b59892604f5a86ac96936cd7ff09e25f18ae6b758...   8ce86a6ae65d3692e7305e2c58ac62eebd97d3d943e093...   8ce86a6ae65d3692e7305e2c58ac62eebd97d3d943e093...   3883138a87732955cea4ec542b22ef82c5342262ca1dab...   ...     8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e...   8aed642bf5118b9d3c859bd4be35ecac75b6e873cce34e...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   c72ae9676454d7cc0014583a9d0a2e28553d5c62f087c7...   a416ea84421fa7e1351582da48235bac88380a337ec5cb...   d0ff5974b6aa52cf562bea5921840c032a860a91a3512f...   1f4d86b1e0415f97659988ec13c7753c4bffc5f95d373c...   1.0
4   8e741abe8c2cdee489ce0b8c7fc3a87e726e66c858bed5...   ca9f6563c7614c5ef5f033c9aaa1aa21611412da771a91...


问:
How do I compress video in Sveltekit using @ffmpeg/ffmpeg?
I am trying to compress video in Sveltekit using @ffmpeg/ffmpeg after npm install @ffmpeg/ffmpeg @ffmpeg/core. Here is my code below in the folder /src/lib/compress.Dolo.js

// @ts-ignore
import fs from 'fs';
// @ts-ignore
import { createFFmpeg, fetchFile } from '@ffmpeg/ffmpeg';
const ffmpeg = createFFmpeg({ log: true });
// @ts-ignore
export async function dolo(inputfile) {
    try {
        await ffmpeg.load();
        ffmpeg.FS('writeFile', 'test.avi', await fetchFile(inputfile));
        await ffmpeg.run('ffmpeg -i', 'test.avi', 'test.mp4');
        await fs.promises.writeFile('./test.mp4', ffmpeg.FS('readFile', 'test.mp4'));
    }
    catch (e) {
        console.log(e);
    }
}
```
<p>After uploading a video file to my +page.server.ts as shown below</p>
<pre class="lang-js prettyprint-override"><code>import {dolo} from '$lib/compress/Dolo'
import fs from 'fs';
import ffmpeg  from '@ffmpeg/ffmpeg';

handleSubmit: async ( event: { request: { formData: () => any; }; }) => {
    const data = await event.request.formData();
    const fileu = data.get('file-input') as File;
    const abuffer = await fileu.arrayBuffer();
    const buffer = Buffer.from(new Uint8Array(abuffer));
    dolo(buffer);
}
</code>```

when i run the code, it gives and error in my console as shown below:

```<code>[info] load ffmpeg-core
[info] loading ffmpeg-core
TypeError: fetch failed
    at fetch (C:\Users\Boteng\Botengsveltekit\node_modules\undici\index.js:105:13) {
  cause: Error: unknown scheme
      at makeNetworkError (C:\Users\Boteng\Botengsveltekit\node_modules\undici\lib\fetch\response.js:351:9)
      at schemeFetch (C:\Users\Boteng\Botengsveltekit\node_modules\undici\lib\fetch\index.js:893:14)
      at C:\Users\Boteng\Botengsveltekit\node_modules\undici\lib\fetch\index.js:602:22
      at mainFetch (C:\Users\Boteng\Botengsveltekit\node_modules\undici\lib\fetch\index.js:652:7)
      at fetching (C:\Users\Boteng\Botengsveltekit\node_modules\undici\lib\fetch\index.js:517:3)
      at fetch (C:\Users\Boteng\Botengsveltekit\node_modules\undici\lib\fetch\index.js:245:16)
      at fetch (C:\Users\Boteng\Botengsveltekit\node_modules\undici\index.js:103:20)
      at C:\Users\Boteng\Botengsveltekit\node_modules\@ffmpeg\core\dist\ffmpeg-core.js:215:32
      at C:\Users\Boteng\Botengsveltekit\node_modules\@ffmpeg\core\dist\ffmpeg-core.js:215:254
      at C:\Users\Boteng\Botengsveltekit\node_modules\@ffmpeg\core\dist\ffmpeg-core.js:215:277 {
    [cause]: undefined
  }
}
</code>```

Please Can anyone tell me what i am doing wrong?

Body:
I am trying to compress video in Sveltekit using @ffmpeg/ffmpeg after npm install @ffmpeg/ffmpeg @ffmpeg/core. Here is my code below in the folder /src/lib/compress.Dolo.js

// @ts-ignore
import fs from 'fs';
// @ts-ignore
import { createFFmpeg, fetchFile } from '@ffmpeg/ffmpeg';
const ffmpeg = createFFmpeg({ log: true });
// @ts-ignore
export async function dolo(inputfile) {
    try {
        await ffmpeg.load();
        ffmpeg.FS('writeFile', 'test.avi', await fetchFile(inputfile));
        await ffmpeg.run('ffmpeg -i', 'test.avi', 'test.mp4');
        await fs.promises.writeFile('./test.mp4', ffmpeg.FS('readFile', 'test.mp4'));
    }
    catch (e) {
        console.log(e);
    }
}

After uploading a video file to my +page.server.ts as shown below

import {dolo} from '$lib/compress/Dolo'
import fs from 'fs';
import ffmpeg  from '@ffmpeg/ffmpeg';

handleSubmit: async ( event: { request: { formData: () => any; }; }) => {
    const data = await event.request.formData();
    const fileu = data.get('file-input') as File;
    const abuffer = await fileu.arrayBuffer();
    const buffer = Buffer.from(new Uint8Array(abuffer));
    dolo(buffer);
}

when i run the code, it gives and error in my console as shown below:

[info] load ffmpeg-core
[info] loading ffmpeg-core
TypeError: fetch failed
    at fetch (C:\Users\Boteng\Botengsveltekit\node_modules\undici\index.js:105:13) {
  cause: Error: unknown scheme
      at makeNetworkError (C:\Users\Boteng\Botengsveltekit\node_modules\undici\lib\fetch\response.js:351:9)
      at schemeFetch (C:\Users\Boteng\Botengsveltekit\node_modules\undici\lib\fetch\index.js:893:14)
      at C:\Users\Boteng\Botengsveltekit\node_modules\undici\lib\fetch\index.js:602:22
      at mainFetch (C:\Users\Boteng\Botengsveltekit\node_modules\undici\lib\fetch\index.js:652:7)
      at fetching (C:\Users\Boteng\Botengsveltekit\node_modules\undici\lib\fetch\index.js:517:3)
      at fetch (C:\Users\Boteng\Botengsveltekit\node_modules\undici\lib\fetch\index.js:245:16)
      at fetch (C:\Users\Boteng\Botengsveltekit\node_modules\undici\index.js:103:20)
      at C:\Users\Boteng\Botengsveltekit\node_modules\@ffmpeg\core\dist\ffmpeg-core.js:215:32
      at C:\Users\Boteng\Botengsveltekit\node_modules\@ffmpeg\core\dist\ffmpeg-core.js:215:254
      at C:\Users\Boteng\Botengsveltekit\node_modules\@ffmpeg\core\dist\ffmpeg-core.js:215:277 {
    [cause]: undefined
  }
}

Please Can anyone tell me what i am doing wrong?


问:
"opencv2/opencv.hpp": No such file or directory
I've been trying to use the library of opencv in a C++ project in Visual Studio 2017, but I've been dealing with an error I don't know how to solve it.

I am trying to do a simple #include <opencv2/opencv.hpp> but I have always the same error, and is that the file is not found

In order to do this I have modified de VC++ directories (first image) and the linker  (second image).
(https://i.stack.imgur.com/BE9v6.png)](https://i.stack.imgur.com/BE9v6.png).

I would be very grateful if someone could help me with this silly question.
Thank you.


问:
discord.py AttributeError: 'Client' object has no attribute 'client' on the latest pip version

client = discord.Client(intents=intents)
```
<p>when I use this ^ code I get the error below.</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
  File "c:\Users\zist\Discord Bot\main.py", line 46, in <module>
@bot.client AttributeError: 'Client' object has no attribute 'client'
</code>```

This is how I define bot:

intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
bot = discord.Client(intents=intents)
```
<p>With older versions of <code>pip</code> I get</p>
<pre class="lang-none prettyprint-override"><code>ImportError: cannot import name 'app_commands' from 'discord' (C:\Users\zist\AppData\Local\Programs\Python\Python310\lib\site-packages\discord__init__.py)
</code>```

I tried looking up for the solution that didn't give me an error and I haven't come across any.

Body:
client = discord.Client(intents=intents)

when I use this ^ code I get the error below.

Traceback (most recent call last):
  File "c:\Users\zist\Discord Bot\main.py", line 46, in <module>
@bot.client AttributeError: 'Client' object has no attribute 'client'

This is how I define bot:

intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
bot = discord.Client(intents=intents)

With older versions of pip I get

ImportError: cannot import name 'app_commands' from 'discord' (C:\Users\zist\AppData\Local\Programs\Python\Python310\lib\site-packages\discord__init__.py)

I tried looking up for the solution that didn't give me an error and I haven't come across any.


问:
Is possible to pass an argument to a pipeline aggregation via url and regex?
I need to perform data aggregation, but variables must be passed in the url and not via arguments ( ?aggregate={}).

I have the following hook enabled:

```<code>def on_aggregate(endpoint, pipeline):
    print(f'endpoint: {endpoint}')
    print(f'pipeline: {pipeline}')
</code>```

My standard config is:

```<code>media_por_user_id = {
    'url': 'views/userid/media',
    'datasource':{
        'source': 'media',
        'aggregation': {
            'pipeline':
                [
                    {
                        '$match': {
                            "user": "$user_id"
                        }
                    }, {
                        '$group': {
                            '_id': '$user',
                            'medias': {
                                '$push': {
                                    'media_filename': '$media_filename',
                                    'media_status': '$media_status'
                                }
                            }
                        }
                    }
                ]
            }
    },
    'schema': schema_media,
}
</code>```

Request: http://127.0.0.1/views/userid/media?aggregate={"$user_id":"639b51720ac10cbf4b0a3d43"}

Response:

```<code>{"_items": [{"_id": "639b51720ac10cbf4b0a3d43", "medias": [{"media_filename": "r", "media_status": "available"}, {"media_filename": "r1", "media_status": "available"}, {"media_filename": "r2", "media_status": "available"}]}], "_meta": {"page": 1, "max_results": 25, "total": 1}, "_links": {"parent": {"title": "home", "href": "/"}, "self": {"title": "views/userid/media", "href": "views/userid/media?aggregate={\"$user_id\":\"639b51720ac10cbf4b0a3d43\"}"}}}
</code>```

Hook Output:

endpoint: media_por_user_id pipeline: [{'$match': {'user': '639b51720ac10cbf4b0a3d43'}}, {'$group': {'_id': '$user', 'medias': {'$push': {'media_filename': '$media_filename', 'media_status': '$media_status'}}}}]

Note how $user_id is captured correctly

2-. Trying to pass $user_id through the url:

```<code>media_por_user_id = {
    'url': 'views/<regex("[a-f0-9]{24}"):user_id>/media',
    'datasource':{
        'source': 'media',
        'aggregation': {
            'pipeline':
                [
                    {
                        '$match': {
                            "user": "$user_id"
                        }
                    }, {
                        '$group': {
                            '_id': '$user',
                            'medias': {
                                '$push': {
                                    'media_filename': '$media_filename',
                                    'media_status': '$media_status'
                                }
                            }
                        }
                    }
                ]
            }
    },
    'schema': schema_media,
}
</code>```

Request: http:/127.0.0.1/views/639b51720ac10cbf4b0a3d43/media

Response:

```<code>{"_items": [], "_meta": {"page": 1, "max_results": 25, "total": 0}, "_links": {"parent": {"title": "home", "href": "/"}, "self": {"title": "views/<regex(\"[a-f0-9]{24}\"):user_id>/media", "href": "views/639b51720ac10cbf4b0a3d43/media"}}}
</code>```

Hook Output:

endpoint: media_por_user_id, pipeline: [{'$match': {'user': '$user_id'}}, {'$group': {'_id': '$user', 'medias': {'$push': {'media_filename': '$media_filename', 'media_status': '$media_status'}}}}]

in this case the value of $user_id is not captured.

I have tried many modifications, but without success. information available in this regard is scarce.
So I'm evaluating sending an empty pipeline to the aggregation hook. and handle it at that level, using the following approach:

```<code>from flask import request

def on_aggregate(endpoint, pipeline):
    print(f'endpoint: {endpoint}')
    print(f'pipeline: {pipeline}')
    url = request.url
    # extract $user_id from url
    # contruct pipeline
    return True
</code>```

But before going to that stage I would like to have clarification if it is a configuration error or Eve does not support this feature.

Thanks

Body:
I need to perform data aggregation, but variables must be passed in the url and not via arguments ( ?aggregate={}).

I have the following hook enabled:

def on_aggregate(endpoint, pipeline):
    print(f'endpoint: {endpoint}')
    print(f'pipeline: {pipeline}')

My standard config is:

media_por_user_id = {
    'url': 'views/userid/media',
    'datasource':{
        'source': 'media',
        'aggregation': {
            'pipeline':
                [
                    {
                        '$match': {
                            "user": "$user_id"
                        }
                    }, {
                        '$group': {
                            '_id': '$user',
                            'medias': {
                                '$push': {
                                    'media_filename': '$media_filename',
                                    'media_status': '$media_status'
                                }
                            }
                        }
                    }
                ]
            }
    },
    'schema': schema_media,
}

Request: http://127.0.0.1/views/userid/media?aggregate={"$user_id":"639b51720ac10cbf4b0a3d43"}

Response:

{"_items": [{"_id": "639b51720ac10cbf4b0a3d43", "medias": [{"media_filename": "r", "media_status": "available"}, {"media_filename": "r1", "media_status": "available"}, {"media_filename": "r2", "media_status": "available"}]}], "_meta": {"page": 1, "max_results": 25, "total": 1}, "_links": {"parent": {"title": "home", "href": "/"}, "self": {"title": "views/userid/media", "href": "views/userid/media?aggregate={\"$user_id\":\"639b51720ac10cbf4b0a3d43\"}"}}}

Hook Output:

endpoint: media_por_user_id pipeline: [{'$match': {'user': '639b51720ac10cbf4b0a3d43'}}, {'$group': {'_id': '$user', 'medias': {'$push': {'media_filename': '$media_filename', 'media_status': '$media_status'}}}}]

Note how $user_id is captured correctly

2-. Trying to pass $user_id through the url:

media_por_user_id = {
    'url': 'views/<regex("[a-f0-9]{24}"):user_id>/media',
    'datasource':{
        'source': 'media',
        'aggregation': {
            'pipeline':
                [
                    {
                        '$match': {
                            "user": "$user_id"
                        }
                    }, {
                        '$group': {
                            '_id': '$user',
                            'medias': {
                                '$push': {
                                    'media_filename': '$media_filename',
                                    'media_status': '$media_status'
                                }
                            }
                        }
                    }
                ]
            }
    },
    'schema': schema_media,
}

Request: http:/127.0.0.1/views/639b51720ac10cbf4b0a3d43/media

Response:

{"_items": [], "_meta": {"page": 1, "max_results": 25, "total": 0}, "_links": {"parent": {"title": "home", "href": "/"}, "self": {"title": "views/<regex(\"[a-f0-9]{24}\"):user_id>/media", "href": "views/639b51720ac10cbf4b0a3d43/media"}}}

Hook Output:

endpoint: media_por_user_id, pipeline: [{'$match': {'user': '$user_id'}}, {'$group': {'_id': '$user', 'medias': {'$push': {'media_filename': '$media_filename', 'media_status': '$media_status'}}}}]

in this case the value of $user_id is not captured.

I have tried many modifications, but without success. information available in this regard is scarce.
So I'm evaluating sending an empty pipeline to the aggregation hook. and handle it at that level, using the following approach:

from flask import request

def on_aggregate(endpoint, pipeline):
    print(f'endpoint: {endpoint}')
    print(f'pipeline: {pipeline}')
    url = request.url
    # extract $user_id from url
    # contruct pipeline
    return True

But before going to that stage I would like to have clarification if it is a configuration error or Eve does not support this feature.

Thanks


问:
From where do I call different services (controller or directly in the service)?
I have an architecture question about my Laravel application. I have the entity post. Then I use the spatie package "spatie/laravel-tags":"^4.3". When I want to create a post I send my request against the Laravel interface. The route forwards to the controller. The controller forwards the request body (the form data) to the PostService. The PostService forwards the data to the PostRepository. The repository creates the new post and returns it to the service. Now I want to attach the tags to the post. My question. Do I call the TagService in the PostService? Or should the PostController do that?


问:
Touching Right click window in Java Selenium Chrome
I can right click on a search term in Java selenium Chrome, but I cannot click where I want in the popup menu. How can I get to the place I want in the window that opens after right-clicking?

Code example where I right click :
Actions action = new Actions(driver); action.moveToElement(driver.findElement(By.xpath("//h3[text()='Example']"))).contextClick().build().perform();

Is there anyone who can help?


问:
ReactTS with ViteJS production build fails in docker file but succeeds locally
My app's frontend is in React 18, with Typescript, and packages are managed with pnpm. The app was created with Vitejs.

My build command as declared in my package.json is the following :

```<code>"build": "tsc --noEmit --skipLibCheck && vite build"
</code>```

Initially, it was only :

```<code>"build": "tsc && vite build"
</code>```

But this led to local build typescript errors.

With the --noEmit --skipLibCheck options, when I run it locally, it builds without issues. However, when I run it with docker, I have the following errors :

```<code>src/App.tsx(2,19): error TS7016: Could not find a declaration file for module 'react'. '/app/node_modules/.pnpm/react@18.2.0/node_modules/react/index.js' implicitly has an 'any' type.
  If the 'react' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react'
</code>```

My tsconfig.json :

```<code>{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": false,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}
</code>```

I have followed the pnpm instruction for the docker file. I am unsure of what the issue might be.
Does anyone know what it could be ?

Body:
My app's frontend is in React 18, with Typescript, and packages are managed with pnpm. The app was created with Vitejs.

My build command as declared in my package.json is the following :

"build": "tsc --noEmit --skipLibCheck && vite build"

Initially, it was only :

"build": "tsc && vite build"

But this led to local build typescript errors.

With the --noEmit --skipLibCheck options, when I run it locally, it builds without issues. However, when I run it with docker, I have the following errors :

src/App.tsx(2,19): error TS7016: Could not find a declaration file for module 'react'. '/app/node_modules/.pnpm/react@18.2.0/node_modules/react/index.js' implicitly has an 'any' type.
  If the 'react' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react'

My tsconfig.json :

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": false,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

I have followed the pnpm instruction for the docker file. I am unsure of what the issue might be.
Does anyone know what it could be ?


问:
ArcGIS Pro - how to find out information about created pyramids and what pyramid level is used in certain scale
I am working with raster data (aerial images) in JPEG2000 using ArcGIS Pro 2.9.

Is there a way in ArcGIS Pro (or using arcpy) how to find out resolution of each pyramid level? And in what scale is certain level displayed? I would like to have a table with pyramid levels, resolution for each level and scale, where the level starts and ends displaying.

Thank you.
AC


问:
How would I slow the overflow: scroll speed?
I used overflow: scroll so if a user were to click on a button redirecting them to the
 below it would scroll smoothly. I feel that the scrolling time is too short and would like to know whether it would be possible to increase the time it takes to scroll down to the below
. Say if the scrolling time was 0.5 seconds, I would like to make it 2 or 3 seconds


问:
Is there any way to message on whatsapp without opening the application
I've been searching for the solution to send the message on whatsapp from the Application or via REST-APIs without opening it.

As I have mentioned below the code will validate for the Whatsapp-type installed in device and then it will send it to user but in this case it launch the whatsapp.

```<code>private void launchWhatsapp(String msg) {
        try {
            boolean installed2 = obj.appInstalledOrNot("com.whatsapp.w4b");
            if (installed2) try {

                Intent sendIntent = new Intent("android.intent.action.MAIN");
                sendIntent.setAction(Intent.ACTION_VIEW);
                sendIntent.setPackage("com.whatsapp.w4b");
                String url = "https://api.whatsapp.com/send?" +
                        "phone=" + PhoneNumberUtils.stripSeparators(Cust_Phone_Code + " " + getIntent().getStringExtra("Cust_Mob")) +
                        "&text=" + msg;
                sendIntent.setData(Uri.parse(url));
                if (sendIntent.resolveActivity(this.getPackageManager()) != null) {
                    startActivityForResult(sendIntent, 104);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            else {
                boolean installed = obj.appInstalledOrNot("com.whatsapp");
                if (installed) {
                    Intent sendIntent = new Intent("android.intent.action.MAIN");
                    sendIntent.setAction(Intent.ACTION_VIEW);
                    sendIntent.setPackage("com.whatsapp");
                    String url = "https://api.whatsapp.com/send?" +
                            "phone=" + PhoneNumberUtils.stripSeparators(Cust_Phone_Code + " " + getIntent().getStringExtra("Cust_Mob")) +
                            "&text=" + msg;
                    sendIntent.setData(Uri.parse(url));
                    if (sendIntent.resolveActivity(this.getPackageManager()) != null) {
                        startActivityForResult(sendIntent, 104);
                    }
                } else {

                    Toast.makeText(InvoiceReport.this, "Whatsapp not available", Toast.LENGTH_SHORT).show();
                }
            }

        } catch (Exception e) {
            //Log.e("Error", "ERROR_OPEN_MESSANGER"+e.toString());
        }
    }
</code>```

I am expecting if anyone click on the browser on send message then this redirect to whatsapp application.

Body:
I've been searching for the solution to send the message on whatsapp from the Application or via REST-APIs without opening it.

As I have mentioned below the code will validate for the Whatsapp-type installed in device and then it will send it to user but in this case it launch the whatsapp.

private void launchWhatsapp(String msg) {
        try {
            boolean installed2 = obj.appInstalledOrNot("com.whatsapp.w4b");
            if (installed2) try {

                Intent sendIntent = new Intent("android.intent.action.MAIN");
                sendIntent.setAction(Intent.ACTION_VIEW);
                sendIntent.setPackage("com.whatsapp.w4b");
                String url = "https://api.whatsapp.com/send?" +
                        "phone=" + PhoneNumberUtils.stripSeparators(Cust_Phone_Code + " " + getIntent().getStringExtra("Cust_Mob")) +
                        "&text=" + msg;
                sendIntent.setData(Uri.parse(url));
                if (sendIntent.resolveActivity(this.getPackageManager()) != null) {
                    startActivityForResult(sendIntent, 104);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            else {
                boolean installed = obj.appInstalledOrNot("com.whatsapp");
                if (installed) {
                    Intent sendIntent = new Intent("android.intent.action.MAIN");
                    sendIntent.setAction(Intent.ACTION_VIEW);
                    sendIntent.setPackage("com.whatsapp");
                    String url = "https://api.whatsapp.com/send?" +
                            "phone=" + PhoneNumberUtils.stripSeparators(Cust_Phone_Code + " " + getIntent().getStringExtra("Cust_Mob")) +
                            "&text=" + msg;
                    sendIntent.setData(Uri.parse(url));
                    if (sendIntent.resolveActivity(this.getPackageManager()) != null) {
                        startActivityForResult(sendIntent, 104);
                    }
                } else {

                    Toast.makeText(InvoiceReport.this, "Whatsapp not available", Toast.LENGTH_SHORT).show();
                }
            }

        } catch (Exception e) {
            //Log.e("Error", "ERROR_OPEN_MESSANGER"+e.toString());
        }
    }

I am expecting if anyone click on the browser on send message then this redirect to whatsapp application.


问:
How can i add directives in custom lit-element tags?
I've defined my custom button using lit-element.
I'm trying to use the button in an angular project to print, using the ngx-print library. This library needs triggers placed as directives:

```<code><button printSectionId="print-section" ngxPrint>print</button>.
</code>```

How can I pass these directives to my custom tag and make the library receive them from the shadowDom?
Es:

```<code><custom-button printSectionId="print-section" ngxPrint>print</custom-button>.
</code>```

Tnx!!

i tried to define new properties in the lit object, but without success. I tried to open the shadowDom but the result does not change. Please help me!!

Body:
I've defined my custom button using lit-element.
I'm trying to use the button in an angular project to print, using the ngx-print library. This library needs triggers placed as directives:

<button printSectionId="print-section" ngxPrint>print</button>.

How can I pass these directives to my custom tag and make the library receive them from the shadowDom?
Es:

<custom-button printSectionId="print-section" ngxPrint>print</custom-button>.

Tnx!!

i tried to define new properties in the lit object, but without success. I tried to open the shadowDom but the result does not change. Please help me!!


问:
How do I configure ActiveDirectoryLdapAuthenticationProvider with a username, password or custom searchfilter?
The only configurable parts of this Authenticator seem to be the URL and the Domain. I'm unable to figure out how I would pass on a username or a password or my own search filter.

I looked at the source code of this class but most of the methods seem to be operating on UsernamePasswordAuthenticationToken from which username and password are being extracted. I was unable to find the methods which are used to create this object.

Here's what I'm currently using for AD LDAP Authentication:

```<code>package com.test;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        ActiveDirectoryLdapAuthenticationProvider adProvider = new ActiveDirectoryLdapAuthenticationProvider("domain.org",
                "ldap://activedirectory-url:389");
        adProvider.setConvertSubErrorCodesToExceptions(true);
        adProvider.setUseAuthenticationRequestCredentials(true);
        auth.authenticationProvider(adProvider);
    }

}
</code>```

Body:
The only configurable parts of this Authenticator seem to be the URL and the Domain. I'm unable to figure out how I would pass on a username or a password or my own search filter.

I looked at the source code of this class but most of the methods seem to be operating on UsernamePasswordAuthenticationToken from which username and password are being extracted. I was unable to find the methods which are used to create this object.

Here's what I'm currently using for AD LDAP Authentication:

package com.test;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        ActiveDirectoryLdapAuthenticationProvider adProvider = new ActiveDirectoryLdapAuthenticationProvider("domain.org",
                "ldap://activedirectory-url:389");
        adProvider.setConvertSubErrorCodesToExceptions(true);
        adProvider.setUseAuthenticationRequestCredentials(true);
        auth.authenticationProvider(adProvider);
    }

}


问:
A Graphics object cannot be created from an image that has an indexed pixel format
```<code>
</code>```

=> System.ArgumentException: A Graphics object cannot be created from an image that has an indexed pixel format.

When We Add this type of image that are in pixel format https://prnt.sc/9UpU7pila2bz on watermark https://prnt.sc/y6C7djHXjGq4, we are getting "System.ArgumentException: A Graphics object cannot be created from an image that has an indexed pixel format." this error
-library we are using for watermark is LazZiya.ImageResize we are using ImageWatermarkOptions() method

=>Solutions we tried

" https://prnt.sc/I1mjwBCNYUXJ  " this solution for this error bat facing same issue
-Tried converting images from jpeg to png as mentioned in their document
https://docs.ziyad.info/en/LazZiya.ImageResize/v4.1/image-watermark.md

```<code></code>```