问:
Not Able To Download Bhav Zip File
Last Time this code is working but now i am not able to download the bhav file from the NSE web site

blow the code i am using

```<code>    Dim WC As New WebClient
    Dim DD, MMM, YYYY As String
    Dim FileName As String
    Dim FileURL As String
    Dim ZipPath As String

        ServicePointManager.Expect100Continue = True
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

        DD = DateTimePicker1.Value.ToString("dd")
        MMM = UCase(DateTimePicker1.Value.ToString("MMM"))
        YYYY = DateTimePicker1.Value.ToString("yyyy")

        If UCase(DateTimePicker1.Value.ToString("dddd")) = "SATURDAY" Then Exit Sub
        If UCase(DateTimePicker1.Value.ToString("dddd")) = "SUNDAY" Then Exit Sub

        FileName = "cm03AUG2021bhav.csv.zip"
        FileName = FileName.Replace("03AUG2021", DD & MMM & YYYY)

        FileURL = "https://www1.nseindia.com/content/historical/EQUITIES/2023/JAN/cm02JAN2023bhav.csv.zip"

        FileURL = FileURL.Replace("2023", YYYY)
        FileURL = FileURL.Replace("JAN", MMM)
        FileURL = FileURL.Replace("02", DD)

        ZipPath = App.Dir.BhavPath & "\" & FileName
        WC.DownloadFile(FileURL, ZipPath)

</code>```

i am trying to download the file but not downloading now

getting the error in vb.net

The remote server returned an error: (403) Forbidden.

url - https://www1.nseindia.com/content/historical/EQUITIES/2023/JAN/cm02JAN2023bhav.csv.zip

getting error in google crome

Access Denied
You don't have permission to access "http://www1.nseindia.com/content/historical/EQUITIES/2023/JAN/cm02JAN2023bhav.csv.zip" on this server.
Reference #18.83e83217.1672846762.b1fb356

i am able to download from this link from google chrome

https://www1.nseindia.com/products/content/all_daily_reports.htm

Title: Not Able To Download Bhav Zip File

Body:
Last Time this code is working but now i am not able to download the bhav file from the NSE web site

blow the code i am using

    Dim WC As New WebClient
    Dim DD, MMM, YYYY As String
    Dim FileName As String
    Dim FileURL As String
    Dim ZipPath As String

        ServicePointManager.Expect100Continue = True
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

        DD = DateTimePicker1.Value.ToString("dd")
        MMM = UCase(DateTimePicker1.Value.ToString("MMM"))
        YYYY = DateTimePicker1.Value.ToString("yyyy")

        If UCase(DateTimePicker1.Value.ToString("dddd")) = "SATURDAY" Then Exit Sub
        If UCase(DateTimePicker1.Value.ToString("dddd")) = "SUNDAY" Then Exit Sub

        FileName = "cm03AUG2021bhav.csv.zip"
        FileName = FileName.Replace("03AUG2021", DD & MMM & YYYY)

        FileURL = "https://www1.nseindia.com/content/historical/EQUITIES/2023/JAN/cm02JAN2023bhav.csv.zip"

        FileURL = FileURL.Replace("2023", YYYY)
        FileURL = FileURL.Replace("JAN", MMM)
        FileURL = FileURL.Replace("02", DD)

        ZipPath = App.Dir.BhavPath & "\" & FileName
        WC.DownloadFile(FileURL, ZipPath)

i am trying to download the file but not downloading now

getting the error in vb.net

The remote server returned an error: (403) Forbidden.

url - https://www1.nseindia.com/content/historical/EQUITIES/2023/JAN/cm02JAN2023bhav.csv.zip

getting error in google crome

Access Denied
You don't have permission to access "http://www1.nseindia.com/content/historical/EQUITIES/2023/JAN/cm02JAN2023bhav.csv.zip" on this server.
Reference #18.83e83217.1672846762.b1fb356

i am able to download from this link from google chrome

https://www1.nseindia.com/products/content/all_daily_reports.htm


来源: stackexchange

问:
SQL 2 Core license installed on 16 Core machine. How will it work? Does SQL utilize only 4 core (2x2) out of 16 core available on machine?
I was just wondering if we install 2 Core license of SQL Standard edition on a 16 Core machine, how will it work? Does SQL utilize only 4 core (2x2) out of 16 core available on machine and 12 cores will not be used?

How to SQL (Microsoft) implement per-core licensing check and works?

I looked through internet but could not find any satisfactory explanation. Can anyone here help or provide link to document that explains the model?

Ran the following query and it shows ALL Cores in use.

SELECT
    DOS.is_online
,   DOS.status
,   DOS.*
FROM
    sys.dm_os_schedulers AS DOS
ORDER BY
    5;
```

ContentLicense: CC BY-SA 4.0


问:
Boolean comparison explanation
I'm studying Javascript and in one of my quizzes I found this

```<code>var foo = function(){};
console.log(foo === foo);  //  true
console.log(foo === function(){});  // false
console.log(function(){} === function(){});// false
console.log(foo instanceof function(){}); // false
console.log(['a'] == ['a']);// false
</code>```

Beside foo === function(){} and foo instanceof function(){} which are evidently false I can't get why all the other comparisons are also false. For example why ['a'] == ['a'] should be false?

Thank you in advance!

Title: Boolean comparison explanation

Body:
I'm studying Javascript and in one of my quizzes I found this

var foo = function(){};
console.log(foo === foo);  //  true
console.log(foo === function(){});  // false
console.log(function(){} === function(){});// false
console.log(foo instanceof function(){}); // false
console.log(['a'] == ['a']);// false

Beside foo === function(){} and foo instanceof function(){} which are evidently false I can't get why all the other comparisons are also false. For example why ['a'] == ['a'] should be false?

Thank you in advance!


问:
Artifactory won't load with blocked HTTPS outbound
I have Artifactory Pro (trial) installed on VM in Azure. I have to check how will it work without internet access. I use only Maven repositories so I created NSG outbound role for blocking HTTPS access. After reboot Artifactory won't load. From log:

2023-01-04T11:27:40.641Z [jfrou] [WARN ] [0e5f4bf9d6dc7f57] [local_topology.go:274         ] [main                ] [] - Readiness test failed with the following error: "required node services are missing or unhealthy"
2023-01-04T11:27:41.087Z 35[jfob ] [INFO ] [44efcd4b59cba041] [artifactory_client.go:159     ] [main                ] [] - Fetching Artifactory version [artifactory_client]
2023-01-04T11:27:41.092Z 35[jfob ] [INFO ] [44efcd4b59cba041] [artifactory_client.go:176     ] [main                ] [] - Got HTTP 503 from Artifactory [artifactory_client]
2023-01-04T11:27:41.092Z 35[jfob ] [INFO ] [44efcd4b59cba041] [artifactory_client.go:183     ] [main                ] [] - Fetch base URL from Artifactory returned: 503


问:
Images not showing since i moved to cloudflare
I am using a WordPress website and elementor and recently moved my Name servers to Cloud flare but since i moved the images and logo are no longer  showing. I suspect elementor but how do i go about to fix it.

I tried disabling elementor plugin but the issue still persists.


问:
DataIntegrityViolationException: The column index is out of range: 1, number of columns: 0
I am trying to execute the following:

```<code>jdbcTemplate.update("DELETE FROM my_table WHERE created <= (NOW() - interval '? milliseconds')", 1);
</code>```

but getting the following error:

org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [DELETE FROM my_table WHERE created <= (NOW() - interval '? milliseconds')]; The column index is out of range: 1, number of columns: 0.; nested exception is org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.

I think it may be because the ? is inside a string literal:

```<code>'? milliseconds'
</code>```

but I'm not sure what the solution is?

I can execute the following ok using the SQL editor, and get results back:

```<code>select * from my_table where created <= (NOW() - interval '1 milliseconds');
</code>```

Body:
I am trying to execute the following:

jdbcTemplate.update("DELETE FROM my_table WHERE created <= (NOW() - interval '? milliseconds')", 1);

but getting the following error:

org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [DELETE FROM my_table WHERE created <= (NOW() - interval '? milliseconds')]; The column index is out of range: 1, number of columns: 0.; nested exception is org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.

I think it may be because the ? is inside a string literal:

'? milliseconds'

but I'm not sure what the solution is?

I can execute the following ok using the SQL editor, and get results back:

select * from my_table where created <= (NOW() - interval '1 milliseconds');


问:
C# FFMPEG - How to get extracted frames without save in file system
I need to process frames from video and live stream without saving into file system.

C# I am trying using below code, but not getting frames

```<code>Process proc = new Process();
            proc.StartInfo.FileName = @"E:\ffmpeg\bin\ffmpeg.exe";
            proc.StartInfo.Arguments = String.Format(@"-i E:\ffmpeg\bin\video.mp4 -f rawvideo pipe:1");
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();
proc.OutputDataReceived += (sender, args) => DataReceived(args);
            proc.ErrorDataReceived += (sender, args) => DataReceived(args);
</code>```

I can get frames in nodejs successfully using below code

```<code>
const spawnProcess = require('child_process').spawn
    ffmpeg = spawnProcess('E:\\ffmpeg\\bin\\ffmpeg.exe', [
      '-i', 'rtsp://username:password@192.168.6.37/ch1/main/sub-stream',
      '-vcodec', 'mjpeg','-vf','fps=2',
      '-f', 'rawvideo',
      //'-s', HW, // size of one frame
      'pipe:1'
  ]);
      ffmpeg.stderr.pipe(logStream);
      let frames = [];
      ffmpeg.stdout.pipe(new ExtractFrames("FFD8FF")).on('data', (data) => {
        var fName=new Date().getTime()+".png";
        (
          async () => await ProcessFrame(Buffer.from(data).toString('base64'))
        )();
      })
</code>```

Same thing await ProcessFrame(Buffer.from(data).toString('base64')) I want in C#

Body:
I need to process frames from video and live stream without saving into file system.

C# I am trying using below code, but not getting frames

Process proc = new Process();
            proc.StartInfo.FileName = @"E:\ffmpeg\bin\ffmpeg.exe";
            proc.StartInfo.Arguments = String.Format(@"-i E:\ffmpeg\bin\video.mp4 -f rawvideo pipe:1");
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();
proc.OutputDataReceived += (sender, args) => DataReceived(args);
            proc.ErrorDataReceived += (sender, args) => DataReceived(args);

I can get frames in nodejs successfully using below code

const spawnProcess = require('child_process').spawn
    ffmpeg = spawnProcess('E:\\ffmpeg\\bin\\ffmpeg.exe', [
      '-i', 'rtsp://username:password@192.168.6.37/ch1/main/sub-stream',
      '-vcodec', 'mjpeg','-vf','fps=2',
      '-f', 'rawvideo',
      //'-s', HW, // size of one frame
      'pipe:1'
  ]);
      ffmpeg.stderr.pipe(logStream);
      let frames = [];
      ffmpeg.stdout.pipe(new ExtractFrames("FFD8FF")).on('data', (data) => {
        var fName=new Date().getTime()+".png";
        (
          async () => await ProcessFrame(Buffer.from(data).toString('base64'))
        )();
      })

Same thing await ProcessFrame(Buffer.from(data).toString('base64')) I want in C#


问:
Identity.TwoFactor cookie not included in subsequent request to WebAPI using Identity Core
I'm building a SPA using React.JS, WebAPI and Identity Core as authentication.

I'm able to authenticate a user, generate a twofactor token and in the webservice response I get the needed cookie to identity the user's two factor request (Identity.TwoFactorUserId).
I am however not able to ensure that the cookie is included in the request when sending the two factor token back to the API.
The issue only occurs on development environment, where the SPA and API is working on separate servers. On Test where its on a single website, cookies work properly.

I'm pretty sure its related to the SameSite policy on the cookie, but not sure how to change it on development.

Dev setup:
React.JS SPA. https://localhost:12345
WebAPI: https://localhost:5050

Dev: The Identity.TwoFactorUserId is in response, but it not sent back with the 2fa request

How it looks on Test. The Identity.TwoFactorUserId is sent with request

My Startup.cs add the identity cookies like this

enter image description here


问:
Quotation marks for the first column of a file using a command in terminal
Having this information in the file
File1.txt

```<code>iron_sword 1420
</code>```

I want to get this result:

```<code>"iron_sword" 1420
</code>```

I tried to do solve with awk command:
awk '{print "$1", $2}'
,but all i got was

```<code>$1 1420
</code>```

Body:
Having this information in the file
File1.txt

iron_sword 1420

I want to get this result:

"iron_sword" 1420

I tried to do solve with awk command:
awk '{print "$1", $2}'
,but all i got was

$1 1420


问:
SSH Into a server using NODE.JS
I'm trying to build an tool in nodeJS to make it easier to ssh into one of our acceptance or production servers. I just want to have the same result as if i type it into the terminal

```<code>exec("ssh <server-ip>", (error, stdout, stderr) => {
  if (error) {
    console.log(`error: ${error.message}`);
    return;
  }
  if (stderr) {
    console.log(`stderr: ${stderr}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
});

</code>```

Now i hoped this would ssh me into the server but it just shows an empty line

Title: SSH Into a server using NODE.JS

Body:
I'm trying to build an tool in nodeJS to make it easier to ssh into one of our acceptance or production servers. I just want to have the same result as if i type it into the terminal

exec("ssh <server-ip>", (error, stdout, stderr) => {
  if (error) {
    console.log(`error: ${error.message}`);
    return;
  }
  if (stderr) {
    console.log(`stderr: ${stderr}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
});

Now i hoped this would ssh me into the server but it just shows an empty line


问:
I have SQL query how can I convert it into Laravel Query Builder format
MySQL query

SELECT
    dri_id,
    COUNT(1) AS total_rides,
    SUM(
        CASE
            WHEN end_loc=next_start_ride THEN 1
            ELSE 0
        END
    ) AS profit_ride
FROM
    (
        SELECT
            *,
            lead(start_loc, 1) over(PARTITION BY dri_id ORDER BY start_time ASC) AS next_start_ride
        FROM
            `drivers`
    ) a
GROUP BY dri_id;
```

Please convert it into Laravel Query Builder format.

Body:
MySQL query

SELECT
    dri_id,
    COUNT(1) AS total_rides,
    SUM(
        CASE
            WHEN end_loc=next_start_ride THEN 1
            ELSE 0
        END
    ) AS profit_ride
FROM
    (
        SELECT
            *,
            lead(start_loc, 1) over(PARTITION BY dri_id ORDER BY start_time ASC) AS next_start_ride
        FROM
            `drivers`
    ) a
GROUP BY dri_id;

Please convert it into Laravel Query Builder format.


问:
How can I save a list of ipyleaflet markers to a file and load them later on?
I'd like to save a list of ipyleaflet markers so I can load them into another ipyleaflet map later on. I have customized the markers using a MarkerCustom class in order to incorporate another attribute (duration), which works fine. Later on I also split them up into different clusters, so I do not want to save them as one cluster at this stage.

```<code>from traitlets import List
import ipyleaflet
from ipywidget import HTML

class MarkerCustom(Marker):
    duration=List().tag(sync=True, o=True)
</code>```

My markers are all part of a longer list named mark:

```<code>mark[0]=MarkerCustom(location=[df.loc[index]['latitude'], df.loc[0]['longitude']], icon=icon, draggable=False, title=tooltip, duration=duration_list, popup=HTML('custom text0'))
mark[1]=MarkerCustom(location=[df.loc[1]['latitude'], df.loc[1]['longitude']], icon=icon, draggable=False, title=tooltip, duration=duration_list,popup=HTML('custom text1'))
</code>```

and so on.

How do I save the list mark and load it later on?

I have tried solutions using : shelve, pickle, and json, but none of these seem to work for this data type.
I also looked into the geojson library (particularly here), but I am fairly new to this and not very familiar with classes yet. I have tried to adjust my custom Marker class in the following way:

```<code>from traitlets import List
import ipyleaflet
from ipywidget import HTML
import geojson

class MarkerCustom(Marker):

    duration=List().tag(sync=True, o=True)

    @property
    def __geo_interface__(self):
        return {self}
</code>```

and then tried to save one of the markers like this , e.g.:

```<code>geojson.dumps(mark[0])
</code>```

But the error is: "TypeError: Object of type set is not JSON serializable"

If I use pickle instead, e.g.:

```<code>import pickle

with open("test", "wb") as fp:
    pickle.dump(mark[0], fp)
</code>```

The error I get is: "TypeError: cannot pickle '_hashlib.HMAC' object"
(The error is the same if I use the entire list mark instead of just one marker, e.g. mark[0])

I have a lot of markers (>1000) in the list, so instead of saving each individual marker mark[0], mark[1] etc, I would prefer to save and load them as the list mark.

Body:
I'd like to save a list of ipyleaflet markers so I can load them into another ipyleaflet map later on. I have customized the markers using a MarkerCustom class in order to incorporate another attribute (duration), which works fine. Later on I also split them up into different clusters, so I do not want to save them as one cluster at this stage.

from traitlets import List
import ipyleaflet
from ipywidget import HTML

class MarkerCustom(Marker):
    duration=List().tag(sync=True, o=True)

My markers are all part of a longer list named mark:

mark[0]=MarkerCustom(location=[df.loc[index]['latitude'], df.loc[0]['longitude']], icon=icon, draggable=False, title=tooltip, duration=duration_list, popup=HTML('custom text0'))
mark[1]=MarkerCustom(location=[df.loc[1]['latitude'], df.loc[1]['longitude']], icon=icon, draggable=False, title=tooltip, duration=duration_list,popup=HTML('custom text1'))

and so on.

How do I save the list mark and load it later on?

I have tried solutions using : shelve, pickle, and json, but none of these seem to work for this data type.
I also looked into the geojson library (particularly here), but I am fairly new to this and not very familiar with classes yet. I have tried to adjust my custom Marker class in the following way:

from traitlets import List
import ipyleaflet
from ipywidget import HTML
import geojson

class MarkerCustom(Marker):

    duration=List().tag(sync=True, o=True)

    @property
    def __geo_interface__(self):
        return {self}

and then tried to save one of the markers like this , e.g.:

geojson.dumps(mark[0])

But the error is: "TypeError: Object of type set is not JSON serializable"

If I use pickle instead, e.g.:

import pickle

with open("test", "wb") as fp:
    pickle.dump(mark[0], fp)

The error I get is: "TypeError: cannot pickle '_hashlib.HMAC' object"
(The error is the same if I use the entire list mark instead of just one marker, e.g. mark[0])

I have a lot of markers (>1000) in the list, so instead of saving each individual marker mark[0], mark[1] etc, I would prefer to save and load them as the list mark.


问:
Error in access WSO2 Identity Server My account page
As per WSO2 documentation ,I change wso2 identity server hostname instead of default https://localhost:9443

and change my account configuration (Access URL and Callback Url)

but token endpoint response error after insert login creational in myaccount page

{"error_description":"Inactive authorization code received from token
request","error":"invalid_grant"}


问:
2nd instance of Wordpress shortcode not running because of Javascript code not showing more than once
I am having a serious problem with a Wordpress plugin I am developing. I have been stuck with this issue for days. I have asked at the forum at Wordpress but their answer is not helping me as their explanation is for someone who already is at their level of PHP and JS competence. Please can someone help me with my code by showing me a completed working form of the code or explain exactly what to do in beginners language on how to fix this problem:

I have created a really simple version of my plugin so that it is easier. I have created a Wordpress plugin that is a shortcode, so you can run the shortcode on a page or post etc using this: [testing-variable-scope]. The problem is that I want to allow for the shortcode to be used more than once on a page, but because I am using a JS script in the shortcode, it is not showing more than one value if I run the shortcode on the page more than once.

I have tried everything to my ability to fix this, I know what variable scope is but I don't know how to implement it and not even sure if that is the answer. I've tried to put the JS into a separate file using wp_localise_script, it all was enqueud successfully, but then the time value is always undefined.

Please can someone help me, if I can get this simple example right then I can learn to do all future examples that include JS in the shortcode in the future. I've honestly searched everywhere, I even used the OpenAI bot. I have nowhere else to go to find this answer, I literally don't know what the answer is.

```<code>                 <script>

            let time;
            let timerBlock;

            </script>

             <?php
            function testing1_shortcode($atts = '', $content = null) {

                $value = shortcode_atts( array(
                    'seconds' => "2000"
                ), $atts, 'testing1_shortcode' );

                echo $seconds = $value['seconds'];

            ?>

            <div class="timer">
            </div><!---timer-->

            <script>
            time = <?php echo $seconds; ?>;

            timerBlock = document.querySelector(".timer");

            function timer() {
                timerBlock.innerText = time;

                if (time < 0) {
                    timerBlock.innerText = "Time's up!";
                    clearInterval();
                }
                time--;
            }

            setInterval(timer, 1000);
            </script>

            <?php

            } // END shortcode

            add_shortcode('testing-variable-scope', 'testing1_shortcode');
</code>```

Body:
I am having a serious problem with a Wordpress plugin I am developing. I have been stuck with this issue for days. I have asked at the forum at Wordpress but their answer is not helping me as their explanation is for someone who already is at their level of PHP and JS competence. Please can someone help me with my code by showing me a completed working form of the code or explain exactly what to do in beginners language on how to fix this problem:

I have created a really simple version of my plugin so that it is easier. I have created a Wordpress plugin that is a shortcode, so you can run the shortcode on a page or post etc using this: [testing-variable-scope]. The problem is that I want to allow for the shortcode to be used more than once on a page, but because I am using a JS script in the shortcode, it is not showing more than one value if I run the shortcode on the page more than once.

I have tried everything to my ability to fix this, I know what variable scope is but I don't know how to implement it and not even sure if that is the answer. I've tried to put the JS into a separate file using wp_localise_script, it all was enqueud successfully, but then the time value is always undefined.

Please can someone help me, if I can get this simple example right then I can learn to do all future examples that include JS in the shortcode in the future. I've honestly searched everywhere, I even used the OpenAI bot. I have nowhere else to go to find this answer, I literally don't know what the answer is.

             <?php
            function testing1_shortcode($atts = '', $content = null) {

                $value = shortcode_atts( array(
                    'seconds' => "2000"
                ), $atts, 'testing1_shortcode' );

                echo $seconds = $value['seconds'];

            ?>

            <?php

            } // END shortcode

            add_shortcode('testing-variable-scope', 'testing1_shortcode');


问:
"relatedEntities.forEach is not a function" Typescript Error
I am building a server with TypeScript and TypeOrm running PostgreSQL, and when I try to save a data related to this Entity on the database, I receive this error: "relatedEntities.forEach is not a function"

this is what my Entity looks like:

```<code>@Entity()
export class ServiceOrder {

@PrimaryGeneratedColumn()
id: number;

@Column()
identifier: String;

@Column()
description: String;

@Column()
creationDate: String;

@Column()
requestedAt: String

@Column({ type: 'decimal', nullable: true })
exectutionValue: number | null;

@Column({ type: 'decimal', nullable: true })
chargedValue: number | null;

@Column({ type: 'text', nullable: true })
comments: String | null;

@OneToMany(() => CostCenter, (costCenter) => costCenter.serviceOrder, { nullable: true
})
@JoinColumn()
costCenter: CostCenter;

@OneToMany(() => ServiceStatus, (serviceStatus) => serviceStatus.status)
@JoinColumn()
status: ServiceStatus;

@ManyToMany(() => ServiceCategory, (serviceCategory) => serviceCategory.serviceOrder, {
nullable: true })
@JoinTable({
  name: "ServiceOrder_category",
  joinColumn: {
    name: "serviceOrder_id",
    referencedColumnName: "id"
  },
  inverseJoinColumn: {
    name: "serviceCategory_id",
    referencedColumnName: "id"
  }
})
category?: ServiceCategory[];
};
</code>```

I believe the issue is with the Many to Many relationship, but I can't tell where the issue is.

This is the entity that the many to many relationship is stablished with:

```<code>@Entity()
export class ServiceCategory {

@PrimaryGeneratedColumn()
id: number;

@Column()
category: string;

@ManyToMany(() => ServiceOrder, (serviceOrder) => serviceOrder.category, { nullable:
true })
serviceOrder: ServiceOrder[] | null;
};
</code>```

Can anyone tell what could be giving me this issue?

Body:
I am building a server with TypeScript and TypeOrm running PostgreSQL, and when I try to save a data related to this Entity on the database, I receive this error: "relatedEntities.forEach is not a function"

this is what my Entity looks like:

@Entity()
export class ServiceOrder {

@PrimaryGeneratedColumn()
id: number;

@Column()
identifier: String;

@Column()
description: String;

@Column()
creationDate: String;

@Column()
requestedAt: String

@Column({ type: 'decimal', nullable: true })
exectutionValue: number | null;

@Column({ type: 'decimal', nullable: true })
chargedValue: number | null;

@Column({ type: 'text', nullable: true })
comments: String | null;

@OneToMany(() => CostCenter, (costCenter) => costCenter.serviceOrder, { nullable: true
})
@JoinColumn()
costCenter: CostCenter;

@OneToMany(() => ServiceStatus, (serviceStatus) => serviceStatus.status)
@JoinColumn()
status: ServiceStatus;

@ManyToMany(() => ServiceCategory, (serviceCategory) => serviceCategory.serviceOrder, {
nullable: true })
@JoinTable({
  name: "ServiceOrder_category",
  joinColumn: {
    name: "serviceOrder_id",
    referencedColumnName: "id"
  },
  inverseJoinColumn: {
    name: "serviceCategory_id",
    referencedColumnName: "id"
  }
})
category?: ServiceCategory[];
};

I believe the issue is with the Many to Many relationship, but I can't tell where the issue is.

This is the entity that the many to many relationship is stablished with:

@Entity()
export class ServiceCategory {

@PrimaryGeneratedColumn()
id: number;

@Column()
category: string;

@ManyToMany(() => ServiceOrder, (serviceOrder) => serviceOrder.category, { nullable:
true })
serviceOrder: ServiceOrder[] | null;
};

Can anyone tell what could be giving me this issue?


问:
React router dom v6 declarative Routing
```<code>        <Route
          path={CONFIRM_DELETE_INSTITUTE}
          handle={({
            match: {
              params: { instituteIndex },
            },
          }) => <ConnectedInstituteConfirmDelete instituteIndex={Number(instituteIndex)} />}
        />
</code>```

I'm using react-router-dom v5 and now I want to migrate it to v6 . How I can convert this code to v6.

Title: React router dom v6 declarative Routing

Body:
        <Route
          path={CONFIRM_DELETE_INSTITUTE}
          handle={({
            match: {
              params: { instituteIndex },
            },
          }) => <ConnectedInstituteConfirmDelete instituteIndex={Number(instituteIndex)} />}
        />

I'm using react-router-dom v5 and now I want to migrate it to v6 . How I can convert this code to v6.


问:
Recursive "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext" development server log
I am working on a Django project and I implemented custom login and logout views for authentication. I am getting these weird development server logs below immediately after I open my site at 127.0.0.1:8000.

```<code>[04/Jan/2023 11:36:30] "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext%25253D/login/%2525253Fnext%2525253D/login/%252525253Fnext%252525253D/login/%25252525253Fnext%25252525253D/login/%2525252525253Fnext%2525252525253D/favicon.ico HTTP/1.1" 302 0
[04/Jan/2023 11:36:30] "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext%25253D/login/%2525253Fnext%2525253D/login/%252525253Fnext%252525253D/login/%25252525253Fnext%25252525253D/login/%2525252525253Fnext%2525252525253D/login/%252525252525253Fnext%252525252525253D/favicon.ico HTTP/1.1" 302 0
[04/Jan/2023 11:36:30] "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext%25253D/login/%2525253Fnext%2525253D/login/%252525253Fnext%252525253D/login/%25252525253Fnext%25252525253D/login/%2525252525253Fnext%2525252525253D/login/%252525252525253Fnext%252525252525253D/login/%25252525252525253Fnext%25252525252525253D/favicon.ico HTTP/1.1" 302 0
</code>```

Here are my two relevant url.py files

from django.urls import path
from .views import login_view, register_user, verify_user, verify_number
from django.contrib.auth.views import LogoutView

urlpatterns = [
    path('accounts/login/', login_view, name="login"),
    path('accounts/<str:phone_number>/verify/', verify_user, name="verify_login"),
    path("accounts/logout/", LogoutView.as_view(), name="logout"),
    path('accounts/register/', register_user, name="register"),
    path('accounts/<str:phone_number>/verify/', verify_number, name="verify_user"),
]
```
<pre class="lang-py prettyprint-override"><code>from django.urls import path, re_path
from django.conf import settings
from django.conf.urls.static import static
from apps.home import views
from apps.authentication import views as auth_views

app_name = 'home'
urlpatterns = [
    # Main Application URLS
    path('', views.home, name='home'),
    ...
    ...
    ...
]
</code>```

I am thing setting in my settings.py

...

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home:index'
LOGOUT_REDIRECT_URL = 'home:home'

...

```
<p>And finally, this is my home function (snippet of my views.py)</p>
<pre class="lang-py prettyprint-override"><code>...

def home(request):
    context = {}
    return render(request, "home.html", context)

...
</code>```

I have tried removing the LOGIN_URL setting but not luck. I am only getting these weird logs on my home page at 127.0.0.1:8001

Anyone with an idea of why I'm getting these logs and a possible solution? :)

Body:
I am working on a Django project and I implemented custom login and logout views for authentication. I am getting these weird development server logs below immediately after I open my site at 127.0.0.1:8000.

[04/Jan/2023 11:36:30] "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext%25253D/login/%2525253Fnext%2525253D/login/%252525253Fnext%252525253D/login/%25252525253Fnext%25252525253D/login/%2525252525253Fnext%2525252525253D/favicon.ico HTTP/1.1" 302 0
[04/Jan/2023 11:36:30] "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext%25253D/login/%2525253Fnext%2525253D/login/%252525253Fnext%252525253D/login/%25252525253Fnext%25252525253D/login/%2525252525253Fnext%2525252525253D/login/%252525252525253Fnext%252525252525253D/favicon.ico HTTP/1.1" 302 0
[04/Jan/2023 11:36:30] "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext%25253D/login/%2525253Fnext%2525253D/login/%252525253Fnext%252525253D/login/%25252525253Fnext%25252525253D/login/%2525252525253Fnext%2525252525253D/login/%252525252525253Fnext%252525252525253D/login/%25252525252525253Fnext%25252525252525253D/favicon.ico HTTP/1.1" 302 0

Here are my two relevant url.py files

from django.urls import path
from .views import login_view, register_user, verify_user, verify_number
from django.contrib.auth.views import LogoutView

urlpatterns = [
    path('accounts/login/', login_view, name="login"),
    path('accounts/<str:phone_number>/verify/', verify_user, name="verify_login"),
    path("accounts/logout/", LogoutView.as_view(), name="logout"),
    path('accounts/register/', register_user, name="register"),
    path('accounts/<str:phone_number>/verify/', verify_number, name="verify_user"),
]

from django.urls import path, re_path
from django.conf import settings
from django.conf.urls.static import static
from apps.home import views
from apps.authentication import views as auth_views

app_name = 'home'
urlpatterns = [
    # Main Application URLS
    path('', views.home, name='home'),
    ...
    ...
    ...
]

I am thing setting in my settings.py

...

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home:index'
LOGOUT_REDIRECT_URL = 'home:home'

...

And finally, this is my home function (snippet of my views.py)

...

def home(request):
    context = {}
    return render(request, "home.html", context)

...

I have tried removing the LOGIN_URL setting but not luck. I am only getting these weird logs on my home page at 127.0.0.1:8001

Anyone with an idea of why I'm getting these logs and a possible solution? :)


问:
How to implement cursor pagination to read through a directory of log files from nth line of nth file to nth line of nth file using node js readline
I am trying to implement the following logic: I have a logger that creates rotation files on a daily basis, and they are saved in a folder called logs. Each file has it's own date in the name. Each file can have different number of lines (logs). I am trying to add pagination (and later filtering and sorting) on the backend so I can be able to show the logs in a table in the front end. What I want to achieve is to always know at which line of which file the last iteration stopped, so the next iteration can start from that point. Let's say that we want to paginate over 50 log lines at a time. For example, let's say that the first recorded file1 has 14 lines of logs, the second file2 has 20, the third file3 has 6, the forth file4 has 40, and so on. On page 1 we should get 50 logs in total, or all logs from file1, file2, file3 and the first 10 lines of file4. On the second page we need to start from the 11th line of file4 until we reach the next 50 lines, and so on.

My code so far looks like this:

```<code>const path = require('path')
const fs = require('fs')
const readline = require('readline')

const checkExtension = (file) => path.extname(file) === '.log'
const checkDateFormat = (file) => /(\d{4})([\/-])(\d{1,2})\2(\d{1,2})/.test(file)
const filterFiles = (files)  => files.filter(file => checkExtension(file) && checkDateFormat(file))

const getFileNames = async (dir: string): Promise<string[]> => {
  const filenames = []
  const files = await fs.promises.readdir(dir)
  files.forEach(file => {
    let fileStat = fs.statSync(dir + '/' + file).isDirectory()
    if(!fileStat) {
      filenames.push(file)
    }
  });
  return filterFiles(filenames)
}

export const readDirectory = async (dir) => {
  const filenames = await getFileNames(dir)
  let parsedData = []
  let dataArr = []
  let currentFile;
  let lineNumber = 0;
  const limit = 50;

  for (let file of filenames) {
    let cursor = 0;
    currentFile = file;
    const absolutePath = path.join(dir, file)
    const fileStream = fs.createReadStream(absolutePath)
    const rl = readline.createInterface({input: fileStream})
      rl.on('line', (line) => {
        lineNumber ++;
        lineNumber <= limit && (dataArr.push(line), cursor ++)
        lineNumber === limit && (rl.close(), console.log('Array is 50 lines long'))
      })
      console.log('DATA', dataArr)
      console.log('LINE NUMBER', lineNumber)
      console.log('CURRENT FILE', currentFile)
      console.log('CURRENT LINE', cursor)
      const bufferData = await fs.promises.readFile(absolutePath)
      const stringData = bufferData.toString('utf8')
      const data = JSON.parse('[' + (stringData.split('\r\n').filter(String)).join(',') + ']')
      parsedData.push(data)
}
  const result = [].concat.apply([], parsedData).reverse();
  return result
}

</code>```

At the moment I am getting the 50 lines printed out in dataArr, but I am not able to get the cursor. Also, I open a readStream for each file that should close once I have 50 recorded lines, but it seems that the stream is created for all files despite the condition.

Body:
I am trying to implement the following logic: I have a logger that creates rotation files on a daily basis, and they are saved in a folder called logs. Each file has it's own date in the name. Each file can have different number of lines (logs). I am trying to add pagination (and later filtering and sorting) on the backend so I can be able to show the logs in a table in the front end. What I want to achieve is to always know at which line of which file the last iteration stopped, so the next iteration can start from that point. Let's say that we want to paginate over 50 log lines at a time. For example, let's say that the first recorded file1 has 14 lines of logs, the second file2 has 20, the third file3 has 6, the forth file4 has 40, and so on. On page 1 we should get 50 logs in total, or all logs from file1, file2, file3 and the first 10 lines of file4. On the second page we need to start from the 11th line of file4 until we reach the next 50 lines, and so on.

My code so far looks like this:

const path = require('path')
const fs = require('fs')
const readline = require('readline')

const checkExtension = (file) => path.extname(file) === '.log'
const checkDateFormat = (file) => /(\d{4})([\/-])(\d{1,2})\2(\d{1,2})/.test(file)
const filterFiles = (files)  => files.filter(file => checkExtension(file) && checkDateFormat(file))

const getFileNames = async (dir: string): Promise<string[]> => {
  const filenames = []
  const files = await fs.promises.readdir(dir)
  files.forEach(file => {
    let fileStat = fs.statSync(dir + '/' + file).isDirectory()
    if(!fileStat) {
      filenames.push(file)
    }
  });
  return filterFiles(filenames)
}

export const readDirectory = async (dir) => {
  const filenames = await getFileNames(dir)
  let parsedData = []
  let dataArr = []
  let currentFile;
  let lineNumber = 0;
  const limit = 50;

  for (let file of filenames) {
    let cursor = 0;
    currentFile = file;
    const absolutePath = path.join(dir, file)
    const fileStream = fs.createReadStream(absolutePath)
    const rl = readline.createInterface({input: fileStream})
      rl.on('line', (line) => {
        lineNumber ++;
        lineNumber <= limit && (dataArr.push(line), cursor ++)
        lineNumber === limit && (rl.close(), console.log('Array is 50 lines long'))
      })
      console.log('DATA', dataArr)
      console.log('LINE NUMBER', lineNumber)
      console.log('CURRENT FILE', currentFile)
      console.log('CURRENT LINE', cursor)
      const bufferData = await fs.promises.readFile(absolutePath)
      const stringData = bufferData.toString('utf8')
      const data = JSON.parse('[' + (stringData.split('\r\n').filter(String)).join(',') + ']')
      parsedData.push(data)
}
  const result = [].concat.apply([], parsedData).reverse();
  return result
}

At the moment I am getting the 50 lines printed out in dataArr, but I am not able to get the cursor. Also, I open a readStream for each file that should close once I have 50 recorded lines, but it seems that the stream is created for all files despite the condition.


问:
Timetabling using multiobjective Genetic Algorithms based on Dynamic Gene Spaces
you can find the code on the last pages of the pdf file
https://www.diegopeluffo.com/Theses/2022_MastersThesis_MartinVelez.pdf

the whole code is like this

```<code>from re import A
from sql import *
import random
import copy
import numpy as np
from pygad import GA
from collections import Counter

pel=56
mutation_num_genes=20
SYNC=get_materia_s_pel(pel) #indeces materias

HORARIO_SYNC=get_horario_s(pel)
DATOS_SYNC=get_datos_s_pel(pel)
INFO_SYNC=get_info_s_pel(pel)
DOCENTE_SYNC=get_doc_s_pel(pel)
MAT_AULAS_HOURS_CONTRAINT=[]
MAT_DOC_CONTRAINT=[]

SHAPE=(SYNC['OFG_NUMERO'].size,5)

CONSTRAINT=[]
DURATION=[]

INVERVALOS_DIAS={}
HORARIO_SYNC.HORAFINAL = HORARIO_SYNC.HORAFINAL -1
HORARIO_SYNC.HORAINICIAL = HORARIO_SYNC.HORAINICIAL -1
HORARIO_SYNC.DIADESDE = HORARIO_SYNC.DIADESDE -1
HORARIO_SYNC.DIAHASTA = HORARIO_SYNC.DIAHASTA -1
acc=0

MAX_HORAS=24

def non_consecutive_combinator(rnge, r, prev=[]):
    if r == 0:
        yield prev

    else:
        for i, item in enumerate(rnge):
            for next_comb in non_consecutive_combinator(rnge[i+2:], r-1, prev+[item]):
                yield next_comb

for dia,intervalo in enumerate(range(0,7)):
    INVERVALOS_DIAS[dia]=list(range(acc,acc+15))
    acc=acc+MAX_HORAS

def clean_hours(int_list,length):
    return [int_list[i] for i in range(0, len(int_list))
            if sum(np.diff(int_list[i:i+length]))==length-1]
def check_option(x,w):
    c=0
    if (x[0]==0 and x[-1]==6):
        return False
    for i in x:
        if w[i]==0.:
            return False
        if w[i]==0.5:
            c+=1
    if c>1:
        return False
    else:
        return True
def seleccion_horario(dias,horas,domain):
    list_days=map(split_day_week,domain)
    b_hour,b_day,c=-1,0,0
    days_count=np.zeros((7))
    days={0:[],1:[],2:[],3:[],4:[],5:[],6:[]}
    for day,hour in list_days:
        hour=join_day_week(day,hour)
        days[day].append(hour)
        if b_hour+1==hour and b_day==day:
            c+=1
        else:
            c=1
        b_hour,b_day=hour,day
        if c>days_count[day]:
            days_count[day]=c
    max_hours=list(filter(lambda x:x>=max(horas),days_count))
    result,selected_day=False,None
    if len(max_hours)>=horas.count(max(horas)) and \
        len(list(filter(lambda x:x>=min(horas),days_count)))-len(max_hours)>=1 \
        or len(max_hours)>=dias:
        result=True

    if result:
        if dias<4:
            max_hours=(days_count>=max(horas)).astype(int)
            prob_hours=max_hours+(max_hours-(days_count>=min(horas)
                                             ).astype(int)==-1).astype(int)*0.5
            desicion=non_consecutive_combinator([0,1,2,3,4,5,6], dias)
            days_list=list(filter(lambda x: check_option(x,prob_hours),desicion))

            if days_list:
                selected_day=random.choice(days_list)
                selected_day=list(filter(lambda x:prob_hours[x]==1,selected_day))+\
                    list(filter(lambda x:prob_hours[x]==0.5,selected_day))
        if not selected_day:
            options=np.where(days_count>=max(horas))[0]
            selected_day=random.sample(list(options),dias-1)
            options_min=list(set(np.where(days_count>=min(horas))[0])
                             -set(selected_day))
            selected_day=selected_day+[random.choice(options_min)]

        horario=[]
        for i,day in enumerate(selected_day):
            horario.append(random.choice(clean_hours(days[day],horas[i])))
        if horario:
            return horario

    return [-666]

def get_horas_dias(t_horas):
    if t_horas<=3:
        dias=1
        horas=[t_horas]
    elif t_horas==4:
        dias=2
        horas=[2,2]
    elif t_horas==5:
        dias=2
        horas=[3,2]
    elif t_horas==6:
        dias=2
        horas=[3,3]
    elif t_horas==7:
        dias=3
        horas=[3,2,2]
    elif t_horas==8:
        dias=3
        horas=[3,3,2]
    elif t_horas==9:
        dias=3
        horas=[3,3,3]
    elif t_horas==11:
        dias=4
        horas=[3,3,3,2]
    elif t_horas==12:
        dias=4
        horas=[3,3,3,3]
    elif t_horas==13:
        dias=5
        horas=[3,3,3,3,1]
    elif t_horas==14:
        dias=5
        horas=[3,3,3,3,2]
    elif t_horas==15:
        dias=5
        horas=[3,3,3,3,3]
    return dias,horas
def obtener_intervalos(ofg_numero,schedule_lvl,schedule_carr,schedule_doc,limit=0):
    info=INFO_SYNC.loc[INFO_SYNC['OFG_NUMERO']==ofg_numero][
        ['CAR_CODIGO','MAA_NIVEL']].drop_duplicates()[limit:]
    domain=[]
    domain_2=[]
    for row, elem in info.iterrows():
        domain=domain+schedule_lvl.get(str(elem.CAR_CODIGO)+'-'+str(elem.MAA_NIVEL),[])
    docente=get_docente(ofg_numero)
    if docente:
        domain=domain+schedule_doc.get(docente,[])
    return domain,domain_2
def set_list(dic,codigo,lista):

    if codigo in dic:
        dic[codigo]+=lista
    else:
        dic[codigo]=lista

def save_best_solution_sync(data):
    data[data<-999]=data[data<-999]/1000
    data[data<0]=-1*data[data<0]
    datos=[]
    for index,row in SYNC.iterrows():

            dias,horas=get_horas_dias(row.DID_HORAS_SINCRONICAS)
            for num_dia,i in enumerate(filter(lambda x: x>0,horas)):
                info=DATOS_SYNC.loc[DATOS_SYNC['OFG_NUMERO']==row.OFG_NUMERO]
                dia,hora=split_day_week(data[index][num_dia])
                for row2,values in info.iterrows():
                    for time in range(hora+1,hora+i+1):
                        datos.append({'OFG_NUMERO':int(values.OFG_NUMERO),
                        'CAR_CODIGO':int(values.CAR_CODIGO),
                        'MAA_NIVEL':int(values.MAA_NIVEL)
                        ,'HDD_DIA':int(dia+1),
                        'HDD_HORA_INICIAL':int(time),
                        'HDD_HORA_FINAL':int(time+1),
                        'FAC_CODIGO':int(values.FAC_CODIGO),
                        'PRA_NUMERO':int(values.PRA_NUMERO),
                        'CAM_CODIGO':int(values.CAM_CODIGO),
                        'SED_CODIGO':int(values.SED_CODIGO),
                        'MAT_CODIGO':int(values.MAT_CODIGO[0]),'PEL_CODIGO':pel,
                        'DOCENTE_AUTOR':int(values.DOCENTE_AUTOR)
                        if not np.isnan(values.DOCENTE_AUTOR) else 0,
                        'DID_CODIGO':int(values.DID_CODIGO)})
    return pd.DataFrame(datos)
def set_horarios(ofg_numero,horas,schedule_lvl,schedule_carr,schedule_ofg,schedule_doc):
    info=INFO_SYNC.loc[INFO_SYNC['OFG_NUMERO']==ofg_numero][['CAR_CODIGO','MAA_NIVEL']].drop_duplicates()
    docente=get_docente(ofg_numero)
    if docente:
        set_list(schedule_doc,docente,horas.copy())
    set_list(schedule_ofg,str(ofg_numero),horas.copy())
    for row, elem in info.iterrows():
        set_list(schedule_lvl,str(elem.CAR_CODIGO)+'-'+str(elem.MAA_NIVEL),horas.copy())

        #set_list(schedule_carr,str(elem.CAR_CODIGO),horas)

def get_probability(todos,values_to_select_from):
    freq=[todos.count(i) for i in values_to_select_from]
    freq=max(freq)-np.array(freq)
    if sum(freq)!=0:
        freq=freq/sum(freq)
    return freq

def get_docente(ofg_numero):
    docente=DOCENTE_SYNC[DOCENTE_SYNC['OFG_NUMERO']==ofg_numero]
    if not docente.empty:
        docente=docente.iloc[0]['DOCENTE_AUTOR']
        if not np.isnan(docente):
            return str(int(docente))

    return False
def remove_domains(ofg_numero,schedule_lvl,schedule_carr,
                   schedule_doc,dias,horas,intv2,domain):
    c=0
    docente=get_docente(ofg_numero)
    aux_domain=domain.copy()
    horario=None
    if docente:
        tmp_domain=schedule_doc.get(docente,[])
        horas_disponibles2=intv2 - set(tmp_domain)
        horario=seleccion_horario(dias,horas,horas_disponibles2)
    else:
        tmp_domain=[]
    if -666 not in horario:
        return True,False,horario
    if not tmp_domain:
        while(tmp_domain!=domain):
            c=c + 1
            domain,_=obtener_intervalos(ofg_numero,schedule_lvl,schedule_carr,
                                         schedule_doc,c)
            if domain != aux_domain:
                horas_disponibles2=intv2 - set(domain)
                horario=seleccion_horario(dias,horas,horas_disponibles2)
                aux_domain=domain.copy()
            if -666 not in horario:
                return True,False,horario
    else:
        return False, True, horario
def select_day(ofg_numero,t_horas,schedule_ofg,schedule_lvl,schedule_carr,schedule_doc):
    dias,horas=get_horas_dias(t_horas)
    domain,_=obtener_intervalos(ofg_numero,schedule_lvl,schedule_carr,schedule_doc)
    intv_completo=set(np.array([INVERVALOS_DIAS[i]
                                for i in INVERVALOS_DIAS]).flatten())
    intv_param=set(intervalo_dias(ofg_numero))
    horas_disponibles_todo=intv_completo - set(domain) #horas disponibles sin tomar encuenta la parametrizacion
    horas_disponibles_param=intv_param - set(domain) #horas disponibles sin tomar en cuenta la parametrizacion
    penalizar_no_param=False
    penalizar_cruze_nivel=False
    horario=seleccion_horario(dias,horas,horas_disponibles_param)
    if -666 in horario:
        horario=seleccion_horario(dias,horas,horas_disponibles_todo) #toma encuenta la parametrizacion y salto de dias
        penalizar_no_param=True
    #Admite cruzes de horarios
    if -666 in horario:
        penalizar_cruze_nivel,penalizar_no_param,horario=remove_domains(
            ofg_numero,schedule_lvl,schedule_carr,schedule_doc,dias,
            horas,intv_completo,domain)

    if -666 not in horario:
        for x,hora_selecionada in enumerate(np.absolute(horario)):
            horas_horario=range(hora_selecionada,hora_selecionada+horas[x])
            set_horarios(ofg_numero,list(horas_horario),schedule_lvl,schedule_carr,schedule_ofg, schedule_doc)
        if penalizar_no_param:
            horario=list(-1*np.array(horario)) #se detectica que no hizo uso de la parametrizacion
        if penalizar_cruze_nivel:
            horario=list(np.array(horario)) #se detectica que no hizo uso de la parametrizacion

    return horario

def intervalo_dias(ofg_numero):
    """
    Busca obtiene el conjunto de intervalos paramatrizados
    """
    intervalo=[]
    horarios_busqueda=HORARIO_SYNC[HORARIO_SYNC['OFG_NUMERO']==ofg_numero]
    for row,horario_busqueda in horarios_busqueda.iterrows():
        inicio=horario_busqueda['DIADESDE']
        fin=horario_busqueda['DIAHASTA']
        hora_ini=horario_busqueda['HORAINICIAL']
        hora_fin=horario_busqueda['HORAFINAL']
        for dia in range(inicio,fin+1):
            intervalo+=list(range(hora_ini+(dia*MAX_HORAS),(dia*MAX_HORAS)+hora_fin))
    return intervalo

def join_day_week(day,hour):
    return day*MAX_HORAS+hour
def split_day_week(value):
    day=value//MAX_HORAS
    time=value%MAX_HORAS
    return int(day),int(time)

def fitness_func(solution, solution_idx):
    actual_populations=solution.reshape(*SHAPE)
    return validate_data(actual_populations)

def check_docente(did_horas_sincronicas,ofg_numero,schedule_doc,schedule_lvl,pobla):
    _,horas=get_horas_dias(did_horas_sincronicas)
    docente=get_docente(ofg_numero)
    horario_docente=schedule_doc.get(docente,[])
    info=INFO_SYNC.loc[INFO_SYNC['OFG_NUMERO']==ofg_numero][['CAR_CODIGO','MAA_NIVEL']].drop_duplicates()
    lista_cruzes_lvl=[]
    for row, elem in info.iterrows():
        lista_cruzes_lvl=lista_cruzes_lvl+\
            schedule_lvl.get(str(elem.CAR_CODIGO)+'-'+str(elem.MAA_NIVEL),[])
    for i, hora in enumerate(horas):
        horario=list(range(int(pobla[i]),int(pobla[i])+hora))
        for j in horario:
            if j in horario_docente:
                return True
            if j in lista_cruzes_lvl:
                return True
    return False
def set_data(did_horas_sincronicas,ofg_numero,schedule_lvl,
             schedule_carr,schedule_ofg, schedule_doc,pobla):
    _,horas=get_horas_dias(did_horas_sincronicas)
    for i, hora in enumerate(horas):
        horario=list(range(int(pobla[i]),int(pobla[i])+hora))
        set_horarios(ofg_numero,horario,schedule_lvl,schedule_carr,
                     schedule_ofg, schedule_doc)

def get_cruzes_docente(did_horas_sincronicas,schedule_doc,pobla,docente):
    _,horas=get_horas_dias(did_horas_sincronicas)
    for i, hora in enumerate(horas):
        horario=list(range(int(pobla[i]),int(pobla[i])+hora))
        for j in horas:
            if j in schedule_doc[docente]:

                return -10000
def validate_data(actual_populations):
    mal_horario=np.where((np.sum(actual_populations,axis=1)<-1)&(np.sum(actual_populations,axis=1)>-1000))[0]
    c_data= save_best_solution_sync(actual_populations.copy())
    prof_mal=-1000000 *len(c_data[['HDD_HORA_INICIAL','HDD_DIA','DOCENTE_AUTOR',
                                'OFG_NUMERO']].drop_duplicates().groupby(
                                ['DOCENTE_AUTOR','HDD_HORA_INICIAL','HDD_DIA'])
                                .filter(lambda x: len(x) > 1)['OFG_NUMERO']
                                .drop_duplicates().values)
    ofgs=c_data[['OFG_NUMERO','CAR_CODIGO','MAA_NIVEL',
                 'HDD_HORA_INICIAL','HDD_DIA']].drop_duplicates().groupby(
    ['CAR_CODIGO','MAA_NIVEL','HDD_DIA','HDD_HORA_INICIAL']
    ).filter(lambda x: len(x) > 1)['OFG_NUMERO'].drop_duplicates()
    ofgs_day_bad=c_data[c_data['HDD_DIA']>7]['OFG_NUMERO'].values
    index=list(SYNC.index[SYNC.OFG_NUMERO.isin(ofgs)].values)
    actual_populations[index]=-1*actual_populations[index]
    index=list(SYNC.index[SYNC.OFG_NUMERO.isin(ofgs_day_bad)].values)
    if index:
        actual_populations[index][0]=-666
    return -len(np.where(np.any(actual_populations==-666,axis=1))[0]
                )*1000000 -SYNC.loc[mal_horario]['CUPO_SUBGRUPO'].sum()\
        -100*SYNC[SYNC.OFG_NUMERO.isin(set(ofgs))].CUPO_SUBGRUPO.sum()+prof_mal-len(
            index)*100000

def start_random_population():
    population=np.zeros(SHAPE)
    create_schedule(population,flag=True)
    return population

def create_schedule(actual_populations,flag=False):
    schedule_ofg={}
    schedule_carr={}
    schedule_lvl={}
    schedule_doc={}

    mutation_indices = random.sample(list(range(0, SHAPE[0])), mutation_num_genes)
    for index,row in SYNC.iterrows():
        chk_docente=check_docente(row.DID_HORAS_SINCRONICAS,row.OFG_NUMERO,
                    schedule_doc,schedule_lvl,np.absolute(actual_populations[index]))
        if flag or index in mutation_indices or np.any(actual_populations[index] <0) \
            or chk_docente:
            result_days=select_day(row.OFG_NUMERO,row.DID_HORAS_SINCRONICAS,
                        schedule_ofg,schedule_lvl,schedule_carr,schedule_doc)
            for i,val in enumerate(result_days):
                actual_populations[index][i]=val
        else:
            set_data(row.DID_HORAS_SINCRONICAS,row.OFG_NUMERO,schedule_lvl,
                     schedule_carr,schedule_ofg, schedule_doc,
                     np.absolute(actual_populations[index]))
    return actual_populations

class GACustomize(GA):
    def random_mutation(self, offspring):
        for offspring_idx in range(offspring.shape[0]):
            create_schedule(offspring[offspring_idx].reshape(SHAPE))
        return offspring

inputs=[start_random_population().flatten() for i in range(5)]

GANN_customize = GACustomize(num_generations=500,
                                sol_per_pop=5,
                                num_parents_mating=2,
                                fitness_func=fitness_func,
                                num_genes=len(inputs),
                                mutation_type="random",
                                initial_population=inputs,
                                keep_parents=0,
                                save_best_solutions=True,
                                mutation_num_genes=15
                                )
GANN_customize.run()
</code>```

There are a lot of undefined values at the beginning of the code that I don't understand
enter image description here anyway colab showed it right away, underlined it in orange

I don't understand if I have to enter these values or is it a library issue. (it didn't accept when I tried to enter a value either)

Body:
you can find the code on the last pages of the pdf file
https://www.diegopeluffo.com/Theses/2022_MastersThesis_MartinVelez.pdf

the whole code is like this

from re import A
from sql import *
import random
import copy
import numpy as np
from pygad import GA
from collections import Counter

pel=56
mutation_num_genes=20
SYNC=get_materia_s_pel(pel) #indeces materias

HORARIO_SYNC=get_horario_s(pel)
DATOS_SYNC=get_datos_s_pel(pel)
INFO_SYNC=get_info_s_pel(pel)
DOCENTE_SYNC=get_doc_s_pel(pel)
MAT_AULAS_HOURS_CONTRAINT=[]
MAT_DOC_CONTRAINT=[]

SHAPE=(SYNC['OFG_NUMERO'].size,5)

CONSTRAINT=[]
DURATION=[]

INVERVALOS_DIAS={}
HORARIO_SYNC.HORAFINAL = HORARIO_SYNC.HORAFINAL -1
HORARIO_SYNC.HORAINICIAL = HORARIO_SYNC.HORAINICIAL -1
HORARIO_SYNC.DIADESDE = HORARIO_SYNC.DIADESDE -1
HORARIO_SYNC.DIAHASTA = HORARIO_SYNC.DIAHASTA -1
acc=0

MAX_HORAS=24

def non_consecutive_combinator(rnge, r, prev=[]):
    if r == 0:
        yield prev

    else:
        for i, item in enumerate(rnge):
            for next_comb in non_consecutive_combinator(rnge[i+2:], r-1, prev+[item]):
                yield next_comb

for dia,intervalo in enumerate(range(0,7)):
    INVERVALOS_DIAS[dia]=list(range(acc,acc+15))
    acc=acc+MAX_HORAS

def clean_hours(int_list,length):
    return [int_list[i] for i in range(0, len(int_list))
            if sum(np.diff(int_list[i:i+length]))==length-1]
def check_option(x,w):
    c=0
    if (x[0]==0 and x[-1]==6):
        return False
    for i in x:
        if w[i]==0.:
            return False
        if w[i]==0.5:
            c+=1
    if c>1:
        return False
    else:
        return True
def seleccion_horario(dias,horas,domain):
    list_days=map(split_day_week,domain)
    b_hour,b_day,c=-1,0,0
    days_count=np.zeros((7))
    days={0:[],1:[],2:[],3:[],4:[],5:[],6:[]}
    for day,hour in list_days:
        hour=join_day_week(day,hour)
        days[day].append(hour)
        if b_hour+1==hour and b_day==day:
            c+=1
        else:
            c=1
        b_hour,b_day=hour,day
        if c>days_count[day]:
            days_count[day]=c
    max_hours=list(filter(lambda x:x>=max(horas),days_count))
    result,selected_day=False,None
    if len(max_hours)>=horas.count(max(horas)) and \
        len(list(filter(lambda x:x>=min(horas),days_count)))-len(max_hours)>=1 \
        or len(max_hours)>=dias:
        result=True

    if result:
        if dias<4:
            max_hours=(days_count>=max(horas)).astype(int)
            prob_hours=max_hours+(max_hours-(days_count>=min(horas)
                                             ).astype(int)==-1).astype(int)*0.5
            desicion=non_consecutive_combinator([0,1,2,3,4,5,6], dias)
            days_list=list(filter(lambda x: check_option(x,prob_hours),desicion))

            if days_list:
                selected_day=random.choice(days_list)
                selected_day=list(filter(lambda x:prob_hours[x]==1,selected_day))+\
                    list(filter(lambda x:prob_hours[x]==0.5,selected_day))
        if not selected_day:
            options=np.where(days_count>=max(horas))[0]
            selected_day=random.sample(list(options),dias-1)
            options_min=list(set(np.where(days_count>=min(horas))[0])
                             -set(selected_day))
            selected_day=selected_day+[random.choice(options_min)]

        horario=[]
        for i,day in enumerate(selected_day):
            horario.append(random.choice(clean_hours(days[day],horas[i])))
        if horario:
            return horario

    return [-666]

def get_horas_dias(t_horas):
    if t_horas<=3:
        dias=1
        horas=[t_horas]
    elif t_horas==4:
        dias=2
        horas=[2,2]
    elif t_horas==5:
        dias=2
        horas=[3,2]
    elif t_horas==6:
        dias=2
        horas=[3,3]
    elif t_horas==7:
        dias=3
        horas=[3,2,2]
    elif t_horas==8:
        dias=3
        horas=[3,3,2]
    elif t_horas==9:
        dias=3
        horas=[3,3,3]
    elif t_horas==11:
        dias=4
        horas=[3,3,3,2]
    elif t_horas==12:
        dias=4
        horas=[3,3,3,3]
    elif t_horas==13:
        dias=5
        horas=[3,3,3,3,1]
    elif t_horas==14:
        dias=5
        horas=[3,3,3,3,2]
    elif t_horas==15:
        dias=5
        horas=[3,3,3,3,3]
    return dias,horas
def obtener_intervalos(ofg_numero,schedule_lvl,schedule_carr,schedule_doc,limit=0):
    info=INFO_SYNC.loc[INFO_SYNC['OFG_NUMERO']==ofg_numero][
        ['CAR_CODIGO','MAA_NIVEL']].drop_duplicates()[limit:]
    domain=[]
    domain_2=[]
    for row, elem in info.iterrows():
        domain=domain+schedule_lvl.get(str(elem.CAR_CODIGO)+'-'+str(elem.MAA_NIVEL),[])
    docente=get_docente(ofg_numero)
    if docente:
        domain=domain+schedule_doc.get(docente,[])
    return domain,domain_2
def set_list(dic,codigo,lista):

    if codigo in dic:
        dic[codigo]+=lista
    else:
        dic[codigo]=lista

def save_best_solution_sync(data):
    data[data<-999]=data[data<-999]/1000
    data[data<0]=-1*data[data<0]
    datos=[]
    for index,row in SYNC.iterrows():

            dias,horas=get_horas_dias(row.DID_HORAS_SINCRONICAS)
            for num_dia,i in enumerate(filter(lambda x: x>0,horas)):
                info=DATOS_SYNC.loc[DATOS_SYNC['OFG_NUMERO']==row.OFG_NUMERO]
                dia,hora=split_day_week(data[index][num_dia])
                for row2,values in info.iterrows():
                    for time in range(hora+1,hora+i+1):
                        datos.append({'OFG_NUMERO':int(values.OFG_NUMERO),
                        'CAR_CODIGO':int(values.CAR_CODIGO),
                        'MAA_NIVEL':int(values.MAA_NIVEL)
                        ,'HDD_DIA':int(dia+1),
                        'HDD_HORA_INICIAL':int(time),
                        'HDD_HORA_FINAL':int(time+1),
                        'FAC_CODIGO':int(values.FAC_CODIGO),
                        'PRA_NUMERO':int(values.PRA_NUMERO),
                        'CAM_CODIGO':int(values.CAM_CODIGO),
                        'SED_CODIGO':int(values.SED_CODIGO),
                        'MAT_CODIGO':int(values.MAT_CODIGO[0]),'PEL_CODIGO':pel,
                        'DOCENTE_AUTOR':int(values.DOCENTE_AUTOR)
                        if not np.isnan(values.DOCENTE_AUTOR) else 0,
                        'DID_CODIGO':int(values.DID_CODIGO)})
    return pd.DataFrame(datos)
def set_horarios(ofg_numero,horas,schedule_lvl,schedule_carr,schedule_ofg,schedule_doc):
    info=INFO_SYNC.loc[INFO_SYNC['OFG_NUMERO']==ofg_numero][['CAR_CODIGO','MAA_NIVEL']].drop_duplicates()
    docente=get_docente(ofg_numero)
    if docente:
        set_list(schedule_doc,docente,horas.copy())
    set_list(schedule_ofg,str(ofg_numero),horas.copy())
    for row, elem in info.iterrows():
        set_list(schedule_lvl,str(elem.CAR_CODIGO)+'-'+str(elem.MAA_NIVEL),horas.copy())

        #set_list(schedule_carr,str(elem.CAR_CODIGO),horas)

def get_probability(todos,values_to_select_from):
    freq=[todos.count(i) for i in values_to_select_from]
    freq=max(freq)-np.array(freq)
    if sum(freq)!=0:
        freq=freq/sum(freq)
    return freq

def get_docente(ofg_numero):
    docente=DOCENTE_SYNC[DOCENTE_SYNC['OFG_NUMERO']==ofg_numero]
    if not docente.empty:
        docente=docente.iloc[0]['DOCENTE_AUTOR']
        if not np.isnan(docente):
            return str(int(docente))

    return False
def remove_domains(ofg_numero,schedule_lvl,schedule_carr,
                   schedule_doc,dias,horas,intv2,domain):
    c=0
    docente=get_docente(ofg_numero)
    aux_domain=domain.copy()
    horario=None
    if docente:
        tmp_domain=schedule_doc.get(docente,[])
        horas_disponibles2=intv2 - set(tmp_domain)
        horario=seleccion_horario(dias,horas,horas_disponibles2)
    else:
        tmp_domain=[]
    if -666 not in horario:
        return True,False,horario
    if not tmp_domain:
        while(tmp_domain!=domain):
            c=c + 1
            domain,_=obtener_intervalos(ofg_numero,schedule_lvl,schedule_carr,
                                         schedule_doc,c)
            if domain != aux_domain:
                horas_disponibles2=intv2 - set(domain)
                horario=seleccion_horario(dias,horas,horas_disponibles2)
                aux_domain=domain.copy()
            if -666 not in horario:
                return True,False,horario
    else:
        return False, True, horario
def select_day(ofg_numero,t_horas,schedule_ofg,schedule_lvl,schedule_carr,schedule_doc):
    dias,horas=get_horas_dias(t_horas)
    domain,_=obtener_intervalos(ofg_numero,schedule_lvl,schedule_carr,schedule_doc)
    intv_completo=set(np.array([INVERVALOS_DIAS[i]
                                for i in INVERVALOS_DIAS]).flatten())
    intv_param=set(intervalo_dias(ofg_numero))
    horas_disponibles_todo=intv_completo - set(domain) #horas disponibles sin tomar encuenta la parametrizacion
    horas_disponibles_param=intv_param - set(domain) #horas disponibles sin tomar en cuenta la parametrizacion
    penalizar_no_param=False
    penalizar_cruze_nivel=False
    horario=seleccion_horario(dias,horas,horas_disponibles_param)
    if -666 in horario:
        horario=seleccion_horario(dias,horas,horas_disponibles_todo) #toma encuenta la parametrizacion y salto de dias
        penalizar_no_param=True
    #Admite cruzes de horarios
    if -666 in horario:
        penalizar_cruze_nivel,penalizar_no_param,horario=remove_domains(
            ofg_numero,schedule_lvl,schedule_carr,schedule_doc,dias,
            horas,intv_completo,domain)

    if -666 not in horario:
        for x,hora_selecionada in enumerate(np.absolute(horario)):
            horas_horario=range(hora_selecionada,hora_selecionada+horas[x])
            set_horarios(ofg_numero,list(horas_horario),schedule_lvl,schedule_carr,schedule_ofg, schedule_doc)
        if penalizar_no_param:
            horario=list(-1*np.array(horario)) #se detectica que no hizo uso de la parametrizacion
        if penalizar_cruze_nivel:
            horario=list(np.array(horario)) #se detectica que no hizo uso de la parametrizacion

    return horario

def intervalo_dias(ofg_numero):
    """
    Busca obtiene el conjunto de intervalos paramatrizados
    """
    intervalo=[]
    horarios_busqueda=HORARIO_SYNC[HORARIO_SYNC['OFG_NUMERO']==ofg_numero]
    for row,horario_busqueda in horarios_busqueda.iterrows():
        inicio=horario_busqueda['DIADESDE']
        fin=horario_busqueda['DIAHASTA']
        hora_ini=horario_busqueda['HORAINICIAL']
        hora_fin=horario_busqueda['HORAFINAL']
        for dia in range(inicio,fin+1):
            intervalo+=list(range(hora_ini+(dia*MAX_HORAS),(dia*MAX_HORAS)+hora_fin))
    return intervalo

def join_day_week(day,hour):
    return day*MAX_HORAS+hour
def split_day_week(value):
    day=value//MAX_HORAS
    time=value%MAX_HORAS
    return int(day),int(time)

def fitness_func(solution, solution_idx):
    actual_populations=solution.reshape(*SHAPE)
    return validate_data(actual_populations)

def check_docente(did_horas_sincronicas,ofg_numero,schedule_doc,schedule_lvl,pobla):
    _,horas=get_horas_dias(did_horas_sincronicas)
    docente=get_docente(ofg_numero)
    horario_docente=schedule_doc.get(docente,[])
    info=INFO_SYNC.loc[INFO_SYNC['OFG_NUMERO']==ofg_numero][['CAR_CODIGO','MAA_NIVEL']].drop_duplicates()
    lista_cruzes_lvl=[]
    for row, elem in info.iterrows():
        lista_cruzes_lvl=lista_cruzes_lvl+\
            schedule_lvl.get(str(elem.CAR_CODIGO)+'-'+str(elem.MAA_NIVEL),[])
    for i, hora in enumerate(horas):
        horario=list(range(int(pobla[i]),int(pobla[i])+hora))
        for j in horario:
            if j in horario_docente:
                return True
            if j in lista_cruzes_lvl:
                return True
    return False
def set_data(did_horas_sincronicas,ofg_numero,schedule_lvl,
             schedule_carr,schedule_ofg, schedule_doc,pobla):
    _,horas=get_horas_dias(did_horas_sincronicas)
    for i, hora in enumerate(horas):
        horario=list(range(int(pobla[i]),int(pobla[i])+hora))
        set_horarios(ofg_numero,horario,schedule_lvl,schedule_carr,
                     schedule_ofg, schedule_doc)

def get_cruzes_docente(did_horas_sincronicas,schedule_doc,pobla,docente):
    _,horas=get_horas_dias(did_horas_sincronicas)
    for i, hora in enumerate(horas):
        horario=list(range(int(pobla[i]),int(pobla[i])+hora))
        for j in horas:
            if j in schedule_doc[docente]:

                return -10000
def validate_data(actual_populations):
    mal_horario=np.where((np.sum(actual_populations,axis=1)<-1)&(np.sum(actual_populations,axis=1)>-1000))[0]
    c_data= save_best_solution_sync(actual_populations.copy())
    prof_mal=-1000000 *len(c_data[['HDD_HORA_INICIAL','HDD_DIA','DOCENTE_AUTOR',
                                'OFG_NUMERO']].drop_duplicates().groupby(
                                ['DOCENTE_AUTOR','HDD_HORA_INICIAL','HDD_DIA'])
                                .filter(lambda x: len(x) > 1)['OFG_NUMERO']
                                .drop_duplicates().values)
    ofgs=c_data[['OFG_NUMERO','CAR_CODIGO','MAA_NIVEL',
                 'HDD_HORA_INICIAL','HDD_DIA']].drop_duplicates().groupby(
    ['CAR_CODIGO','MAA_NIVEL','HDD_DIA','HDD_HORA_INICIAL']
    ).filter(lambda x: len(x) > 1)['OFG_NUMERO'].drop_duplicates()
    ofgs_day_bad=c_data[c_data['HDD_DIA']>7]['OFG_NUMERO'].values
    index=list(SYNC.index[SYNC.OFG_NUMERO.isin(ofgs)].values)
    actual_populations[index]=-1*actual_populations[index]
    index=list(SYNC.index[SYNC.OFG_NUMERO.isin(ofgs_day_bad)].values)
    if index:
        actual_populations[index][0]=-666
    return -len(np.where(np.any(actual_populations==-666,axis=1))[0]
                )*1000000 -SYNC.loc[mal_horario]['CUPO_SUBGRUPO'].sum()\
        -100*SYNC[SYNC.OFG_NUMERO.isin(set(ofgs))].CUPO_SUBGRUPO.sum()+prof_mal-len(
            index)*100000

def start_random_population():
    population=np.zeros(SHAPE)
    create_schedule(population,flag=True)
    return population

def create_schedule(actual_populations,flag=False):
    schedule_ofg={}
    schedule_carr={}
    schedule_lvl={}
    schedule_doc={}

    mutation_indices = random.sample(list(range(0, SHAPE[0])), mutation_num_genes)
    for index,row in SYNC.iterrows():
        chk_docente=check_docente(row.DID_HORAS_SINCRONICAS,row.OFG_NUMERO,
                    schedule_doc,schedule_lvl,np.absolute(actual_populations[index]))
        if flag or index in mutation_indices or np.any(actual_populations[index] <0) \
            or chk_docente:
            result_days=select_day(row.OFG_NUMERO,row.DID_HORAS_SINCRONICAS,
                        schedule_ofg,schedule_lvl,schedule_carr,schedule_doc)
            for i,val in enumerate(result_days):
                actual_populations[index][i]=val
        else:
            set_data(row.DID_HORAS_SINCRONICAS,row.OFG_NUMERO,schedule_lvl,
                     schedule_carr,schedule_ofg, schedule_doc,
                     np.absolute(actual_populations[index]))
    return actual_populations

class GACustomize(GA):
    def random_mutation(self, offspring):
        for offspring_idx in range(offspring.shape[0]):
            create_schedule(offspring[offspring_idx].reshape(SHAPE))
        return offspring

inputs=[start_random_population().flatten() for i in range(5)]

GANN_customize = GACustomize(num_generations=500,
                                sol_per_pop=5,
                                num_parents_mating=2,
                                fitness_func=fitness_func,
                                num_genes=len(inputs),
                                mutation_type="random",
                                initial_population=inputs,
                                keep_parents=0,
                                save_best_solutions=True,
                                mutation_num_genes=15
                                )
GANN_customize.run()

There are a lot of undefined values at the beginning of the code that I don't understand
enter image description here anyway colab showed it right away, underlined it in orange

I don't understand if I have to enter these values or is it a library issue. (it didn't accept when I tried to enter a value either)


问:
How to show dialog to send email AND call phone number in Android?
I am wondering if there is a way to have a "contact" button in Android and when the button is pressed a menu pops up giving you the possibility:

to send an email (showing all available email accounts, send-to is a predefined email address

or to call a predefined phone number

This should everything be in the same menu, so similar to this but also with the option to place a call:

http://mobile.tutsplus.com/tutorials/android/android-email-intent/ (sorry, as a new user I cannot post images yet...)

Is there a pre-defined function to do this or do I have to code the whole menu from scratch?

Thanks for your help,

Reto

ContentLicense: CC BY-SA 3.0


问:
VLC-package for Spyder
```<code>import vlc
import pafy

if mood == "Chilled":
        url = "https://www.youtube.com/watch?v=2Y11BC2qQW4&ab_channel=LofiMelody"
        video = pafy.new(url)
        best = video.getbest(0)
        playurl = best.url
        Instance = vlc.Instance()

        player = Instance.media_player_new()
        Media = Instance.media_new(playurl)
        Media.get_mrl()
        player.set_media(Media)
        player.play()
</code>```

Hello, I am trying to view a VLC video in Spyder. I have the VLC package installed in Ubuntu, but I can't manage to install it for Spyder.

I get the following error message: "Could not find module 'C:\Users\Veronika\Desktop\Informatik\libvlc.dll' (or one of its dependencies). Try using the full path with constructor syntax."

I tried to install the vlc package using "pip install VLC" in CMD.exe Prompt in Anaconda, but it did not work. I tried it in PowerShell, too - did not work either.

None of How to instal Python packages for Spyder worked for me.

Title: VLC-package for Spyder

Body:
import vlc
import pafy

if mood == "Chilled":
        url = "https://www.youtube.com/watch?v=2Y11BC2qQW4&ab_channel=LofiMelody"
        video = pafy.new(url)
        best = video.getbest(0)
        playurl = best.url
        Instance = vlc.Instance()

        player = Instance.media_player_new()
        Media = Instance.media_new(playurl)
        Media.get_mrl()
        player.set_media(Media)
        player.play()

Hello, I am trying to view a VLC video in Spyder. I have the VLC package installed in Ubuntu, but I can't manage to install it for Spyder.

I get the following error message: "Could not find module 'C:\Users\Veronika\Desktop\Informatik\libvlc.dll' (or one of its dependencies). Try using the full path with constructor syntax."

I tried to install the vlc package using "pip install VLC" in CMD.exe Prompt in Anaconda, but it did not work. I tried it in PowerShell, too - did not work either.

None of How to instal Python packages for Spyder worked for me.


问:
Importing Tweet Views count into Google Spreadsheet using importXML
I have a Google Spreadsheet with a column of Tweet links. I'm trying to get the view count using ImportXML formula. Could anyone help me please?

I dont know how to use the formula exactly to address the view count in tweet.

Thanks in advance


问:
Set properties in nested class at runtime
I'm taking a course in C# and just started to play around with reflection.
I'm trying to build a model that I use in a Win Forms app. The model looks like this (but with more _value:s and other stuff).

```<code>public class ParentClass
{
    private int _id;
    private string _value1, _value2, _value3;
    private Random _random;
    private List<string> _registryStuff;
    private User _user;
    private ChildClass1 _childClass1;
    private ChildClass2 _childClass2;

    public ParentClass()
    {
        _user = new User();
        _random = new Random();
        _childClass1 = new ChildClass1();
        _childClass2 = new ChildClass2();
    }

    public User User
    {
        get => _user;
        set => _user = value;
    }

    public int Id
    {
        get => _id; set => _id = _random.Next(1, 100);
    }

    public string Value1
    {
        get => _value1; set => _value1 = _childClass1.Method()[1];
    }

    public string Value2
    {
        get => _value2; set => _value2 = _childClass1.Method()[2];
    }

    public string Value3
    {
        get => _value3; set => _value3 = _childClass1.Method()[3];
    }

    public List<string> RegistryStuff
    {
        get => _registryStuff; set => _registryStuff = GetData();
    }

    private List<string> GetData()
    {
        List<string> keys = new List<string>()
        {
            @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
            @"SOFTWARE\WOW6432Node\Windows\CurrentVersion\Uninstall"
        };

        List<string> result = new List<string>();

        return _childClass2.Method(RegistryKey.OpenBaseKey(RegistryHive.CurrentUser,
        RegistryView.Registry64), keys, result);
    }
}

// ChildClass1.cs
public class ChildClass1
{
    public string[] Method()
    {
        //... do stuff...
        // return the string array from there
    }
}

// ChildClass2.cs
public class ChildClass2
{
    public List<string> Method(RegistryKey regKey, List<string> keys, List<string> result)
    {
        //... do stuff..
        // return the List from there
    }
}
</code>```

How can I set _id, _value1, _value2, _value3 etc at runtime? Is it even possible this way?
The ParentClass.User.Value1, Value2 etc is set via textboxes in the form.

My thought was I could use reflection to set the values.

This works if I change the props to something like: get => _childClass1.Method()[1]; set => _value1 = value; and then use a method like this when I want to populate a data grid in the form.

```<code>    private static DataTable CreateTable(object obj, DataGridView grid)
    {
        DataTable _dTable = new DataTable();
        DataRow _dRow = _dTable.NewRow();

        grid.DataSource = _dTable;
        grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

        _dTable.Rows.Add(_dRow);
        _dTable.Columns.Add("PropName", typeof(string));
        _dTable.Columns.Add("PropType", typeof(string));
        _dTable.Columns.Add("PropValue", typeof(string));

        obj.GetType().GetProperties().ToList().ForEach(prop =>
        {
            try
            {
                _dTable.Rows.Add(prop.Name, prop.PropertyType, prop.GetValue(obj));
            }
            catch (Exception e)
            {
                throw;
            }
        });

        return _dTable;
    }

</code>```

Body:
I'm taking a course in C# and just started to play around with reflection.
I'm trying to build a model that I use in a Win Forms app. The model looks like this (but with more _value:s and other stuff).

public class ParentClass
{
    private int _id;
    private string _value1, _value2, _value3;
    private Random _random;
    private List<string> _registryStuff;
    private User _user;
    private ChildClass1 _childClass1;
    private ChildClass2 _childClass2;

    public ParentClass()
    {
        _user = new User();
        _random = new Random();
        _childClass1 = new ChildClass1();
        _childClass2 = new ChildClass2();
    }

    public User User
    {
        get => _user;
        set => _user = value;
    }

    public int Id
    {
        get => _id; set => _id = _random.Next(1, 100);
    }

    public string Value1
    {
        get => _value1; set => _value1 = _childClass1.Method()[1];
    }

    public string Value2
    {
        get => _value2; set => _value2 = _childClass1.Method()[2];
    }

    public string Value3
    {
        get => _value3; set => _value3 = _childClass1.Method()[3];
    }

    public List<string> RegistryStuff
    {
        get => _registryStuff; set => _registryStuff = GetData();
    }

    private List<string> GetData()
    {
        List<string> keys = new List<string>()
        {
            @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
            @"SOFTWARE\WOW6432Node\Windows\CurrentVersion\Uninstall"
        };

        List<string> result = new List<string>();

        return _childClass2.Method(RegistryKey.OpenBaseKey(RegistryHive.CurrentUser,
        RegistryView.Registry64), keys, result);
    }
}

// ChildClass1.cs
public class ChildClass1
{
    public string[] Method()
    {
        //... do stuff...
        // return the string array from there
    }
}

// ChildClass2.cs
public class ChildClass2
{
    public List<string> Method(RegistryKey regKey, List<string> keys, List<string> result)
    {
        //... do stuff..
        // return the List from there
    }
}

How can I set _id, _value1, _value2, _value3 etc at runtime? Is it even possible this way?
The ParentClass.User.Value1, Value2 etc is set via textboxes in the form.

My thought was I could use reflection to set the values.

This works if I change the props to something like: get => _childClass1.Method()[1]; set => _value1 = value; and then use a method like this when I want to populate a data grid in the form.

    private static DataTable CreateTable(object obj, DataGridView grid)
    {
        DataTable _dTable = new DataTable();
        DataRow _dRow = _dTable.NewRow();

        grid.DataSource = _dTable;
        grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

        _dTable.Rows.Add(_dRow);
        _dTable.Columns.Add("PropName", typeof(string));
        _dTable.Columns.Add("PropType", typeof(string));
        _dTable.Columns.Add("PropValue", typeof(string));

        obj.GetType().GetProperties().ToList().ForEach(prop =>
        {
            try
            {
                _dTable.Rows.Add(prop.Name, prop.PropertyType, prop.GetValue(obj));
            }
            catch (Exception e)
            {
                throw;
            }
        });

        return _dTable;
    }


问:
pyqt checkbox resolution for different scales
I am developing a windows app with pyside6. I have a QTableView and have used a QItemDelegate to add checkboxes to the table. The checkboxes are drawn in the paint method of the QItemDelegate, using the method drawCheck

class CheckBoxDelegate(QItemDelegate):
    """
    A delegate that places a fully functioning QCheckBox cell of the column to which it's applied.
    """
    def __init__(self, parent):
        QItemDelegate.__init__(self, parent)

    def createEditor(self, parent, option, index):
        """
        Important, otherwise an editor is created if the user clicks in this cell.
        """
        return None

    def paint(self, painter, option, index):
        """
        Paint a checkbox without the label.
        """
        value = int(index.data())
        if value == 0:
            value = Qt.Unchecked
        else:
            value = Qt.Checked
        self.drawCheck(painter, option, option.rect, value)

    def editorEvent(self, event, model, option, index):
        """
        Change the data in the model and the state of the checkbox
        if the user presses the left mousebutton and this cell is editable. Otherwise do nothing.
        """
        if not int(index.flags() & Qt.ItemIsEditable) > 0:
            return False

        if event.type() == QEvent.MouseButtonRelease and event.button() == Qt.LeftButton:
            # Change the checkbox-state
            self.setModelData(None, model, index)
            return True

        return False

    def setModelData(self, editor, model, index):
        """
        Set new data in the model
        """
        model.setData(index, 1 if int(index.data()) == 0 else 0, Qt.EditRole)
```
<p>The problem is that the checkboxes are only correctly displayed if the scale is set at 100%. Changing it to 125% or more, makes the checkbox too big and the icon inside blurry (images below)</p>
<p>checkboxes at 125%</p>
<p>checkboxes at 100%</p>
<p>I have tried different settings for scaling the app. The combination of settings that works to scale the rest of the application is:</p>
<pre class="lang-python prettyprint-override"><code>os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "0"
os.environ["QT_FONT_DPI"] = "96"
os.environ["QT_SCALE_FACTOR"] = "1"
QApplication.setHighDpiScaleFactorRoundingPolicy(QtCore.Qt.HighDpiScaleFactorRoundingPolicy.Floor)
</code>```

Still changing these settings has no effect on the checkboxes resolution

Body:
I am developing a windows app with pyside6. I have a QTableView and have used a QItemDelegate to add checkboxes to the table. The checkboxes are drawn in the paint method of the QItemDelegate, using the method drawCheck

class CheckBoxDelegate(QItemDelegate):
    """
    A delegate that places a fully functioning QCheckBox cell of the column to which it's applied.
    """
    def __init__(self, parent):
        QItemDelegate.__init__(self, parent)

    def createEditor(self, parent, option, index):
        """
        Important, otherwise an editor is created if the user clicks in this cell.
        """
        return None

    def paint(self, painter, option, index):
        """
        Paint a checkbox without the label.
        """
        value = int(index.data())
        if value == 0:
            value = Qt.Unchecked
        else:
            value = Qt.Checked
        self.drawCheck(painter, option, option.rect, value)

    def editorEvent(self, event, model, option, index):
        """
        Change the data in the model and the state of the checkbox
        if the user presses the left mousebutton and this cell is editable. Otherwise do nothing.
        """
        if not int(index.flags() & Qt.ItemIsEditable) > 0:
            return False

        if event.type() == QEvent.MouseButtonRelease and event.button() == Qt.LeftButton:
            # Change the checkbox-state
            self.setModelData(None, model, index)
            return True

        return False

    def setModelData(self, editor, model, index):
        """
        Set new data in the model
        """
        model.setData(index, 1 if int(index.data()) == 0 else 0, Qt.EditRole)

The problem is that the checkboxes are only correctly displayed if the scale is set at 100%. Changing it to 125% or more, makes the checkbox too big and the icon inside blurry (images below)

checkboxes at 125%

checkboxes at 100%

I have tried different settings for scaling the app. The combination of settings that works to scale the rest of the application is:

os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "0"
os.environ["QT_FONT_DPI"] = "96"
os.environ["QT_SCALE_FACTOR"] = "1"
QApplication.setHighDpiScaleFactorRoundingPolicy(QtCore.Qt.HighDpiScaleFactorRoundingPolicy.Floor)

Still changing these settings has no effect on the checkboxes resolution


问:
I have a object in my Parent component and I have to pass that object in my child component
So I have Patient-prescription.components.ts this parent component and I have to pass object from here to this child component Patient-prescription-expand-view.component.ts</p>


问:
What is difference between extends and anchor tag (<<: *anchor) in yaml (Gitlab CICD)?
When we use extends and when we use anchor tag ?
Please refer below CI CD pipeline

```<code>  stages:
    - stage1
  .random-variables:
    variables:
      ABC: ${XYZ}

  .hidden-job: &hidden-job
    stage: stage1
    image: docker:latest
    services:
      - docker:dind
    script:
      #  My Scripts

  hidden-job:dev:
    extends:
      - .random-variables
    <<: *hidden-job
    only:
      - dev
</code>```

Thanks in advance for clarifying my doubt.

As of now I understand how pipeline is working like anchor tag is use with <<: *alias to pull in the other block of code in current block.

Same extends is use to pull in variables in current block

Body:
When we use extends and when we use anchor tag ?
Please refer below CI CD pipeline

  stages:
    - stage1
  .random-variables:
    variables:
      ABC: ${XYZ}

  .hidden-job: &hidden-job
    stage: stage1
    image: docker:latest
    services:
      - docker:dind
    script:
      #  My Scripts

  hidden-job:dev:
    extends:
      - .random-variables
    <<: *hidden-job
    only:
      - dev

Thanks in advance for clarifying my doubt.

As of now I understand how pipeline is working like anchor tag is use with <<: *alias to pull in the other block of code in current block.

Same extends is use to pull in variables in current block


问:
Persian URL in Cpanel Django
I have the url http://127.0.0.1:8000/shop/جکوزی-آپارتمانی/p/وان-جکوزی-مدل-L188/ in my development project and it's is working fine till i upload it to cpanel which returns Page not found (404)

here is my urls.py:

```<code>from django.urls import path , re_path
from . import views as v

urlpatterns = [
    path('', v.index.as_view(), name="ShopView"),
    path('seach/' , v.SearchResultsView.as_view() , name="search_results"),
    re_path(r'c/(?P<categoriese>[-\w]+)/' , v.categoryView , name="ProShopView2"),
    re_path(r'(?P<namecate>[-\w]+)/p/(?P<namepro>[-\w]+)/', v.ProductDetailsView , name="productview"),
    path('products/<str:proname>/comment/' , v.commentView , name="commentviewshop"),

]
</code>```

first re_path is for category which the url is http://127.0.0.1:8000/shop/c/جکوزی-آپارتمانی/
second re_path is for category and product http://127.0.0.1:8000/shop/جکوزی-آپارتمانی/p/وان-جکوزی-مدل-L188/

here is my category model:

```<code>class categories(models.Model):
    name = models.CharField(max_length=50, null=True,blank=True,unique=True)
    url_name = models.SlugField(unique=True , null=True , blank=True,allow_unicode=True)
    image = ResizedImageField(size=[1920,1920], crop=['top', 'left','bottom', 'right'],upload_to = upload_image_path ,   null=True , blank=True)
    def __str__(self):
        return self.name
</code>```

**here is my productmodel:  **
*deleted some of the unnecessary fields.

```<code>class productmodel(models.Model):
    Seller = models.ForeignKey(User , on_delete=models.CASCADE , null=True , blank=True)
    category = models.ForeignKey(categories ,blank=True, null=True, on_delete=models.CASCADE , related_name="categories_main")
    ProductName = models.CharField(max_length=60)
    slug = models.SlugField(unique=True , null=True , blank=True,allow_unicode=True)
    ProductBody = models.TextField(max_length=800)
    image = ResizedImageField(size=[1920,1920], crop=['top', 'left','bottom', 'right'],upload_to = upload_image_path , null=True , blank=True)
    def __str__(self):
        # return f'ProuctName:{self.ProductName} ProductAuthor:{self.author} ProductId:{self.id}'
        return self.ProductName
    def getsnippet(self):
        return self.ProductBody[0:30]
</code>```

**here is my category views: **

```<code>def categoryView(req , categoriese):
    if categories.objects.filter(url_name = categoriese):
        cat = categories.objects.filter(url_name = categoriese)
        for i in cat:
            o = i.id
            pro = productmodel.objects.filter(category = o, deleted=False)
            return render(req , 'shop/shop.html' , {'products':pro} )
    else:
        return redirect("H404")
</code>```

here is my product views:

```<code>def ProductDetailsView(req ,namecate ,namepro):
    cate = categories.objects.get(url_name=namecate)
    if productmodel.objects.get(slug = namepro , category=cate):
        pro = productmodel.objects.get(slug = namepro, category=cate)
        same_pro = productmodel.objects.filter(category=cate)
        commentobject = ModelCommentProduct.objects.filter(accepted = True , post = pro)
        comment_count = commentobject.count()
        context = {'p':pro,'same_pro':same_pro , 'com':commentobject , 'c_count':comment_count}
        return render(req , 'shop/product-details.html' ,context )
    else:
        return redirect("H404")
</code>```

**I tried re_path which didn't seem to work in cpanel anyway  **
my first url parameters were:

```<code>path('<str:categoriese>/' , v.categoryView , name="ProShopView2"),
path('products/<str:namecate>/<str:namepro>' , v.ProductDetailsView , name="productview"),
</code>```

so i changed them to:

```<code>re_path(r'c/(?P<categoriese>[-\w]+)/' , v.categoryView , name="ProShopView2"),
re_path(r'(?P<namecate>[-\w]+)/p/(?P<namepro>[-\w]+)/', v.ProductDetailsView , name="productview"),
</code>```

with allow_unicode=True in models.py
i checked persian text in url django
but couldn't find my answer

Title: Persian URL in Cpanel Django

Body:
I have the url http://127.0.0.1:8000/shop/جکوزی-آپارتمانی/p/وان-جکوزی-مدل-L188/ in my development project and it's is working fine till i upload it to cpanel which returns Page not found (404)

here is my urls.py:

from django.urls import path , re_path
from . import views as v

urlpatterns = [
    path('', v.index.as_view(), name="ShopView"),
    path('seach/' , v.SearchResultsView.as_view() , name="search_results"),
    re_path(r'c/(?P<categoriese>[-\w]+)/' , v.categoryView , name="ProShopView2"),
    re_path(r'(?P<namecate>[-\w]+)/p/(?P<namepro>[-\w]+)/', v.ProductDetailsView , name="productview"),
    path('products/<str:proname>/comment/' , v.commentView , name="commentviewshop"),

]

first re_path is for category which the url is http://127.0.0.1:8000/shop/c/جکوزی-آپارتمانی/
second re_path is for category and product http://127.0.0.1:8000/shop/جکوزی-آپارتمانی/p/وان-جکوزی-مدل-L188/

here is my category model:

class categories(models.Model):
    name = models.CharField(max_length=50, null=True,blank=True,unique=True)
    url_name = models.SlugField(unique=True , null=True , blank=True,allow_unicode=True)
    image = ResizedImageField(size=[1920,1920], crop=['top', 'left','bottom', 'right'],upload_to = upload_image_path ,   null=True , blank=True)
    def __str__(self):
        return self.name

**here is my productmodel:  **
*deleted some of the unnecessary fields.

class productmodel(models.Model):
    Seller = models.ForeignKey(User , on_delete=models.CASCADE , null=True , blank=True)
    category = models.ForeignKey(categories ,blank=True, null=True, on_delete=models.CASCADE , related_name="categories_main")
    ProductName = models.CharField(max_length=60)
    slug = models.SlugField(unique=True , null=True , blank=True,allow_unicode=True)
    ProductBody = models.TextField(max_length=800)
    image = ResizedImageField(size=[1920,1920], crop=['top', 'left','bottom', 'right'],upload_to = upload_image_path , null=True , blank=True)
    def __str__(self):
        # return f'ProuctName:{self.ProductName} ProductAuthor:{self.author} ProductId:{self.id}'
        return self.ProductName
    def getsnippet(self):
        return self.ProductBody[0:30]

**here is my category views: **

def categoryView(req , categoriese):
    if categories.objects.filter(url_name = categoriese):
        cat = categories.objects.filter(url_name = categoriese)
        for i in cat:
            o = i.id
            pro = productmodel.objects.filter(category = o, deleted=False)
            return render(req , 'shop/shop.html' , {'products':pro} )
    else:
        return redirect("H404")

here is my product views:

def ProductDetailsView(req ,namecate ,namepro):
    cate = categories.objects.get(url_name=namecate)
    if productmodel.objects.get(slug = namepro , category=cate):
        pro = productmodel.objects.get(slug = namepro, category=cate)
        same_pro = productmodel.objects.filter(category=cate)
        commentobject = ModelCommentProduct.objects.filter(accepted = True , post = pro)
        comment_count = commentobject.count()
        context = {'p':pro,'same_pro':same_pro , 'com':commentobject , 'c_count':comment_count}
        return render(req , 'shop/product-details.html' ,context )
    else:
        return redirect("H404")

**I tried re_path which didn't seem to work in cpanel anyway  **
my first url parameters were:

path('<str:categoriese>/' , v.categoryView , name="ProShopView2"),
path('products/<str:namecate>/<str:namepro>' , v.ProductDetailsView , name="productview"),

so i changed them to:

re_path(r'c/(?P<categoriese>[-\w]+)/' , v.categoryView , name="ProShopView2"),
re_path(r'(?P<namecate>[-\w]+)/p/(?P<namepro>[-\w]+)/', v.ProductDetailsView , name="productview"),

with allow_unicode=True in models.py
i checked persian text in url django
but couldn't find my answer


问:
Function which creates a vertical line with a gap in Python
I want to create a function which produces something like this where we have a vertical line which has a gap in it.

I have a feeling it'll involve heaviside functions but I'm not sure