mteb/BrightProStackoverflowRetrieval huggingface dataset:
CannotDeliverBroadcastException On Samsung devices running Android 13 (API 33)

We got lot of crash reports from Firebase regarding this crash.

```
Fatal Exception: android.app.RemoteServiceException$CannotDeliverBroadcastException: can't deliver broadcast
       at android.app.ActivityThread.throwRemoteServiceException(ActivityThread.java:2219)
       at android.app.ActivityThread.-$$Nest$mthrowRemoteServiceException()
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2508)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loopOnce(Looper.java:226)
       at android.os.Looper.loop(Looper.java:313)
       at android.app.ActivityThread.main(ActivityThread.java:8762)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:604)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067)
```

Crash happens only on Samsung devices running android 13 (API 33)

We followed this post CannotDeliverBroadcastException only on Pixel devices running Android 12

The thing is - we can't just silence/absorb this crash, as some of our app functionality is build on the broadcast (BroadcastReceiver, registered in Manifest).

We need to actually prevent this crash (somehow :))

We checked also this one on google issue tracker but it seems there is no solution https://issuetracker.google.com/issues/245258072

Any of you found a solution for this? Thanks
How to control Argo(helm) flow with Script output

I have a script defined in Argo WorkflowTemplate as follows. This may either print status:true or status:false (I have simplified this)

```
- name:util-script
    script:
      image: python3
      command: ["python3"]
      script |
         print(status:true)
```

Is there a way to control dag flow based on the above script output? I know helm provides flow control like Helm Doc - Flow control

Following is what I tried so far, but this always jumps to else condition. anything Im doing wrong? Appreciate any input on this

```
{{- if contains "status:true" `tasks.util-script.outputs.result` }}
  # even result is `status:true`, does not reach here
{{ else }}
  # always reach here
{{ end }}
```

I have verified tasks.util-script.outputs.result indeed returns the expected result.
How can I convert a PredictResponse to JSON?

I have a VertexAI project I want to access. I'm currently trying two approaches, via a React frontend and via a Python backend, which I would then connect to the FE. I posted a question about making requests to VertexAI from Node here.

In the python approach, I'm able to make the request and receive the correct response. However, in order for it to be accessible by the FE, I would need to convert it to JSON. I'm struggling with how to do that.

Here's the code I'm using:

```
# The AI Platform services require regional API endpoints.
client_options = {"api_endpoint": api_endpoint}
# Initialize client that will be used to create and send requests.
# This client only needs to be created once, and can be reused for multiple requests.
client = PredictionServiceClient(
    client_options=client_options, credentials=credentials
)
instance = schema.predict.instance.TextClassificationPredictionInstance(
    content=content,
).to_value()
instances = [instance]
parameters_dict = {}
parameters = json_format.ParseDict(parameters_dict, Value())
endpoint = client.endpoint_path(
    project=project_id, location=compute_region, endpoint=endpoint_id
)
response = client.predict(
    endpoint=endpoint, instances=instances, parameters=parameters
)
response_dict = [dict(prediction) for prediction in response.predictions]
```

`response_dict` is printable, but I can't convert `response` to json using `json.dumps` because:

```
TypeError: Object of type PredictResponse is not JSON serializable
```
This is the error that has been plaguing me in every attempt. DuetAI simply tells me to use `json.dumps`.

EDIT
Here's the working code using the accepted response:
```
    ...
    response = client.predict(
        endpoint=endpoint, instances=instances, parameters=parameters
    )

    predictions = MessageToDict(response._pb)
    predictions = predictions["predictions"][0]
```
How can I initialise a constexpr array with values using std::generate

For example, if I wanted a constexpr std::array<int,100> initialised with all the multiples of 3 from 1-300 at compile time how can I do this?

My first thought was to use std::generate, something like:

```
constexpr std::array<int,100> a { std::generate(a.begin(), a.end(), [n=0]()mutable{ return n+=3; });
```

I get an error such as `<source>:9:52: error: void value not ignored as it ought to be`.

and I can't use std::generate after this because of course, it's read only at that point.
django add filtes in template is not work expectedly

I am a Django and Python beginner, and I encountered a problem while using Django. I hope to use a filter in the template to get the string I need, but the result below is not what I expected.

```
# filter definition

@register.filter
def to_class_name(obj):
    return obj.__class__.__name__
```

```
# HTML template for UpdateView (This template will be used by multiple models.)
# object = Order()

{{ object|to_class_name }} #reulst: Order

{{ 'wms'|add:object|to_class_name }} #result: str, expect: object

```

I roughly understand that the issue lies with the order, but it seems I can't add parentheses to modify it.

```
{{ 'wms'|add:(object|to_class_name) }} #cause SyntaxError
```

Is there any way to solve this problem? Or is there a better way to determine the page data I need to output based on the model class when multiple models share one template? Thank you all.
Saving a scipy.sparse matrix directly as a regular txt file

I have a scipy.sparse matrix (csr_matrix()). But I need to save it to a file not in the .npz format but as a regular .txt or .csv file. My problem is that I don't have enough memory to convert the sparse matrix into a regular np.array() and then save it to a file. Is there a way to have the data as a sparse matrix in memory but save it directly as a regular matrix to the disk? Or is there a way to "unzip" a .npz file without loading it into memory inside Python?
dbms_random.value() in Snowflake - Oracle to snowflake conversion

Below is the oracle sql query that I got to convert to snowflake. In here, i am blocked in creating dbms_random.value() in snowflake

```
select emp_id, emp_name, emp_mob,
(case when dbms_random.value() >= 0.85 then 'Y' else 'N' end) as tag
from eds_dwg.employee_data
```

Can someone help me on this?

Thanks
Command-line to reverse byte order/change endianess

I'm hacking around in some scripts trying to parse some data written by Javas `DataOutputStream#writeLong(...)`. Since java always seems to write big endian, I have a problem feeding the bytes to `od`. This is due to the fact that `od` always assumes that the endianess matches the endianess of the arch that you are currently on, and I'm on a little endian machine.

I'm looking for an easy one-liner to reverse the byte order. Let's say that you know that the last 8 bytes of a file is a long written by the aforementioned `writeLong(...)` method. My current best attempt to print this long is

```
tail -c 8 file | tac | od -t d8
```

, but `tac` only seems to work on text (fair enough). I've found some references to `dd conv=swab`, but this only swaps bytes in pairs, and cannot reverse these eight bytes.

Does anyone know a good one-liner for this?
Vectorization with multiple rows and columns of dataframe instead of one

Currently working on building a csv file that include historical stock info, while not only includes historical prices, but momentum indicators. I've successfully added indicators by looping through an entire dataframe (w/ > 25,000,000 rows), but it takes too long (30 - 36 h).

What I'm trying to accomplish: I'd like start with the the 3 day high:

```
high = stock_df.loc[x+1:x+4, "High"].max(axis=0)
```

and divide that by the day 0 low:
```
low =  stock_df.loc[x, "Low"] 
```

without iterating through entire loop like as shown below:
```
stock_ticker_list = df.Symbol.unique()
for ticker in stock_ticker_list:
    #return dataframe thats historical infor for one stock
    print(ticker)
    stock_df = df.loc[df.Symbol == ticker]
    start = stock_df.index[stock_df['Symbol'] == ticker][0]
    for x in range(start, start + len(stock_df) - 2):
        try:
            high = stock_df.loc[x+1:x+4, "High"].max(axis=0)  
            low =  stock_df.loc[x, "Low"] 
            df2.loc[x,"H/L"] = high/low
        except:
            df2.loc[x,"H/L"] = pd.NA
```

I've look through the documentation and found methods like pandas.Series.pct_change and pandas.Series.div but it does not appear as though these functions will work without me also creating a column for the 3 day high. I tried to create a column for the three day high

```
s = stock_df["High"] 
stock_df['Three_day_high'] = max([s.diff(-1),s.diff(-2),s.diff(-3)]) + s
```

but got a ValueError (`ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().`)
What effect does the `virtual` modifier have on an interface member?

Say I have an interface like interface IThing { virtual string A => "A"; }. What effect does the virtual keyword have on implementing types here? Surprisingly, I couldn't find anything regarding this on either SO, dotnet GitHub pages and discussions, nor on learn.microsoft.com, possibly buried under all the unrelated content where the words interface and virtual appear in any combination. From my quick testing it doesn't appear to have any sensible effect. My intuition tells me to expect from the implementing classes' hierarchy to have been introduced the given virtual members, as if the base implementing class has declared them itself, but it's not the case.

For example:
```
class Thing: IThing
{   
}   
    
class Thing2: Thing
{
    override public string A => "!"; // ERROR: No suitable method found to override.
}
```

If I declare the A property on Thing, but do not declare it explicitly as virtual, it still won't compile. I also have the freedom apparently to just define them w/o the modifier despite it being present in the interface and it compiles. And code using IThing only sees the default implementation of A regardless of what I do unless the class implements the interface directly and not through inheritance in this setup.

Can somebody clarify the use of the virtual modifier on interface members? I use the latest stable language version of C#.
Child component not re-rendering after parent component gets updated

I have 1 parent(Container) and 2 (List, SelectedItem) child components, Initially I render all data to Container and send all data to list and first item as selectedItem to selected Item component. So ar so good

When a user clicks an item in the List component, it updates the selected item of the Parent through a function, the parent is able to update state, But it is not re-rendering selected item component.

List Component:
```
 import "./SelectedImage.css"

function ListSection({items, updateSelectedItem}) {
  return (
    <div className="list-section">
      <ul>
        {
          (items).map((item) => {
            return <li key={item.id} onClick={() => updateSelectedItem(item.id)}>{item.name}</li>
          })
        }
      </ul>
    </div>
  );
}

export default ListSection;
```

Container Component
```
import LeftSection from './LeftSection';
import logo from './logo.svg';
import RightSection from './RightSection ';
import SelectedItem from './SelectedItem';
import "./App.css";
import ListSection from './ListSection';
import { Component, useState } from 'react';

const products = [
  {id: 1, name: "Lime", size: ["large", "medium", "small"], category: "Juice", image: "lime-juice.jpg"},
  {id: 2, name: "Orange", size: ["large", "medium", "small"], category: "Juice", image: "orange-juice.jpg"},
  {id: 3, name: "Mango", size: ["large", "medium", "small"], category: "Juice", image: "mango-juice.jpg"},
]

function Container() {
  let [selectItem, setSelectItem] = useState(products[0]);

  function chooseSelectedItem(id) {
    let item = products.filter((value) => {
      console.log(value.id);
      return (value.id == id)
    })
    setSelectItem(item[0]);
    console.log(item[0]);
  }

  return (
    <div className="Container">
      <ListSection items={products} updateSelectedItem={chooseSelectedItem}/>
      <SelectedItem CurrentSelectedItem={selectItem}/>
    </div>
  );
}

export default Container;
```

SelectedItemComponent

```
import QuantityBar from "./QuantityBar";
import "./SelectedImage.css"
import { useState } from "react";

function SelectedItem({CurrentSelectedItem}) {
  let [item, setItem] = useState(CurrentSelectedItem);  

  return (
    <div className="selected-item">
      {/* <img src={item.image} className="selected-image" /> */}
      {item.name}
      {/* <QuantityBar itemCount={0} /> */}
    </div>
  );
}

export default SelectedItem;
```
How to show python/openCV outcome images on ssh-client, not in ssh server?

I am connected to a ssh server using ssh -Y username@adress. On the server I run python2.7 using IDLE. If I use matplotlib I can see the outcome graphs on client. This suggests the graphical forwarding has no problem. However, when I am using OpenCV:

```
cv2.imshow('img_final', img_final)
cv2.waitKey(0)
cv2.destroyAllWindows()
```

It opens and show the image in the ssh server screen, not in the client ssh computer.

I did search and research, and in response of typical trobleshooting: - On my computer running client-ssh, echo $DISPLAY responds :0. It runs xterm. -On my server ssh computer, My sshd_config file seems to be ok (X11Forwarding yes). echo $DISPLAY shows localhost:10.0.

Moreover, I can use imageviewer such as 'feh' and shows images on client without any problem.

I do not think I have a configuration problem, because server is able to display graphics on client.

Is there a way to execute python scripts on server, and show outcome images from OpenCV directly on client (as MAtplotlib does) ?

Thanks
Selenium code working fine on main laptop, but not on my other one

I wrote some code in Pycharm last year, to loop through VAT numbers entered into the Gov website, to make sure they were still valid. It still works fine on the original laptop, but not on my other laptop, even thought the code is exactly the same (the only adjustment was for the location of the spreadsheet). I have given my code down below. When I try to run it on my other laptop, it comes up with the following error.

```
Traceback (most recent call last): File "C:\Users\neils\Documents\Pycharm Projects\VATChecker\VATChecker.py", line 30, in VAT = web.find_element_by_xpath('//*[@id="target"]') ^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'

Process finished with exit code 1
```

One thing I also notice, is that the import sys and import datetime are both greyed out. I guess that's because it crashed before these imports were used?

I should mention, the version of Chrome is the same for both laptops (version 123), and I have the same chromedriver installed for both. Both laptops are windows 64 bit, in case you're thinking that might be the issue.

Are you able to advise me what the problem is please? Many thanks in advance.

```
import datetime
import sys

from selenium import webdriver
from openpyxl import workbook, load_workbook
from datetime import date

web = webdriver.Chrome()

wb = load_workbook('C:\\Users\\neils\\Documents\\NSO\\Self Billing agreements\\VATMusiciansCheckerUK.xlsx', data_only=True, read_only=False)

ws = wb.active
x=2
y=1
current_datetime = datetime.datetime.now()
current_datetime.strftime('%x %X')

invalid = ""

while ws.cell(x,1).value !=None:

    ws.cell(x,9).value = ""

    web.get("https://www.tax.service.gov.uk/check-vat-number/enter-vat-details")

    web.implicitly_wait(10)

    VatNumber = ws.cell(x,4).value

    VAT = web.find_element_by_xpath('//*[@id="target"]')
    VAT.send_keys(VatNumber)

    VAT.submit()

    web.implicitly_wait(4)

    registered = web.find_element_by_xpath('/html/body/div[2]')
    if (registered.text.find("Invalid")) > 0:
        ws.cell(x,9).value = "Invalid VAT number"
        invalid = invalid + str(y) + " " + ws.cell(x,1).value + " " + ws.cell(x,2).value + ", "
        y=y+1
    else:
        ws.cell(x,9).value = "Valid VAT number"

        ws.cell(x,6).value = current_datetime

    x=x+1

if invalid == "":

    print("All VAT records are correct")
else:
   print("Invalid VAT records are " + invalid)


wb.save('C:\\Users\\neils\\Documents\\NSO\\Self Billing agreements\\VATMusiciansCheckerUK.xlsx')
```
Getting a list of occurrences for a given vCalendar

I'm trying to use vobject, without success, to get a list of datetime objects for all event occurrences (see the RRULE paramether that sets the event to be repeated daily until a date) for a given vCalendar, which seems to be well-formatted (apparently):

```
BEGIN:VCALENDAR
CALSCALE:GREGORIAN
PRODID:iCalendar-Ruby
VERSION:2.0
BEGIN:VEVENT
DTEND:20110325T200000
DTSTAMP:20110926T135132
DTSTART:20110325T080000
EXDATE:
RRULE:FREQ=DAILY;UNTIL=20110331;INTERVAL=1
SEQUENCE:0
UID:2011-09-26T13:51:32+02:00_944954531@cultura0306.gnuine.com
END:VEVENT
END:VCALENDAR
```

Documentation is not really friendly, and google results are scarce...Any idea or example? (the example can be for vobject or any other library or method).

Thanks!

H.
Issue with Passing Retrieved Documents to Large Language Model in RetrievalQA Chain

I'm currently enrolled in a course on Coursera where I'm learning to implement a retrieval-based question-answering (RetrievalQA) system in Python. The course provides code that utilizes the RetrievalQA.from_chain_type() method to create a RetrievalQA chain with both a large language model (LLM) and a vector retriever.

Upon reviewing the provided code, it's evident that relevant documents are retrieved from the vector store using vectordb.similarity_search(). However, there doesn't appear to be a clear step for explicitly passing these retrieved documents to the LLM for question-answering within the RetrievalQA chain.

My understanding is that in a typical RetrievalQA process, relevant documents retrieved from the vector store are subsequently passed to the LLM. This ensures that the LLM can utilize the retrieved information to generate accurate responses to user queries.

I'm seeking clarification on the proper methodology for integrating the retrieved documents into the RetrievalQA chain to ensure effective utilization by the LLM. Any insights, suggestions, or code examples on how to achieve this integration would be greatly appreciated. Thank you for your assistance!

```
from langchain.vectorstores import Chroma
from langchain.embeddings.openai import OpenAIEmbeddings
persist_directory = 'docs/chroma/'
embedding = OpenAIEmbeddings()
vectordb = Chroma(persist_directory=persist_directory, embedding_function=embedding)
question = "What are major topics for this class?"
docs = vectordb.similarity_search(question,k=3)
len(docs)
from langchain.chat_models import ChatOpenAI
llm = ChatOpenAI(model_name=llm_name, temperature=0)
from langchain.chains import RetrievalQA

qa_chain = RetrievalQA.from_chain_type(
    llm,
    retriever=vectordb.as_retriever()
)result = qa_chain({"query": question})
result["result"]
```
How i can send TOO MANY requests to DEFFERENT sites and get responses?

How can I send a lot of requests to DIFFERENT sites, I have a database of sites (1kk) and need to check whether they are alive or not, conditionally if you just do it through grequests(python) chunks of software (100 requests in 10 threads ~128second) it will take 12.5 days, but for me it's too long and I I am sure that this can be done much faster. Can you tell me what I can use in this case? I'm just collecting information about the main page of the sites.

Here is my code, I want to improve it somehow, what can you recommend? I tried to throw every request into the stream, but it feels like something is blocking it, I will use a proxy so that my IP is not blocked due to more requests Help who can!

```
def start_parting(urls:list,chunk_num,chunks):
    if len(urls)>0:
        chunk_num+=1
        print(f'Chunck [{Fore.CYAN}{chunk_num}/{chunks}{Style.RESET_ALL}] started! Length: {len(urls)}')
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"}
        rs = [grequests.get(url.split(' ')[0].strip(), headers=headers,timeout=10) for url in urls]
        responses = grequests.map(rs)
        for response in responses:
            if response is None:
                continue
            if response.status_code == 200:
                check_pattern = r'(pat1|pat2)'
                match = re.search(check_pattern, response.text, re.IGNORECASE)
                if match:
                    site = match.group(1)
                    print(f'Site {site}')
        print(f'Chunck [{Fore.LIGHTCYAN_EX}{chunk_num}/{chunks}{Style.RESET_ALL}] ended!')

def test_sites_for_file(file,num_threads = 10,chunk_size=100):
    print('Start check!')
    urls = file.readlines()
    with ThreadPoolExecutor(max_workers=num_threads) as executor:
        parts = [urls[i:i + chunk_size] for i in range(0, len(urls), chunk_size)]
        finals = [executor.submit(start_parting, part , part_num,len(parts)) for part_num,part in enumerate(parts)]
        t = time.time()
        for final in as_completed(finals):
            pass
        print(f'Resultate: {time.time()-t}')
```
How can I observe the attribute lookup chain in Python?

I am trying to delve into Python's class descriptors, and have come across an article explaining the lookup chain of class attributes. Namely, it is said that the first priority is the __get__ method of the data descriptor (that is, a class that implements __set__ or __delete__ method. Then comes the dict of the object followed by get method of non-data descriptor.

This seems extremely confusing to me, and I am hopeless to find a real example demonstrating how, say, data descriptors come before dict lookup of an instance. I would really appreciate a minimum example with prints that illustrates this theoretical stuff.
EF Core ignore column when requesting a list, but include when getting by Id

I have a list of invoices, which have generated files which are stored in the database.

I want to avoid loading the file data itself when retrieving a list of the invoices, but load it when the user clicks the download button for it.

Is there a way to achieve this? I saw the ignore for fluent configuration but it ignores it all the time.

Example code:

Class:
```
public class InvoiceFile
{
    public Guid Id { get; set; }
    public string FileName { get; set; }
    public byte[] File { get; set; }

    public Guid InvoiceId { get; set; }
    public Invoice Invoice { get; set; }
}
```

I want the File property to be ignored in the first query, but loaded in the second:

```
var invoices = await _payoutDbContext.Invoices
    .Include(x => x.InvoiceFiles)
    .AsNoTracking()
    .AsSplitQuery()
    .ToListAsync();
var file - await _payoutDbContext.InvoiceFiles
    .Where(x => x.Id == invoiceId)
    .AsNoTracking()
    .FirstOrDefaultAsync();
```