satoshi-2000/llms-suitable huggingface dataset:
Question: Why does ruby recognise a method outside of a class, but not inside?

I am trying to build a simple language translating program. I imported the 'language_converter' gem to aid with this goal. I wrote the following code:
require 'language_converter'

class Translator
    def initialize
        @to = 'ja';  
        @from = 'en';   
    end

    def translate text
        lc(text, @to,@from)
    end
end

#puts lc('welcome to Japan!', 'ja','en');
 
t = Translator.new

p t.translate('welcome to Japan!');

This code results in the error: undefined method 'lc' for #<Translator:0x0000000101167a90 @to="ja", @from="en"> (NoMethodError)
However, when i uncomment the code on line 15, ruby can access the lc method and return some japanese. Does anyone know why the method is 'defined' outside of the class but not inside?
Edit: the language-converter gem is not my own. also, I cannot find the source code on its homepage.
I have also tried adding two semicolons before the lc method like so: ::lc(text, @to,@from). This results in the error: syntax error, unexpected local variable or method, expecting constant


Answer:
The gem is more than 10 years old and only has one method. And that method is implemented as a class method.
You are properly better off with just rewriting that method in your application with a modern Ruby syntax and proper error handling.
For reference, this it how lib/language_converter.rb in the gem looks like:
require 'net/http'
require 'rubygems'
require "uri"
require 'json'

class UnSupportedLanguage < RuntimeError

  def initialize(message='')
    @msg = "not supported."
  end
end


  def self.lc( text, to, from='en' )

    begin

      uri = URI.parse("http://mymemory.translated.net/api/get")

      response = Net::HTTP.post_form(uri, {"q" => text,"langpair"=>"#{from.to_s.downcase}|#{to.to_s.downcase}", "per_page" => "50"})

      json_response_body = JSON.parse( response.body )

      if json_response_body['responseStatus'] == 200
        json_response_body['responseData']['translatedText']
      else
        puts json_response_body['responseDetails']
        raise StandardError, response['responseDetails']
      end
    rescue UnSupportedLanguage
      raise UnSupportedLanguage.new
    rescue => err_msg
      puts "#{err_msg}"
    end

  end
Question: How to override parent's styles in css?

In this example, I want the purple rectangle to change its opacity to 100% regardless of the value of the parent. I tried using all: unset/initial and !important but it doesn't seem to work.


.rect {
    width: 500px;
    height: 600px;
    margin-top: 200px;
    margin-left: 300px;
    background-color: black;
    /* this V */
    opacity: 37%;
    z-index: -1;
}

.rect1 {
    all: unset;
    position: absolute;
    z-index: 10;
    width: 259px;
    height: 300px;
    margin-top: 500px;
    margin-left: 50px;
    background-color: purple;
    /* to this V */
    opacity: 100% !important;
}
<div class="rect">
  <div class="rect1"></div>
</div>





Answer:
So like Haworth pointed out, using opacity on the element itself brings all children under the influence of the pixelshading used to make the opacity effect.
If you want to get the same effect while retaining your html structure I'd recommend a different approach for the same result using RGBA or hex with an alpha channel on the background-color property directly. See example below.


body {
  height: 100%;
  width: 100%;
  background: url(https://picsum.photos/800) no-repeat;
  background-size: cover;
}

.rect {
    width: 500px;
    height: 600px;
    margin-top: 200px;
    margin-left: 300px;
    background-color: rgba(0,0,0,.37);
    /* this V
    opacity: 37%;*/
    z-index: -1;
}

.rect1 {
    position: absolute;
    z-index: 10;
    width: 259px;
    height: 300px;
    margin-top: 500px;
    margin-left: 50px;
    background-color: purple;
    /* to this V */
    opacity: 100% !important;
}
<div class="rect">
  <div class="rect1"></div>
</div>
Question: How to generate a log file of the windows prompt when I run a bat file

I'm running a bat file in windows. I'm trying to generate a log file of all the output that appears in the command prompt, to have as a document.
Note, Not a log file of the contents of the bat file but of the command prompt that it outputs.
How would I do this? Thanks


Answer:
Redirecting to output is done by using > or appending to file using >>
for batch-file, we typically call them.
(call script.cmd)2>&1>"logfile.log"

or append
(call script.cmd)2>&1>>"logfile.log"

Note, 2>&1 2>&1 is redirecting the stderr stream 2 to the stdout stream 1, it is important here, seeing as you said you want to log all of the output results to logfile.
So that should also give the clue that you can in fact redirect success (stdout) results to one file and failures (stderr) to another, i.e
(call script.cmd) 1>"Output.log" 2>"Errors.log"

Note, some commands and executables sends everything to the stdout stream and nothing to stderr, example ping.exe.
Question: calculate an object property based on the value of another property of the same object

I need to find out the value of "name" inside on the obj object. How can I find it without function invocation?
I wanna use just obj.isActive not obj.isActive()
let obj = {
  name: "X Æ A-12 Musk",
  isActive: function () {
    return this.name.length > 4;
  },
};

// and after a while I need to check if is active:

console.log(obj);

// { 
//   name: 'X Æ A-12 Musk',
//   isActive: [Function: isActive]  <--------- NOT COOL ! 
// }



If use an IFEE:
let obj = {
  name: "X Æ A-12 Musk",
  isActive: (function () {
    return this.name.length > 4;
  })(),
};

I get:
return this.name.length > 4;
                ^
TypeError: Cannot read properties of undefined (reading 'length') 



Answer:
If you do not want to have to call isActive as a function, you can use a getter.


const obj = {
  name: "X Æ A-12 Musk",
  get isActive () {
    return this.name.length > 4;
  },
};

console.log(obj.isActive);
Question: Code to format JSON data and append hardcoded data to create a flat .txt file

Source Data::
json_data = [{"studentid": 1, "name": "ABC", "subjects": ["Python", "Data Structures"]},
             {"studentid": 2, "name": "PQR", "subjects": ["Java", "Operating System"]}]

Hardcoded_Val1 = 10
Hardcoded_Val2 = 20
Hardcoded_Val3 = str(datetime.datetime.now())

Need to create a flat .txt file with the below data.
ID,DEPT,"studentid|name|subjects",execution_dt
10,20,"1|ABC|Python,Data Structures",2023-06-01
10,20,"2|PQR|Java,Operating System",2023-06-01

I am very new in python. Have already tried to figure it out to achieve it but couldn't. Your help will be much appreciated.
import datetime
import pandas as pd
import json


json_data = [{"studentid": 1, "name": "ABC", "subjects": ["Python", "Data Structures"]},
             {"studentid": 2, "name": "PQR", "subjects": ["Java", "Operating System"]}]

Hardcoded_Val1 = 10
Hardcoded_Val2 = 20
Hardcoded_Val3 = str(datetime.datetime.now())

profile = str(Hardcoded_Val1) + ',' + str(Hardcoded_Val2) + ',"' + str(json_data) + '",' + Hardcoded_Val3
        
print(profile)
#data = json.dumps(profile, indent=True)
#print(data)
data_list = []
for data_info in profile:
   data_list.append(data_info.replace(", '", '|'))
data_df = pd.DataFrame(data=data_list)
data_df.to_csv(r'E:\DataLake\api_fetched_sample_output.txt', sep='|', index=False, encoding='utf-8')




Answer:
I would bypass using pandas for this and just build the string manually primarily using a list comprehension and join().
import datetime
import csv

Hardcoded_Val1 = 10
Hardcoded_Val2 = 20
Hardcoded_Val3 = str(datetime.date.today())
json_data = [
    {"studentid": 1, "name": "ABC", "subjects": ["Python", "Data Structures"]},
    {"studentid": 2, "name": "PQR", "subjects": ["Java", "Operating System"]}
]

csv_data = []
for row in json_data:
    keys = "|".join(row.keys())
    values = "|".join([
        ",".join(value) if isinstance(value, list) else str(value)
        for value in row.values()
    ])
    csv_data.append(dict([
        ("ID", Hardcoded_Val1),
        ("DEPT", Hardcoded_Val2),
        (keys, values),
        ("execution_dt", Hardcoded_Val3)
    ]))

with open("out.csv", "w", encoding="utf-8", newline="") as file_out:
    writer = csv.DictWriter(file_out, fieldnames=list(csv_data[0].keys()))
    writer.writeheader()
    writer.writerows(csv_data)

This will produce a file with the following contents:
ID,DEPT,studentid|name|subjects,execution_dt
10,20,"1|ABC|Python,Data Structures",2023-06-02
10,20,"2|PQR|Java,Operating System",2023-06-02
Question: jquery above and below screen sizes

I have added a script for showing a div before different divs in different screen size. This is the code I used:
jQuery(function($){ 
jQuery(document).ready(function(){
    jQuery(window).on('resize', function(){
        if(jQuery(window).width() <= 1024){
            jQuery( ".checkout.woocommerce-checkout .woocommerce-shipping-fields__wrapper" ).insertBefore( ".checkout.woocommerce-checkout .flux-step.flux-step--2 .flux-checkout__shipping-table" );
        }
        else if(jQuery(window).width() >= 1025){
            jQuery( ".checkout.woocommerce-checkout .woocommerce-shipping-fields__wrapper" ).insertBefore( ".checkout.woocommerce-checkout .flux-checkout__content-right #order_review" );
        }
    }); 
}); 
});

But the code is not working when I open the site. It only works if I resize the screen. May be due to the resize function is used.
Can anyone please guide me how to make it so that it'll show the 2 conditions even without resizing the screen and one'll work above 1024px and another below 1024px.
TIA


Answer:
Just put your code in a function and call it on the document ready:


$(function(){
  
  resize();
  
  $(window).on('resize', resize);

  function resize(){
    $( ".checkout.woocommerce-checkout .woocommerce-shipping-fields__wrapper" )
      .insertBefore(
        $(window).width() <= 1024 ? 
        ".checkout.woocommerce-checkout .flux-step.flux-step--2 .flux-checkout__shipping-table" : 
        ".checkout.woocommerce-checkout .flux-checkout__content-right #order_review"
      );
   }
   
});
Question: How is arbitrary distributed for Int? Why is it limited by so small values?

I am trying to compare the QuickCheck library to the SmallCheck one. In SmallCheck I can reach particular value manipulating depth parameter. In QuickCheck:
>a<-generate (replicateM 10000 arbitrary) :: IO [Int]
>length a
10000
>maximum a
30

and my question then is: why are 10,000 "random" ("arbitrary") integers limited by 30?! I expected to see more "widely" distributed values within the range 0..10,000, maybe the maximum value close to 5,000.


Answer:
The documentation contains a clue:

The size passed to the generator is always 30

By default QuickCheck works by starting with 'easy' or 'small' inputs to see if it can find counterexamples with those. Only if it finds no problems with the small inputs does it gradually widen the range of generated input. The size value (which runs implicitly throughout everything that QuickCheck does) is the value that controls this behaviour.
When you run QuickCheck (e.g. with quickCheck) it automatically increases the size as it goes.
You're not really supposed to use the generate function directly, but if you do, you can resize it:
ghci> b <- generate (replicateM 10000 (resize 60 arbitrary)) :: IO [Int]
ghci> maximum b
60

That said, how are you supposed to use QuickCheck? The documentation describes quickCheck along with a multitude of variations you can use to evaluate properties.
Personally, I integrate my QuickCheck properties with a unit testing framework with testProperty. You can see examples here: Property-based testing is not the same as partition testing.
Question: How can I resolve the TypeScript error 'Function lacks ending return statement and return type does not include 'undefined'' in my code?

I have the following simple function (make) that calls the handle function and is supposed to retry a number of times whenever that function throws. If the retries are exhausted, the make function should throw the error.
const handle = async (): Promise<string> => 'hi';

const make = async (): Promise<string> => {
  const MAX_RETRIES = 2;
  for (let idx = 0; idx <= MAX_RETRIES; idx++) {
    try {
      return await handle();
    } catch (err) {
      if (idx < MAX_RETRIES) {
        continue;
      } else {
        throw err;
      }
    }
  }
};

I'm using TypeScript, which is complaining because the return type doesn't include undefined:

Function lacks ending return statement and return type does not include 'undefined'.

For reference, this is the TS Playground for the code above.
I'm looking for guidance on how to handle the return type for the function.
Note that:

I don't want to change my tsconfigs (currently set to strict)
I don't want to modify the return type to Promise<string | undefined>

My understanding is that the make function can only either return a string (inside the try block) or throw an error once the retries have been exhausted. If that's the case then where does the undefined that TS is asking for comes from? Am I missing something?


Answer:

My understanding is that the make function can only either return a string (inside the try block) or throw an error once the retries have been exhausted.

I'm fairly sure you're right, but TypeScript can't quite follow logic that complex, so it (incorrectly, I think) sees a path through the function that doesn't do an explicit return and so implicitly returns undefined (wrapped in a promise).
You can solve it in a few ways:

Add a return ""; at the end with a comment noting it'll never happen. (Blech.)
Add a throw new Error("Logic error, this will never be reached."); at the end.
Rewrite the function to make the final attempt more obviously a return-or-throw situation by using < instead of <= and then repeating the return await handle(); at the end. (Not great to have to repeat it, but it's very simple.)

I don't think #1 or #2 need examples, but here's what #3 might look like:
const make = async (): Promise<string> => {
    const MAX_RETRIES = 2;
    for (let idx = 0; idx < MAX_RETRIES; idx++) {
        try {
            return await handle();
        } catch (err) {
            continue; // I guess technically we don't need this, since
                      // the loop doesn't do anything else
        }
    }
    return await handle();
};

For me, #2 is the winner (or jcalz's rewrite), but any of them will make TypeScript happy, it's really a style choice.
Question: How can i get all the metrics where two label have same values using promql?

I am new to promql. So not sure if promql supports my requirement or not.
max_over_time(cbnode_systemstats_cpu_utilization_rate{instance="a",node="a"}[6h])

This above query gives me result  of max cpu utilization in past 6 hr for instance a single instnace a.
However I want a query which fetches all metrics for all the instances where instance and node has same value. Something similar to below:
max_over_time(cbnode_systemstats_cpu_utilization_rate{instance = node}[6h])



Answer:
There is no easy elegant way to do that.
But you can utilize label_replace, logic of label matching for binary operations and a pinch of ingenuity.
label_replace(cbnode_systemstats_cpu_utilization_rate{}, "pseudoid", "$1", "instance", "(.*)")
 == label_replace(cbnode_systemstats_cpu_utilization_rate{}, "pseudoid", "$1", "node", "(.*)")

Here we add to LHS metric new label called pseudoid with value of instance, and same for RHS, but with value of node.
Result will be returned only if all labels are the same, and in turn it will mean that instance == pseudoid == node.
Demo of similar query can be seen here.
Notice that since it is not the instant vector selector, you'll need to use subquery syntax to pass it into max_over_time.
You resulting query should look like this:
max_over_time(
 (
   label_replace(cbnode_systemstats_cpu_utilization_rate{}, "pseudoid", "$1", "instance", "(.*)")
     == label_replace(cbnode_systemstats_cpu_utilization_rate{}, "pseudoid", "$1", "node", "(.*)")
 )[6h:]
)
Question: Javascript: run specific parts of strings through a function

I want to parse some data that's in a string format. Anything enclosed in parenthesis in the string to parse should be replaced with itself run through a function. This is what I want:
function foo(str) {
    return parseInt(str) + 1; // Example function, not actually what the function will be
}

function parse(str) {
    // everything in str that is enclosed in parenthesis should be replaced with itself ran through foo();

    // Example
    // Input: "My name is foo and I am (0) year old."
    // Output: "My name is foo and I am 1 year old."
    // "(0)" has been replaced with the result of foo("0")
}

I have thought up a couple bad workarounds, but I want something more robust. For example:
function parse(str) {
    // Input: "My name is foo and I am (0) year old."
    str = str.replaceAll("(", "${foo('");
    str = str.replaceAll(")", "')}");
    str = "`" + str + "`"
    // Here str will be "`My name is foo and I am ${foo(0)} year old.`"
    // And I can use eval() or something to treat it like I've typed that
}

This, however, is kind of a bad way of doing it.
EDIT: I tested it, it works, but it is quite vulnerable.
I can't think of anything else and I'm not very good with RegEx. (although I'd accept a solution using it)


Answer:
Here's what I would do. I would match the string with a RegEx that would match anything inside parenthesis in the string. With that, I would then use str.replaceAll() to replace the matched string with the result of the foo() function.
const regex = /\((\d*)\)/gm;

function foo(str) {
    return parseInt(str) + 1;
}

function parse(str) {
  
  // Loop all match the regex find in the string
  let m;
  while ((m = regex.exec(str)) !== null) {
    
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // Replace all instance of the match with the operation of the match
    str = str.replaceAll(m[0], foo(m[1]))
  }
  return str;
}

let p = parse('My name is foo and I am (0) year old and I want (54) apples');

// The result will be: My name is foo and I am 1 year old and I want 55 apples

With that, you won't need to use eval() as it potentially pose a risk for your application.
I hope that would work for you. If I missed anything, tell me, I will edit my answer.
Question: Find unique date from existing dataframe and make a new CSV with corresponding column values

I have a time series every which looks like this :




Time
Volume every minute




2023-05-25T00:00:00Z
284


2023-05-25T00:01:00Z
421


.
.


.
.


2023-05-27T23:58:00Z
894


2023-05-27T23:59:00Z
357




I have to make new CSV by iterating Time column finding unique date and making new columns with corresponding values of volume every minute. For example desired output:




Date
min1
min2
...
min1440




2023-05-25
284
421
...
578


2023-05-26
512
645
...
114


2023-05-27
894
357
...
765




i am able to fetch unique dates but after that i am clueless. please find my sample codes:
import pandas as pd

train_data = pd.read_csv('date25to30.csv')

print(pd.to_datetime(train_data['time']).dt.date.unique())



Answer:
First add parameter parse_dates to read_csv for convert Time column to datetimes:
train_data = pd.read_csv('date25to30.csv', parse_dates=['Time'])

Then create minutes by converting HH:MM:SS to timedeltas by to_timedelta and Series.dt.total_seconds, divide 60 and add 1 because python count from 0:
minutes = (pd.to_timedelta(train_data['Time'].dt.strftime('%H:%M:%S'))
             .dt.total_seconds()
             .div(60)
             .astype(int)
             .add(1))

Last pass to DataFrame.pivot_table with DataFrame.add_prefix:
df = (train_data.pivot_table(index=train_data['Time'].dt.date,
                             columns=minutes,
                             values='Volume',
                             aggfunc='sum').add_prefix('min'))
print (df)
Time         min1   min2  min1439  min1440
Time                                      
2023-05-25  284.0  421.0      NaN      NaN
2023-05-27    NaN    NaN    894.0    357.0
Question: Cannot properly hide the appbar title on scroll in flutter

I want to hide the AppBar on scroll. The search icon is hidden properly and also the opacity decreases on scroll. But for the title, it is not working.
import 'package:flutter/material.dart';
import 'package:vet_mobile/screens/chat.dart';
import 'package:vet_mobile/screens/logot.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        body: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              SliverAppBar(
                title: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      'WhatsApp',
                      style: TextStyle(
                        color: Theme.of(context).textTheme.bodyLarge!.color,
                      ),
                    ),
                    IconButton(
                      onPressed: () {},
                      icon: Icon(
                        Icons.search,
                        color: Theme.of(context).textTheme.bodyLarge!.color,
                      ),
                    ),
                  ],
                ),
                pinned: true,
                floating: true,
                elevation: 5,
                bottom: TabBar(
                  indicatorSize: TabBarIndicatorSize.tab,
                  indicatorWeight: 4,
                  indicatorColor: Theme.of(context).textTheme.bodyLarge!.color,
                  labelStyle:
                      TextStyle(fontSize: 13, fontWeight: FontWeight.w600),
                  labelColor: Theme.of(context).textTheme.bodyLarge!.color,
                  unselectedLabelColor:
                      Theme.of(context).textTheme.bodySmall!.color,
                  dividerColor: Colors.transparent,
                  tabs: const [
                    Tab(text: 'CHATS'),
                    Tab(text: 'STATUS'),
                    Tab(text: 'CALLS'),
                  ],
                ),
              ),
            ];
          },
          body: const TabBarView(
            children: [
              Center(child: LogoutScreen()),
              Center(child: ChatScreen()),
              Center(child: Text('Patient')),
            ],
          ),
        ),
      ),
    );
  }
}



As we can see the opacity of the search button decreases slowly as I scroll down but not for the title.
I tried using the preferred height, animation controller, but it messed up more.


Answer:
Seems that this effect does not work when you set a custom style. Remove the fixed style setting from here:
Text(
  'PawCare',
  // remove this
  /*style: TextStyle(
    color: Theme.of(context).textTheme.bodyLarge!.color,
  ),*/
),

To set the style of the title text, use the titleTextStyle configuration of SliverAppBar:
SliverAppBar(
  titleTextStyle: TextStyle(
   color: Theme.of(context).textTheme.bodyLarge!.color),
...