问:
How to identify this JavaScript "undefined" console error?
I could use some help identifying a way to track down this random "undefined" error I am getting in my console. It tells me the violation is in the jquery.validate.unobtrusive but not telling what fails.It is not affecting any functionality from as far as I can tell but I would like to fix it regardless as to not cause future issues when this view is changed and updated which it significantly needs.
I tried to cut down the code below as much as possible.
View:

```<code>@using (Html.BeginForm("PushToDiamond", "Support", FormMethod.Post, new { id = "TransactionView" }))
{
    <input type="submit" form="TransactionView" onclick='return SubmitValues();' class="btn btn-success btn-sm" value='PushToDiamond' />
}
@section scripts{
    @Scripts.Render("~/bundles/SupportScript")
}
</code>```

JavaScript Function:

```<code>function SubmitValues() {
    debugger;
    if ($('input[name="IsSelected"]:checked').length == 0) {
        alert("Please select check boxes to process.");
        return false;
    }
    var i = 0;
    $('input[name="IsSelected"][type="checkbox"]').each(function (e, g) {
        if ($(g).prop('checked')) {
            var c = document.createElement('input');
            $(c).attr({ 'type': 'hidden', 'name': 'PolicyTransactionPKList[' + i + ']', 'value': $(g).val() });
            $('#TransactionView').append(c);
            i++;
        }
    });
    return true;
};
</code>```

Controller Method:

```<code>public ActionResult PushToEmerald(SupportModel model)
{
     _logger.LogInformation("Support - Pushing");
     var env = GetEnv(model?.Country);
     var rq = new PushToEmeraldRq {
          Environment = env,
          PolicyTransactionPK = model.PolicyTransactionPK ?? 0,
          PolicyTransactionPKList = model.PolicyTransactionPKList ?? new List<int>()
     };
     var rs = _policyTransactionService.PushToEmerald(rq);
     model.ProcessRecord = rs.ProcessRecord;
     model.PolicyTransactions = rs.PolicyTransactions;
     return View("Index", model);
}
</code>```

Ambiguous Console Error:

```<code>Uncaught SyntaxError: "undefined" is not valid JSON
    at Function.parse [as parseJSON] (<anonymous>)
    at HTMLFormElement.onError (jquery.validate.unobtrusive.js:41:25)
    at $.validator.proxy (jquery-3.6.0.js:10780:13)
    at $.validator.showLabel (jquery.validate.js:983:35)
    at $.validator.defaultShowErrors (jquery.validate.js:928:11)
    at $.validator.showErrors (jquery.validate.js:553:10)
    at $.validator.form (jquery.validate.js:468:9)
    at HTMLFormElement.<anonymous> (jquery.validate.js:106:20)
    at HTMLFormElement.dispatch (jquery-3.6.0.js:5430:27)
    at elemData.handle (jquery-3.6.0.js:5234:28)
onError @   jquery.validate.unobtrusive.js:41
proxy   @   jquery-3.6.0.js:10780
showLabel   @   jquery.validate.js:983
defaultShowErrors   @   jquery.validate.js:928
showErrors  @   jquery.validate.js:553
form    @   jquery.validate.js:468
(anonymous) @   jquery.validate.js:106
dispatch    @   jquery-3.6.0.js:5430
elemData.handle @   jquery-3.6.0.js:5234
</code>```

Debugger Console Results:

```<code>$("form").serialize()
'Country=Usa&IsAllTransactionsSelected=false&IsSelected=37644306&IsSelected=37647734&Country=Usa'
</code>```
```<code>$("form").validate()
$.validator {settings: {…}, currentForm: form, labelContainer: jQuery.fn.init(0), errorContext: jQuery.fn.init(1), containers: jQuery.fn.init(0), …}
containers: jQuery.fn.init [prevObject: jQuery.fn.init(0)]
currentElements: jQuery.fn.init []
currentForm: form
errorContext: jQuery.fn.init [form]
errorList: []
errorMap: {}
groups: {}
invalid: {}
labelContainer:
jQuery.fn.init []
pending: {}
pendingRequest: 0
settings: {messages: {…}, groups: {…}, rules: {…}, errorClass: 'input-validation-error', pendingClass: 'pending', …}
submitted: {}
successList: []
toHide: jQuery.fn.init []
toShow: jQuery.fn.init []
valueCache: {}
[[Prototype]]: Object
</code>```

I have tried adding a debugger into the JavaScript to hit as soon as the button is clicked and testing the form.serialize() and form.validate() commands however they come back successful and as soon as I continue the error persists.
This is the first line from the button click so I am kind of lost.
I have tried VS Debugging and nothing is caught. I have tried breakpoints on the controller but that is kind of irrelevant considering the error posts to the console before the controller is called.

Body:
I could use some help identifying a way to track down this random "undefined" error I am getting in my console. It tells me the violation is in the jquery.validate.unobtrusive but not telling what fails.It is not affecting any functionality from as far as I can tell but I would like to fix it regardless as to not cause future issues when this view is changed and updated which it significantly needs.
I tried to cut down the code below as much as possible.
View:

@using (Html.BeginForm("PushToDiamond", "Support", FormMethod.Post, new { id = "TransactionView" }))
{
    <input type="submit" form="TransactionView" onclick='return SubmitValues();' class="btn btn-success btn-sm" value='PushToDiamond' />
}
@section scripts{
    @Scripts.Render("~/bundles/SupportScript")
}

JavaScript Function:

function SubmitValues() {
    debugger;
    if ($('input[name="IsSelected"]:checked').length == 0) {
        alert("Please select check boxes to process.");
        return false;
    }
    var i = 0;
    $('input[name="IsSelected"][type="checkbox"]').each(function (e, g) {
        if ($(g).prop('checked')) {
            var c = document.createElement('input');
            $(c).attr({ 'type': 'hidden', 'name': 'PolicyTransactionPKList[' + i + ']', 'value': $(g).val() });
            $('#TransactionView').append(c);
            i++;
        }
    });
    return true;
};

Controller Method:

public ActionResult PushToEmerald(SupportModel model)
{
     _logger.LogInformation("Support - Pushing");
     var env = GetEnv(model?.Country);
     var rq = new PushToEmeraldRq {
          Environment = env,
          PolicyTransactionPK = model.PolicyTransactionPK ?? 0,
          PolicyTransactionPKList = model.PolicyTransactionPKList ?? new List<int>()
     };
     var rs = _policyTransactionService.PushToEmerald(rq);
     model.ProcessRecord = rs.ProcessRecord;
     model.PolicyTransactions = rs.PolicyTransactions;
     return View("Index", model);
}

Ambiguous Console Error:

Uncaught SyntaxError: "undefined" is not valid JSON
    at Function.parse [as parseJSON] (<anonymous>)
    at HTMLFormElement.onError (jquery.validate.unobtrusive.js:41:25)
    at $.validator.proxy (jquery-3.6.0.js:10780:13)
    at $.validator.showLabel (jquery.validate.js:983:35)
    at $.validator.defaultShowErrors (jquery.validate.js:928:11)
    at $.validator.showErrors (jquery.validate.js:553:10)
    at $.validator.form (jquery.validate.js:468:9)
    at HTMLFormElement.<anonymous> (jquery.validate.js:106:20)
    at HTMLFormElement.dispatch (jquery-3.6.0.js:5430:27)
    at elemData.handle (jquery-3.6.0.js:5234:28)
onError @   jquery.validate.unobtrusive.js:41
proxy   @   jquery-3.6.0.js:10780
showLabel   @   jquery.validate.js:983
defaultShowErrors   @   jquery.validate.js:928
showErrors  @   jquery.validate.js:553
form    @   jquery.validate.js:468
(anonymous) @   jquery.validate.js:106
dispatch    @   jquery-3.6.0.js:5430
elemData.handle @   jquery-3.6.0.js:5234

Debugger Console Results:

$("form").serialize()
'Country=Usa&IsAllTransactionsSelected=false&IsSelected=37644306&IsSelected=37647734&Country=Usa'

$("form").validate()
$.validator {settings: {…}, currentForm: form, labelContainer: jQuery.fn.init(0), errorContext: jQuery.fn.init(1), containers: jQuery.fn.init(0), …}
containers: jQuery.fn.init [prevObject: jQuery.fn.init(0)]
currentElements: jQuery.fn.init []
currentForm: form
errorContext: jQuery.fn.init [form]
errorList: []
errorMap: {}
groups: {}
invalid: {}
labelContainer:
jQuery.fn.init []
pending: {}
pendingRequest: 0
settings: {messages: {…}, groups: {…}, rules: {…}, errorClass: 'input-validation-error', pendingClass: 'pending', …}
submitted: {}
successList: []
toHide: jQuery.fn.init []
toShow: jQuery.fn.init []
valueCache: {}
[[Prototype]]: Object

I have tried adding a debugger into the JavaScript to hit as soon as the button is clicked and testing the form.serialize() and form.validate() commands however they come back successful and as soon as I continue the error persists.
This is the first line from the button click so I am kind of lost.
I have tried VS Debugging and nothing is caught. I have tried breakpoints on the controller but that is kind of irrelevant considering the error posts to the console before the controller is called.


来源: stackexchange

问:
Can the same graphql schema be used across multiple strawberry fastapi routers?
I have strawberry setup to run with fastapi.  Basically, like the examples, the fastapi initialization code creates a GraphQLRouter with a Schema object and a context_getter.

Everything works great, I use __get_context to pass some Dependencies in.

What I don't know is, how do I conditionally call Dependencies?

Like I might want a Depends(UserManager) on some graphql calls and Depends(ClientManager) on others.   Normally in fast api, I could use different routers to assign different dependencies.  But most of the strawberry fastapi examples use a single router for a single schema. Or more rarely multiple routers across multiple schemas.

How do I break up a strawberry GraphQL Schema across multiple GraphQLRouters so I can use different Depends chains for different requests?

ContentLicense: CC BY-SA 4.0


问:
tsc compiles with import from 'src'
I have imports like this in my project:

import { helloAndChoose } from "src/handlers/helloAndChoose";
```
<p>When I run <code>tsc</code>, the imports in compiled files are from the <code>src</code> folder, which does not exist in the <code>dist</code> folder:</p>
<pre class="lang-js prettyprint-override"><code>const helloAndChoose_1 = require("src/handlers/helloAndChoose");
</code>```

The folder structure is as follows:

The tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es2021",
    "moduleResolution": "node",
    "strict": true,
    "sourceMap": true,
    "lib": ["es2021"],
    "skipLibCheck": true,
    "rootDir": "src",
    "baseUrl": ".",
    "outDir": "dist"
  },
  "include": ["src/**/*"]
}
```

I know there are many questions like this, but none helped this far...

Title: tsc compiles with import from 'src'

Body:
I have imports like this in my project:

import { helloAndChoose } from "src/handlers/helloAndChoose";

When I run tsc, the imports in compiled files are from the src folder, which does not exist in the dist folder:

const helloAndChoose_1 = require("src/handlers/helloAndChoose");

The folder structure is as follows:

The tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es2021",
    "moduleResolution": "node",
    "strict": true,
    "sourceMap": true,
    "lib": ["es2021"],
    "skipLibCheck": true,
    "rootDir": "src",
    "baseUrl": ".",
    "outDir": "dist"
  },
  "include": ["src/**/*"]
}

I know there are many questions like this, but none helped this far...


问:
SignalR on Azure sends message to SignalR client within a LAN
We have the following mixed-environment scenario (Azure and LAN):

Azure Web App calls a method in the Azure API (triggered by some user action in the web app).

This Azure API then establishes a SignalR HubContext connection .

The HubContext broadcasts a message.

The SignalR client (consuming the message) is a Windows Service installed on a machine on the LAN, behind the firewall.

Our client is complaining that the connection often breaks, and therefore several messages are missing on a daily basis.

Here is a test method in the Azure API, which attempts to broadcast a message:

using Microsoft.AspNet.SignalR;
using System;
using System.IO;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.Caching;
using System.Text;
using System.Web.Http;
using System.Xml;
...

namespace MyTestAPI.Controllers

    [AllowCrossSiteJson]
    [RoutePrefix("api/Test")]
    public class HL7Controller : ApiController

      [HttpGet]
      [Route("TestSignalR")]
      public IHttpActionResult TestSignalR()
      {
          string reportData = $"<TestReport>This is a test message generated on { DateTime.Now }.</TestReport>";
          var hubContext = GlobalHost.ConnectionManager.GetHubContext<HL7Hub>();
          hubContext.Clients.All.SendReportData(reportData);
          return Ok(reportData);
      }
     ...
  }
  ```
</div>
</div>
</p>
<p>And in the client's environment, there's a Win Service installed - it acts as the <em><strong>SignalR Client</strong></em>
<img src="https://i.stack.imgur.com/hmcQs.png" alt="enter image description here" /></p>
<p>And here's a snippet of our H..NotificationsService solution (vs2019, Framework <strong>4.6.1</strong>)</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>using log4net.Ext.EventID;
using Microsoft.AspNet.SignalR.Client;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Net;
using System.ServiceProcess;
using System.Threading;

namespace H_NotificationSrv
{
    public partial class H_NotificationService : ServiceBase

      public async void StartListner()
              {
                  try
                  {
                      var hubConnection = new HubConnection(hl7APIUrl);
                      hubConnection.Credentials = CredentialCache.DefaultNetworkCredentials;
                      var hubProxy = hubConnection.CreateHubProxy("MyTestHub");
                      hubProxy.On<string>("SendReportData", reportData =>
                      {
                          SendReportDataToSomeone(reportData);
                      });
                      await hubConnection.Start();
                  }
                  catch (Exception ex)
                  {
                      string errorMessage = ex.Message;
                      if (ex.InnerException != null)
                          errorMessage += " Inner Exception: " + ex.InnerException.Message;
                      applog.Error(errorMessage);
                  }
              }
       }
}</code>```

Body:
We have the following mixed-environment scenario (Azure and LAN):

Azure Web App calls a method in the Azure API (triggered by some user action in the web app).

This Azure API then establishes a SignalR HubContext connection .

The HubContext broadcasts a message.

The SignalR client (consuming the message) is a Windows Service installed on a machine on the LAN, behind the firewall.

Our client is complaining that the connection often breaks, and therefore several messages are missing on a daily basis.

Here is a test method in the Azure API, which attempts to broadcast a message:

using Microsoft.AspNet.SignalR;
using System;
using System.IO;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.Caching;
using System.Text;
using System.Web.Http;
using System.Xml;
...

namespace MyTestAPI.Controllers

    [AllowCrossSiteJson]
    [RoutePrefix("api/Test")]
    public class HL7Controller : ApiController

      [HttpGet]
      [Route("TestSignalR")]
      public IHttpActionResult TestSignalR()
      {
          string reportData = $"<TestReport>This is a test message generated on { DateTime.Now }.</TestReport>";
          var hubContext = GlobalHost.ConnectionManager.GetHubContext<HL7Hub>();
          hubContext.Clients.All.SendReportData(reportData);
          return Ok(reportData);
      }
     ...
  }

And in the client's environment, there's a Win Service installed - it acts as the SignalR Client

And here's a snippet of our H..NotificationsService solution (vs2019, Framework 4.6.1)

using log4net.Ext.EventID;
using Microsoft.AspNet.SignalR.Client;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Net;
using System.ServiceProcess;
using System.Threading;

namespace H_NotificationSrv
{
    public partial class H_NotificationService : ServiceBase

      public async void StartListner()
              {
                  try
                  {
                      var hubConnection = new HubConnection(hl7APIUrl);
                      hubConnection.Credentials = CredentialCache.DefaultNetworkCredentials;
                      var hubProxy = hubConnection.CreateHubProxy("MyTestHub");
                      hubProxy.On<string>("SendReportData", reportData =>
                      {
                          SendReportDataToSomeone(reportData);
                      });
                      await hubConnection.Start();
                  }
                  catch (Exception ex)
                  {
                      string errorMessage = ex.Message;
                      if (ex.InnerException != null)
                          errorMessage += " Inner Exception: " + ex.InnerException.Message;
                      applog.Error(errorMessage);
                  }
              }
       }
}


问:
Pydrake Autodiff Hessian
Almost a year ago, a question (stackoverflow.com/questions/71027922) was asked concerning computing Hessians or other higher order derivatives using AutoDiff. I was wondering whether there has been any movement on this front.

I've found that for Jacobians, Drake's AutoDiff has much better performance (often over 10x wall clock time) vs. other frameworks like Jax for complicated functions I'm differentiating. To compute second-order derivatives, I've had to analytically compute the first derivative and then differentiate that.

If there are any unofficial workarounds in the meantime that could circumvent the need to compute the analytical first derivative so that I could do something like hessian(function, x), that would be much appreciated!

Title: Pydrake Autodiff Hessian


问:
Custom on_message method with fast-api mqtt
I want to combine REST with MQTT. I am using fastapi_mqtt and fastapi.
I want to handle messages from specfic topics ( my code is below, some methods are copied from fastapi-mqtt documentation https://sabuhish.github.io/fastapi-mqtt/mqtt/). I realized that no if statement actually works in on_message method, only print which is outside of on_message. Do you have any idea why? And how to manage custom on_message handler?

```<code>import logging
import requests
from fastapi import FastAPI
from fastapi_mqtt import FastMQTT, MQTTConfig

url = '127.0.0.1:8000' # im testing on my local broker
settings = get_settings()
app = FastAPI(title="System Controller")

mqtt_config = MQTTConfig(
    host = settings.mqtt_host,
    port= settings.mqtt_port,
    username=settings.mqtt_user,
    password=settings.mqtt_password
    )

mqtt = FastMQTT(
    config=mqtt_config)

mqtt.init_app(app)

async def publish():
    mqtt.publish("/mqtt", "Hello from Fastapi") #publishing mqtt topic

    return {"result": True,"message":"Published" }

@mqtt.on_connect()
def connect(client, flags, rc, properties):
    # subscribing mqtt topic
    if rc == 0:
        print('Connected to MQTT Broker')
        mqtt.client.subscribe("#")
        print("Connected: ", client, flags, rc, properties)
    else:
        print('Failed to connect, return code %d\n',rc)

def test_events_handler(client, topic, payload):
    # topic stucture /test/{sub_topic}/{device_id}
    device_id = topic.split('/')[2]
    sub_topic = topic.split('/')[1]
    msg = payload.decode()
    if sub_topic == '1':
        logging.debug(f'Received level message from {device_id}')
        try:
            PARAMS = {'level': msg}
            r = requests.get(url = f'{url}/test/msg', params=PARAMS)
            data = r.json()
            print(data)
        except:
            print('Level value is not correct')
    elif sub_topic =='2':
        print(f'Received dose message from user. Send to {device_id}')
    else:
        print('There is no handler to that topic')

def topic_handler(client, topic, payload):
    if topic.startswith('/test'):
        # handling topics related to feeder device
        tests_events_handler(client, topic, payload)
        print("Received message: ",topic, payload.decode())
    elif topic.startswith('/nexttest'):
        pass

@mqtt.on_message()
async def message(client, topic, payload, qos, properties):
    print(topic)
    topic_handler(client, topic, payload)

@mqtt.subscribe("#")
async def message_to_topic(client, topic, payload, qos, properties):
    print("Received message to specific topic: ", topic, payload.decode(), qos, properties)

@mqtt.on_disconnect()
def disconnect(client, packet, exc=None):
    print("Disconnected")

@mqtt.on_subscribe()
def subscribe(client, mid, qos, properties):
    print("subscribed", client, mid, qos, properties)

@app.get('/')
async def func():

    return {'result': True, 'message': 'Published'}

</code>```

I want this program to works like that:
subscribes MQTT topics, lets say'/test/#' and '/nextest/#'. and on message from one of that topics it checks if message came from topic one or two and then reads the rest of the topic and depends on remaining part of the topic it sends specific get request to fast api.

Body:
I want to combine REST with MQTT. I am using fastapi_mqtt and fastapi.
I want to handle messages from specfic topics ( my code is below, some methods are copied from fastapi-mqtt documentation https://sabuhish.github.io/fastapi-mqtt/mqtt/). I realized that no if statement actually works in on_message method, only print which is outside of on_message. Do you have any idea why? And how to manage custom on_message handler?

import logging
import requests
from fastapi import FastAPI
from fastapi_mqtt import FastMQTT, MQTTConfig

url = '127.0.0.1:8000' # im testing on my local broker
settings = get_settings()
app = FastAPI(title="System Controller")

mqtt_config = MQTTConfig(
    host = settings.mqtt_host,
    port= settings.mqtt_port,
    username=settings.mqtt_user,
    password=settings.mqtt_password
    )

mqtt = FastMQTT(
    config=mqtt_config)

mqtt.init_app(app)

async def publish():
    mqtt.publish("/mqtt", "Hello from Fastapi") #publishing mqtt topic

    return {"result": True,"message":"Published" }

@mqtt.on_connect()
def connect(client, flags, rc, properties):
    # subscribing mqtt topic
    if rc == 0:
        print('Connected to MQTT Broker')
        mqtt.client.subscribe("#")
        print("Connected: ", client, flags, rc, properties)
    else:
        print('Failed to connect, return code %d\n',rc)

def test_events_handler(client, topic, payload):
    # topic stucture /test/{sub_topic}/{device_id}
    device_id = topic.split('/')[2]
    sub_topic = topic.split('/')[1]
    msg = payload.decode()
    if sub_topic == '1':
        logging.debug(f'Received level message from {device_id}')
        try:
            PARAMS = {'level': msg}
            r = requests.get(url = f'{url}/test/msg', params=PARAMS)
            data = r.json()
            print(data)
        except:
            print('Level value is not correct')
    elif sub_topic =='2':
        print(f'Received dose message from user. Send to {device_id}')
    else:
        print('There is no handler to that topic')

def topic_handler(client, topic, payload):
    if topic.startswith('/test'):
        # handling topics related to feeder device
        tests_events_handler(client, topic, payload)
        print("Received message: ",topic, payload.decode())
    elif topic.startswith('/nexttest'):
        pass

@mqtt.on_message()
async def message(client, topic, payload, qos, properties):
    print(topic)
    topic_handler(client, topic, payload)

@mqtt.subscribe("#")
async def message_to_topic(client, topic, payload, qos, properties):
    print("Received message to specific topic: ", topic, payload.decode(), qos, properties)

@mqtt.on_disconnect()
def disconnect(client, packet, exc=None):
    print("Disconnected")

@mqtt.on_subscribe()
def subscribe(client, mid, qos, properties):
    print("subscribed", client, mid, qos, properties)

@app.get('/')
async def func():

    return {'result': True, 'message': 'Published'}

I want this program to works like that:
subscribes MQTT topics, lets say'/test/#' and '/nextest/#'. and on message from one of that topics it checks if message came from topic one or two and then reads the rest of the topic and depends on remaining part of the topic it sends specific get request to fast api.


问:
KeyError: 0 when calculate likelihood in EM algorithm
I have a model EM algorithm. The model should select random columns and then calculate the likelihood. For example, the dataset has 39 attributes, the model selects 19 attributes only and displays likelihood.

define several functions :
initialize_model_params, expected_hidden_vars , update_model,  likelihood

the problem when calculating likelihood I got the error

KeyError: 0

It's related to the index

function likelihood

```<code> def calc_likelihood(data, means, covariances, weights):

  n_samples, n_features = data.shape
  n_components = len(means)

  # Initialize likelihood to 0
  likelihood = 0

  # Loop over each sample in the data
  for i in range(n_samples):
    sample_likelihood = 0
    # Loop over each component in the mixture
    for j in range(n_components):
      # Calculate the probability of the sample given the component
      component_prob = weights[j] * multivariate_normal.pdf(data[i], mean=means[j], cov=covariances[j])
      # Add the component probability to the sample likelihood
      sample_likelihood += component_prob
    # Add the sample likelihood to the overall likelihood
    likelihood += np.log(sample_likelihood)

  return likelihood
</code>```

function em

```<code>    def em(data, columns, num_iterations):
  # Initialize the model parameters
  model_params = initialize_model_params(data, columns)
# Select a random subset of columns
  selected_columns = random.sample(list(columns), k=len(columns) // 2)
  print(selected_columns)

  for i in range(num_iterations):

    # E step: calculate the expected value of the hidden variables using the selected columns
    expected_hidden_vars = calculate_expected_hidden_vars(data, selected_columns, model_params)

    # M step: update the estimates of the model parameters using the selected columns and the expected hidden variables
    model_params = update_model_params(data, selected_columns, expected_hidden_vars)

    means, covariances, weights = model_params
    print('params', model_params)

    # Calculate the likelihood of the data given the current model parameters
    likelihood = calc_likelihood(data, means, covariances, weights)
    print('likelihood : ' , likelihood)

  # Return the maximum likelihood estimates of the model parameters
  return model_params
</code>```

how to fix it. can anyone help me?

Body:
I have a model EM algorithm. The model should select random columns and then calculate the likelihood. For example, the dataset has 39 attributes, the model selects 19 attributes only and displays likelihood.

define several functions :
initialize_model_params, expected_hidden_vars , update_model,  likelihood

the problem when calculating likelihood I got the error

KeyError: 0

It's related to the index

function likelihood

 def calc_likelihood(data, means, covariances, weights):

  n_samples, n_features = data.shape
  n_components = len(means)

  # Initialize likelihood to 0
  likelihood = 0

  # Loop over each sample in the data
  for i in range(n_samples):
    sample_likelihood = 0
    # Loop over each component in the mixture
    for j in range(n_components):
      # Calculate the probability of the sample given the component
      component_prob = weights[j] * multivariate_normal.pdf(data[i], mean=means[j], cov=covariances[j])
      # Add the component probability to the sample likelihood
      sample_likelihood += component_prob
    # Add the sample likelihood to the overall likelihood
    likelihood += np.log(sample_likelihood)

  return likelihood

function em

    def em(data, columns, num_iterations):
  # Initialize the model parameters
  model_params = initialize_model_params(data, columns)
# Select a random subset of columns
  selected_columns = random.sample(list(columns), k=len(columns) // 2)
  print(selected_columns)

  for i in range(num_iterations):

    # E step: calculate the expected value of the hidden variables using the selected columns
    expected_hidden_vars = calculate_expected_hidden_vars(data, selected_columns, model_params)

    # M step: update the estimates of the model parameters using the selected columns and the expected hidden variables
    model_params = update_model_params(data, selected_columns, expected_hidden_vars)

    means, covariances, weights = model_params
    print('params', model_params)

    # Calculate the likelihood of the data given the current model parameters
    likelihood = calc_likelihood(data, means, covariances, weights)
    print('likelihood : ' , likelihood)

  # Return the maximum likelihood estimates of the model parameters
  return model_params

how to fix it. can anyone help me?


问:
VIteJS Import native compiled node module fails 'Unexpected character'
I am trying to transition an electron application built with create-react-app to ViteJS. So far, I've managed to get a lot of things fixed, but I'am having an issue with one of our dependencies.

My project uses an internal library built in golang for performance reasons, and this library is called from the main process of the electron application. However, I get the following error when running vite build.

```<code>[commonjs--resolver] Unexpected character '�' (Note that you need plugins to import files that are not JavaScript)
</code>```

This happens with the following line

```<code>module.exports = require('./build/Release/goapi.node');
</code>```

goapi.node is the compiled library. This library is compiled using node-gyp, and I'm 100% sure that the compilation is right, because it is working with the current setup that uses create-react-app.

Is there a plugin to add in the vite config to support importing native modules? If not, how can I get around this problem?

Body:
I am trying to transition an electron application built with create-react-app to ViteJS. So far, I've managed to get a lot of things fixed, but I'am having an issue with one of our dependencies.

My project uses an internal library built in golang for performance reasons, and this library is called from the main process of the electron application. However, I get the following error when running vite build.

[commonjs--resolver] Unexpected character '�' (Note that you need plugins to import files that are not JavaScript)

This happens with the following line

module.exports = require('./build/Release/goapi.node');

goapi.node is the compiled library. This library is compiled using node-gyp, and I'm 100% sure that the compilation is right, because it is working with the current setup that uses create-react-app.

Is there a plugin to add in the vite config to support importing native modules? If not, how can I get around this problem?


问:
I have a string that want to split. I have done the next but the result is an error. Need some help finding the error in my code

library(stringr)
I want to substract the secong number on the string per_ocu in a bigger table. I did use a nested ifelse with substr() but the result is the last table below. It is only substracting the last line and it worked previously with the perocu_min version. I have also tried to trim the string. What is wrong with my code?

t_perocu

A tibble: 7 × 3

Groups:   per_ocu [7]

per_ocu              char_perocu       n

1 0 a 5 personas                14 1471172
2 101 a 250 personas            18    3531
3 11 a 30 personas              16   37998
4 251 y mï¿½s personas          20    3014
5 31 a 50 personas              16    5178
6 51 a 100 personas             17    3468
7 6 a 10 personas               15   85071

This is my code. (I want to make sure there is no bug in my R Studio Version.)

denue_1$perocu_max <- ifelse(denue_1$char_perocu == 14, substr(denue_1$per_ocu, 5, 1),

```<code>                         ifelse(denue_1$char_perocu == 15, substr(denue_1$per_ocu, 5, 2),
</code>```

```<code>                                ifelse(denue_1$char_perocu == 16, substr(denue_1$per_ocu, 6, 2),
</code>```

```<code>                                       ifelse(denue_1$char_perocu == 17, substr(denue_1$per_ocu, 6, 3),
</code>```

```<code>                                              ifelse(denue_1$char_perocu == 18, substr(denue_1$per_ocu, 7, 3),
</code>```

```<code>                                                     ifelse(denue_1$char_perocu == 20, substr(denue_1$per_ocu, 1, 3), 0))))))
</code>```

table(denue_1$perocu_max)

table(denue_1$perocu_max)

This is what I got:

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

1606418    3014

This is what I was expecting

View(tperocu_max)
tperocu_max
Var1    Freq     emp
1    5 1471172 7355860
2   10   85071  850710
3   30   37998 1139940
4   50    5178  258900
5  100    3468  346800
6  250    3531  882750
7  251    3014  756514

Body:
library(stringr)
I want to substract the secong number on the string per_ocu in a bigger table. I did use a nested ifelse with substr() but the result is the last table below. It is only substracting the last line and it worked previously with the perocu_min version. I have also tried to trim the string. What is wrong with my code?

t_perocu

A tibble: 7 × 3

Groups:   per_ocu [7]

per_ocu              char_perocu       n

1 0 a 5 personas                14 1471172
2 101 a 250 personas            18    3531
3 11 a 30 personas              16   37998
4 251 y mï¿½s personas          20    3014
5 31 a 50 personas              16    5178
6 51 a 100 personas             17    3468
7 6 a 10 personas               15   85071

This is my code. (I want to make sure there is no bug in my R Studio Version.)

denue_1$perocu_max <- ifelse(denue_1$char_perocu == 14, substr(denue_1$per_ocu, 5, 1),

                         ifelse(denue_1$char_perocu == 15, substr(denue_1$per_ocu, 5, 2),

                                ifelse(denue_1$char_perocu == 16, substr(denue_1$per_ocu, 6, 2),

                                       ifelse(denue_1$char_perocu == 17, substr(denue_1$per_ocu, 6, 3),

                                              ifelse(denue_1$char_perocu == 18, substr(denue_1$per_ocu, 7, 3),

                                                     ifelse(denue_1$char_perocu == 20, substr(denue_1$per_ocu, 1, 3), 0))))))

table(denue_1$perocu_max)

table(denue_1$perocu_max)

This is what I got:

        251

1606418    3014

This is what I was expecting

View(tperocu_max)
tperocu_max
Var1    Freq     emp
1    5 1471172 7355860
2   10   85071  850710
3   30   37998 1139940
4   50    5178  258900
5  100    3468  346800
6  250    3531  882750
7  251    3014  756514


问:
Members of Spring components should be injected - autowired=false
To fix "Members of Spring components should be injected(https://rules.sonarsource.com/java/RSPEC-3749)" sonar qube issue, if i use @Autowired(required=false) for TestB so warning will go and initialize TestB in @PostConstruct. Does it has any negative impact.

```<code>@Component
public class Test {

    @Autowired
    private TestA testa;

    private TestB testb;

    @PostConstruct
    private void doSomething() {
        testb = new TestB();
        ....
    }
}
</code>```

Note - I am aware about actual sonar rule reason but injecting TestB dependency needs lot of code refactoring which is not possible currently. Also cannot remove/disable this rule. So looking for workaround to solve this issue.

Body:
To fix "Members of Spring components should be injected(https://rules.sonarsource.com/java/RSPEC-3749)" sonar qube issue, if i use @Autowired(required=false) for TestB so warning will go and initialize TestB in @PostConstruct. Does it has any negative impact.

@Component
public class Test {

    @Autowired
    private TestA testa;

    private TestB testb;

    @PostConstruct
    private void doSomething() {
        testb = new TestB();
        ....
    }
}

Note - I am aware about actual sonar rule reason but injecting TestB dependency needs lot of code refactoring which is not possible currently. Also cannot remove/disable this rule. So looking for workaround to solve this issue.


问:
Discord Bot spam reply issue
```<code>public class PingPong extends ListenerAdapter {

    public void onMessageReceived (MessageReceivedEvent ereignis) {

        if (ereignis.isFromGuild()) {

            if (ereignis.getMessage().getContentStripped().equals("ping"));
            {

                ereignis.getChannel().sendMessage("pong!").queue();

            }
        }
    }

</code>```

I tried to programm a ping and pong reply game where i type ping and the bot replys pong, but when i type ping it spams pong.

Edit: I found the Problem, it responds to every Message sent not only ping, but i still dont know why.

Title: Discord Bot spam reply issue

Body:
public class PingPong extends ListenerAdapter {

    public void onMessageReceived (MessageReceivedEvent ereignis) {

        if (ereignis.isFromGuild()) {

            if (ereignis.getMessage().getContentStripped().equals("ping"));
            {

                ereignis.getChannel().sendMessage("pong!").queue();

            }
        }
    }

I tried to programm a ping and pong reply game where i type ping and the bot replys pong, but when i type ping it spams pong.

Edit: I found the Problem, it responds to every Message sent not only ping, but i still dont know why.


问:
How to change logo color on scroll and on hover
Need to change the logo color on hover, than change it on scroll.

I got it to change on hover, but having trouble changing it on scroll. Can someone please look at my JSFiddle and help?

Maybe it's just the classes that are clashing or my JS logic, maybe I need to step off and let my brain refresh.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

  <style>
    .newROInav {
        padding: 40px;
        width: 100%;
        transition-duration: 0.5s;
        transition-timing-function: ease-in-out;
    }

    .newROInav:hover {
        background-color: white;
    }

    .light {
      display: block;
    }
    .dark {
      display: none;
    }
    .newROInav:hover div[class="dark"] {
      display: block;
    }
    .newROInav:hover div[class="light"] {
      display: none;
    }

    $color-darkgreen: #006072;

    html,
    body {
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        font-size: 16px;
        padding: 0;
        margin: 0;
        width: 100vw;
        height: 1000vw;
    }

    body p {
        padding: 40px;
    }

    .sticky-top {
        position: sticky;
        top: 0px;
        z-index: 1020;
    }

    ul,
    li {
        padding: 0;
        margin: 0;
    }

    main {
        transition: background-color 0.3s ease;
        background-color: $color-darkgreen;
        margin: 0;
        padding: 0;
        position: fixed;
        text-align: center;
        top: 0;
        width: 100vw;

        ul {
            width: 100%;
            height: 100%;
            position: relative;
            padding: 30px;

            li {
                display: inline;
                top: 50%;
                padding: 2rem;

                a {
                    color: #fff;
                }
            }
        }

        &.inverted {
            background-color: #fff;
            box-shadow: 0 3px 5px 0.3px rgba(0, 0, 0, 0.1);

            a {
                color: $color-darkgreen;
            }
        }

    }
</style>

<main class="newROInav sticky-top">
  <div class="test">
    <div class="dark">
      <ul>
        <li><a href="#"><img src="http://newnavstg.wpengine.com/wp-content/uploads/logo-dark.svg" /></a></li>
      </ul>
    </div>
    <div class="light">
      <ul>
        <li><a href="#"><img src="http://newnavstg.wpengine.com/wp-content/uploads/logo.svg" /></a></li>
      </ul>
    </div>
  </div>
</main>
<p>
  Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ipsa reiciendis quas, optio ullam debitis adipisci et
  voluptates tenetur? Dolor ea optio aspernatur? Aspernatur, omnis ea consequuntur cum quod asperiores veniam.
</p>

<script>
  var className = "inverted";
  var scrollTrigger = 60;

  window.onscroll = function() {
  // We add pageYOffset for compatibility with IE.
  if (window.scrollY >= scrollTrigger || window.pageYOffset >= scrollTrigger) {
      document.getElementsByTagName("main")[0].classList.add(className);
  } else {
      document.getElementsByTagName("main")[0].classList.remove(className);
  }
  };
</script>
</code>```

Body:
Need to change the logo color on hover, than change it on scroll.

I got it to change on hover, but having trouble changing it on scroll. Can someone please look at my JSFiddle and help?

Maybe it's just the classes that are clashing or my JS logic, maybe I need to step off and let my brain refresh.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

  Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ipsa reiciendis quas, optio ullam debitis adipisci et
  voluptates tenetur? Dolor ea optio aspernatur? Aspernatur, omnis ea consequuntur cum quod asperiores veniam.


问:
JUnit tests: How to "inherit" Spring application context without extending base test class?
My tests of a Spring application are written using JUnit 4. To ease writing of JUnit tests and reduce repetitive code, I use a base class (AbstractDaoTest) that defines a basic Spring application context using annotation @ContextConfiguration(classes = …):

@ContextConfiguration(classes = TestDbConf.class)
public abstract class AbstractDaoTest {
    ...
}
```
<p>Subclasses extend the application context by defining extra annotation <code>ContextConfiguration(…)</code> with additional classes:</p>
<pre class="lang-java prettyprint-override"><code>@ContextConfiguration(classes = SomeExtraBean.class)
public class SomeTestClass extends AbstractDaoTest {
    ...
}
</code>```

JUnit 5 came with the modern approach "composition is better than inheritance".

I like the idea so I tried to avoid inheritance by defining a composed annotation:

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = TestDbConf.class)
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
public @interface DaoTest { }
```
<p>… and using the annotation on a test class:</p>
<pre class="lang-java prettyprint-override"><code>@DaoTest
@ContextConfiguration(classes = ExtraBeanClass.class)
public class SomeTest {
    ...
}
</code>```

But when I execute it, it seems that the @ContextConfiguration annotation causes the application context to be shadowed/overwritten, i.e. the context defined by annotation @DaoTest is not used.

What is the correct approach? Is it possible to achieve the goal using JUnit 5 extension?

I searched the internet and read several articles about JUnit 5 extensions and JUnit 5 in general but I couldn't find the answer in any of them.

Body:
My tests of a Spring application are written using JUnit 4. To ease writing of JUnit tests and reduce repetitive code, I use a base class (AbstractDaoTest) that defines a basic Spring application context using annotation @ContextConfiguration(classes = …):

@ContextConfiguration(classes = TestDbConf.class)
public abstract class AbstractDaoTest {
    ...
}

Subclasses extend the application context by defining extra annotation ContextConfiguration(…) with additional classes:

@ContextConfiguration(classes = SomeExtraBean.class)
public class SomeTestClass extends AbstractDaoTest {
    ...
}

JUnit 5 came with the modern approach "composition is better than inheritance".

I like the idea so I tried to avoid inheritance by defining a composed annotation:

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = TestDbConf.class)
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
public @interface DaoTest { }

… and using the annotation on a test class:

@DaoTest
@ContextConfiguration(classes = ExtraBeanClass.class)
public class SomeTest {
    ...
}

But when I execute it, it seems that the @ContextConfiguration annotation causes the application context to be shadowed/overwritten, i.e. the context defined by annotation @DaoTest is not used.

What is the correct approach? Is it possible to achieve the goal using JUnit 5 extension?

I searched the internet and read several articles about JUnit 5 extensions and JUnit 5 in general but I couldn't find the answer in any of them.


问:
jquery UI tabs and jscal2.js calendar not working onChange
I had added the jquery UI tabs but something is not right, i have form inside and a javascript based calendar inside inpoput fields but someone it stopped working

Here is what i have

i am using this jsCal

Dynarch Calendar -- JSCal2, version 1.9

and this triggers the calendar but its not displaying me an error

```<code><input type="text" name="sdate" class="date"    value="12/16/2022" id="calfield1" REQUIRED="yes" data-message="Please enter start date (MM/dd/yyyy)."  onchange="StartDateUpdateManually(this.form.startdatetxt.value);"/>
                          <button id="Startbtn1"><img src="images/cal.gif" /></button>
                              <script type="text/javascript">//<![CDATA[
                                    Calendar.setup({
                                       inputField: "calfield1",
                                    dateFormat: "%m/%d/%Y",
                                    trigger: "Startbtn1",
                                    bottomBar: false,
                                    fdow: 0,
                                    onSelect:  StartDateUpdateFromCal
                            });
                              //]]></script>

                      </td>
</code>```

here are my functions

```<code>function StartDateUpdateFromCal(cal)
        {
        var date1 = cal.selection.get();
        var dStart = new Date(Calendar.intToDate(date1));

        document.getElementById('SubmitButton_ID').disabled=false;
        ReturnCode = StartDateCalcs(dStart);
        cal.hide();

    }

    function StartDateUpdateManually(sdate)
        {
            if (CheckDate(sdate) > 0)
                {
                    var dStart = new Date.parseExact(sdate, "#JSDateFormat#");

                    document.getElementById('SubmitButton_ID').disabled=false;
                    ReturnCode = StartDateCalcs(dStart);

                }

    }
</code>```

but now i am getting an error

```<code>jscal2.js:11 Uncaught TypeError: Calendar.parseDate is not a function
    at HTMLButtonElement.<anonymous> (jscal2.js:11:24375)
</code>```

Body:
I had added the jquery UI tabs but something is not right, i have form inside and a javascript based calendar inside inpoput fields but someone it stopped working

Here is what i have

i am using this jsCal

Dynarch Calendar -- JSCal2, version 1.9

and this triggers the calendar but its not displaying me an error

<input type="text" name="sdate" class="date"    value="12/16/2022" id="calfield1" REQUIRED="yes" data-message="Please enter start date (MM/dd/yyyy)."  onchange="StartDateUpdateManually(this.form.startdatetxt.value);"/>
                          <button id="Startbtn1"></button>

here are my functions

function StartDateUpdateFromCal(cal)
        {
        var date1 = cal.selection.get();
        var dStart = new Date(Calendar.intToDate(date1));

        document.getElementById('SubmitButton_ID').disabled=false;
        ReturnCode = StartDateCalcs(dStart);
        cal.hide();

    }

    function StartDateUpdateManually(sdate)
        {
            if (CheckDate(sdate) > 0)
                {
                    var dStart = new Date.parseExact(sdate, "#JSDateFormat#");

                    document.getElementById('SubmitButton_ID').disabled=false;
                    ReturnCode = StartDateCalcs(dStart);

                }

    }

but now i am getting an error

jscal2.js:11 Uncaught TypeError: Calendar.parseDate is not a function
    at HTMLButtonElement.<anonymous> (jscal2.js:11:24375)


问:
Shopify: Incorporate Metafields in Javascript
I've got a Javascript set up to display different text based upon which variant is clicked. It works using standard text like this simplified example:

```<code>$(function() {
  var copyFlavor = [
    '<p>' + 'Some copy goes here' + ' </p><p>' + 'Even more copy goes here' +  '<p>'
  ];
  $("#swatch-0").click(function () {
     $(".product-shop-description").html(copyFlavor[0]);
     console.log(copyFlavor[0]);
  });
</code>```

However, this is difficult for the client to update themselves. So I'm trying to incorporate metafields, so its much easier for the client to add copy.

However, I can't seem to incorporate Liquid into the script. I've tried both this:

```<code>$(function() {
  var copyFlavor = [
    '{{ product.metafields.flavor0.short_description.value }}'
  ];
  $("#swatch-0").click(function () {
     $(".product-shop-description").html(copyFlavor[0]);
     console.log(copyFlavor[0]);
  });
</code>```

or....

$(function() {
$("#swatch-0").click(function () {
$(".product-shop-description").html('{{ product.metafields.flavor0.short_description.value }}');
console.log('{{ product.metafields.flavor0.short_description.value }}');
});

Neither of which work and the function breaks.

Any idea of a way to incorporate metafields into this script?

Body:
I've got a Javascript set up to display different text based upon which variant is clicked. It works using standard text like this simplified example:

$(function() {
  var copyFlavor = [
    '
' + 'Some copy goes here' + '

' + 'Even more copy goes here' +  '
'
  ];
  $("#swatch-0").click(function () {
     $(".product-shop-description").html(copyFlavor[0]);
     console.log(copyFlavor[0]);
  });

However, this is difficult for the client to update themselves. So I'm trying to incorporate metafields, so its much easier for the client to add copy.

However, I can't seem to incorporate Liquid into the script. I've tried both this:

$(function() {
  var copyFlavor = [
    '{{ product.metafields.flavor0.short_description.value }}'
  ];
  $("#swatch-0").click(function () {
     $(".product-shop-description").html(copyFlavor[0]);
     console.log(copyFlavor[0]);
  });

or....

$(function() {
$("#swatch-0").click(function () {
$(".product-shop-description").html('{{ product.metafields.flavor0.short_description.value }}');
console.log('{{ product.metafields.flavor0.short_description.value }}');
});

Neither of which work and the function breaks.

Any idea of a way to incorporate metafields into this script?


问:
Serializing data with AWS Ion
I need to serialize data in binary format and transport it over BLE. First I looked into Protobuf.  But it doesn't support framing, self describing message and random access - a few capabilities I need for my project.  AWS ion supports self describing message and random access to message.  But I haven't found a complete example how to serialize a transport an IonStruct over BLE.  Any idea how I can do that?

Thanks!

Title: Serializing data with AWS Ion


问:
Nice formatting when sending gmail emails from mutt
I have been using mutt with my gmail account and recently got told that the emails I send look odd on some devices, particularly mobiles.

e.g.:

```<code>This is a wrapped sentence, and
it should display in a nice
fashion
but for some reason it does not
when it is received on some devices
I am
hoping that someone can help me with
this.
</code>```

I have set text_flowed=yes in my muttrc, and compose with formatoptions+=w in my vim settings to add a space to the end of each line.

In gmail I can selected 'plain text mode' in the compose window, but can't see anywhere to permanently set this.

After all of this when I compose an email and then send it it still appears badly formatted/not text flowed as above. I've been through various blog posts/SO questions but can't seem to get this to work. Am I missing something or is this not possible? TIA

Body:
I have been using mutt with my gmail account and recently got told that the emails I send look odd on some devices, particularly mobiles.

e.g.:

This is a wrapped sentence, and
it should display in a nice
fashion
but for some reason it does not
when it is received on some devices
I am
hoping that someone can help me with
this.

I have set text_flowed=yes in my muttrc, and compose with formatoptions+=w in my vim settings to add a space to the end of each line.

In gmail I can selected 'plain text mode' in the compose window, but can't see anywhere to permanently set this.

After all of this when I compose an email and then send it it still appears badly formatted/not text flowed as above. I've been through various blog posts/SO questions but can't seem to get this to work. Am I missing something or is this not possible? TIA


问:
store all numbers from the array that has index 0 in another array in another function and calculate their average
```<code>#include <stdio.h>

float avg_km(int jogador[], int n) {
  #define MAX 1000

  int zero[MAX];
  int i, j = 0, sum = 0;
  float avg;

  for (i = 0; i < n; i++) {
    if (i == 0) {
      zero[j] = jogador[i];
      j++;
    }
  }

  for (i = 0; i < j; i++) {
    sum += zero[i];
  }

  avg = (float)sum / j;

  return avg;
}

void test_worldcup() {
  #define MAX 1000

  int jogador[MAX];
  int i = 0;
  float avg;

  while (scanf("%d", &jogador[i]) != EOF) {
    i++;
  }

  // chama a função avg_km para calcular a média dos valores do array com índice zero
  avg = avg_km(jogador, i);

  printf("%.2f\n", avg);
}

int main() {
  test_worldcup();

  return 0;
}
</code>```

I am practicing some exercises to take an exam at the university in a month but I am stuck on this exercise that seems very easy but I don't know what to do. Supposedly I need to have a main function that "calls" another function called test_worldcup in this function I have to store the inputs and write the answer using another function called avg_km, what I need to do in this function is calculate the average of all the numbers with index 0 of all the arrays that were placed, this code is what I have until now but I don't know what else to do.

Any tip?

Body:
#include <stdio.h>

float avg_km(int jogador[], int n) {
  #define MAX 1000

  int zero[MAX];
  int i, j = 0, sum = 0;
  float avg;

  for (i = 0; i < n; i++) {
    if (i == 0) {
      zero[j] = jogador[i];
      j++;
    }
  }

  for (i = 0; i < j; i++) {
    sum += zero[i];
  }

  avg = (float)sum / j;

  return avg;
}

void test_worldcup() {
  #define MAX 1000

  int jogador[MAX];
  int i = 0;
  float avg;

  while (scanf("%d", &jogador[i]) != EOF) {
    i++;
  }

  // chama a função avg_km para calcular a média dos valores do array com índice zero
  avg = avg_km(jogador, i);

  printf("%.2f\n", avg);
}

int main() {
  test_worldcup();

  return 0;
}

I am practicing some exercises to take an exam at the university in a month but I am stuck on this exercise that seems very easy but I don't know what to do. Supposedly I need to have a main function that "calls" another function called test_worldcup in this function I have to store the inputs and write the answer using another function called avg_km, what I need to do in this function is calculate the average of all the numbers with index 0 of all the arrays that were placed, this code is what I have until now but I don't know what else to do.

Any tip?


问:
How can I make responsive display that scales layouts and widgets inside them when I resize window at runtime with PyQt6 and Q tDesigner?
This seems something that should be very simple, but for whatever resason I've been looking for a solution for hours now.

Here is example window:

The buttons are on a grid layout. Grid layouts right side ends where right buttons end. When I resize the window at runtime I want buttons to scale down with the window. Instead buttons stay the way they are and I get this:

I have found many examples with c++, but nothing that works with PyQt.


问:
Receiving Error: 'apxs' command appears not to be installed
This is the error I am receiving:
RuntimeError: The 'apxs' command appears not to be installed or is not executable. Please check the list of prerequisites in the documentation for this package and install any missing Apache httpd server packages.

How can I get around this? I have received this while trying to install different packages. I am working on a Django project. I have already made sure the apache2-dev package is installed. I am developing on linux.


问:
Debug javascript file in the browser that was received via ajax
I want to debug a JavaScript file in the browser that was received via AJAX. After locating the .js file in the Network tab, I double click and it does not open in the Debug tab. Instead, it opens a new tab. How can I solve this?

I've already completed some procedures in the browser configuration and they didn't work. This file comes from an AJAX request using JQuery


问:
Failed to bind to address https://localhost:7090 - The server mode SSL must use a certificate with the associated private key
We've been trying to fix a developer's machine with all sorts of HTTPS issues running:

Windows 11

Visual Studio 2022

A .NET 7 C# MVC application

When we attempt to start debugging in Visual Studio, it fails on app.Run() with the following exception:

```<code>System.IO.IOException
  HResult=0x80131620
  Message=Failed to bind to address https://localhost:7090.
  Source=Microsoft.AspNetCore.Server.Kestrel.Core
  StackTrace:
   at Microsoft.AspNetCore.Server.Kestrel.Core.LocalhostListenOptions.<BindAsync>d__2.MoveNext()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.<BindAsync>d__2.MoveNext()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.<BindAsync>d__0.MoveNext()
  at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.<BindAsync>d__33.MoveNext()
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.<StartAsync>d__30`1.MoveNext()
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.<StartAsync>d__37.MoveNext()
   at Microsoft.Extensions.Hosting.Internal.Host.<StartAsync>d__12.MoveNext()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at Program.<Main>$(String[] args) in C:\MyApp\Program.cs:line 78

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
AggregateException: One or more errors occurred. (The server mode SSL must use a certificate with the associated private key.) (The server mode SSL must use a certificate with the associated private key.)

Inner Exception 2:
NotSupportedException: The server mode SSL must use a certificate with the associated private key.
</code>```

We recently reinstalled IIS and Visual Studio to get the IIS Express Development Certificate regenerated on the machine. It was then exported from Personal->Certificates and imported into Trusted Root Certification Authorities->Certificates.

We also tried using dotnet dev-certs https to generate a certificate as well. It does say:

```<code>A trusted certificate was found: 5DA2.....AFAC - CN=localhost - Valid from 2022-12-09 15:33:53Z to 2023-12-09 15:33:53Z - IsHttpsDevelopmentCertificate: true - IsExportable: true
</code>```

When we deploy the .NET 7 application and run it through the local IIS, the page loads, but some static content files (like jquery.js and site.css) will error out with ERR_CONNECTION_RESET and sometimes the page will just load forever without timing out.  The Event Viewer reports nothing out of the ordinary.  And everything works fine under HTTP.

Body:
We've been trying to fix a developer's machine with all sorts of HTTPS issues running:

Windows 11

Visual Studio 2022

A .NET 7 C# MVC application

When we attempt to start debugging in Visual Studio, it fails on app.Run() with the following exception:

System.IO.IOException
  HResult=0x80131620
  Message=Failed to bind to address https://localhost:7090.
  Source=Microsoft.AspNetCore.Server.Kestrel.Core
  StackTrace:
   at Microsoft.AspNetCore.Server.Kestrel.Core.LocalhostListenOptions.<BindAsync>d__2.MoveNext()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.<BindAsync>d__2.MoveNext()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.<BindAsync>d__0.MoveNext()
  at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.<BindAsync>d__33.MoveNext()
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.<StartAsync>d__30`1.MoveNext()
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.<StartAsync>d__37.MoveNext()
   at Microsoft.Extensions.Hosting.Internal.Host.<StartAsync>d__12.MoveNext()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at Program.$(String[] args) in C:\MyApp\Program.cs:line 78

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
AggregateException: One or more errors occurred. (The server mode SSL must use a certificate with the associated private key.) (The server mode SSL must use a certificate with the associated private key.)

Inner Exception 2:
NotSupportedException: The server mode SSL must use a certificate with the associated private key.

We recently reinstalled IIS and Visual Studio to get the IIS Express Development Certificate regenerated on the machine. It was then exported from Personal->Certificates and imported into Trusted Root Certification Authorities->Certificates.

We also tried using dotnet dev-certs https to generate a certificate as well. It does say:

A trusted certificate was found: 5DA2.....AFAC - CN=localhost - Valid from 2022-12-09 15:33:53Z to 2023-12-09 15:33:53Z - IsHttpsDevelopmentCertificate: true - IsExportable: true

When we deploy the .NET 7 application and run it through the local IIS, the page loads, but some static content files (like jquery.js and site.css) will error out with ERR_CONNECTION_RESET and sometimes the page will just load forever without timing out.  The Event Viewer reports nothing out of the ordinary.  And everything works fine under HTTP.


问:
Open database backup file with .backup extension typically used with pgAdmin
I received a database backup file from a governmental org with a .backup extension. It is about 1.4 GB. They said "This is a database backup file that we use within pgAdmin typically."

Would I need to install pgAdmin in order to view the contents? I have tried MS Excel and Notepad ++ but the file is too large. I do have MS Access, but I cannot seem to import it. Also I have SQL Server but I am not proficient in it.


问:
How to build an app from Visual Studio Code
I have a small python programme here I’d like to make into an executable. I wrote it down in Visual Studio Code. How do I do this?

I’m guessing that because VS code is just a code editor it probably doesn’t have the function to build? The search results from online are all about standard VS

What should I be using to build? Is this done through command line using just the already installed python


问:
How can I ensure browser compatibility for the webcrypto API in Typescript?
So, what I'm trying to achieve is to use the Webcrypto API in Typescript and compile it to Javascript code that runs in the browser.
In the Browser, accessing the Webcrypto API is simple. Just window.crypto or crypto for short.
In node.js, you have to import it from the built-in "crypto" library first:

import { webcrypto as crypto } from "crypto"
```
<p>Since I want to run it in the browser, I don't have to and also can not import it.</p>
<p>And here is the problem: For Typescript, I have to import the node library to get the necessary types. If I don't, this is the error:</p>
```src/main.ts:15:43 - error TS2503: Cannot find namespace 'crypto'.
```
<p>So, for Typescript to compile, I have to import "crypto", but for the browser to run it I must not.</p>
<p>Possible work-arounds I can think of are:</p>
<ul>
<li>tell Typescript that "crypto" (window.crypto) exists and is equivalent to crypto.webcrypto from the node library</li>
<li>tell Typescript to not include the line with the import in the output Javascript file</li>
<li>tell the browser to ignore that import</li>
</ul>
<p>None of those I could find in the internet.</p>
<p>What I also tried is to use a dynamic import so I can conditionally import it, something like:</p>
<pre class="lang-js prettyprint-override"><code>let _crypto: any = window?.crypto
if (!_crypto) {
    _crypto = await import("crypto")
}
const crypto: any = _crypto
</code>```

In theory, this should make the browser just ignore that "crypto" import since window.crypto exists.
But Typescript doesn't import the necessary types for dynamic imports for some reason.

In case this is needed, this is part of my code:

export function sign(privkey: crypto.CryptoKey, data: any) {
    data = YSON.stringify(data)
    data = new TextEncoder().encode(data).buffer
    return crypto.subtle.sign({name: "ECDSA", hash: {name: "SHA-256"}}, privkey, data)
}
```

This function takes some data, stringifies it, and signs it using a private key.
The Y in YSON is intended.

The error is in the first line of that code snippet, I'm using the crypto.CryptoKey type.

Body:
So, what I'm trying to achieve is to use the Webcrypto API in Typescript and compile it to Javascript code that runs in the browser.
In the Browser, accessing the Webcrypto API is simple. Just window.crypto or crypto for short.
In node.js, you have to import it from the built-in "crypto" library first:

import { webcrypto as crypto } from "crypto"

Since I want to run it in the browser, I don't have to and also can not import it.

And here is the problem: For Typescript, I have to import the node library to get the necessary types. If I don't, this is the error:

src/main.ts:15:43 - error TS2503: Cannot find namespace 'crypto'.

So, for Typescript to compile, I have to import "crypto", but for the browser to run it I must not.

Possible work-arounds I can think of are:

tell Typescript that "crypto" (window.crypto) exists and is equivalent to crypto.webcrypto from the node library

tell Typescript to not include the line with the import in the output Javascript file

tell the browser to ignore that import

None of those I could find in the internet.

What I also tried is to use a dynamic import so I can conditionally import it, something like:

let _crypto: any = window?.crypto
if (!_crypto) {
    _crypto = await import("crypto")
}
const crypto: any = _crypto

In theory, this should make the browser just ignore that "crypto" import since window.crypto exists.
But Typescript doesn't import the necessary types for dynamic imports for some reason.

In case this is needed, this is part of my code:

export function sign(privkey: crypto.CryptoKey, data: any) {
    data = YSON.stringify(data)
    data = new TextEncoder().encode(data).buffer
    return crypto.subtle.sign({name: "ECDSA", hash: {name: "SHA-256"}}, privkey, data)
}

This function takes some data, stringifies it, and signs it using a private key.
The Y in YSON is intended.

The error is in the first line of that code snippet, I'm using the crypto.CryptoKey type.


问:
Google script to stay/function without being "activated" on duplicate sheets
I have a Google Sheet "Template" that will be duplicated several hundred times. I use Document Studio to merge certain data into specific fields (like invoices). Once the worksheets have been duplicated with customer specific data, I want the google script to function for the customer without them needing to "Validate" the script. For instance, customers with a certain code have a column that hides by using the script.

I just tested the process and I'm guessing because of the use of Document Studio, it's not carrying over the scripts?

Any help is appreciated!

Once the worksheets have been duplicated with customer specific data, I want the google script to function for the customer without them needing to "Validate" the script. For instance, customers with a certain code have a column that hides. Because the script isn't validated, they are seeing the column that should be hidden.

I just tested the process and I'm guessing because I use Document Studio, it's not carrying over the scripts?

Any help is appreciated!


问:
SocketIo behind traefik and reverse proxy. Unable to connect
I am unable to connect to socketio in production.
This is my traefik file. my backend gets all calls which go to /api....

```<code>  backend:
build:
  context: ./backend
  dockerfile: Dockerfile
command: ["npm", "run", "start"]
labels:
  - "traefik.enable=true"
  - "traefik.http.routers.backend.rule=Host(`mydomain.com`) && PathPrefix(`/api`)"

networks:
  - web
</code>```

My express server:

```<code>export const io = new Server(server, {
  cors: {
    origin: [
      "http://localhost:5173",
      "https://mysecretdomain.com",
    ],
  },
});
</code>```

My react frontend:

```<code>let socket: any;
if (import.meta.env.MODE === 'development') {
  socket = io(API_CONFIGS.SOCKET_IO_URL);
} else {
  // the app runs with traefik and is available under the prefix /api

  socket = io(API_CONFIGS.SOCKET_IO_URL, { path: '/api/socket.io' });
}
</code>```

In Development, everything works fine but in prod im getting a 404 error

example call from my domain

```<code>https://mysecretdomain/api/socket.io/?EIO=4&transport=polling&t=OKSmUX8
Status:404
</code>```

I am completly out of ideas. Can someone help me out?

Body:
I am unable to connect to socketio in production.
This is my traefik file. my backend gets all calls which go to /api....

  backend:
build:
  context: ./backend
  dockerfile: Dockerfile
command: ["npm", "run", "start"]
labels:
  - "traefik.enable=true"
  - "traefik.http.routers.backend.rule=Host(`mydomain.com`) && PathPrefix(`/api`)"

networks:
  - web

My express server:

export const io = new Server(server, {
  cors: {
    origin: [
      "http://localhost:5173",
      "https://mysecretdomain.com",
    ],
  },
});

My react frontend:

let socket: any;
if (import.meta.env.MODE === 'development') {
  socket = io(API_CONFIGS.SOCKET_IO_URL);
} else {
  // the app runs with traefik and is available under the prefix /api

  socket = io(API_CONFIGS.SOCKET_IO_URL, { path: '/api/socket.io' });
}

In Development, everything works fine but in prod im getting a 404 error

example call from my domain

https://mysecretdomain/api/socket.io/?EIO=4&transport=polling&t=OKSmUX8
Status:404

I am completly out of ideas. Can someone help me out?


问:
I'm trying to do a taskscheduler and am getting this error message
My script looks like this

```<code>taskscheduler_create(taskname = "test_run2", rscript = "C:/Fol1/FOLD2/Fol3/Folder 4/Good Folder 5/Folder-6/Folder7/1_Load_Files.R",
                 schedule = "MONTH", starttime = format(Sys.time() + 50, "%H:%M"),startdate = format(Sys.Date()+1, "%m/%d/%Y"), modifier = 1)
</code>```

The script on its own works. I have issue when i change the parameters to daily or monthly and it then does not work.

I get this error message

```<code>"ERROR: Value for '/TR' option cannot be more than 261 character(s)."
 attr(,"status")
 [1] 16389

</code>```

Body:
My script looks like this

taskscheduler_create(taskname = "test_run2", rscript = "C:/Fol1/FOLD2/Fol3/Folder 4/Good Folder 5/Folder-6/Folder7/1_Load_Files.R",
                 schedule = "MONTH", starttime = format(Sys.time() + 50, "%H:%M"),startdate = format(Sys.Date()+1, "%m/%d/%Y"), modifier = 1)

The script on its own works. I have issue when i change the parameters to daily or monthly and it then does not work.

I get this error message

"ERROR: Value for '/TR' option cannot be more than 261 character(s)."
 attr(,"status")
 [1] 16389


问:
RenderDT is bleeding over the area that shiny giving it
The fluid box or row will not allow all of the columns to be in the box or increase the size of the box to what I need it to be. is there not a way for the white background to match the amount of the table's columns?

Here is the UI code.

```<code> tabPanel("School Vaccine Exemptions", h1('School Vaccine Exemptions', style = 'color: #23A595'),
                        p('Here we will have a paragraph of explanatory text to talk about the graphs below. Here we will have a paragraph of explanatory text to talk about the graphs below. Here we will have a paragraph of explanatory text to talk about the graphs below. Here we will have a paragraph of explanatory text to talk about the graphs below. Here we will have a paragraph of explanatory text to talk about the graphs below.', style = 'color: white'),
                        fluidRow(
                          selectizeInput("school_name","Enter School Name",
                                         choices = NULL,
                                         selected = NULL,
                                         multiple = FALSE,
                                         options = list(create = FALSE)),
                          box(dataTableOutput(outputId = "school_table")),
                          )

</code>```

I am just simply trying to get the table to render correctly then other formatting will be applied.

```<code>  output$school_table <- renderDT(

    school_data_with_exempt_rates_outputtable,options = list(columns.width = "5px"
                                                             ),
    rownames= FALSE

    )
</code>```

Body:
The fluid box or row will not allow all of the columns to be in the box or increase the size of the box to what I need it to be. is there not a way for the white background to match the amount of the table's columns?

Here is the UI code.

 tabPanel("School Vaccine Exemptions", h1('School Vaccine Exemptions', style = 'color: #23A595'),
                        p('Here we will have a paragraph of explanatory text to talk about the graphs below. Here we will have a paragraph of explanatory text to talk about the graphs below. Here we will have a paragraph of explanatory text to talk about the graphs below. Here we will have a paragraph of explanatory text to talk about the graphs below. Here we will have a paragraph of explanatory text to talk about the graphs below.', style = 'color: white'),
                        fluidRow(
                          selectizeInput("school_name","Enter School Name",
                                         choices = NULL,
                                         selected = NULL,
                                         multiple = FALSE,
                                         options = list(create = FALSE)),
                          box(dataTableOutput(outputId = "school_table")),
                          )

I am just simply trying to get the table to render correctly then other formatting will be applied.

  output$school_table <- renderDT(

    school_data_with_exempt_rates_outputtable,options = list(columns.width = "5px"
                                                             ),
    rownames= FALSE

    )


问:
Django return a ManyToMany field from other class in HTML
I have two classes in django:

```<code>class MovementsGyn(models.Model):

    gyn_name = models.CharField('Name', max_length=70)
    gyn_desc = models.TextField('Description', blank=True, null=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        ordering = ['id']

class Rod(models.Model):
    Rod_name = models.CharField('Rod Name', max_length=70)
    movements_gym = models.ManyToManyField(MovementsGyn)
        owner = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
             ordering = ['id']
</code>```

And a view to show the result grouped:

```<code>def estatistica(request):
    template = 'moviment.html'
    estatic_movem_gyn = Rod.objects.filter(owner=request.user) \
                        .values('movements_gym__gyn_name').order_by('movements_gym__gyn_name') \
                        .annotate(qtde=Count('id'))

    context = {
        'estatic_movem_gyn' : estatic_movem_gyn
    }
    return render(request, template_name, context)
</code>```

The result, in Postgress, is gyn_name grouped and, in qtde, the quantity of register that we have in database.

But i'm havving problema to show it in HTML:

```<code>{% for estatic_movem_gyn in estatic_movem_gyn %}
                                    <tr>
                                        <td>{{  estatic_movem_gyn.gyn_name }}</td>
                                        <td>{{  estatic_movem_gyn.qtde }}</td>
                                    </tr>
                            {% endfor %}
</code>```

The qtde appears but HTML doesn't show gyn_name.

Body:
I have two classes in django:

class MovementsGyn(models.Model):

    gyn_name = models.CharField('Name', max_length=70)
    gyn_desc = models.TextField('Description', blank=True, null=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        ordering = ['id']

class Rod(models.Model):
    Rod_name = models.CharField('Rod Name', max_length=70)
    movements_gym = models.ManyToManyField(MovementsGyn)
        owner = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
             ordering = ['id']

And a view to show the result grouped:

def estatistica(request):
    template = 'moviment.html'
    estatic_movem_gyn = Rod.objects.filter(owner=request.user) \
                        .values('movements_gym__gyn_name').order_by('movements_gym__gyn_name') \
                        .annotate(qtde=Count('id'))

    context = {
        'estatic_movem_gyn' : estatic_movem_gyn
    }
    return render(request, template_name, context)

The result, in Postgress, is gyn_name grouped and, in qtde, the quantity of register that we have in database.

But i'm havving problema to show it in HTML:

{% for estatic_movem_gyn in estatic_movem_gyn %}

                                        {{  estatic_movem_gyn.gyn_name }}
                                        {{  estatic_movem_gyn.qtde }}

                            {% endfor %}

The qtde appears but HTML doesn't show gyn_name.


问:
Iterate over constraints in Clang static Analyzer
I am developing a Clang static analyzer. In this analyzer, I need to iterate over the constraints in a RangedConstraintManager, but it seems this class is not public and I can't call its methods nor access its variables.

Is there any way to bypass this problem?

My current solution is to print the constraints using printJson method of ConstraintManager class and use its output to implement the logic of my analyzer in a program separated from Clang source code. However, it will be much better if I can implement the analyzer in Clang source code itself. (e.g. to later contribute to LLVM project)


问:
How to decode Windows-1254 file to a readable format in Python
I have a file that contains a Windows-1254 encoded data and I want to decode it to a readable format with python but I have no success so far.

I tried this code but I am getting an erorr:

```<code>file = open('file_name', 'rb')
content_of_file = file.read()
file.close()
decoded_data = content_of_file.decode('cp1254') # here I am trying to decode that file
print(decoded_data)
</code>```

This is the error that I get:

Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.10/encodings/cp1254.py", line 15, in decode
return codecs.charmap_decode(input,errors,decoding_table)
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 658: character maps to

The way that I now that this file was encoded in Windows-1254 is by using the chardet.detect(data)['encoding'] so keep that in mind.

Does someone knows how can I decode taht data in a way I could understand it?

this is the file content if someone need it.
b'c\x00\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00C\x00\x00\x00s3\x03\x00\x00d\x01\x00\x01\x03\x03\x03\t\x02\x02\t\x03\x03\x03\t\x02\x02\td\x02\x00d\x00\x00l\x00\x00}\x01\x00d\x02\x00d\x00\x00l\x01\x00}\x02\x00t\x02\x00\x83\x00\x00}\x03\x00d\x03\x00}\x00\x00t\x03\x00|\x03\x00\x83\x01\x00d\x04\x00k\x03\x00rZ\x00d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\xd0\x02|\x03\x00d\x06\x00\x19d\x07\x00k\x03\x00ry\x00d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00t\x05\x00|\x03\x00d\x08\x00\x19\x83\x01\x00d\t\x00Ad\n\x00k\x03\x00r\xa2\x00d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d\x0b\x00d\x0c\x00!d\x00\x00d\x00\x00d\x02\x00\x85\x03\x00\x19j\x06\x00d\r\x00\x83\x01\x00s\xd4\x00d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00t\x07\x00d\x0e\x00\x83\x01\x00\x19j\x08\x00\x83\x00\x00\x0co\x07\x01|\x03\x00t\x07\x00d\x0e\x00\x83\x01\x00\x19d\x0f\x00j\t\x00d\x10\x00\x83\x01\x00k\x02\x00s\x19\x01d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00|\x01\x00j\n\x00d\x11\x00d\x04\x00\x83\x02\x00d\x06\x00\x14d\x11\x00\x17\x19j\x0b\x00d\x12\x00\x83\x01\x00d\x13\x00k\x03\x00rU\x01d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00t\x05\x00|\x03\x00d\x14\x00\x19\x83\x01\x00t\x05\x00|\x03\x00d\x15\x00\x19\x83\x01\x00Ad\x16\x00k\x03\x00s\x89\x01|\x03\x00d\x14\x00\x19d\x17\x00k\x03\x00r\x98\x01d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d\x18\x00\x19d\x19\x00j\t\x00d\x1a\x00\x83\x01\x00k\x03\x00r\xc0\x01d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d\x1b\x00\x19d\x1c\x00j\x0c\x00d\x1c\x00d\x1d\x00\x83\x02\x00k\x03\x00r\xeb\x01d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00t\r\x00d\x1e\x00d\x0b\x00\x83\x02\x00\x19t\x0e\x00d\x11\x00\x83\x01\x00d\x1f\x00\x17j\t\x00d\x10\x00\x83\x01\x00k\x03\x00r&\x02d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d \x00d!\x00!j\x0c\x00d"\x00d\x00\x00d\x00\x00d\x02\x00\x85\x03\x00\x19d\x1c\x00\x83\x02\x00d\x1c\x00k\x03\x00ra\x02d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d!\x00\x19t\x0f\x00i\x00\x00\x83\x01\x00j\x10\x00d\x0b\x00\x19k\x03\x00r\x8d\x02d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d#\x00\x19t\x0e\x00d\x06\x00\x83\x01\x00k\x03\x00r\xb2\x02d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d$\x00\x19d%\x00k\x07\x00r\xd1\x02d&\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x02\x00j\x01\x00|\x03\x00d'\x00\x19\x83\x01\x00j\x11\x00\x83\x00\x00d(\x00k\x03\x00r\xff\x02d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00t\x05\x00|\x03\x00d)\x00\x19\x83\x01\x00t\x07\x00d*\x00\x83\x01\x00k\x03\x00r*\x03d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00d+\x00GHd\x00\x00S(,\x00\x00\x00Ns\x1a\x00\x00\x00#Import random,md5 modulesi\xff\xff\xff\xffs\x14\x00\x00\x00#Start checking flagi\x12\x00\x00\x00s\x05\x00\x00\x00NO!!!i\x00\x00\x00\x00t\x01\x00\x00\x00Mi\x01\x00\x00\x00i\xff\x00\x00\x00i\xaa\x00\x00\x00i\x02\x00\x00\x00i\x04\x00\x00\x00t\x02\x00\x00\x00HCs\x10\x00\x00\x00([] > {}) << -~1t\x02\x00\x00\x007bt\x03\x00\x00\x00hexi\x05\x00\x00\x00t\x06\x00\x00\x00base64s\x05\x00\x00\x00ZA==\ni\x06\x00\x00\x00i\x07\x00\x00\x00i\x1a\x00\x00\x00t\x01\x00\x00\x00ii\x08\x00\x00\x00t\x01\x00\x00\x00nt\x05\x00\x00\x00rot13i\t\x00\x00\x00t\x00\x00\x00\x00t\x01\x00\x00\x00st\x04\x00\x00\x001010t\x01\x00\x00\x00fi\x0b\x00\x00\x00i\r\x00\x00\x00t\x02\x00\x00\x00ypi\x0e\x00\x00\x00i\x0f\x00\x00\x00t\x08\x00\x00\x00dddddddds\x06\x00\x00\x00NO!!!!i\x10\x00\x00\x00t \x00\x00\x00eccbc87e4b5ce2fe28308fd9f2a7baf3i\x11\x00\x00\x00sM\x00\x00\x00~(~(~((((~({}<[])<<({}<[]))<<({}<[]))<<({}<[]))<<({}<[]))<<({}<[]))<<({}<[]))s\n\x00\x00\x00Bazinga!!!(\x12\x00\x00\x00t\x06\x00\x00\x00randomt\x03\x00\x00\x00md5t\t\x00\x00\x00raw_inputt\x03\x00\x00\x00lent\x04\x00\x00\x00quitt\x03\x00\x00\x00ordt\n\x00\x00\x00startswitht\x04\x00\x00\x00evalt\x07\x00\x00\x00isalphat\x06\x00\x00\x00decodet\x07\x00\x00\x00randintt\x06\x00\x00\x00encodet\x07\x00\x00\x00replacet\x03\x00\x00\x00intt\x03\x00\x00\x00strt\x04\x00\x00\x00typet\x08\x00\x00\x00__name__t\t\x00\x00\x00hexdigest(\x04\x00\x00\x00t\x07\x00\x00\x00commentR\x0f\x00\x00\x00R\x10\x00\x00\x00t\x03\x00\x00\x00ans(\x00\x00\x00\x00(\x00\x00\x00\x00sA\x00\x00\x00XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXt\x0c\x00\x00\x00get_the_flag\x0b\x00\x00\x00sl\x00\x00\x00\x00\x02\x12\x01\x0c\x01\x0c\x01\t\x02\x06\x01\x12\x01\x05\x01\n\x02\x10\x01\x05\x01\n\x01\x1a\x01\x05\x01\n\x01#\x01\x05\x01\n\x016\x01\x05\x01\n\x01-\x01\x05\x01\n\x014\x01\x05\x01\n\x01\x19\x01\x05\x01\n\x01\x1c\x01\x05\x01\n\x01,\x01\x05\x01\n\x01,\x01\x05\x01\n\x01\x1d\x01\x05\x01\n\x01\x16\x01\x05\x01\n\x01\x10\x01\x05\x01\n\x01\x1f\x01\x05\x01\n\x01\x1c\x01\x05\x01\n\x01'

Body:
I have a file that contains a Windows-1254 encoded data and I want to decode it to a readable format with python but I have no success so far.

I tried this code but I am getting an erorr:

file = open('file_name', 'rb')
content_of_file = file.read()
file.close()
decoded_data = content_of_file.decode('cp1254') # here I am trying to decode that file
print(decoded_data)

This is the error that I get:

Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.10/encodings/cp1254.py", line 15, in decode
return codecs.charmap_decode(input,errors,decoding_table)
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 658: character maps to

The way that I now that this file was encoded in Windows-1254 is by using the chardet.detect(data)['encoding'] so keep that in mind.

Does someone knows how can I decode taht data in a way I could understand it?

this is the file content if someone need it.
b'c\x00\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00C\x00\x00\x00s3\x03\x00\x00d\x01\x00\x01\x03\x03\x03\t\x02\x02\t\x03\x03\x03\t\x02\x02\td\x02\x00d\x00\x00l\x00\x00}\x01\x00d\x02\x00d\x00\x00l\x01\x00}\x02\x00t\x02\x00\x83\x00\x00}\x03\x00d\x03\x00}\x00\x00t\x03\x00|\x03\x00\x83\x01\x00d\x04\x00k\x03\x00rZ\x00d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\xd0\x02|\x03\x00d\x06\x00\x19d\x07\x00k\x03\x00ry\x00d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00t\x05\x00|\x03\x00d\x08\x00\x19\x83\x01\x00d\t\x00Ad\n\x00k\x03\x00r\xa2\x00d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d\x0b\x00d\x0c\x00!d\x00\x00d\x00\x00d\x02\x00\x85\x03\x00\x19j\x06\x00d\r\x00\x83\x01\x00s\xd4\x00d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00t\x07\x00d\x0e\x00\x83\x01\x00\x19j\x08\x00\x83\x00\x00\x0co\x07\x01|\x03\x00t\x07\x00d\x0e\x00\x83\x01\x00\x19d\x0f\x00j\t\x00d\x10\x00\x83\x01\x00k\x02\x00s\x19\x01d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00|\x01\x00j\n\x00d\x11\x00d\x04\x00\x83\x02\x00d\x06\x00\x14d\x11\x00\x17\x19j\x0b\x00d\x12\x00\x83\x01\x00d\x13\x00k\x03\x00rU\x01d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00t\x05\x00|\x03\x00d\x14\x00\x19\x83\x01\x00t\x05\x00|\x03\x00d\x15\x00\x19\x83\x01\x00Ad\x16\x00k\x03\x00s\x89\x01|\x03\x00d\x14\x00\x19d\x17\x00k\x03\x00r\x98\x01d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d\x18\x00\x19d\x19\x00j\t\x00d\x1a\x00\x83\x01\x00k\x03\x00r\xc0\x01d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d\x1b\x00\x19d\x1c\x00j\x0c\x00d\x1c\x00d\x1d\x00\x83\x02\x00k\x03\x00r\xeb\x01d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00t\r\x00d\x1e\x00d\x0b\x00\x83\x02\x00\x19t\x0e\x00d\x11\x00\x83\x01\x00d\x1f\x00\x17j\t\x00d\x10\x00\x83\x01\x00k\x03\x00r&\x02d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d \x00d!\x00!j\x0c\x00d"\x00d\x00\x00d\x00\x00d\x02\x00\x85\x03\x00\x19d\x1c\x00\x83\x02\x00d\x1c\x00k\x03\x00ra\x02d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d!\x00\x19t\x0f\x00i\x00\x00\x83\x01\x00j\x10\x00d\x0b\x00\x19k\x03\x00r\x8d\x02d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d#\x00\x19t\x0e\x00d\x06\x00\x83\x01\x00k\x03\x00r\xb2\x02d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x03\x00d$\x00\x19d%\x00k\x07\x00r\xd1\x02d&\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00|\x02\x00j\x01\x00|\x03\x00d'\x00\x19\x83\x01\x00j\x11\x00\x83\x00\x00d(\x00k\x03\x00r\xff\x02d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00t\x05\x00|\x03\x00d)\x00\x19\x83\x01\x00t\x07\x00d*\x00\x83\x01\x00k\x03\x00r*\x03d\x05\x00GHt\x04\x00\x83\x00\x00\x01n\x00\x00d+\x00GHd\x00\x00S(,\x00\x00\x00Ns\x1a\x00\x00\x00#Import random,md5 modulesi\xff\xff\xff\xffs\x14\x00\x00\x00#Start checking flagi\x12\x00\x00\x00s\x05\x00\x00\x00NO!!!i\x00\x00\x00\x00t\x01\x00\x00\x00Mi\x01\x00\x00\x00i\xff\x00\x00\x00i\xaa\x00\x00\x00i\x02\x00\x00\x00i\x04\x00\x00\x00t\x02\x00\x00\x00HCs\x10\x00\x00\x00([] > {}) << -~1t\x02\x00\x00\x007bt\x03\x00\x00\x00hexi\x05\x00\x00\x00t\x06\x00\x00\x00base64s\x05\x00\x00\x00ZA==\ni\x06\x00\x00\x00i\x07\x00\x00\x00i\x1a\x00\x00\x00t\x01\x00\x00\x00ii\x08\x00\x00\x00t\x01\x00\x00\x00nt\x05\x00\x00\x00rot13i\t\x00\x00\x00t\x00\x00\x00\x00t\x01\x00\x00\x00st\x04\x00\x00\x001010t\x01\x00\x00\x00fi\x0b\x00\x00\x00i\r\x00\x00\x00t\x02\x00\x00\x00ypi\x0e\x00\x00\x00i\x0f\x00\x00\x00t\x08\x00\x00\x00dddddddds\x06\x00\x00\x00NO!!!!i\x10\x00\x00\x00t \x00\x00\x00eccbc87e4b5ce2fe28308fd9f2a7baf3i\x11\x00\x00\x00sM\x00\x00\x00~(~(~((((~({}<[])<<({}<[]))<<({}<[]))<<({}<[]))<<({}<[]))<<({}<[]))<<({}<[]))s\n\x00\x00\x00Bazinga!!!(\x12\x00\x00\x00t\x06\x00\x00\x00randomt\x03\x00\x00\x00md5t\t\x00\x00\x00raw_inputt\x03\x00\x00\x00lent\x04\x00\x00\x00quitt\x03\x00\x00\x00ordt\n\x00\x00\x00startswitht\x04\x00\x00\x00evalt\x07\x00\x00\x00isalphat\x06\x00\x00\x00decodet\x07\x00\x00\x00randintt\x06\x00\x00\x00encodet\x07\x00\x00\x00replacet\x03\x00\x00\x00intt\x03\x00\x00\x00strt\x04\x00\x00\x00typet\x08\x00\x00\x00__name__t\t\x00\x00\x00hexdigest(\x04\x00\x00\x00t\x07\x00\x00\x00commentR\x0f\x00\x00\x00R\x10\x00\x00\x00t\x03\x00\x00\x00ans(\x00\x00\x00\x00(\x00\x00\x00\x00sA\x00\x00\x00XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXt\x0c\x00\x00\x00get_the_flag\x0b\x00\x00\x00sl\x00\x00\x00\x00\x02\x12\x01\x0c\x01\x0c\x01\t\x02\x06\x01\x12\x01\x05\x01\n\x02\x10\x01\x05\x01\n\x01\x1a\x01\x05\x01\n\x01#\x01\x05\x01\n\x016\x01\x05\x01\n\x01-\x01\x05\x01\n\x014\x01\x05\x01\n\x01\x19\x01\x05\x01\n\x01\x1c\x01\x05\x01\n\x01,\x01\x05\x01\n\x01,\x01\x05\x01\n\x01\x1d\x01\x05\x01\n\x01\x16\x01\x05\x01\n\x01\x10\x01\x05\x01\n\x01\x1f\x01\x05\x01\n\x01\x1c\x01\x05\x01\n\x01'


问:
500 Internal Server Error - Python- Webhook- Google Cloud
I am trying to connect my tradingview with Binance account, after wrote the Python code and tested through the localhost, it works fine. however, I added my files to google cloud it did not work and alway give me

500 Internal Server Error: The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

```<code>import ccxt
import config

exchange = ccxt.binanceusdm({
    'apiKey': config.API_KEY,
    'secret': config.API_SECRET,
    'password': config.PASSPHRASE
})

def Karim_Crypto(request):
    data = request.get_json()
    if 'PASSPHRASE' not in data or data['PASSPHRASE'] != config.PASSPHRASE:
        return {
            "code": "error",
            "message": "You are Unauthorized"
        }

    tickers = {
        'ETHUSDT': 'ETH/USDT',
        'ETHUSDTPERP': 'ETH/USDT'
    }

    ticker = tickers[data['ticker']]
    amount = data['amount']
    side = data['side'].upper()
    type = "MARKET"
    price= "None"
    params= "cross"

    order = exchange.create_order(ticker, type, side, amount)
    return order

</code>```

Body:
I am trying to connect my tradingview with Binance account, after wrote the Python code and tested through the localhost, it works fine. however, I added my files to google cloud it did not work and alway give me

500 Internal Server Error: The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

import ccxt
import config

exchange = ccxt.binanceusdm({
    'apiKey': config.API_KEY,
    'secret': config.API_SECRET,
    'password': config.PASSPHRASE
})

def Karim_Crypto(request):
    data = request.get_json()
    if 'PASSPHRASE' not in data or data['PASSPHRASE'] != config.PASSPHRASE:
        return {
            "code": "error",
            "message": "You are Unauthorized"
        }

    tickers = {
        'ETHUSDT': 'ETH/USDT',
        'ETHUSDTPERP': 'ETH/USDT'
    }

    ticker = tickers[data['ticker']]
    amount = data['amount']
    side = data['side'].upper()
    type = "MARKET"
    price= "None"
    params= "cross"

    order = exchange.create_order(ticker, type, side, amount)
    return order


问:
Azure AD setting up multiple Enterprise Apps for AWS Client VPN
I had success setting up an app for AWS Client VPN in Azure but I can't add another one due to the Entity ID must be unique Entity ID
I had success with other apps adding #1 at the end of the URL but here I am dealing with this URN
How to overcome this, obviously I am a huge noob with SAML.
Thanks in advance.

I have tried adding #1 at the end and other simbols
I am expecting having another app for the same purpose.
I can get away with a solution that would allow using one app in Azure but redirecting to separate Client VPN.


问:
I cannot access my supabase table from my app
Currently I have my insertIntoDB function that takes in values from my formik/MUI form.

```<code>import { supabase } from '../../../Utilities/SupabaseClient';

export const insertIntoDB = async (values) => {
  let error;
  try {
    error = await supabase.from('supplier_initial_assessment_1').insert([{
      comapny_name: values.companyName,
      climate_change_policy: values.climateChangePolicy,
      climate_change_policy_description: values.climateChangePolicyDescription,
      climate_team_responsible: values.climateTeamResponsible,
      climate_team_description: values.climateTeamDescription,
      currently_measure_emissions: values.currentlyMeasureEmissions,
      currently_measured_emissions_program_description:
        values.currentlyMeasuredEmissionsProgramDescription,
      scopes_measured_description: values.scopesMeasuredDescription,
      emissions_data_stored_description: values.emissionsDataStoredDescription,
    }],{ returning: "minimal" });

    console.log(values);
  } catch (error) {
    console.log('Error message', error);
    throw error;
  }
};

</code>```

When I try to submit I get the following error in the dev console
enter image description here

I have tried setting the table RLS to:

```<code>BEGIN;
  ALTER POLICY "Enable insert for authenticated users only" ON "public"."supplier_initial_assessment_1" WITH CHECK (false);
COMMIT;
</code>```

Body:
Currently I have my insertIntoDB function that takes in values from my formik/MUI form.

import { supabase } from '../../../Utilities/SupabaseClient';

export const insertIntoDB = async (values) => {
  let error;
  try {
    error = await supabase.from('supplier_initial_assessment_1').insert([{
      comapny_name: values.companyName,
      climate_change_policy: values.climateChangePolicy,
      climate_change_policy_description: values.climateChangePolicyDescription,
      climate_team_responsible: values.climateTeamResponsible,
      climate_team_description: values.climateTeamDescription,
      currently_measure_emissions: values.currentlyMeasureEmissions,
      currently_measured_emissions_program_description:
        values.currentlyMeasuredEmissionsProgramDescription,
      scopes_measured_description: values.scopesMeasuredDescription,
      emissions_data_stored_description: values.emissionsDataStoredDescription,
    }],{ returning: "minimal" });

    console.log(values);
  } catch (error) {
    console.log('Error message', error);
    throw error;
  }
};

When I try to submit I get the following error in the dev console
enter image description here

I have tried setting the table RLS to:

BEGIN;
  ALTER POLICY "Enable insert for authenticated users only" ON "public"."supplier_initial_assessment_1" WITH CHECK (false);
COMMIT;


Title: I ask user to enter name of"object" for the data they want to receive. But when I enter "1" the output says "Sorry, invalid input" how can I fix it?

Body:
here is my data:

|Object |  HJD 24... |    Filter | Magnitude |
|-------| ---------- |-----------|-----------|
|SU_Hor | 55896.30476|      B    |  14.877   |
|SU_Hor | 55896.27438|     Ic    |  13.885   |
|SU_Hor | 55896.27349|      B    |  14.809   |
|SU_Hor | 55896.27397|      V    |  14.434   |
|SU_Hor | 55896.40882|     Ic    |  14.033   |
|SU_Hor | 55896.40829|      V    |  14.540   |
|SU_Hor | 55896.40770|      B    |  14.941   |
|SU_Hor | 55896.34973|     Ic    |  13.958   |
|SU_Hor | 55896.34943|      V    |  14.494   |
|SU_Hor | 55896.34906|      B    |  14.861   |
|SU_Hor | 55896.30542|     Ic    |  13.912   |
|SU_Hor | 55896.30512|      v    |  14.440   |
|SU_Hor | 55897.38547|      V    |  14.536   |
|SU_Hor | 55897.28281|      B    |  14.882   |
|SU_Hor | 55897.28317|      V    |  14.428   |
|SU_Hor | 55897.28347|     Ic    |  13.927   |
|RZ_Lyr | 27359.3030 |      V    |  10.630   |
|RZ_Lyr | 27684.4510 |      V    |  10.610   |
|RZ_Lyr | 27685.4780 |      V    |  10.580   |
|RZ_Lyr | 27701.3150 |      V    |  10.700   |
|RZ Lyr | 27934.4560 |      V    |  10.660   |
|RZ Lyr | 27955.4100 |      V    |  10.570   |
|rzlyr  | 30604.2000 |      V    |  11.030   |
|RZ_Lyr | 55314.5695 |      B    |  12.047   |
|RZ_Lyr | 55314.5724 |      B    |  12.036   |
|RZ_Lyr | 55314.5900 |      B    |  12.042   |
|RZ_Lyr | 55314.6105 |      B    |  12.045   |
|RZ_Lyr | 55314.6163 |      B    |  12.027   |
|RZ_Lyr | 55342.3509 |      B    |  12.057   |
|RZLyr  | 55342.3557 |      B    |  12.058   |
|RZ_Lyr | 55342.3606 |      B    |  12.052   |
|RZ_Lyr | 55342.3654 |      B    |  12.058   |

my code:

mport csv

def searchByObject():
    object = input('Enter Object name\n')
    csv_file = csv.reader(open("D:/Астрономия Курс 2/PycharmProjects/Python_2ndLab.csv", "r"))

    for column in csv_file:
        if object == column[0]:
            print(column)

def searchByFilter():
    filter = str(input('Enter filter to show data'))
    csv_file = csv.reader(open("D:/Астрономия Курс 2/PycharmProjects/Python_2ndLab.csv", "r"))

    for column in csv_file:
        if filter in column[2]:
            print(column)

print('Enter 1 to search by object name')
print('Enter 2 to search by filter')

src = (input('Enter here: '))

if src == 1:
    searchByObject()
elif src == 2:
    searchByFilter()
else:
    print('Sorry, invalid input')

the Output:

Name: Filter, dtype: object

Enter 1 to search by object name

Enter 2 to search by filter

Enter here: 1
Sorry, invalid input

What I expected the Output will be like:

Name: Filter, dtype: object

Enter 1 to search by object name

Enter 2 to search by filter

Enter here: 1

Enter the object name to show data: SU_Hor
(let's imagine all of the data from SU_Hor appear)