satoshi-2000/llms-suitable huggingface dataset:
Question: Creating a WHILE Loop in Visio ShapeSheet

I'm aware that this can be easily done using VBA, but I'd like a macroless solution if possible.
I have 2 User rows in a Shape's ShapeSheet: User.Count and User.Loop. User.Count will simply store a number, and the While loop will be performed by User.Loop using the following basic conditional:
User.Loop = IF(User.Count < 1000, SETF(GETREF(User.Count), User.Count + 1), "Loop complete!")  + DEPENDSON(User.Count)

This executes to User.Count = 41 (these pulses of 41 are consistent). Is performing this type of loop possible?


Answer:

because if the answer ever becomes 42 then that is the end of Life, The Universe and Everything!

Paul you are right ! :)

changing the loop limit to 40 and

Sad, but this trick dont works…

My experiment results.

My example file
My loop can't make it to the 1000 mark. It has to stop at 80. You can continue the loop through the context menu Go to 1000 limit.
Question: Manage edge's weight and attributes with Netoworkx

I'm facing on a trouble related to how I'm managing the edges and their weight and attributes in a MultiDiGraph.
I've a list of edges like below:
[
(0, 1, {'weight': {'weight': 0.8407885973127324, 'attributes': {'orig_id': 1, 'direction': 1, 'flip': 0, 'lane-length': 3181.294317920477, 'lane-width': 3.6, 'lane-shoulder': 0.0, 'lane-max-speed': 50.0, 'lane-typology': 'real', 'lane-access-points': 6, 'lane-travel-time': 292.159682258003, 'lane-capacity': 7200.0, 'lane-cost': 0.8407885973127324, 'other-attributes': None, 'linestring-wkt': 'LINESTRING (434757.15286960197 4524762.33387408, 434267.30180536775 4525511.90463009, 436180.7891782945 4526762.385413274)'}}}), 
(1, 4, {'weight': {'weight': 0.6659876355281887, 'attributes': {'orig_id': 131, 'direction': 1, 'flip': 0, 'lane-length': 2496.129360921626, 'lane-width': 3.6, 'lane-shoulder': 0.0, 'lane-max-speed': 50.0, 'lane-typology': 'real', 'lan...

That list is used to add weight and attributes to a MultiDiGraph previous mentioned:
 graph = ntx.MultiDiGraph(weight=None)
 graph.add_weighted_edges_from(edge_list)

Trying to read the properties of a single edge(graph.edges.data()) I see this:
(0, 1, {'weight': {'weight': 0.8407885973127324, 'attributes': {'orig_id': 1, 'direction': 1, 'flip': 0, 'lane-length': 3181.294317920477, 'lane-width': 3.6, 'lane-shoulder': 0.0, 'lane-max-speed': 50.0, 'lane-typology': 'real', 'lane-access-points': 6, 'lane-travel-time': 292.159682258003, 'lane-capacity': 7200.0, 'lane-cost': 0.8407885973127324, 'other-attributes': None, 'linestring-wkt': 'LINESTRING (434757.15286960197 4524762.33387408, 434267.30180536775 4525511.90463009, 436180.7891782945 4526762.385413274)'}}})

Every edge is builded in that way: [node[0], node[1], {'weight': weight, 'attributes': attributes}].
If I use this way: [node[0], node[1], weight], I see the right use of the weight but I need to use also the attributes.
[(0, 1, {'weight': 0.8407885973127324}), (1, 4, {'weight': 0.6659876355281887}), (1, 46, {'weight': None}), (4, 5, {'weight': 1.2046936800705539}), (4, 6, {'weight': 0.4469496439663275})....

What is the correct way to manage in the same time both weight and attributes?


Answer:
Using add_weighted_edges_from does not have an option to add independent edge attributes. It takes a list of triples (u,v,w) and consider w as the weight. That's why, you find a nested dictionary in the weight attribute of the node.
You can add shared attribute for the bunch by specifying keyword argument:
graph.add_weighted_edgees_from([...], attr1=..., attr2=...)

but you will find the same attribute values for all edges in the bunch.
Instead, you can directly use the add_edge method in a for loop:
for u, v, attr in [...]:
   graph.add_edge(u, v, **attr)

which will add your edges with individual attributes.
Question: Table only appears for a split second on button click

I have a button and a table on my webpage. I want to view the table when I click that button. I have tried it using javascript but the table only appears for a split second and then disappears. following is the code for my table:


var button = document.getElementById('BtnNextInsured'); // Assumes element with id='button'

button.onclick = function() {
  var div = document.getElementById('tblContact');
  if (div.style.display !== 'none') {
    div.style.display = 'none';
  } else {
    div.style.display = 'block';
  }
};
<button id="BtnNextInsured" class="btn btn-md btn-primary">Next</button> Table to show:

<table id="tblContact" class="table table-light table-borderless" style="display:none;">
  <tr>
    <td class="cellContent">
      <input id="txtEmail" class="txt" placeholder="Email" />
    </td>
    <td class="cellContent">
      <input id="txtCell" class="txt" placeholder="Cell Phone" />
    </td>
    <td class="cellContent">
      <input id="txtLandline" class="txt" placeholder="Landline" />
    </td>
  </tr>

  <tr>
    <td colspan="3" style="text-align: right">
      <button id="BtnNextContact" class="btn btn-md btn-primary">Next</button>
    </td>
  </tr>
</table>



I don't understand what's wrong with my code. I am a beginner to javascript.


Answer:
as comments saying better using eventlistener.
with the eventlistene, you can use the event and like here stop it to avoid double click.
to appear disappear use a class 'hide' so you can toggle it, easier than than checking display none.


const tableAppear = () => {
  document.querySelector('#BtnNextInsured').addEventListener('click', evt => {
    evt.stopImmediatePropagation();
    document.querySelector('#tblContact').classList.toggle('hide');
  });
}
window.addEventListener('load', tableAppear);
.hide {
  display: none;
}
<button id="BtnNextInsured" class="btn btn-md btn-primary">Next</button> Table to show:

<table id="tblContact" class="table table-light table-borderless hide">
  <tr>
    <td class="cellContent">
      <input id="txtEmail" class="txt" placeholder="Email" />
    </td>
    <td class="cellContent">
      <input id="txtCell" class="txt" placeholder="Cell Phone" />
    </td>
    <td class="cellContent">
      <input id="txtLandline" class="txt" placeholder="Landline" />
    </td>
  </tr>

  <tr>
    <td colspan="3" style="text-align: right">
      <button id="BtnNextContact" class="btn btn-md btn-primary">Next</button>
    </td>
  </tr>
</table>
Question: Why am I able to use C# lists without writing "using System.Collections.Generic;" at the beginning of my file?

Take a look at this simple C# program:
using System;

namespace testProgram
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string>();
            list.Add("List element.");
            Console.WriteLine(list[0]);
        }
    }
}

Output:
List element.

You can see that it uses a list. I always saw on the Internet that in order to use a list, I need to add "using System.Collections.Generic;" at the beginning of my file. However, the program can run without this line, why?


Answer:
Look at your project file. I strongly suspect it will include this:
<ImplicitUsings>enable</ImplicitUsings>

The ImplicitUsings feature is described here:

The ImplicitUsings property can be used to enable and disable implicit global using directives in C# projects that target .NET 6 or a later version and C# 10 or a later version. When the feature is enabled, the .NET SDK adds global using directives for a set of default namespaces based on the type of project SDK. Set this property to true or enable to enable implicit global using directives. To disable implicit global using directives, remove the property or set it to false or disable.

Note that that means you don't need using System; either.
Combined with top-level statements, your whole file could actually be:
List<string> list = new List<string>();
list.Add("List element.");
Console.WriteLine(list[0]);

Or if the namespace is important to you:
namespace testProgram;

List<string> list = new List<string>();
list.Add("List element.");
Console.WriteLine(list[0]);
Question: import python libraries (eg: rapidjson) in airflow

I want to use the Python library rapidjson in my Airflow DAG. My code repo is hosted on Git. Whenever I merge something into the master or test branch, the changes are automatically configured to reflect on the Airflow UI.
My Airflow is hosted as a VM on AWS EC2. Under the EC2 instances, I see three different instances for: scheduler, webserver, workers.
I connected to these 3 individually via Session Manager. Once the terminal opened, I installed the library using
pip install python-rapidjson

I also verified the installation using pip list. Now, I import the library in my dag's code simply like this:
import rapidjson

However, when I open the Airflow UI, my DAG has an error that:
No module named 'rapidjson'

Are there additional steps that I am missing out on? Do I need to import it into my Airflow code base in any other way as well?
Within my Airflow git repository, I also have a "requirements.txt" file. I tried to include
python-rapidjson==1.5.5
this there as well but I do not know how to actually install this.
I tried this:
pip install requirements.txt
within the session manager's terminal as well. However, the terminal is not able to locate this file. In fact, when I do "ls", I don't see anything.
pwd
/var/snap/amazon-ssm-agent/6522



Answer:
Have you tried using the PythonVirtualEnvOperator ?
It will allow you to install the library at runtime so you don't need to make changes on the server just for one job.
To run a function called my_callable, simply use the following:
from airflow.operators.python import PythonVirtualenvOperator


my_task = PythonVirtualenvOperator(
        task_id="my_task ",
        requirements="python-rapidjson==1.5.5",
        python_callable=my_callable,
    )

I still recommend updating your server environment for core libs, but this is a best practice when using special libs for a small minority of jobs.
Question: Is there a way to set a ConsoleColor value equal to a variable?

I am working on creating a class to support a console app I am developing, and I would like to create a method within to change both the background and foreground color.  Is there a way to set a ConsoleColor value (which I believe is an enum) to another variable so this can easily be changed by the user at runtime?  For instance, I am hoping for something like the following.
Public class ConsoleOutput
{
  private var consoleBackground = ConsoleColor.White;
  private var consoleForeground = ConsoleColor.Black;
  
  Public ConsoleOutput
  {
    Console.BackgroundColor = consoleBackground
    Console.ForegroundColor = consoleForeground
  }
}

This, however, did not work.


Answer:
You don't seem to ever write to the console in your program, which you obviously need to do. Other then that you also need a way to change the colors during runtime using e.g. setters or a function like ChangeColors().
Here a working sample program for reference:
namespace MyProgram;

class Program
{
    static void Main(string[] args)
    {
        var coloredPrinter = new ColoredPrinter(ConsoleColor.White, ConsoleColor.Blue);
        coloredPrinter.WriteLine("This is white text on blue background");
        coloredPrinter.ChangeColors(ConsoleColor.Yellow, ConsoleColor.Red);
        coloredPrinter.WriteLine("This is yellow text on red background");
        Console.WriteLine("This is the default");
    }
}

class ColoredPrinter
{
    public ConsoleColor ForegroundColor { get; set; }
    public ConsoleColor BackgroundColor { get; set; }

    public ColoredPrinter(ConsoleColor foregroundColor, ConsoleColor backgroundColor)
    {
        ChangeColors(foregroundColor, backgroundColor);
    }

    public void ChangeColors(ConsoleColor foregroundColor, ConsoleColor backgroundColor)
    {
        ForegroundColor = foregroundColor;
        BackgroundColor = backgroundColor;
    }

    public void WriteLine(string text)
    {
        Console.ResetColor();
        Console.BackgroundColor = BackgroundColor;
        Console.ForegroundColor = ForegroundColor;
        Console.WriteLine(text);
        Console.ResetColor();
    }
}


This prints out the following:
Question: How to destroy an initiated GameObject on collision?

I have created a script that spawns bullets/projectiles that moves forward with a certain force. However, the bullet itself does not disappear on collision. Since it is a instantiated object, how do I make it disappear? I've tried OnCollisionEnter() but to no avail. The code below is how i created the bullet.
// Instantiate bullet/projectile
GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);
        
// Rotate bullet to shoot direction
currentBullet.transform.forward = directionWithSpread.normalized;

// Add forces to bullet
currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse);

EDIT
Perhaps, is there anyway to assign a script to a prefab that will be instantiated?


Answer:
You can choose two paths to achieve this
1) Adding the script to the prefab (done in the editor)
You can edit the prefab (opening it from the editor) and add the script to it.
2) Adding the script to the instance (done programmatically)
In this case your first instantiate the prefab and then programmatically add the script to it with something like this:
GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);

currentBullet.AddComponent<YourScript>();

3? Using RayCasting (this option in my opinion fits your needs)
Usually the best way to handle bullets is using RayCast
In this case the bullet does not need the code to handle its collision but it is just the visual representation of the bullet, the real collision detection and other actions linked to it are controlled by the raycasting, in this way you save some memory
Hope this helps
Question: reading input from .txt file in C

john smith 21 VETERAN 1   
I have  a .txt file writing this . I want to read this .txt file and take john smith as a variable . but I can't read with whitespaces.
edit: I want to take john smith and print it in the console with
 printf("%s",name);
I tried code below but didnt work. only takes smith.
while (fscanf(file, "%s, %d %s %d", name, &age, priorityGroup, &priorityLevel) == 4)

edit2:


Answer:
The task is not easy for beginners learning C.
There can be different approaches.
I can suggest the following approach.
At first a full record is read from the file using standard C function fgets as for example
char record[100];

fgets( record, sizeof( record ), fp );

Now let's assume that the record is already read. Then to output the first two words in record you can use standard C function sscanf as shown in the demonstration program below.
#include <stdio.h>

int main( void )
{
    char record[] = "john smith 21 VETERAN 1\n";

    int n = 0;

    for (size_t i = 0; i < 2; i++)
    {
        const char *p = record + n;
        int m;

        sscanf( p, "%*s%n", &m );

        n += m;
    }

    printf( "\"%.*s\"\n", n, record );
}

The program output is
"john smith"

Or you could make a string of the two words just writing
record[n] = '\0';
printf( "\"%s\"\n", record );

Or if your compiler supports variable length arrays you could write
#include <string.h>

//...

char name[n + 1];

memcpy( name, record, n );
name[n] = '\0';

printf( "\"%s\"\n", name );

If the compiler does not support variable length arrays then you will need to allocate an array dynamically like for example
#include <string.h>
#include <stdlib.h>

//...

char *name = malloc( n + 1 );

memcpy( name, record, n );
name[n] = '\0';

printf( "\"%s\"\n", name );

In this case do not forget to free the allocated memory when it will not be required any more
free( name );

In the demonstration program the string literal used as an initializer of the array record is appended with the new line character '\n' because the function fgets itself can store this character in the destination array.
Question: ForEach method skips Console.WriteLine() on each iteration, then dumps all the logs when loop is done. Why?

I have this piece of code:
[Test]
public void LinqConsoleOutputTest() {
    Enumerable.Range(0, 10).ToList().ForEach(_ => {
        Thread.Sleep(500);
        Console.WriteLine($"Slept...");
    });
}

And to my surprise the code was executing around 5 seconds as expected, but it did not print to the console. It just dumped all 10 logs when it finished ForEach loop.
And I am just curious why does it work that way? Is it related to ForEach/Linq or maybe to the Console object?


Answer:
Console.WriteLine() writes to whatever is the Standard Output which might not be a console in case of a test. Run the same code in a simple "normal" C# program and it will print as expected.
Consider this program:
namespace MyProgram;

class Program
{
    static void Main(string[] args)
    {
        using var fileStream = File.OpenWrite("./consoleOutput.txt");
        using var streamWriter = new StreamWriter(fileStream);
        // redirect standard output
        Console.SetOut(streamWriter);
        Enumerable.Range(0, 10).ToList().ForEach(_ =>
        {
            Thread.Sleep(500);
            Console.WriteLine($"Slept... {DateTime.UtcNow}");
        });
        Console.WriteLine("Done");
    }
}

What this program does is, it redirects the standard output to write to a FileStream of a file called consoleOutput.txt. So when you run the program it creates the file and writes everything you would normally print to the console to the file. If you have a look at the file you can see that in fact it contains the whole output:
consoleOutput.txt
Slept... 6/3/2023 9:34:42 PM
Slept... 6/3/2023 9:34:42 PM
Slept... 6/3/2023 9:34:43 PM
Slept... 6/3/2023 9:34:43 PM
Slept... 6/3/2023 9:34:44 PM
Slept... 6/3/2023 9:34:44 PM
Slept... 6/3/2023 9:34:45 PM
Slept... 6/3/2023 9:34:45 PM
Slept... 6/3/2023 9:34:46 PM
Slept... 6/3/2023 9:34:46 PM
Done
Question: Nested for loop not looping on the first set, Python

I have written this code in python. In the end I would like to use this to get the indices to cut up a 100x100 matrix into squares that overlap by 10. However, at the bottom there is a nested loop and the y values print how I think they should but not the x-values, the x-values never change... Can anyone help? Thanks
x_split = np.linspace(0, 100, 4 + 1, dtype=int)
x_start = x_split[:-1] - 5
x_start[0] = 0
x_end = x_split[1:] + 5
x_end[-1] = 100

y_split = np.linspace(0, 100, 4 + 1, dtype=int)
y_start = y_split[:-1] - 5
y_start[0] = 0
y_end = y_split[1:] + 5
y_end[-1] = 100

x_inds = zip(x_start, x_end)
y_inds = zip(y_start, y_end)

i = 0
for start_x, end_x in x_inds:
    for start_y, end_y in y_inds:
        i += 1
        print(f"i = {i}")
        print(f"x = {start_x} {end_x}")
        print(f"y = {start_y} {end_y}")
        print("")

Current output:
i = 1
x = 0 30
y = 0 30

i = 2
x = 0 30
y = 20 55

i = 3
x = 0 30
y = 45 80

i = 4
x = 0 30
y = 70 100

And then stops. I want to to continue...
i = 5
x = 20 55
y = 0 30

i = 6
x = 20 55
y = 20 55

...



Answer:
zip(y_start, y_end) returns an iterator.  After the first series of Xs, y_inds is exhausted and yields no more values for the subsequent values of X.
Make it y_inds a list, so it can be reused on subsequence X rows:
*y_inds, = zip(y_start, y_end)

You could also let numpy do the iterating for you to produce a matrix of square coordinates:
coords  = np.repeat(x_start,y_start.size)[:,None], \
          np.repeat(x_end,  y_start.size)[:,None], \
          np.tile(y_start,x_start.size)[:,None],   \
          np.tile(y_end,  x_start.size)[:,None]
squares = np.concatenate(coords,axis=1)
print(squares)
[[  0  30   0  30]
 [  0  30  20  55]
 [  0  30  45  80]
 [  0  30  70 100]
 [ 20  55   0  30]
 [ 20  55  20  55]
 [ 20  55  45  80]
 [ 20  55  70 100]
 [ 45  80   0  30]
 [ 45  80  20  55]
 [ 45  80  45  80]
 [ 45  80  70 100]
 [ 70 100   0  30]
 [ 70 100  20  55]
 [ 70 100  45  80]
 [ 70 100  70 100]]
Question: Flutter - in_app_purchase plugin - iOS - works in sim but not on device

Building an iOS app, _inAppPurchase.queryProductDetails(productIds); returns product details in a simulator (ipad, iphone) and everything works. But if I run on a physical iPhone productDetailResponse.productDetails.isEmpty is true and my product ids are in notFoundIDs. Same if I 'flutter build ipa' and try in TestFlight. Using synced StoreKit.storekit.. in_app_purchase: ^3.1.7. Why this may be?


Answer:
Getting all "Agreements, Tax and Banking" bits sorted and "Active" in App Store Connect has fixed it. Things started working the same on the device, simulator and TestFlight as soon as the forms got reviewed and approved.
Question: Not explicitly saying `return` gives error: `match` arms have incompatible types

I am very new to Rust.
The following function:
async fn create(body: String) -> impl IntoResponse {
    let j = match serde_json::from_str::<CreationJSON>(&body) {
        Ok(j) => j,
        Err (_) => (
            StatusCode::UNPROCESSABLE_ENTITY,
            "body is invalid".to_string(),
        ),
    };
    println!("{:?}", j.record_stringified);

    (
        StatusCode::CREATED,
        "created".to_string(),
    )
}

gives error:
error[E0308]: `match` arms have incompatible types
   --> src/main.rs:128:20
    |
126 |       let j = match serde_json::from_str::<CreationJSON>(&body) {
    |               ------------------------------------------------- `match` arms have incompatible types
127 |           Ok(j) => j,
    |                    - this is found to be of type `CreationJSON`
128 |           Err (_) => (
    |  ____________________^
129 | |             StatusCode::UNPROCESSABLE_ENTITY,
130 | |             "body is invalid".to_string(),
131 | |         ),
    | |_________^ expected `CreationJSON`, found `(StatusCode, String)`
    |
    = note: expected struct `CreationJSON`
                found tuple `(axum::http::StatusCode, std::string::String)`

However, if I add a "return" to the Err arm, then it works fine:
async fn create(body: String) -> impl IntoResponse {
    let j = match serde_json::from_str::<CreationJSON>(&body) {
        Ok(j) => j,
        Err (_) => return (
            StatusCode::UNPROCESSABLE_ENTITY,
            "body is invalid".to_string(),
        ),
    };
    println!("{:?}", j.record_stringified);

    (
        StatusCode::CREATED,
        "created".to_string(),
    )
}

Why do I need to add the return in the Err arm? I thought a function with no semi-colon was supposed to automatically return in Rust?


Answer:
return returns from the function. If you don't use the return keyword, then it'll "return" from the statement. In your first example, you're trying to assign the tuple to the variable j, while in the second you return from the function.