satoshi-2000/llms-suitable huggingface dataset:
Question: Combine list of lists of tuples with different lengths

I'm having a problem to combine list of lists of tuples, and the main problem comes from different sizes of those tuples. I'm also trying to do it "pythonic" way, which isn't very easy.
What I actually have is a list of objects, having coordinates given in tuple.
Objects (let's say: lines) always have start and end as (x1,y1) and (x2,y2), they also usually have some "path". The problem is that "path" is sometimes empty and in general number of points on the path is different.
start=[ (3,5), (23,50), (5,12), (51,33), (43,1)]
end = [(23,19), (7,2), (34,4),  (8,30), (20,10)]
path=[[(10,7),(14,9),(18,15)],
      [],
      [(15,7)],
      [(42,32),(20,31)],
      [(30,7)]]

Expected result should look like this:
whole_path = [[(3,5),(10,7),(14,9),(18,15),(23,19)],
              [(23,50),(7,2)],
              [(5,12),(15,7),(34,4)],
              [(51,33),(42,32),(20,31),(8,30)],
              [(43,1),(30,7),(20,10)]]

I was trying to use zip - it works well for similar size items in start/end/paths lists but not with their differences.
Promising solutions might come with use path.insert(0,start) and path.extend([end]), but I couldn't make that working, there is also an option to put that into two loops, but it doesn't look well and... it's not very "pythonic".
So: any suggestions would be nice.


Answer:
A solution with zip and *-unpacking of the variable-length path element is reasonably clean:
from pprint import pprint

start=[ (3,5), (23,50), (5,12), (51,33), (43,1)]
end = [(23,19), (7,2), (34,4),  (8,30), (20,10)]
path=[[(10,7),(14,9),(18,15)],
      [],
      [(15,7)],
      [(42,32),(20,31)],
      [(30,7)]]

whole_path = [[s, *p, e] for s, p, e in zip(start, path, end)]
pprint(whole_path)

giving the required:
[[(3, 5), (10, 7), (14, 9), (18, 15), (23, 19)],
 [(23, 50), (7, 2)],
 [(5, 12), (15, 7), (34, 4)],
 [(51, 33), (42, 32), (20, 31), (8, 30)],
 [(43, 1), (30, 7), (20, 10)]]
Question: Blade: anonymous component doesn't show when passing data

I'm new to Blade and tried to use anonymous components for sections that I will use frequently.
The problem is that when I'm trying to pass down data to the component, it won't show anything.
Here is my Code:
Controller:
public function edit(Workingtime $workingtime)
    {
      $user = User::find(Auth::id());
      $workingtime_array = $user->getWorkingtimesOfThisDay($workingtime->id);
            
      return view('workingtime-edit', compact('workingtime_array', 'workingtime'));     
    }

workingtime-edit.blade.php:
<p>Overview of Workingtimes</p>

@if(count($workingtime_array) > 0)
    <x-workingtime-timeline :workingtimeArray = "$workingtime_array"/>
@endif


workingtime-timeline.blade.php (component):
@props(['workingtimeArray']) 

@php

    if(isset($workingtimeArray) AND count ($workingtimeArray) > 0){
        $start = strtotime($workingtimeArray[0]->time_begin);
        $end = strtotime($workingtimeArray[count($workingtimeArray)-1]->time_end);
    } 

@endphp

@foreach ($workingtimeArray as $worktime)

    <p>Start: {{ $worktime->time_begin }} </p>
    <p>End: {{ $worktime->time_end }} </p>

@endforeach;

When I don't use variables and @props, it shows me the content of the component.
I tried to change the <x-workingtime-timeline :workingtimeArray = "$workingtime_array"/> line but nothing worked.
Things I tried:
<x-workingtime-timeline :workingtimeArray = "$workingtime_array"> </x-workingtime-timeline>
<x-workingtime-timeline workingtimeArray = "$workingtime_array"/>


Answer:
In workingtime-edit.blade.php you need to remove the spaces around the = for the attribute you are setting:
<x-workingtime-timeline :workingtimeArray="$workingtime_array"/>

I think this is a limitation of Laravel's parsing of component attributes, since this is not a general requirement of HTML attributes.
Question: How can I prevent existing categories from disappearing when I add a new category to an email item using Exchange Web Services in C#?

I am trying to add a new category to an email item using Exchange WEB Services but when I run the code, existing categories disappear and the category I added becomes the only category.
For example an email has categories X and Y and after I add my category Z to this mail item, X and Y disappears and only category for the mail becomes Z
Any help is much appreciated.
Thanks in advance
Please note that I am running this code inside a software called Blue Prism a low code no code scripting software and it is near impossible to implement third party libraries etc due to corporate chain of approvals and stuff
When I do it manually on the outlook 2019 it works the way I intended
Here is the method I am using
The DLL That uses this code is Microsoft.Exchange.WebServices.dll
//Here I initialize exchange object and authenticate
ExchangeService exchange = null;

void ConnectEWS(string ewsURL, string _exchangeVersion, string username, string password)
{
    ServicePointManager.ServerCertificateValidationCallback = delegate {return true;} ;
    try
    {
        exchange                = new ExchangeService();
        exchange.Url            = new Uri(ewsURL);
        exchange.Credentials    = new WebCredentials(username,password);
    }
    catch (Exception ex)
    {
        throw new Exception("failed to initialize exchange object!!="+ex.Message);
    }   
}
//here is my void method that adds a new category to an email item
void addCategoryToMail(string msgid, string category)
{
    if(exchange==null)
    {
        throw new Exception("exchange object is null!!");
    }   
    EmailMessage message = EmailMessage.Bind(exchange,msgid, BasePropertySet.IdOnly );
    if(message.Categories.Contains(category)==false)
    {
        message.Categories.Add(category);
        //message.Update(ConflictResolutionMode.AlwaysOverwrite);
        message.Update(ConflictResolutionMode.AutoResolve);
    }
}



Answer:
The line
EmailMessage message = EmailMessage.Bind(exchange,msgid, BasePropertySet.IdOnly );

only requests the message id. You need to request categories. See if BasePropertySet.FirstClassProperties brings categories in. If not, explicitly request categories.
Question: How to read and translate a filename.z.json file

My file has a .z.json-extension and can be found here.
The content of the file is
"7ZQ7a8MwFIX/i2Yn3IekK3nv3EIztCkdQslgSpySuFPwf6+USMZZbiGzFyODPs7RuY+LeTmeu6E79qb9uJhNd9ifh93hx7SGgHgFbkVhg7Z10kJcB+YAIFvTmKd+OHX7s2kvBvPnddgNv+nXPPeb0+7rO115M+1KPGFj3vMJbTptTeuAx8aQAnkrcIMi51OGMENWg4TjDQrRuwJRghBUqTBJoZ9T2qu8g6IVyVOhJFOaw5QF1SwYZlmg18OoWkw4dxgUipArVJSszalrWQgGW/yJDUUJM6VmIVCoCBhmxSK1xN75SoU7inWt0k1RarXoSqmdYf2UYOCi5TMlao1j1UKZ584P9bvVHbrq8NpZk0PnVIdUe5dcHROXKK9nyK7Oyd1wiZqG5ykNmlNBn5PaUSnDML1rHJt/dg3CGoTFW1p2zbJrll2z7JrHd83n+Ac="

Apparently, the most common type of file that contains the .z-file extension is compressed Unix files.
How do I translate / uncompress this file to its human-understandable version? I have no additional information.


Answer:
That is Base-64 encoded raw deflate data. You need to decode the Base-64 to binary, and then use zlib to inflate it. The result is 2278 bytes of json.
Question: Cast pandas series containing list elements to a 2d numpy array

Take the following series:
import pandas as pd

s = pd.Series([1, 3, 2, [1, 3, 7, 8], [6, 6, 10, 4], 5])

I want to convert this series into the following array:
np.array([
    [ 1.,  1.,  1.,  1.],
    [ 3.,  3.,  3.,  3.],
    [ 2.,  2.,  2.,  2.],
    [ 1.,  3.,  7.,  8.],
    [ 6.,  6., 10.,  4.],
    [ 5.,  5.,  5.,  5.]
])

Currently, I am using this logic:
import numpy as np
import pandas as pd
from itertools import zip_longest

# Convert series and each element in series into list
ls = list(map(lambda v: v if isinstance(v, list) else [v], s.to_list()))
# Cast list elements to 2d numpy array with longest list element as column number
a = np.array(list(zip_longest(*ls, fillvalue=np.nan))).T
# Convert to DataFrame, apply 'ffill' row-wise and re-convert to numpy array
a = pd.DataFrame(a).fillna(method="ffill", axis=1).values

My solution is not really satisfying me, especially the last line where I convert my array to a DataFrame and then back to an array again. Does anyone know a better alternative? You can assume that all list elements have the same length.


Answer:
Assuming all list elements have the same length (as indicated), what about using masks and numpy.repeat?
s2 = pd.to_numeric(s, errors='coerce')
m = s2.isna()

out = np.repeat(s2.to_numpy()[:, None], 4, axis=1)
out[m] = np.array(s[m].tolist())

Output:
array([[ 1,  1,  1,  1],
       [ 3,  3,  3,  3],
       [ 2,  2,  2,  2],
       [ 1,  3,  7,  8],
       [ 6,  6, 10,  4],
       [ 5,  5,  5,  5]])
Question: How can I make sure a SQL record's column doesn't refer to its own primary key?

I have a Node table with a ParentID column, which refers to a NodeID that is its parent. I want to make sure no Node can refers to itself (i.e. a Node's ParentID cannot its own NodeID), so I tried adding a check constraint CHECK(NodeID != ParentID).
However, I got this error: Error Code: 3818. Check constraint 'node_chk_1' cannot refer to an auto-increment column.
I also couldn't add the ParentID as a foreign key of Node.
Using MySQL, How can I make sure that there are no new records where NodeID = ParentID?


Answer:
Use a trigger:
mysql> create table node ( 
  id int auto_increment primary key, 
  parentid int, 
  foreign key (parentid) references node (id)
);

mysql> delimiter ;;

mysql> create trigger no_self_ref after insert on node for each row begin
if NEW.parentid = NEW.id then
  signal sqlstate '45000' message_text = 'no self-referencing hierarchies';
end if;
end;;

mysql> delimiter ;

Note that it must be an AFTER trigger, because the auto-increment id has not yet been generated in a BEFORE trigger.
Demo:
mysql> insert into node values (1, null);
Query OK, 1 row affected (0.00 sec)

mysql> insert into node values (2, 2);
ERROR 1644 (45000): no self-referencing hierarchies

mysql> insert into node values (2, 1);
Query OK, 1 row affected (0.01 sec)

You will also need a similar AFTER UPDATE trigger, if you want to prevent users from updating the row and setting the parentid to the same value as the id in the same row.

An alternative solution would be to make the primary key non-auto-increment. You will have to specify every id value in your INSERT statements, instead of letting them be auto-incremented. But this will allow you to use a CHECK constraint.
Question: Android PhotoPicker returns NULL URI

ActivityResultLauncher<PickVisualMediaRequest> pickImage = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {

        if(uri==null) {
            //URI always NULL here
        } else {
            //Never reached
        }


    });

pickImage.launch(new PickVisualMediaRequest.Builder()
                        .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                        .build());


I have tried the same code in a new project and it is returning a valid URI. But PhotoPicker returns a NULL URI in my project. Any idea what could be the issue here?


Answer:
Apparently, PhotoPicker (or ActivityResultLauncher in general) fails if onActivityResult() is also Overridden in the Activity. I removed that and now PhotoPicker is returning a valid URI.
Question: How can I update the master Username and password of and existing AWS RDS cluster using the serverless-framework?

Can't update username of existing RDS cluster
Updating the masterUsername and masterUserPassword in the serverless.yml file for my postgresql database results in the password being updated but not the username.
i.e. I can only access the db with the old username and new password.
I am using the serverless framework to manage aws assests.
It's an RDS cluster.
Everything builds successfully and I can access the data (using the old username).
Waiting for over 30 minutes doesn't have an effect.


Answer:
I understand you want to update the MasterUsername property on an existing RDS instance that you created with Serverless Framework.
Serverless Framework uses AWS CloudFormation. According to the AWS CF docs, the MasterUsername property cannot be updated on an existing RDS instance. Any attempt will result in a resource replacement.
If you still want to update the MasterUsername, your only option is to destroy the RDS instance and create a new one.
Question: List comprehension in Python for if, elif, pass?

I see syntax for if pass but not finding syntax for if elif pass: List comprehension with else pass
Basically
if condition:
    something
elif condition
    something
else
    pass



Answer:
Use an if at the end of the list comprehension (a filter) in order to completely exclude an item from the list.  For example, if you wanted to do this as a list comprehension:
result = []
for i in range(10):
    if i % 2:
        result.append("two")
    elif i % 3:
        result.append("three")
    else:
        pass  # note that you do not actually need this "else" at all

you could do:
result = ["two" if i % 2 else "three" for i in range(10) if i % 2 or i % 3]
Question: how do temporarily turn of vs-code error highlighting

VS Code error hi-lighting can offer quite a bit of clutter during code edits with its squiggles and colorization. It is a useful horn but once the problem is noticed it can become a nuisance that even makes it difficult to perceive the text and fix the problem. I don't think this feature was intended to get in the way.
Is there a convenient way to toggle VSCode error hi-lighting on and off without going through settings.json and playing with a bunch of flags?
Conclusion...

Feature does not exist.

Work around is to install and use the When_File VSCode extension to mask the error noise with less visible colors when the file has unsaved edits, as clarified below.




Answer:
you can use the extension When File
Add this setting to your workspace settings.json
  "whenFile.change": {
    "byLanguageId": {
      "rust": {
        "whenDirty": {
          "editorError.foreground": "#ff000020",
          "editorWarning.foreground": "#ff000020",
          "editorInfo.foreground": "#ff000020"
        }
      }
    }
  }
Question: How can the ASP.NET built-in DI read dependencies from a file at runtime?

As you can see in C# Unity container, we can configure a container (a list of dependency and object creation policy) from a file, and it is very good when, I want change a dependency (backend for interface) in the runtime environment without need to upload my project again, or in a dockerise paradigm, I do not need to build the Docker image again.
At now, I want to migrate to the ASP.NET 6 built-in DI, How can I provide the same functionality in the built-in DI?
For example, something like
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias alias="IProductService" type="UnityExample.Service.IProductService, UnityExample.Service" />
    <containers>
      <container name="Service">
        <register type="IProductService" mapTo="ProductService"/>
      </container>
    </containers>
  </unity>
</configuration>



Answer:
While you could have a hard time making the new service provider compatible with Unity, consider switching to Autofac. Autofac can replace the builtin .NET Core's container  and also it supports loading configuration from a file.
Question: What's the idiomatic way to add a calculated column to multiple data frames?

I have a few dataframes, let's call them rates, sensors with "session_start", "value_timestamp" (timestamps) and "value" (float) columns. I want to add an "elapsed" column, which I've done successfully using the following code:
def add_elapsed_min(df):
  df["elapsed"] = (
    df["value_timestamp"] - df["session_start"].min()
  ).dt.total_seconds() / 60.0

for df in [rates, sensors]:
  add_elapsed_min(df)

Now, this code does work, and the elapsed column is correct. The minor problem is that I keep getting the SettingWithCopyWarning. I've tried changing the code as suggested by the warning, tried adding a contextlib.suppress, but can't seem to remove this warning. This makes me think I must be breaking some idiomatic way to do this. So I'm wondering: If you want to add a calculated column to many dataframes at once, how are you supposed to do this?


Answer:
Although I cannot create your warning in Pandas 1.5.3 and considering using .loc does not suppress the warning for you, one other option is to use df.insert instead.
def add_elapsed_min(df):
  elapsed = (df["value_timestamp"] - df["session_start"].min()) / 60.0
  df.insert(df.shape[1], 'elapsed', elapsed)

for df in [rates, sensors]:
  add_elapsed_min(df)
Question: Javascript plugin and environment variables

I was reading the documentation here https://developer.shopware.com/docs/guides/plugins/plugins/storefront/add-custom-javascript but cannot find a mention on how to make usage of environment variables in a  javascript plugin.
Currently I tried to put a .env file at the root of my plugin in custom/apps/MyPlugin/.env and to capture them via process.env but it fallbacks to my default values...
Is there a way to handle a .env file when you run bash bin/build-storefront.sh?
Thanks.


Answer:
Here's one way to do it...
First create a custom webpack.config.js at src/Resources/app/storefront/build. Also in that build directory run npm install dotenv, as you will need it to parse your .env file.
Your webpack.config.js could then look like this:
const fs = require('fs');
const dotenv = require(`${__dirname}/node_modules/dotenv/lib/main.js`);

module.exports = () => {
    // given you `.env` is located directly in your plugin root dir
    const contents = fs.readFileSync(`${__dirname}/../../../../../.env`);
    const config = dotenv.parse(contents);

    return {
        externals: {
            myPluginEnv: JSON.stringify(config),
        }
    };
};

Then inside your sources you can import myPluginEnv.
import * as myPluginEnv from 'myPluginEnv';

/*
 * Example .env content:
 * FOO=1
 * BAR=1
 */

console.log(myPluginEnv);
// {FOO: '1', BAR: '1'}
Question: Finding keys with the minimum values in each group in a dictionary with jumps (Python)

I have a dictionary where jumps happen in its keys. How can I find the key in between each group where the value is minimum?
For example, I have
myDict = {
        0.98:0.001,
        1.0:0.002,
        1.02: 0.0001,
        3.52:0.01,
        3.57:0.004,
        3.98: 0.005,
        4.01: 0.02,
        6.87: 0.01,
        6.90:0.02,
        6.98:0.001,
        7.0: 0.02
}

My desired output would be 1.02, 3.57, 6.98.
The actual dictionary I'm working with has over 1000 items.


Answer:
Here is a solution, supposing the dictionary is sorted in ascending order according to key (explanations in the comments of the code):
def main():
    d = {
        0.98: 0.001, 1.0: 0.002, 1.02: 0.0001,
        3.52: 0.01, 3.57: 0.004, 3.98: 0.005, 4.01: 0.02,
        6.87: 0.01, 6.90: 0.02, 6.98: 0.001, 7.0: 0.02
    }

    all_groups = []  # list to store the groups
    minimums = []  # list to store all mins
    # initializing holders for minimum key and value
    min_k = 1000
    min_v = 0

    for k, v in d.items():
        # an if-statement just to add the first group with key inside
        if len(all_groups) == 0:
            all_groups.append([k])
            min_k = k
            min_v = d.get(k)
        else:
            # check if the difference is less or equal to 1
            if k - all_groups[-1][-1] <= 1.0:
                all_groups[-1].append(k)

                # each time we add a key to a group, we check if it is the minimum
                if d.get(k) < min_v:
                    min_k = k
                    min_v = d.get(k)
            else:
                minimums.append((min_k, min_v))

                # we append a new list with the new key inside to `all_groups`
                # in which we will store the next elements
                all_groups.append([k])
                min_k = k
                min_v = d.get(k)

    minimums.append((min_k, min_v))  # adding last minimums because for loop ends without adding them

    for i in minimums:
        print(i[0])  # 1.02, 3.57, 6.98


if __name__ == "__main__":
    main()
Question: Change the font size of the output of python code chunk

Consider the following quarto document:
---
title: "Untitled"
format: pdf
---

```{python}
#|echo: false
#|result: 'asis'

import pandas as pd

df = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'],
    'B': ['one', 'one', 'two', 'two', 'one', 'one'],
    'C': ['dull', 'dull', 'shiny', 'shiny', 'dull', 'dull'],
    'D': [1, 3, 2, 5, 4, 1]})

print(df)
```

How to scale down the output of the python chunk, say, to 50%. Is that possible?


Answer:
I can suggest two approaches to do this, use whatever suits you!
Option 01
Code chunk outputs are wrapped inside the verbatim environment. So to change the font size for a single code chunk, one option could be redefining the verbatim environment to have a smaller font size just before that code chunk and then again redefining the verbatim environment to get the default font size for later code chunk outputs.
---
title: "Untitled"
format: pdf
---

\let\oldvrbtm\verbatim
\let\endoldvrbtm\endverbatim

<!-- % redefine the verbatim environment -->
\renewenvironment{verbatim}{\tiny\oldvrbtm}{\endoldvrbtm}

```{python}
#|echo: false
#|result: 'asis'

import pandas as pd

df = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'],
    'B': ['one', 'one', 'two', 'two', 'one', 'one'],
    'C': ['dull', 'dull', 'shiny', 'shiny', 'dull', 'dull'],
    'D': [1, 3, 2, 5, 4, 1]})

print(df)
```

<!-- % redefine the environment back to normal -->
\renewenvironment{verbatim}{\oldvrbtm}{\endoldvrbtm}

```{python}
#|echo: false
#|result: 'asis'

print(df)
```

Option 02
This idea actually is actually taken from this answer on TeXStackExchange. Here A command is defined to control the verbatim font size. So change the font sizes as needed.
---
title: "Untitled"
format: pdf
include-in-header: 
  text: |
    \makeatletter
    \newcommand{\verbatimfont}[1]{\renewcommand{\verbatim@font}{\ttfamily#1}}
    \makeatother
---

\verbatimfont{\tiny}

```{python}
#|echo: false
#|result: 'asis'

import pandas as pd

df = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'],
    'B': ['one', 'one', 'two', 'two', 'one', 'one'],
    'C': ['dull', 'dull', 'shiny', 'shiny', 'dull', 'dull'],
    'D': [1, 3, 2, 5, 4, 1]})

print(df)
```

\verbatimfont{\normalsize}

```{python}
#|echo: false
#|result: 'asis'

print(df)
```

Note: The predefined font sizes that you can use in both of the above options are, \Huge, \huge, \LARGE, \Large, \large, \normalsize, \small, \footnotesize, \scriptsize, \tiny