satoshi-2000/llms-suitable huggingface dataset:
Question: How to extract blob data from websocket response

I'm trying to get market data from bingx websocket API but once my connection stablished i recieve blob data and i dont know how can i read candlestick data from that blob response with javascript does any one know how can i extract data?
here is my Js code :
var ws = new WebSocket('wss://open-ws-swap.bingbon.pro/ws');

    ws.onopen = (event) => {
        const msg = {
            id: "548",
            reqType:"sub",
            dataType: "market.kline.BTC-USDT.1min",
        }
        ws.send(JSON.stringify(msg));
        console.log('connection stablished!')
    }


    // Listen for messages
    ws.onmessage = function(event) {
        console.log(event.data);
    }

    ws.onclose = function(event) {
        console.log(event)
    };

    ws.onerror = function(error) {
        console.log(error);
    };

And here is the result in console:

I tried this answer bot not working:
text


Answer:
From the docs ->

All response data from Websocket server are compressed into GZIP
format. Clients have to decompress them for further use

So using this information we can use DecompressionStream -> https://developer.mozilla.org/en-US/docs/Web/API/DecompressionStream  to uncompress the data, and then use TextDecoder to convert that into to text, finally JSON.parse to convert into an object.
Finally you will want to watch for the Ping message, as the API will disconnect if you don't send a Pong.
eg.


var ws = new WebSocket('wss://open-ws-swap.bingbon.pro/ws');


async function decompressBlob(blob) {
  const ds = new DecompressionStream("gzip");
  const decompressedStream = blob.stream().pipeThrough(ds);
  return await new Response(decompressedStream).blob();
}




ws.onopen = (event) => {
   const msg = {
      id: "548",
      reqType:"sub",
      dataType: "market.kline.BTC-USDT.1min",
   }
   ws.send(JSON.stringify(msg));
   console.log('connection stablished!')
}

// Listen for messages
ws.onmessage = async function(event) {
   const data = await decompressBlob(event.data);
   const txt = new TextDecoder().decode(await data.arrayBuffer());
   if (txt === 'Ping') {
     //this keeps the api open
     ws.send('Pong');
   } else {
     console.log(JSON.parse(txt));
   }
}

ws.onclose = function(event) {
   console.log(event)
};

ws.onerror = function(error) {
   console.log(error);
};
Question: Rspec confused when I run the tests on the rspec with the --pattern and --exclude-patternn flags

I need to run all the tests from the "spec/workers/**" folder, but I don't want to run the tests in a specific folder that is inside the "spec/workers/". I'm using the --pattern flags to say what I want and --exclude--pattern to say what I don't want to run. and it still does what is described in --exclude-pattern.
Eg:
bundle exec rspec --pattern "spec/workers/**/*_spec.rb" --exclude-pattern "spec/workers/study_workers/*_spec.rb"



Answer:
This is not a bug but expected behavior.
When there are two filters defined, one to include a specific files and another to exclude the same specific files, then excluding pattern has a lower priority and therefore the file is included.
Please see the discussion in this GitHub issue.
Question: to_timesamp converting month to different month

Any idea why snowflake to_timestamp is converting February month to January?
    SELECT to_timestamp(to_char('2022-02-02 08:01:29 AM'),'YYYY-MM-DD HH12:MM:SS AM');
    -- 2022-01-02 08:00:29.000



Answer:
MM represent month when you convert to char , you should use MI for minute in snowflake, I assume the issue comes from there :
SELECT to_timestamp(to_char('2022-02-02 08:01:29 AM','YYYY-MM-DD HH12:MI:SS AM'));
Question: Parent variable in Vue 3 not updated when using update-emit on prop

I've the following very simple Vue 3 component:
<template lang="pug">
b-modal(v-model="dshow")
  template(v-slot:default) test
</template>

<script>
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dshow: false
    }
  },
  watch: {
    show: function () {
      this.dshow = this.show
    },
    dshow: function () {
      this.$emit('update:show', this.dshow)
    }
  }
}
</script>

In my parent component, I'm using this as following:
import demo from 'mymodal.vue'

<template lang="pug">
button.btn.btn-primary.hstack.gap-2(@click="showModal= true") Show Modal!
demo(:show.sync="showModal")
</template>

<script>
export default {
  components: {
    demo
  },
  data() {
    return {
      showModal: false
    }
  }
}
</script>

Now, when I click on my button in the parent, the modal appears and when I close / hide the dialog, the callback for my watched variable dshow is also called. But unfortunately, my parent component isn't informed about the update. So when I click on my button next time, nothing happens, because the showModal hasn't been updated. this.$emit('update:show', this.dshow) is emitted, but the parent value isn't updated.
Any idea on this? I run completely out of ideas on this :-(


Answer:
In Vue 3, the .sync modifier has been removed in favor of arguments to v-model (see migration guide)
So
:show.sync="showModal"

now has to be
v-model:show="showModal"
Question: Enable clear-text local traffic on iOS not working in .NET MAUI

I'm trying to connect to http in my .net MAUI app and I disabled the Apple Transport Security (ATS) following Microsoft documentation (from here) by adding below configuration in the info.plist file:
<key>NSAppTransportSecurity</key>    
<dict>
    <key>NSAllowsLocalNetworking</key>
    <true/>
</dict>

However, I'm still getting below error message when attempting to communicate with the API using http:
[0:] An error occurred: 'Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection., NSErrorFailingURLStringKey=http://restapi.adequateshop.com/api/Tourist, NSErrorFailingURLKey=http://restapi.adequateshop.com/api/Tourist, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <27DB8D6A-2EB6-41FE-953E-6FA2BFDBEDDC>.<1>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <27DB8D6A-2EB6-41FE-953E-6FA2BFDBEDDC>.<1>, NSUnderlyingError=0x280b9b330 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}}'. Callstack: ''

Any idea how to resolve this? Thank you in advance.


Answer:
The key that is specified in that documentation page only works for local addresses like IP addresses or addresses that end in .local as you can see in the Apple documentation.
From your error message it seems that you are trying to reach a regular web address. In that case the key you need is: NSAllowsArbitraryLoads so that it opts out of ATS altogether.
Your full entry will then look like this:
<key>NSAppTransportSecurity</key>    
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

However, I would not recommend doing this. Please try to get your endpoints on HTTPS. It should not be expensive anymore nowadays and this way your users and you will be at risk.
If you really can't add HTTPS, try to limit the unsafe connections made for your app to a single domain. How that is done can be found here in the Apple documentation.
Basically, your info.plist entry should now look something like this:
<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <false/>
  <key>NSExceptionDomains</key>
  <dict>
    <key>adequateshop.com</key>
    <dict>
      <key>NSIncludesSubdomains</key>
      <true/>
      <key>NSExceptionAllowsInsecureHTTPLoads</key>
      <true/>
    </dict>
  </dict>
</dict>

But again, I would recommend fixing the server to be secure above all.
Question: How to extract specific records from a JSON file that all have the same value in a specified field with python?

I have a json file that has over 1000 records in it all similar to the one below:
[{"id":0,"occupation":"teacher","county":"Santa Rosa","grade":"3rd","workID":"147767"},

I want to extract all the records that have a certain occupation, in this case I want to return the records where the occupations are teacher.
This is what I have tried:
specified_occ = {}
for o in data:
    specified_occ[o["occupation"]] = o
specOcc = (specified_occ['teacher'])  

but it only returns the first instance rather than all of them that match.
My dataset has 50 records where the occupation is 'teacher' I want every record returned.


Answer:
You can use a list comprehension to filter over your data and only select the needed elements. In general a list comprehension looks like this
filtered_list = [element for element in original_list if element == requirement]

Here you only select the elements from the original list if the elements match some requirement.
For this specific problem you would use
filtered_data = [person for person in data if person['occupation'] == 'teacher']

This is syntactically equivalent to
speccified_o = []
for o in data:
    if o['occupation'] == 'teacher':
        speccified_o.append(o)
Question: Why is my C++ string erase-remove-idiom implementation causing an infinite loop with conditional statements?

index is going out of bound it's not triggering while(i<str.length()) break; i tried to implement this line differently
string delStr(string s, int sIdx, int nChar) {
  string ans = "";
  int i = 0;
  int n = s.length()-1;
  while(n--){
    
    if(i==sIdx){
      i += nChar;
    }

    if(n<0) break;
    ans.push_back(s[i]);
    i++;
  }
}


Trying to implement string erase method.


Answer:
You should be sure to post a minimal, reproducible example when you ask a question. This will help people provide an answer.
If I understand the function correctly, I believe it is supposed to return a new std::string with the characters from sIdx to sIdx + nChar removed. If that is the case, there is a logic error that I can't quite follow. You can compare the posted code to the sample below and maybe that will help you correct it.
In the sample code, I show two different solutions. The first uses the standard library algorithms and the second just iterates over the characters similar to the posted code. The advantage of using the algorithms is that they are well-tested for correctness, have efficient implementations, and serve as a common language among developers.
Sample Code
#include <iostream>

using std::cout, std::endl;

std::string delete_substr(const std::string& str, int sIdx, int nChar) {
    std::string answer;
    std::copy(str.begin(), str.begin() + sIdx, std::back_inserter(answer));
    std::copy(str.begin() + sIdx + nChar, str.end(), std::back_inserter(answer));
    return answer;
}

std::string delStr(const std::string& str, int sIdx, int nChar) {
    std::string answer;
    int i{};
    while (i < str.size()) {
        if (i == sIdx)
            i += nChar;
        else
            answer.push_back(str[i++]);
    }
    return answer;
}

int main(int argc, const char *argv[]) {
    std::string s0 = "abcdefghi";
    cout << delete_substr(s0, 3, 3) << endl;
    cout << delStr(s0, 3, 3) << endl;
    return 0;
}

Output
abcghi
abcghi
Question: How to fix dynamically generated runner files importing from 'cucumber.api' in Cucumber/Junit parallel testing?

I was trying to achieve parallel testing using cucumber with Junit. When I am trying to run the feature file parallely the runner file generated is importing from cucumber.api instead of io.cucumber. I want to know why it is dynamically taking from cucumber.api and also how can i fix that.Dynamic generated runner file
Tried Adding latest version of cucumber and junit but didint worked


Answer:
You're using a more modern version of Cucumber then the code generator you're using was written for.
You don't need the code generator anymore because Cucumber supports parallel execution now.
You can use the cucumber-java-skeleton to get started. The cucumber-junit-platform-engine docs should explain everything else.
Question: SQL ORACLE, How to subtract sysdate?

How can I subtract the system date from the created task date in SQL ORACLE to get the difference in days, hours, minutes?
I tried this code but i get wrong values:
TO_CHAR(TO_DATE('1970-01-01 00:00:00','yyyy-mm-dd hh24:mi:ss') + (sysdate - a.CREATE_DATE_PL ), 'dd:hh24:mi:ss')  AS TT_LIFETIME
My results is below (the report has been generated 02.06  14:05
enter image description here


Answer:
Difference of two DATE datatype values is number of days between them, so you have to do some arithmetic to extract days/hours/minutes, or - another option - to try extract with numtodsinterval.
For example:
SQL> WITH
  2     test (create_date_pl)
  3     AS
  4        (SELECT TO_DATE ('01.06.2023 08:10', 'dd.mm.yyyy hh24:mi') FROM DUAL)
  5  SELECT SYSDATE,
  6         create_date_pl,
  7         --
  8         SYSDATE - create_date_pl diff,
  9         NUMTODSINTERVAL (SYSDATE - create_date_pl, 'day') c1,
 10         EXTRACT (DAY FROM NUMTODSINTERVAL (SYSDATE - create_date_pl, 'day')) cd,
 11         EXTRACT (HOUR FROM NUMTODSINTERVAL (SYSDATE - create_date_pl, 'day')) ch,
 12         EXTRACT (MINUTE FROM NUMTODSINTERVAL (SYSDATE - create_date_pl, 'day')) cm
 13    FROM test;

SYSDATE          CREATE_DATE_PL         DIFF C1                                               CD         CH         CM
---------------- ---------------- ---------- ---------------------------------------- ---------- ---------- ----------
02.06.2023 14:29 01.06.2023 08:10 1,26333333 +000000001 06:19:12.000000000                     1          6         19

SQL>

When I ran that code, it was 2th of June 2023 at 14:29. Date to be subtracted was 1st of June 2023 (yesterday) at 08:10.

diff represents number of days between those two values
c1 is what numtodsinterval returns
cd, ch and cm contain extracted number of days/hours/minutes, i.e. difference is 1 day, 6 hours and 19 minutes
Question: dependency injection in Angular when extending a class

I am a Java guy learning Angular.
I have a service and I would like to have injected that service into my object. This doc explains well how to do it in a normal case. As I understand the concept, in the example we use constructor dependency injection.
But in my case, this is not possible because I am extending a class that has its own constructor with 3 parameters and I am not allowed to modify the parent constructor. So I can not add a 4th parameter to my constructor to have injected the service.
This code does not work because the last constructor param is invalid.
my code:
export class ChildComponent extends ParentComponent {

  constructor(readonly service1: Service1,
              readonly service2: Service2,
              el?: ElementRef | null,
              readonly service3: Service3) { <-- invalid param
    super(service1, service2, el);
  }

What is the alternative dependency injection if the constructor injection is not an option?


Answer:
Instead of injecting the service through the constructor, you can declare a property in your child component and annotate it with the @Inject decorator to specify the service you want to inject.
Question: Can't connect to outside from the docker container managed by ECS on EC2

I have ECS which uses EC2 and EC2 has a contianer.
From EC2 node I can access the outside with this command.
[ec2-user@ip-172-31-23-50 ~]$ curl google.com
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>

Then I login container running on this node, docker exec -it container-name /bin/bash
 root@ip-172-31-24-234:/# curl google.com

I can't access(nothing appears).
So, I check the security group of ECS Service.
However all outbound connection is allowed

Test
on EC2 node I try to run another container (Becasue I wanted to test the container which is not managed by ECS service).
`docker run -it ubuntu`

then install curl and try curl in the this ubuntu containaer,I can connect to the outside from the container.
So the problem happens only in ECS managed container,
My task difinition is made by CDK, maybe this Network mode is related....??
const adminTaskDefinition = new ecs.Ec2TaskDefinition(this, 'AdminTaskDefinition', {
  networkMode: ecs.NetworkMode.AWS_VPC,
})



Answer:
Perhaps set your Network Mode = host in your task definition.
Question: Creating a new column in SQL Oracle with a subquery - any suggestions?

I have the columns Yearmonth, code, type and clntamount in my table. I want to derive column clntamount_der.
Table view

I want the 110 value in clntamount with the type = Total to be in the column clntamount_der where the type = base and the rest two rows(adj and total) as zero.
Please help with the logic.
I tried case statemnt but it didnt work maybe a subquery will work


Answer:
You may use the conditional max window function as the following:
select t.*, 
  case 
    when TYPE = 'BASE' 
       then max(case when TYPE = 'TOTAL' then CLNTAMOUNT end) over
               (partition by YearMonth, Code)
       else 0
    end as clntamount_der
from tbl t
order by 
  YearMonth, Code,
  case TYPE
    when 'BASE' then 1
    when 'ADJUST' then 2
    when 'TOTAL' then 3
  end

demo
Also, it seems that the TOTAL is the sum of other types (BASE, ADJUST), in this case, it would be better to calculate the TOTAL on the fly (and not store it as a separate row) to avoid data inconsistency. i.e. when you update the CLNTAMOUNT value where type = 'BASE' how would you reflect this to the value where type = 'TOTAL'?
consider the following without having the TOTAL type stored in the table.
select d.*
  from
(
  select t.YearMonth, t.Code, t.Type, t.CLNTAMOUNT,
    case 
      when TYPE = 'BASE' 
         then sum(t.CLNTAMOUNT) over (partition by t.YearMonth, t.Code)
         else 0
      end as clntamount_der
  from tbl t
  
  union all
  
  select t.YearMonth, t.Code, 'TOTAL',
          sum(t.CLNTAMOUNT), 0 
  from tbl t
  group by t.YearMonth, t.Code
) d
order by 
  d.YearMonth, d.Code,
  case d.TYPE
    when 'BASE' then 1
    when 'ADJUST' then 2
    when 'TOTAL' then 3
  end

demo
Question: Assign new values later to the underlying object of the interface in go

I am trying to assign new values to the underlying structure of an interface in code below. But it keeps the older values. Below is the example code.
package main

import (
    "fmt"
    "math"
)

type Shape interface {
    Area() float64
}

type Circle struct {
    Radius float64
    Name   string
}

func (c Circle) Area() float64 {
    return math.Pi * c.Radius * c.Radius
}

type Rectangle struct {
    Length float64
    Width  float64
    Name   string
}

func (r Rectangle) Area() float64 {
    return r.Length * r.Width
}

func assignRadius(s Shape, radius float64, name string) {
    switch s := s.(type) {
    case Circle:
        s.Radius = radius
        s.Name = name
    case Rectangle:
        s.Length = radius
        s.Name = name
    }
}

func main() {
    var s Shape
    c := Circle{Radius: 0, Name: "My Circle"}
    s = c
    fmt.Println(s.Area())
    fmt.Println(c.Radius)
    fmt.Println(c.Name)
    assignRadius(s, 10, "My New Circle")
    fmt.Println(c.Radius)
    fmt.Println(c.Name)
}

The type of Shape isn't known beforehand in the assignRadius. I know it has something to do with the pointers. But can't figure it out.


Answer:
The interface variable s contains a copy of the shape value. To modify it like you attempted to do, it has to contain a pointer to that shape:
var s Shape
c := Circle{Radius: 0, Name: "My Circle"}
s = &c

and in the function modifying them, you have to type-assert the pointer value:
func assignRadius(s Shape, radius float64, name string) {
    switch s := s.(type) {
    case *Circle:
        s.Radius = radius
        s.Name = name
    case *Rectangle:
        s.Length = radius
        s.Name = name
    }
Question: symbols in paths in React Router v6

I'm migrating from v5 to v6. It v6 it seems you can't use regexp anymore. Is there a quick workaround for a path like this? The problem is the dash, of course.
<Route path="/doc/:id-:version" />



Answer:
You can't use partial dynamic segments, it's all or nothing. Use a single param and then apply string splitting logic on it in the component.
Example:
<Route path="/doc/:idVersion" element={....} />

const { idVersion } = useParams();

const [id, version] = idVersion.split("-");

See Dynamic Segments for more information.
Question: How do you declare that a type belongs to a marker interface?

If I have these types:
type Orange struct {
  Size float32
}

type Lemon struct {
   Color string
}

type Wood struct {
   Variety string
}

And that interface:
type Fruit interface {
}

How do I declare that Orange and Lemon are Fruit,
so that, elsewhere, a function may return only things who are of kind Fruit?
(Fruit being a marker interface).


Answer:
To declare that a type belongs to a marker interface in Go, you need to explicitly state that the type implements the interface. In your case, to declare that Orange and Lemon types are of kind Fruit, you can do the following:
type Fruit interface {

}
type Orange struct {
Size float32
}
func (o Orange) MethodOfFruit() {
// Implement any methods of Fruit interface if required

}
type Lemon struct {
Color string

}
func (l Lemon) MethodOfFruit()
{
// Implement any methods of Fruit interface if required

}
Question: API Mocking - How do I implement request forward while using a Javascript mock?

I am aware that in a mock server feature file, it is possible to forward requests to a specific endpoint using karate.proceed(): https://karatelabs.github.io/karate/karate-netty/#karateproceed.
We recently decided to opt for Javascript mocks, as they enable us to write more complex business logic for simulating the API we consume. Is there out-of-the-box functionality equivalent to karate.proceed() that I can use in a JS mock? Is there a way I can invoke karate.proceed() within this mock? Or is one expected to write Javascript code to enable this functionality?


Answer:
Great question, and yes there is no context.proceed(). You need to use context.http() and manually create a new request and handle the response. All the data you need will be on the request object. For example request.method will give you the HTTP method as a string.
This is indeed an un-documented part of Karate, yet to become "mainstream". Feel free to add a feature request for a context.proceed() that will auto-use the request in scope, that does sound useful. If you could contribute a PR or two that would be awesome :)