问:
Joining Tables in Entity Framework correct syntax query
I'm trying to make a join in EF in an efficient way, using two tables. Table1 and Table2

I'm currently doing two queries and able to consolidate the data later, which is working without issue, but I'm trying to condense it into a single query with no luck so far. Here are the separate queries:

```<code>var data1 = Context.Table1.Where(x => listOfIds.Contains(x.ObjectId)).OrderBy(x => x.Order).ToList();
</code>```

This gets me all columns from Table1

```<code>var data2 = data1.Join(Context.Table2, a => a.ObjectId, b => b.ObjectId, (a, b) => b)
.Select(x => new { x.ObjectId, x.OtherThing });
</code>```

This gets me the extra field I need from Table2

These give me 2 data sets with a matching id that I can then combine with a foreach, but I know there is a way to get that all consolidated with 1 query, but can't get the logic / syntax after looking at many posts.

Here's what I've been trying in terms of a single query:

```<code>var data1 = Context.Table1.Where(x => listOfIds.Contains(x.ObjectId)).OrderBy(x => x.Order)
.Join(Context.Table2, a => a.ObjectId, b => b.ObjectId, (a, b) => b)
.Select(x => new { x.ObjectId, x.OtherThing });
.ToList();
</code>```
```<code>var data1 = Context.Table1.Join(Context.Table2, a => a.ObjectId, b => b.ObjectId, (a, b) => b)
.Select(x => new { x.ObjectId, x.OtherThing })
.Where(x => listOfIds.Contains(x.ObjectId)).OrderBy(x => x.Order);
.ToList();
</code>```

I'm expecting to get a single data object that has all columns from Table1 and 1 additional column from table 2.

Anyone able to highlight what I'm doing wrong?  Any help at all is much appreciated. Thanks.

Body:
I'm trying to make a join in EF in an efficient way, using two tables. Table1 and Table2

I'm currently doing two queries and able to consolidate the data later, which is working without issue, but I'm trying to condense it into a single query with no luck so far. Here are the separate queries:

var data1 = Context.Table1.Where(x => listOfIds.Contains(x.ObjectId)).OrderBy(x => x.Order).ToList();

This gets me all columns from Table1

var data2 = data1.Join(Context.Table2, a => a.ObjectId, b => b.ObjectId, (a, b) => b)
.Select(x => new { x.ObjectId, x.OtherThing });

This gets me the extra field I need from Table2

These give me 2 data sets with a matching id that I can then combine with a foreach, but I know there is a way to get that all consolidated with 1 query, but can't get the logic / syntax after looking at many posts.

Here's what I've been trying in terms of a single query:

var data1 = Context.Table1.Where(x => listOfIds.Contains(x.ObjectId)).OrderBy(x => x.Order)
.Join(Context.Table2, a => a.ObjectId, b => b.ObjectId, (a, b) => b)
.Select(x => new { x.ObjectId, x.OtherThing });
.ToList();

var data1 = Context.Table1.Join(Context.Table2, a => a.ObjectId, b => b.ObjectId, (a, b) => b)
.Select(x => new { x.ObjectId, x.OtherThing })
.Where(x => listOfIds.Contains(x.ObjectId)).OrderBy(x => x.Order);
.ToList();

I'm expecting to get a single data object that has all columns from Table1 and 1 additional column from table 2.

Anyone able to highlight what I'm doing wrong?  Any help at all is much appreciated. Thanks.


来源: stackexchange

问:
Splitting 800mb file in smaller text files
I am trying to split huge text file into smaller txt files. I am using gitbash. With split command

```<code>split myfilename -l 39000
</code>```

I am able to split many files with 39000 lines. But I want to split each file after 39000 line the first line start with H.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to split huge text file into smaller txt files. I am using gitbash. With split command

split myfilename -l 39000

I am able to split many files with 39000 lines. But I want to split each file after 39000 line the first line start with H.


问:
How do I add new data to datacube using socket in trading vue js?
```<code><template>
<trading-vue :data="dc" :extensions="ext"/>
</template>
<script>

import TradingVue from 'trading-vue-js'
import XP from 'tvjs-xp'

export default {
    name: 'app',
    components: { TradingVue },
    data() {
        return {
            ext: Object.values(XP),
            dc: new DataCube(...)
        }
    }
}

</script>
How can I listen to instant data with socket and update the chart in Trading vue js?
</code>```

For example, how can I add the data taken in the candle or line chart to the chart up-to-date?

Body:
<template>
<trading-vue :data="dc" :extensions="ext"/>
</template>

How can I listen to instant data with socket and update the chart in Trading vue js?

For example, how can I add the data taken in the candle or line chart to the chart up-to-date?


问:
y axis of graph is out of order
I was plotting a graph using matplotlib for a csv file.

The Y axis in the graph seems to be out of order. I have check the column. It is of int().

If I try to change y.append(row[1]) to y.append(int(row[1]))
I am getting Value ErrorValueError: invalid literal for int() with base 10: 'Rating/total'

Below is the code

```<code>x = []
y = []

with open('Abhigyan_alternate_school.csv','r') as csvfile:
    lines = csv.reader(csvfile, delimiter=',')
    for row in lines:
        x.append(row[0])
        y.append(row[1])

plt.plot(x, y, color = 'g', linestyle = 'dashed',
         marker = 'o',label = "school ratings")

plt.xticks(rotation = 50)
plt.xlabel('school Name')
plt.ylabel('Rating/total')
plt.title('school ratings', fontsize = 20)
plt.grid()
plt.legend()
plt.show()
</code>```

Title: y axis of graph is out of order

Body:
I was plotting a graph using matplotlib for a csv file.

The Y axis in the graph seems to be out of order. I have check the column. It is of int().

If I try to change y.append(row[1]) to y.append(int(row[1]))
I am getting Value ErrorValueError: invalid literal for int() with base 10: 'Rating/total'

Below is the code

x = []
y = []

with open('Abhigyan_alternate_school.csv','r') as csvfile:
    lines = csv.reader(csvfile, delimiter=',')
    for row in lines:
        x.append(row[0])
        y.append(row[1])

plt.plot(x, y, color = 'g', linestyle = 'dashed',
         marker = 'o',label = "school ratings")

plt.xticks(rotation = 50)
plt.xlabel('school Name')
plt.ylabel('Rating/total')
plt.title('school ratings', fontsize = 20)
plt.grid()
plt.legend()
plt.show()


问:
How to convert a void * into a usable type using enum
So I have a structure that contains two things:

void * to a value.

enum Types type that specifies what type the pointer is pointing to.

enum Types { CHAR, INT };

struct MyStructure {
  void *value;
  enum Types type;
}
```
<p>I wanted to get the value of the <code>void *</code>, to do that I need something that indicates what is the type of the pointer, I have an <strong>enum</strong> (<code>enum Types { CHAR, INT }</code>) their value(the possibles types) can be either a <code>CHAR</code> or a <code>INT</code> which should be converted to <code>char</code> and <code>int</code> C types respectively, but how can I do this?</p>
<p>I could use an <code>if else</code> statement to check the enum types and convert the <strong>value</strong> to the right type, like:</p>
<pre class="lang-c prettyprint-override"><code>if (my_structure.type == CHAR) char *value_with_type = (char *)value;
else if (my_structure.type == INT) int *value_with_type = (int *)value;
</code>```

But doing like that would mean that if I wanted to expand the types in the future, I would have to also change the if else to be able to convert the new types.

Is it possible to do what I'm saying?

Body:
So I have a structure that contains two things:

void * to a value.

enum Types type that specifies what type the pointer is pointing to.

enum Types { CHAR, INT };

struct MyStructure {
  void *value;
  enum Types type;
}

I wanted to get the value of the void *, to do that I need something that indicates what is the type of the pointer, I have an enum (enum Types { CHAR, INT }) their value(the possibles types) can be either a CHAR or a INT which should be converted to char and int C types respectively, but how can I do this?

I could use an if else statement to check the enum types and convert the value to the right type, like:

if (my_structure.type == CHAR) char *value_with_type = (char *)value;
else if (my_structure.type == INT) int *value_with_type = (int *)value;

But doing like that would mean that if I wanted to expand the types in the future, I would have to also change the if else to be able to convert the new types.

Is it possible to do what I'm saying?


问:
How to filter data using IQueryable into a NHibernate DynamicJsonType Mapping
I'm saving a list of  Json into a varchar on my data base

```<code>[
   {
      "Id":37,
      "Name":"John",
      "Departament":{
         "Name":"Criminal Justice",
         "Id":12
      }
   },
]
</code>```

NHibernate works well on save and update as Mapped like this:

```<code>       Map(x => x.Competencias)
            .CustomType<DynamicJsonType<IEnumerable<Competencias>>>()
            .CustomSqlType($"NVARCHAR({int.MaxValue})")
            .Length(int.MaxValue)
            .Column("competencia_jurisdicao");

</code>```

The problem occures over filtering:

SearchParamclass Param

```<code>public class SearchParam
{
    public int? IdFunction{ get; set; }

    public string Endpoint { get; set; }

    public IEnumerable<CompetenciaDTO> Competencias { get; set; }
}
</code>```

Controller

```<code>    [HttpPost("searchByFilters")]
    public IList<ResponseDTO> SearchByFilters([FromServices] Paginator<Function> paginator, [FromBody] SearchParam filter = null)
    {
        using (UnitOfWork.BeginReadOnlyTransaction())
        {
            var query = Repository.FindAll<Function>();
            var limit = 0;
            var offset = 0;

            if (filter != null)
            {

                if (filter.Competencias != null)
                {
                    foreach (var competencia in filter.Competencias)
                    {

                        query = query.Where(o => o.Competencias.All(c => c.Id == competencia.Id));
                    }
                }
            }

            var total = query.Count();
            return paginator.Split(query, limit, offset, total, HttpContext)
            .AdaptToType<IList<ResponseDTO>>();
         }
     }
</code>```

Nhibernate builds up a query like this:

```<code>select (count(*)) as col_0_0_
  from dbo.mni_function  function0_
 where not (exists
             (select function0_ .id
                from dbo.mni_function function0_
                where not (function0_ .id = ?)
             )
            )
</code>```

Body:
I'm saving a list of  Json into a varchar on my data base

[
   {
      "Id":37,
      "Name":"John",
      "Departament":{
         "Name":"Criminal Justice",
         "Id":12
      }
   },
]

NHibernate works well on save and update as Mapped like this:

       Map(x => x.Competencias)
            .CustomType<DynamicJsonType<IEnumerable<Competencias>>>()
            .CustomSqlType($"NVARCHAR({int.MaxValue})")
            .Length(int.MaxValue)
            .Column("competencia_jurisdicao");

The problem occures over filtering:

SearchParamclass Param

public class SearchParam
{
    public int? IdFunction{ get; set; }

    public string Endpoint { get; set; }

    public IEnumerable<CompetenciaDTO> Competencias { get; set; }
}

Controller

    [HttpPost("searchByFilters")]
    public IList<ResponseDTO> SearchByFilters([FromServices] Paginator<Function> paginator, [FromBody] SearchParam filter = null)
    {
        using (UnitOfWork.BeginReadOnlyTransaction())
        {
            var query = Repository.FindAll<Function>();
            var limit = 0;
            var offset = 0;

            if (filter != null)
            {

                if (filter.Competencias != null)
                {
                    foreach (var competencia in filter.Competencias)
                    {

                        query = query.Where(o => o.Competencias.All(c => c.Id == competencia.Id));
                    }
                }
            }

            var total = query.Count();
            return paginator.Split(query, limit, offset, total, HttpContext)
            .AdaptToType<IList<ResponseDTO>>();
         }
     }

Nhibernate builds up a query like this:

select (count(*)) as col_0_0_
  from dbo.mni_function  function0_
 where not (exists
             (select function0_ .id
                from dbo.mni_function function0_
                where not (function0_ .id = ?)
             )
            )


问:
Unity Facebook SDK doesn't login on android devices
i'm really struggling to make facebook work on android devices, it works fine on IOS but on android it keep getting stuck on the facebook application, if i uninstall the facebook app it logs in on the web but on the app it doesn't show me the login dialog, it shows a loading panel for a bit and then stop,

things i've tried to fix this,

i generated the key hash using both these commands for debug and release

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

keytool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore YOUR_RELEASE_KEY_PATH | openssl sha1 -binary | openssl base64

i tried to generate the key hash from google play console( yes my app is published)
both the upload key and app signing key, i used a key hash generator to base64

i tried to force web login in unity SDK using
FB.Mobile.ShareDialogMode = ShareDialogMode.WEB;
but doesn't work it still opens the facebook app

i added these parameters to the login with read permissions but still no luck
new List() { "public_profile", "email" },

this is my manifest file :


问:
"Expected an expression" error when trying to use va_arg
I'm trying to use va_arg to assign the value of an argument to a variable. The code compiles but does not work as intended. When I try to debug with vscode (Debug C/C++ File) I get that error.

```<code>void    ft_printf_char(specifier *fmt)
    {
        const char  c = va_arg(fmt->args, int);
        ft_putchar_fd(c, 1);
    }

static char *parse_format_specifier(char *str, specifier *fmt)
    {
        if (*str == 'c')
            ft_printf_char(fmt);
        return (++str);
    }

int ft_printf(const char *str, ...)
    {
        int return_value;
        specifier fmt;

        return_value = 0;
        va_start(fmt.args, str);
        while (*str)
            if (*str == '%' && *str++)
            {
                str = parse_format_specifier((char *)str, &fmt);
            }
            else
            {
                return_value++;
                ft_putchar_fd(*str++, 1);
            }
        va_end(fmt.args);
        return_value += fmt.len;
        return return_value;
    }
</code>```

// in another file

```<code>#ifndef FT_PRINTF_H
# define FT_PRINTF_H

#include <stdarg.h>

typedef struct specifier
{
    int         len;
    va_list     args;

}   specifier;

int ft_printf(const char *str, ...);
void    ft_printf_char(specifier *fmt);

#endif
</code>```

// main.c

```<code>void main()
{
    ft_printf("print char %c", 'c');
}
</code>```

I have no idea what the error message means. The thingy that warns you about errors on the editor says

```<code>#define va_arg(ap,type) __builtin_va_arg(ap, type)
Expands to:

__builtin_va_arg(fmt->args, int)
expected an expressionC/C++(29)
</code>```

Maybe there's syntax error that I can't find?

Body:
I'm trying to use va_arg to assign the value of an argument to a variable. The code compiles but does not work as intended. When I try to debug with vscode (Debug C/C++ File) I get that error.

void    ft_printf_char(specifier *fmt)
    {
        const char  c = va_arg(fmt->args, int);
        ft_putchar_fd(c, 1);
    }

static char *parse_format_specifier(char *str, specifier *fmt)
    {
        if (*str == 'c')
            ft_printf_char(fmt);
        return (++str);
    }

int ft_printf(const char *str, ...)
    {
        int return_value;
        specifier fmt;

        return_value = 0;
        va_start(fmt.args, str);
        while (*str)
            if (*str == '%' && *str++)
            {
                str = parse_format_specifier((char *)str, &fmt);
            }
            else
            {
                return_value++;
                ft_putchar_fd(*str++, 1);
            }
        va_end(fmt.args);
        return_value += fmt.len;
        return return_value;
    }

// in another file

#ifndef FT_PRINTF_H
# define FT_PRINTF_H

#include <stdarg.h>

typedef struct specifier
{
    int         len;
    va_list     args;

}   specifier;

int ft_printf(const char *str, ...);
void    ft_printf_char(specifier *fmt);

#endif

// main.c

void main()
{
    ft_printf("print char %c", 'c');
}

I have no idea what the error message means. The thingy that warns you about errors on the editor says

#define va_arg(ap,type) __builtin_va_arg(ap, type)
Expands to:

__builtin_va_arg(fmt->args, int)
expected an expressionC/C++(29)

Maybe there's syntax error that I can't find?


问:
How to create and sensibly manage several Gtk.SpinButtons?
I need to create several Gtk.SpinButton - their amount will vary.
How to create and sensibly manage several Gtk.SpinButtons?

Gtk3+ and Python

```<code>    def d_on_value_changed(self, scroll):
        print(self.e_spinbutton.get_value_as_int())

        print("Zmieniam nowy")

        return True

    def touch_entry_element(self, line):

        self.e_spinbutton = str('self.espinbutton_')+str(line)
        self.e_on_value_changed = str('self.e_on_value_changed_')+str(line)
        print(self.e_spinbutton)
        # spinbutton
        adjustment = Gtk.Adjustment(upper=5000, step_increment=5, page_increment=20)
        self.e_spinbutton = Gtk.SpinButton()
        self.e_spinbutton.set_adjustment(adjustment)
        self.e_spinbutton.connect("value-changed", self.d_on_value_changed)
</code>```

Body:
I need to create several Gtk.SpinButton - their amount will vary.
How to create and sensibly manage several Gtk.SpinButtons?

Gtk3+ and Python

    def d_on_value_changed(self, scroll):
        print(self.e_spinbutton.get_value_as_int())

        print("Zmieniam nowy")

        return True

    def touch_entry_element(self, line):

        self.e_spinbutton = str('self.espinbutton_')+str(line)
        self.e_on_value_changed = str('self.e_on_value_changed_')+str(line)
        print(self.e_spinbutton)
        # spinbutton
        adjustment = Gtk.Adjustment(upper=5000, step_increment=5, page_increment=20)
        self.e_spinbutton = Gtk.SpinButton()
        self.e_spinbutton.set_adjustment(adjustment)
        self.e_spinbutton.connect("value-changed", self.d_on_value_changed)


问:
SQLite - How to build 'SQLite.Interop.dll'
As I am learning SQLite, I downloaded the latest sources, sqlite-netFx-source-1.0.117.0.zip, extracted them, and used VS2017 to open the SQLite.NET.2017.sln and build it. The build works fine, however, then I tried test.exe, it gave me "Unable to load DLL 'SQLite.Interop.dll': The specified module could not be found" exception. I can see that this dll is not in the bin folder, even though the SQLite.Interop.2017 project compiles just fine.

I thought that the SQLite.Interop.2017 project produces 'SQLite.Interop.dll', but I cannot find it anywhere. Please help.


问:
Import/Export in Javascript, I get a "net::ERR_ABORTED 404 (Not Found)"
I'm creating a basic project and I am trying to use ES6 Modules to split my code into multiple files. So I wanted to test it first using some basic stuff like exporting a single const. But it's not working and it's throwing me the "net::ERR_ABORTED 404 (Not Found)".

The second file code(the file that I want to export the code from):

```<code>export const myName = 'Name';
</code>```

The first file code:

```<code>import { myName } from "./appTwo";

console.log(myName);
</code>```

I looked it up online and most of the answers are regarding backend. I did make my script tag type="module", it still doesn't work.

Body:
I'm creating a basic project and I am trying to use ES6 Modules to split my code into multiple files. So I wanted to test it first using some basic stuff like exporting a single const. But it's not working and it's throwing me the "net::ERR_ABORTED 404 (Not Found)".

The second file code(the file that I want to export the code from):

export const myName = 'Name';

The first file code:

import { myName } from "./appTwo";

console.log(myName);

I looked it up online and most of the answers are regarding backend. I did make my script tag type="module", it still doesn't work.


问:
how to solve captcha
```<code>from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup
import pandas as pd
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import csv
import requests
from csv import writer

url="https://allegro.pl/oferta/lurlego-76900-speed-champions-koenigsegg-jesko-11096977887"
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--disable-gpu")
options.add_argument("--window-size=1920x1080")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

driver.get(url)

try:
    title=driver.find_element(By.XPATH,'//div[@class="msub_k4"]//h4').text
except:
    pass
print(title)
</code>```

How to solve that will scraping the data  any solution for it....is there any possible solution for that kindly recommend me any solution...

Title: how to solve captcha

Body:
from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup
import pandas as pd
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import csv
import requests
from csv import writer

url="https://allegro.pl/oferta/lurlego-76900-speed-champions-koenigsegg-jesko-11096977887"
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--disable-gpu")
options.add_argument("--window-size=1920x1080")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

driver.get(url)

try:
    title=driver.find_element(By.XPATH,'//div[@class="msub_k4"]//h4').text
except:
    pass
print(title)

How to solve that will scraping the data  any solution for it....is there any possible solution for that kindly recommend me any solution...


问:
Sending file as attachment using mailx command
I have few xlsx files with different timestamps. I have mentioned sample files for reference.

```<code>abt_rpt_20221216_0137.xlsx
abt_rpt_20221216_0136.xlsx
</code>```

I want only the first file (with latest timestamp) as an attachment via email. Since the file size is huge, I'm trying to zip the file and email the file(which has latest timestamp as an attachment). Looks like I'm making error in my script.

The email shoould contain the attachment of a single .xlsx file which has the latest timestamp.

```<code>#!/bin/bash
dt=$(date +"%Y%m%d_%H%M")
cd /dev/abd_dev/alb/test/Scripts/albt/at

zip -r /dev/abd_dev/alb/test/Scripts/albt/at/report.zip /dev/abd_dev/alb/test/Scripts/albt/at/*.xlsx | head -1

# Sending Email

for file in *.zip ; do
  [[ -f "${file}" ]] || continue
    attachments+=( "-a" "${file}" )
done

echo "Hi,
      File Attached"| mailx -s "Test" "${attachments[@]}" "test@gmail.com"
</code>```

Need to understand what I'm doing wrong. Can anyone guide me on this?

Body:
I have few xlsx files with different timestamps. I have mentioned sample files for reference.

abt_rpt_20221216_0137.xlsx
abt_rpt_20221216_0136.xlsx

I want only the first file (with latest timestamp) as an attachment via email. Since the file size is huge, I'm trying to zip the file and email the file(which has latest timestamp as an attachment). Looks like I'm making error in my script.

The email shoould contain the attachment of a single .xlsx file which has the latest timestamp.

#!/bin/bash
dt=$(date +"%Y%m%d_%H%M")
cd /dev/abd_dev/alb/test/Scripts/albt/at

zip -r /dev/abd_dev/alb/test/Scripts/albt/at/report.zip /dev/abd_dev/alb/test/Scripts/albt/at/*.xlsx | head -1

# Sending Email

for file in *.zip ; do
  [[ -f "${file}" ]] || continue
    attachments+=( "-a" "${file}" )
done

echo "Hi,
      File Attached"| mailx -s "Test" "${attachments[@]}" "test@gmail.com"

Need to understand what I'm doing wrong. Can anyone guide me on this?


问:
Append data to excel sheet with pandas
I have an excel sheet I am need to add new data without deleting old data I am trying many times and Posted on Discord Servers many times and posting on stack overflow and don't getting solution for this If anyone can help me I will be very thankful for him because I missed my deadline with my client.
If someone want to help me by sharing my screen with them and speaking, No Problem my English is not bad

Discord Tag: Nour Eldin#9789

My Code:

editableExcelSheet = ExcelWriter(
    r'D:\Projects\MOJ\MOJ.xlsx',
    mode="a",
    engine="openpyxl",
    if_sheet_exists="overlay",
)
serialNumberFromSheet_htmlName = request.form.get("serialNumberFromSheet_htmlName")
dataSet = {'SerialNumber': [serialNumberFromSheet_htmlName],
newCase = pd.DataFrame(dataSet)
newCase.to_excel(editableExcelSheet, sheet_name='Sheet1')
```

Thanks in advance

Title: Append data to excel sheet with pandas

Body:
I have an excel sheet I am need to add new data without deleting old data I am trying many times and Posted on Discord Servers many times and posting on stack overflow and don't getting solution for this If anyone can help me I will be very thankful for him because I missed my deadline with my client.
If someone want to help me by sharing my screen with them and speaking, No Problem my English is not bad

Discord Tag: Nour Eldin#9789

My Code:

editableExcelSheet = ExcelWriter(
    r'D:\Projects\MOJ\MOJ.xlsx',
    mode="a",
    engine="openpyxl",
    if_sheet_exists="overlay",
)
serialNumberFromSheet_htmlName = request.form.get("serialNumberFromSheet_htmlName")
dataSet = {'SerialNumber': [serialNumberFromSheet_htmlName],
newCase = pd.DataFrame(dataSet)
newCase.to_excel(editableExcelSheet, sheet_name='Sheet1')

Thanks in advance


问:
How to avoid sending a Connect/Disconnect-ExchangeOnline for every pwsh command in a c# Blazor app
I am developing a server side Blazor app to facilitate Exchange online management via a GUI. I have a helper class that setups the runspace and communicates the results back to the the Blazor component. I added the class via an scoped Dependency Injection.

The helper class is setup as:

    InitialSessionState runspaceConfiguration = InitialSessionState.CreateDefault();
    runspaceConfiguration.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.RemoteSigned;
    runspaceConfiguration.ImportPSModule("ExchangeOnlineManagement");
    runspaceConfiguration.ThrowOnRunspaceOpenError = true;
    _runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
    // Open local runspace
    _runspace.Open();
    _shell = PowerShell.Create();
    _shell.Runspace = _runspace;
    SetUpEventHandlers();
```
<p>My function to execute commands is a follow:</p>
<pre class="lang-cs prettyprint-override"><code>public async Task ExecuteScript(string scriptContents)
{
    _shell.AddScript(scriptContents);
    OutputEventArgs rtc = new() {
       Data = await _shell.InvokeAsync().ConfigureAwait(true)
    };
    _shell.Streams.ClearStreams();
    _shell.Commands.Clear();
    ResultsAvailable?.Invoke(this, rtc);
}
</code>```

To connect to Exchnage Online I use a certificate, it looks like:

    string? certificateThumbPrint = config.GetValue<string>("certificateThumbPrint");
    string? appId = config.GetValue<string>("appId");
    string? tenant = config.GetValue<string>("tenant");
    logger.Info($"Running : Connect-ExchangeOnline -Certificate {certificateThumbPrint} -AppID {appId} -Organization {tenant} -ShowProgress $false -ShowBanner $false");
    string scriptContents = $"Connect-ExchangeOnline -CertificateThumbPrint {certificateThumbPrint} -AppID {appId} -Organization {tenant}";
    await objPowerShell.ExecuteScript(scriptContents);
```
<p>I have setup EventHandler's that handle all the streams and results async, and everything works fine for one user. The problem is when I have multiple users. It still all works fine, except when one user disconnects the session, all active connections to the Exchange Online environment are disconnected. As I am using EXO v3, I cannot save the PSSession and import it.</p>
<p>So my question is how can I disconnect one user without having an impact on the other.</p>
<p>I did tried to do the same thing directly in PowerShell:</p>
```    $Initialstate = [InitialSessionState]::CreateDefault()
    $RunspacePool = [runspacefactory]::CreateRunspacePool(1,5)
    $RunspacePool.Open()
    $Runspace1 = [runspacefactory]::CreateRunspace()
    $PowerShell1 = [powershell]::Create()
    $PowerShell1.RunspacePool = $RunspacePool
    $Runspace1.Open()
    [void]$PowerShell1.AddScript({
        $cert = Get-ChildItem Cert:\LocalMachine\My\0CF..4C17.
        Connect-ExchangeOnline -Certificate $cert -AppID 70539...5889 -Organization myorg.onmicrosoft.com
    })
    $PowerShell1.Invoke()
    $PowerShell1.Commands.Clear()
    [void]$PowerShell1.AddScript({
        Get-ConnectionInformation
    })
    $conn1 = $PowerShell1.Invoke()
    $PowerShell1.Commands.Clear()
    [void]$PowerShell1.AddScript({
        Get-MailBox "ue*" -resultsize 2 | Select-Object PrimarySmtpAddress
    })
    $mbx1 = $PowerShell1.Invoke()
    $mbx1 # Gets the info ok
    $PowerShell2 = [powershell]::Create()
    $PowerShell2.RunspacePool = $RunspacePool
    [void]$PowerShell2.AddScript({
        $cert = Get-ChildItem Cert:\LocalMachine\My\0CF.4C17D
        Connect-ExchangeOnline -Certificate $cert -AppID 70539...5889 -Organization myorg.onmicrosoft.com
    })
    $PowerShell2.Invoke()
    $PowerShell2.Commands.Clear()
    [void]$PowerShell2.AddScript({
        Get-ConnectionInformation
    })
    $conn2 = $PowerShell2.Invoke()
    $PowerShell2.Commands.Clear()
    [void]$PowerShell2.AddScript({
        Get-MailBox "uz*" -resultsize 2 | Select-Object PrimarySmtpAddress
    })
    $mbx2 = $PowerShell2.Invoke()
    $mbx2 # Gets the info ok
```

But when I execute now "Get-ConnectionInformation" I see 2 connections and "Disconnect-ExchangeOnline" disconnects them both. So, how can I only disconnect one ?

Body:
I am developing a server side Blazor app to facilitate Exchange online management via a GUI. I have a helper class that setups the runspace and communicates the results back to the the Blazor component. I added the class via an scoped Dependency Injection.

The helper class is setup as:

    InitialSessionState runspaceConfiguration = InitialSessionState.CreateDefault();
    runspaceConfiguration.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.RemoteSigned;
    runspaceConfiguration.ImportPSModule("ExchangeOnlineManagement");
    runspaceConfiguration.ThrowOnRunspaceOpenError = true;
    _runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
    // Open local runspace
    _runspace.Open();
    _shell = PowerShell.Create();
    _shell.Runspace = _runspace;
    SetUpEventHandlers();

My function to execute commands is a follow:

public async Task ExecuteScript(string scriptContents)
{
    _shell.AddScript(scriptContents);
    OutputEventArgs rtc = new() {
       Data = await _shell.InvokeAsync().ConfigureAwait(true)
    };
    _shell.Streams.ClearStreams();
    _shell.Commands.Clear();
    ResultsAvailable?.Invoke(this, rtc);
}

To connect to Exchnage Online I use a certificate, it looks like:

    string? certificateThumbPrint = config.GetValue<string>("certificateThumbPrint");
    string? appId = config.GetValue<string>("appId");
    string? tenant = config.GetValue<string>("tenant");
    logger.Info($"Running : Connect-ExchangeOnline -Certificate {certificateThumbPrint} -AppID {appId} -Organization {tenant} -ShowProgress $false -ShowBanner $false");
    string scriptContents = $"Connect-ExchangeOnline -CertificateThumbPrint {certificateThumbPrint} -AppID {appId} -Organization {tenant}";
    await objPowerShell.ExecuteScript(scriptContents);

I have setup EventHandler's that handle all the streams and results async, and everything works fine for one user. The problem is when I have multiple users. It still all works fine, except when one user disconnects the session, all active connections to the Exchange Online environment are disconnected. As I am using EXO v3, I cannot save the PSSession and import it.

So my question is how can I disconnect one user without having an impact on the other.

I did tried to do the same thing directly in PowerShell:

    $Initialstate = [InitialSessionState]::CreateDefault()
    $RunspacePool = [runspacefactory]::CreateRunspacePool(1,5)
    $RunspacePool.Open()
    $Runspace1 = [runspacefactory]::CreateRunspace()
    $PowerShell1 = [powershell]::Create()
    $PowerShell1.RunspacePool = $RunspacePool
    $Runspace1.Open()
    [void]$PowerShell1.AddScript({
        $cert = Get-ChildItem Cert:\LocalMachine\My\0CF..4C17.
        Connect-ExchangeOnline -Certificate $cert -AppID 70539...5889 -Organization myorg.onmicrosoft.com
    })
    $PowerShell1.Invoke()
    $PowerShell1.Commands.Clear()
    [void]$PowerShell1.AddScript({
        Get-ConnectionInformation
    })
    $conn1 = $PowerShell1.Invoke()
    $PowerShell1.Commands.Clear()
    [void]$PowerShell1.AddScript({
        Get-MailBox "ue*" -resultsize 2 | Select-Object PrimarySmtpAddress
    })
    $mbx1 = $PowerShell1.Invoke()
    $mbx1 # Gets the info ok
    $PowerShell2 = [powershell]::Create()
    $PowerShell2.RunspacePool = $RunspacePool
    [void]$PowerShell2.AddScript({
        $cert = Get-ChildItem Cert:\LocalMachine\My\0CF.4C17D
        Connect-ExchangeOnline -Certificate $cert -AppID 70539...5889 -Organization myorg.onmicrosoft.com
    })
    $PowerShell2.Invoke()
    $PowerShell2.Commands.Clear()
    [void]$PowerShell2.AddScript({
        Get-ConnectionInformation
    })
    $conn2 = $PowerShell2.Invoke()
    $PowerShell2.Commands.Clear()
    [void]$PowerShell2.AddScript({
        Get-MailBox "uz*" -resultsize 2 | Select-Object PrimarySmtpAddress
    })
    $mbx2 = $PowerShell2.Invoke()
    $mbx2 # Gets the info ok

But when I execute now "Get-ConnectionInformation" I see 2 connections and "Disconnect-ExchangeOnline" disconnects them both. So, how can I only disconnect one ?


问:
Telegram long polling bot on AWS on Java
I'm from Ukraine! As you know, we have difficult situation with electricity now, so I created a bot for Telegram, that check is the electricity on or off in our house. Bot written on Java + Spring Boot + Hibernate (with MySQL, store some data when electricity become off or on).

Used the most popular API for telegram bots on Java org.telegrambots, it spring-boot-starter particularly TelegramLongPollingBot implementation.

I deployed code on AWS on ElasticBeanstalk. Database also stored on AWS RDS (without making backups). Use it Free tire account.

What actually bot do - it has scheduled Spring task (java function), that executes ones  per 30 seconds in next way:

Firstly it call some service (that can provide info about electricity in my house) using simple HTTP GET request - actual result;

Then it call DataBase to get last row with data about electricity - last remembered result;

If actual result is the same as last remembered, function end it execution and wait 30 seconds more. And repeat all.

Else it will send appropriate message to telegram chat (electricity off/on) and store new row in DB. This case works twice a day.

That's all a bot do.

Sorry for all this text, hope it needed.

Now my question: today I got email from AWS that I exceeded 85% of the usage limit for one or more AWS Free Tier-eligible services for the month of December.

What actually are those 2,000 Put, Copy, Post or List Requests? Maybe telegram API make some requests on background or what...

Has anybody problems like this? And how to reduce this calls?

Thanks!


问:
How to Force an Error on Glue Crawler from Lambda
I have a pipeline that uses a Glue Crawler and then a Glue Job that aggregates and loads to Redshift.

Is there a way to create a simple Python script that will start the crawler and then, after a bit of a delay, force an error to stop the crawler?

Same for the Glue Job too.

My goal here is to have a on-demand lambda that I can use to see if my alarming is working, maybe something to use while creating pipelines and then tear down before wrapping up the project.

I can see where I can start Glue Crawlers and Jobs, but the stopping or forcing error part is a bit more unclear.


问:
How can I send different json responses for different request parameter values in postman?
I am trying to test my APIs in postman's mock server. I have an endpoint which returns a json with a few key value pairs.

In my request I have some key value pairs in the json format. What I want to test is as follows

Lets say if the request has a parameter called "parameter1" with value "p1". Now I want to return a different json response because it has the value of "p1". Lets say I make another request with the "parameter1" now having a value "p2" I want to return a different response. How do I do this?

I want to execute if statements / filters like if parameter1 == "p1" then return x1, if else parameter1 == "p2" then return something else etc

I looked at postman documentation but cannot figure out. Thanks in advance.


问:
Cronjob fails when script is located in other folder
I have a bash script that has a sentence like this:

```<code>readarray users < <(cat /etc/passwd | grep 'aText' | awk -F':' '{print $1}');
</code>```

When I run it in my home folder, it works. Same if I run it with sudo. Same success when I run it as a crontab job adding it with sudo crontab -e and defined like this: /15 * * * * /home/my-home/myscript.sh > /home/my-home/myscript.log 2>&1

When I move the script to the folder /opt/my-org/my-app/utils/myscript.sh I can still run it, however when I update the cronjob with sudo crontab -e to /15 * * * * /opt/my-org/my-app/utils/myscript.sh > /opt/my-org/my-app/utils/myscript.log 2>&1 I get the next error in the log file:

```<code>/opt/my-org/my-app/utils/myscript.sh: line 6: syntax error near unexpected token `<'
/opt/my-org/my-app/utils/myscript.sh: line 6: `readarray users < <(cat /etc/passwd | grep 'aText' | awk -F':' '{print $1}');'
</code>```

I am using RHEL 7.9

Why is this happening?

My script has the #!/bin/bash line, also bash version is 4.3

Also, I noticed this:

```<code>$ readarray users < <(cat /etc/passwd | grep 'aText' | awk -F':' '{print $1}');
$ echo $?
0

$ sudo readarray users < <(cat /etc/passwd | grep 'aText' | awk -F':' '{print $1}');
sudo: readarray: command not found
$ echo $?
1
</code>```

I am expecting the crontab job to run successfully independently where is it located .

Body:
I have a bash script that has a sentence like this:

readarray users < <(cat /etc/passwd | grep 'aText' | awk -F':' '{print $1}');

When I run it in my home folder, it works. Same if I run it with sudo. Same success when I run it as a crontab job adding it with sudo crontab -e and defined like this: /15 * * * * /home/my-home/myscript.sh > /home/my-home/myscript.log 2>&1

When I move the script to the folder /opt/my-org/my-app/utils/myscript.sh I can still run it, however when I update the cronjob with sudo crontab -e to /15 * * * * /opt/my-org/my-app/utils/myscript.sh > /opt/my-org/my-app/utils/myscript.log 2>&1 I get the next error in the log file:

/opt/my-org/my-app/utils/myscript.sh: line 6: syntax error near unexpected token `<'
/opt/my-org/my-app/utils/myscript.sh: line 6: `readarray users < <(cat /etc/passwd | grep 'aText' | awk -F':' '{print $1}');'

I am using RHEL 7.9

Why is this happening?

My script has the #!/bin/bash line, also bash version is 4.3

Also, I noticed this:

$ readarray users < <(cat /etc/passwd | grep 'aText' | awk -F':' '{print $1}');
$ echo $?
0

$ sudo readarray users < <(cat /etc/passwd | grep 'aText' | awk -F':' '{print $1}');
sudo: readarray: command not found
$ echo $?
1

I am expecting the crontab job to run successfully independently where is it located .


问:
Flink: Wait for Kafka CDC to playback from earliest-offset at start up
I am trying to implement a way to wait until the table kafka-connector has caught up with the latest offset.

I've already tried implementing a session gap window operator on that table (kafka-connector to a compact topic) to wait for inactivity on the table and then collect the result locally (in an attempt to close the operator/task) but it became a global operator and the rest of my topology doesn't get executed (because this window operator creates a disjoint topology)


问:
Is there a list of which ciphers suites BoringSSL lib supports?
I'm trying to get a comprehensive list of all supported ciphers suites by BoringSSL. I didn't find that in the docs.

Looking into the source I found the file ssl_cipher.cc and the constant SSL_CIPHER with the IANA names of ciphers:

```<code>TLS_RSA_WITH_NULL_SHA
TLS_RSA_WITH_3DES_EDE_CBC_SHA
TLS_RSA_WITH_AES_128_CBC_SHA
TLS_RSA_WITH_AES_256_CBC_SHA
TLS_PSK_WITH_AES_128_CBC_SHA
TLS_PSK_WITH_AES_256_CBC_SHA
TLS_RSA_WITH_AES_128_GCM_SHA256
TLS_RSA_WITH_AES_256_GCM_SHA384
TLS_AES_128_GCM_SHA256
TLS_AES_256_GCM_SHA384
TLS_CHACHA20_POLY1305_SHA256
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256
</code>```

Are those all the supported ciphers?

Body:
I'm trying to get a comprehensive list of all supported ciphers suites by BoringSSL. I didn't find that in the docs.

Looking into the source I found the file ssl_cipher.cc and the constant SSL_CIPHER with the IANA names of ciphers:

TLS_RSA_WITH_NULL_SHA
TLS_RSA_WITH_3DES_EDE_CBC_SHA
TLS_RSA_WITH_AES_128_CBC_SHA
TLS_RSA_WITH_AES_256_CBC_SHA
TLS_PSK_WITH_AES_128_CBC_SHA
TLS_PSK_WITH_AES_256_CBC_SHA
TLS_RSA_WITH_AES_128_GCM_SHA256
TLS_RSA_WITH_AES_256_GCM_SHA384
TLS_AES_128_GCM_SHA256
TLS_AES_256_GCM_SHA384
TLS_CHACHA20_POLY1305_SHA256
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256

Are those all the supported ciphers?


问:
Print output with color style in GDB python script?
I'd like to call print('somestr') in a python script called in GDB ((gdb) source my_script.py),  and style the output in console colors. I tried the python colorama package which works in terminal, but not when invoking from GDB. Is there a way to print in colors in GDB python script? Haven't got any clue from the Python API below.

https://sourceware.org/gdb/onlinedocs/gdb/Python-API.html


问:
Refreshing Angular app breaks one component, but only on version hosted on Heroku
I am working on a personal project for my portfolio and I'm completely stuck.

I have an Angular 14 app I've been working on. The stack is PEAN. I currently have a live version of it hosted on Heroku. The issue I'm running into is that in my local development version of the app, everything works as intended, however on the live version on Heroku, If I refresh the page using f5 while on the main backlog page, it does not refresh, and instead shows a blank page with "[ ]" at the top of the page. Every other part of the app functions fine, and it does not fully crash when I run into this issue. If I type a different URL in and go to that page, it works again. If after doing so, I click a link that loads the crashed component, it will reload just fine. It appears that the component only breaks if I refresh the component with f5 (or clicking the refresh button on chrome).

I've been working on this for a long time and I think I've narrowed it down a bit. So far I've:

confirmed that my express server is serving my static HTML files from their folder correctly

added a catch all code block at the bottom of my express file to redirect to index.html

made sure that Heroku was actually executing my server.js file

removed potential offending portions of code, like auth/error interceptors and newly added Google Sign-in

I've also:

checked with various browsers/mobile browsers

checked for console errors (there are none)

checked network tab on refresh. (just shows a 304-OK response)

checked Heroku logs. No errors there either.

The issue can not be recreated locally, and it only happens on refresh of one component, the Backlog component.

If there is any more info I can add please let me know, I'm hoping this is a regularly encountered issue. I can't seem to find anything that specifically deals with my exact issue by searching. Any help is greatly appreciated.

update

The blank page with "[ ]" appears to be my database's response when hit without a user ID to check against, and return data. I've narrowed this down to an HTTP-INTERCEPTOR that injects the user ID into the headers, which the route that would use that info for the DB wouldn't have. This makes my DB return "[]".

The only thing I don't understand is that this happens only when hosted on heroku, and not locally.


问:
Vector of structure IDL.Record to array Javacript
I am wondering if there is a way to read in a vector of structure

const Quote = IDL.Record({
    'buy_premium' : Tokens,
    'contracts' : Tokens,
    'datetime' : IDL.Nat64,
});
```

to an array in javascript.

This vector is passed in from a call to my back-end that I am making that is coded in Rust, but my js front end is unable tointerpret this and just reads as [Object, object].

Is there a method to interpret this?

Body:
I am wondering if there is a way to read in a vector of structure

const Quote = IDL.Record({
    'buy_premium' : Tokens,
    'contracts' : Tokens,
    'datetime' : IDL.Nat64,
});

to an array in javascript.

This vector is passed in from a call to my back-end that I am making that is coded in Rust, but my js front end is unable tointerpret this and just reads as [Object, object].

Is there a method to interpret this?


问:
Matplotlib option cmap.set_over not working
I was using WSL on windows 11 when wrote my code. Everething was working fine on jupyter notebook. Changing to linux made the cp.cmap.set_over('w') not work anymore and i can't find the error. Didn't change anything on the code.

```<code>import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate
import matplotlib.pylab as pylab
params = {'legend.fontsize': 15,
          'figure.figsize': (10, 8),
         'axes.labelsize': 20,
         'axes.titlesize':20,
         'xtick.labelsize':20,
         'ytick.labelsize':20}
pylab.rcParams.update(params)

N = 1000 #number of points for plotting/interpolation

x, y, z , derx, dery = np.genfromtxt(r'fes.dat', unpack=True)

xi = np.linspace(x.min(), x.max(), N)
yi = np.linspace(y.min(), y.max(), N)
zi = scipy.interpolate.griddata((x, y), z/4.2, (xi[None,:], yi[:,None]), method='linear')

fig = plt.figure(constrained_layout=True)
cp = plt.contourf(xi, yi, zi,levels = np.linspace(0,30,11), origin='lower', colors=['#000044','#000085','b','#2c2cff','#4e91fd', '#ffcfdc','#ff474c', 'red','#990000','#660000'],extend='max')
cp.cmap.set_over('white')
plt.contour(cp,colors='black')
cbar = plt.colorbar(cp)
plt.title('FES')
plt.xlabel('s(R)')
plt.ylabel('z(R)')
cbar.ax.set_title('\u0394G')
plt.savefig('fes.png',bbox_inches='tight',facecolor='white')
plt.show()

</code>```

I tried to change position of cp.cmap.set_over('w'), delete some import calls, but nothing worked

Body:
I was using WSL on windows 11 when wrote my code. Everething was working fine on jupyter notebook. Changing to linux made the cp.cmap.set_over('w') not work anymore and i can't find the error. Didn't change anything on the code.

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate
import matplotlib.pylab as pylab
params = {'legend.fontsize': 15,
          'figure.figsize': (10, 8),
         'axes.labelsize': 20,
         'axes.titlesize':20,
         'xtick.labelsize':20,
         'ytick.labelsize':20}
pylab.rcParams.update(params)

N = 1000 #number of points for plotting/interpolation

x, y, z , derx, dery = np.genfromtxt(r'fes.dat', unpack=True)

xi = np.linspace(x.min(), x.max(), N)
yi = np.linspace(y.min(), y.max(), N)
zi = scipy.interpolate.griddata((x, y), z/4.2, (xi[None,:], yi[:,None]), method='linear')

fig = plt.figure(constrained_layout=True)
cp = plt.contourf(xi, yi, zi,levels = np.linspace(0,30,11), origin='lower', colors=['#000044','#000085','b','#2c2cff','#4e91fd', '#ffcfdc','#ff474c', 'red','#990000','#660000'],extend='max')
cp.cmap.set_over('white')
plt.contour(cp,colors='black')
cbar = plt.colorbar(cp)
plt.title('FES')
plt.xlabel('s(R)')
plt.ylabel('z(R)')
cbar.ax.set_title('\u0394G')
plt.savefig('fes.png',bbox_inches='tight',facecolor='white')
plt.show()

I tried to change position of cp.cmap.set_over('w'), delete some import calls, but nothing worked


问:
Apple Watch Extension - where is the best location for comm and also storing shared data?
Normally in the past I have used an iOS application's AppDelegate to keep common data that I can later reference from various view controllers. It worked pretty well. I have an Apple Watch Extension app that will be handling back and forth comm with an iOS application. I have various interface controllers and I would like 1 place to store common data that can be referenced by those interface controllers.

Is that an apporpirate approach? If so, can I use the ExtensionDelegate to host this data - and thus probably handle the session for the comms? OR should is there someplace common and always available that can handle the session calls between iOS and Watch and store the received data from iOS someplace? Looking for something easy to use yet flexible for a common source of truth in my watch app.

Thanks!

I am looking into the ExtensionDelegate but it doesn't seem like the place for what I need.


问:
pygame installation error windows 11 core i7
pip install pygame
Collecting pygame
Using cached pygame-2.1.2.tar.gz (10.1 MB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error

× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─> [77 lines of output]

```<code>  WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
  Using WINDOWS configuration...

  Traceback (most recent call last):
    File "<string>", line 2, in <module>
    File "<pip-setuptools-caller>", line 34, in <module>
    File "C:\Users\camel\AppData\Local\Temp\pip-install-kdfq7kvv\pygame_d061f90eb3d6460ea821de0f37ddef4e\setup.py", line 359, in <module>
      buildconfig.config.main(AUTO_CONFIG)
    File "C:\Users\camel\AppData\Local\Temp\pip-install-kdfq7kvv\pygame_d061f90eb3d6460ea821de0f37ddef4e\buildconfig\config.py", line 225, in main
      deps = CFG.main(**kwds)
             ^^^^^^^^^^^^^^^^
    File "C:\Users\camel\AppData\Local\Temp\pip-install-kdfq7kvv\pygame_d061f90eb3d6460ea821de0f37ddef4e\buildconfig\config_win.py", line 511, in main
      return setup_prebuilt_sdl2(prebuilt_dir)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\camel\AppData\Local\Temp\pip-install-kdfq7kvv\pygame_d061f90eb3d6460ea821de0f37ddef4e\buildconfig\config_win.py", line 471, in setup_prebuilt_sdl2
      DEPS.configure()
    File "C:\Users\camel\AppData\Local\Temp\pip-install-kdfq7kvv\pygame_d061f90eb3d6460ea821de0f37ddef4e\buildconfig\config_win.py", line 336, in configure
      from . import vstools
    File "C:\Users\camel\AppData\Local\Temp\pip-install-kdfq7kvv\pygame_d061f90eb3d6460ea821de0f37ddef4e\buildconfig\vstools.py", line 11, in <module>
      compiler.initialize()
    File "C:\Users\camel\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\_distutils\msvc9compiler.py", line 403, in initialize
      vc_env = query_vcvarsall(VERSION, plat_spec)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\camel\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\_distutils\msvc9compiler.py", line 281, in query_vcvarsall
      raise DistutilsPlatformError("Unable to find vcvarsall.bat")
  distutils.errors.DistutilsPlatformError: Unable to find vcvarsall.bat
  Making dir :prebuilt_downloads:
  Downloading... https://www.libsdl.org/release/SDL2-devel-2.0.18-VC.zip ed561079ec622b0bab5a9e02976f5d540b0622da
  Unzipping :prebuilt_downloads\SDL2-devel-2.0.18-VC.zip:
  Downloading... https://www.libsdl.org/projects/SDL_image/release/SDL2_image-devel-2.0.5-VC.zip 137f86474691f4e12e76e07d58d5920c8d844d5b
  Unzipping :prebuilt_downloads\SDL2_image-devel-2.0.5-VC.zip:
  Downloading... https://www.libsdl.org/projects/SDL_ttf/release/SDL2_ttf-devel-2.0.15-VC.zip 1436df41ebc47ac36e02ec9bda5699e80ff9bd27
  Unzipping :prebuilt_downloads\SDL2_ttf-devel-2.0.15-VC.zip:
  Downloading... https://www.libsdl.org/projects/SDL_mixer/release/SDL2_mixer-devel-2.0.4-VC.zip 9097148f4529cf19f805ccd007618dec280f0ecc
  Unzipping :prebuilt_downloads\SDL2_mixer-devel-2.0.4-VC.zip:
  Downloading... https://www.pygame.org/ftp/jpegsr9d.zip ed10aa2b5a0fcfe74f8a6f7611aeb346b06a1f99
  Unzipping :prebuilt_downloads\jpegsr9d.zip:
  Downloading... https://pygame.org/ftp/prebuilt-x64-pygame-1.9.2-20150922.zip 3a5af3427b3aa13a0aaf5c4cb08daaed341613ed
  Unzipping :prebuilt_downloads\prebuilt-x64-pygame-1.9.2-20150922.zip:
  copying into .\prebuilt-x64
  Path for SDL: prebuilt-x64\SDL2-2.0.18
  ...Library directory for SDL: prebuilt-x64/SDL2-2.0.18/lib/x64
  ...Include directory for SDL: prebuilt-x64/SDL2-2.0.18/include
  Path for FONT: prebuilt-x64\SDL2_ttf-2.0.15
  ...Library directory for FONT: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64
  ...Include directory for FONT: prebuilt-x64/SDL2_ttf-2.0.15/include
  Path for IMAGE: prebuilt-x64\SDL2_image-2.0.5
  ...Library directory for IMAGE: prebuilt-x64/SDL2_image-2.0.5/lib/x64
  ...Include directory for IMAGE: prebuilt-x64/SDL2_image-2.0.5/include
  Path for MIXER: prebuilt-x64\SDL2_mixer-2.0.4
  ...Library directory for MIXER: prebuilt-x64/SDL2_mixer-2.0.4/lib/x64
  ...Include directory for MIXER: prebuilt-x64/SDL2_mixer-2.0.4/include
  Path for PORTMIDI: prebuilt-x64
  ...Library directory for PORTMIDI: prebuilt-x64/lib
  ...Include directory for PORTMIDI: prebuilt-x64/include
  DLL for SDL2: prebuilt-x64/SDL2-2.0.18/lib/x64/SDL2.dll
  DLL for SDL2_ttf: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64/SDL2_ttf.dll
  DLL for SDL2_image: prebuilt-x64/SDL2_image-2.0.5/lib/x64/SDL2_image.dll
  DLL for SDL2_mixer: prebuilt-x64/SDL2_mixer-2.0.4/lib/x64/SDL2_mixer.dll
  DLL for portmidi: prebuilt-x64/lib/portmidi.dll
  Path for FREETYPE not found.
  ...Found include dir but no library dir in prebuilt-x64.
  Path for PNG not found.
  ...Found include dir but no library dir in prebuilt-x64.
  Path for JPEG not found.
  ...Found include dir but no library dir in prebuilt-x64.
  DLL for freetype: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64/libfreetype-6.dll

  ---
  For help with compilation see:
      https://www.pygame.org/wiki/CompileWindows
  To contribute to pygame development see:
      https://www.pygame.org/contribute.html
  ---

  [end of output]
</code>```

note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

Body:
pip install pygame
Collecting pygame
Using cached pygame-2.1.2.tar.gz (10.1 MB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error

× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─> [77 lines of output]

  WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
  Using WINDOWS configuration...

  Traceback (most recent call last):
    File "<string>", line 2, in <module>
    File "<pip-setuptools-caller>", line 34, in <module>
    File "C:\Users\camel\AppData\Local\Temp\pip-install-kdfq7kvv\pygame_d061f90eb3d6460ea821de0f37ddef4e\setup.py", line 359, in <module>
      buildconfig.config.main(AUTO_CONFIG)
    File "C:\Users\camel\AppData\Local\Temp\pip-install-kdfq7kvv\pygame_d061f90eb3d6460ea821de0f37ddef4e\buildconfig\config.py", line 225, in main
      deps = CFG.main(**kwds)
             ^^^^^^^^^^^^^^^^
    File "C:\Users\camel\AppData\Local\Temp\pip-install-kdfq7kvv\pygame_d061f90eb3d6460ea821de0f37ddef4e\buildconfig\config_win.py", line 511, in main
      return setup_prebuilt_sdl2(prebuilt_dir)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\camel\AppData\Local\Temp\pip-install-kdfq7kvv\pygame_d061f90eb3d6460ea821de0f37ddef4e\buildconfig\config_win.py", line 471, in setup_prebuilt_sdl2
      DEPS.configure()
    File "C:\Users\camel\AppData\Local\Temp\pip-install-kdfq7kvv\pygame_d061f90eb3d6460ea821de0f37ddef4e\buildconfig\config_win.py", line 336, in configure
      from . import vstools
    File "C:\Users\camel\AppData\Local\Temp\pip-install-kdfq7kvv\pygame_d061f90eb3d6460ea821de0f37ddef4e\buildconfig\vstools.py", line 11, in <module>
      compiler.initialize()
    File "C:\Users\camel\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\_distutils\msvc9compiler.py", line 403, in initialize
      vc_env = query_vcvarsall(VERSION, plat_spec)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\camel\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\_distutils\msvc9compiler.py", line 281, in query_vcvarsall
      raise DistutilsPlatformError("Unable to find vcvarsall.bat")
  distutils.errors.DistutilsPlatformError: Unable to find vcvarsall.bat
  Making dir :prebuilt_downloads:
  Downloading... https://www.libsdl.org/release/SDL2-devel-2.0.18-VC.zip ed561079ec622b0bab5a9e02976f5d540b0622da
  Unzipping :prebuilt_downloads\SDL2-devel-2.0.18-VC.zip:
  Downloading... https://www.libsdl.org/projects/SDL_image/release/SDL2_image-devel-2.0.5-VC.zip 137f86474691f4e12e76e07d58d5920c8d844d5b
  Unzipping :prebuilt_downloads\SDL2_image-devel-2.0.5-VC.zip:
  Downloading... https://www.libsdl.org/projects/SDL_ttf/release/SDL2_ttf-devel-2.0.15-VC.zip 1436df41ebc47ac36e02ec9bda5699e80ff9bd27
  Unzipping :prebuilt_downloads\SDL2_ttf-devel-2.0.15-VC.zip:
  Downloading... https://www.libsdl.org/projects/SDL_mixer/release/SDL2_mixer-devel-2.0.4-VC.zip 9097148f4529cf19f805ccd007618dec280f0ecc
  Unzipping :prebuilt_downloads\SDL2_mixer-devel-2.0.4-VC.zip:
  Downloading... https://www.pygame.org/ftp/jpegsr9d.zip ed10aa2b5a0fcfe74f8a6f7611aeb346b06a1f99
  Unzipping :prebuilt_downloads\jpegsr9d.zip:
  Downloading... https://pygame.org/ftp/prebuilt-x64-pygame-1.9.2-20150922.zip 3a5af3427b3aa13a0aaf5c4cb08daaed341613ed
  Unzipping :prebuilt_downloads\prebuilt-x64-pygame-1.9.2-20150922.zip:
  copying into .\prebuilt-x64
  Path for SDL: prebuilt-x64\SDL2-2.0.18
  ...Library directory for SDL: prebuilt-x64/SDL2-2.0.18/lib/x64
  ...Include directory for SDL: prebuilt-x64/SDL2-2.0.18/include
  Path for FONT: prebuilt-x64\SDL2_ttf-2.0.15
  ...Library directory for FONT: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64
  ...Include directory for FONT: prebuilt-x64/SDL2_ttf-2.0.15/include
  Path for IMAGE: prebuilt-x64\SDL2_image-2.0.5
  ...Library directory for IMAGE: prebuilt-x64/SDL2_image-2.0.5/lib/x64
  ...Include directory for IMAGE: prebuilt-x64/SDL2_image-2.0.5/include
  Path for MIXER: prebuilt-x64\SDL2_mixer-2.0.4
  ...Library directory for MIXER: prebuilt-x64/SDL2_mixer-2.0.4/lib/x64
  ...Include directory for MIXER: prebuilt-x64/SDL2_mixer-2.0.4/include
  Path for PORTMIDI: prebuilt-x64
  ...Library directory for PORTMIDI: prebuilt-x64/lib
  ...Include directory for PORTMIDI: prebuilt-x64/include
  DLL for SDL2: prebuilt-x64/SDL2-2.0.18/lib/x64/SDL2.dll
  DLL for SDL2_ttf: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64/SDL2_ttf.dll
  DLL for SDL2_image: prebuilt-x64/SDL2_image-2.0.5/lib/x64/SDL2_image.dll
  DLL for SDL2_mixer: prebuilt-x64/SDL2_mixer-2.0.4/lib/x64/SDL2_mixer.dll
  DLL for portmidi: prebuilt-x64/lib/portmidi.dll
  Path for FREETYPE not found.
  ...Found include dir but no library dir in prebuilt-x64.
  Path for PNG not found.
  ...Found include dir but no library dir in prebuilt-x64.
  Path for JPEG not found.
  ...Found include dir but no library dir in prebuilt-x64.
  DLL for freetype: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64/libfreetype-6.dll

  ---
  For help with compilation see:
      https://www.pygame.org/wiki/CompileWindows
  To contribute to pygame development see:
      https://www.pygame.org/contribute.html
  ---

  [end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.


问:
d3.js transform.rescaleX() returning big and negative values
I'm making a semantic zoom on xAxis using the helper function transform.rescaleX() inside zoomed function

```<code>private manageZoom(svgs: AllSvg, allAxis: AllAxis, dimension: Dimension, sillons: Circulation[]): D3ZoomBehavior {
    const zoom: D3ZoomBehavior = d3
        .zoom()
        .scaleExtent([1, 40])
        .translateExtent([
            [0, 0],
            [dimension.width, dimension.height]
        ])
        .on('zoom', zoomed.bind(null, allAxis, sillons, dimension, this.drawSillonService));

    svgs.svgContainer.call(zoom);
    return zoom;

    function zoomed(
        { xAxis, xAxisBottom, yAxis }: AllAxis,
        sillons: Circulation[],
        dimension: Dimension,
        drawSillonService: DrawSillonService,
        { transform }: any
    ) {
        xAxis.axisContainer.call(xAxis.axis.scale(transform.rescaleX(xAxis.scale)) as any);
        xAxisBottom.axisContainer.call(xAxisBottom.axis.scale(transform.rescaleX(xAxisBottom.scale)) as any);
            svgs.sillons
            .selectAll('path')
            .nodes()
            .forEach((path, j) => {
                const pathSelect = d3.select(path);
                const pathData = JSON.parse(pathSelect.attr('data'));
                const line = d3
                    .line()
                    .x((d) => {
                        const transformScaled = transform.rescaleX(xAxis.scale);
                        const value = transformScaled(d[0]);
                        return value;
                    })
                    .y((d) => d[1]);
                pathSelect.attr('d', line(pathData));
            });
            ...
</code>```

Here's the values of transform:

```<code>k:1.6817928305074288
x:-278.99232789420023
y:
-200.42112372679287
</code>```

when d[0] = 0 the transformScaled(d[0]) return -133335,..

I don't know why I get these values. When I calculate transformation manually using  x * transform.k + transform.x I get the right values (-79.5), but I would use rescaleX function.

Body:
I'm making a semantic zoom on xAxis using the helper function transform.rescaleX() inside zoomed function

private manageZoom(svgs: AllSvg, allAxis: AllAxis, dimension: Dimension, sillons: Circulation[]): D3ZoomBehavior {
    const zoom: D3ZoomBehavior = d3
        .zoom()
        .scaleExtent([1, 40])
        .translateExtent([
            [0, 0],
            [dimension.width, dimension.height]
        ])
        .on('zoom', zoomed.bind(null, allAxis, sillons, dimension, this.drawSillonService));

    svgs.svgContainer.call(zoom);
    return zoom;

    function zoomed(
        { xAxis, xAxisBottom, yAxis }: AllAxis,
        sillons: Circulation[],
        dimension: Dimension,
        drawSillonService: DrawSillonService,
        { transform }: any
    ) {
        xAxis.axisContainer.call(xAxis.axis.scale(transform.rescaleX(xAxis.scale)) as any);
        xAxisBottom.axisContainer.call(xAxisBottom.axis.scale(transform.rescaleX(xAxisBottom.scale)) as any);
            svgs.sillons
            .selectAll('path')
            .nodes()
            .forEach((path, j) => {
                const pathSelect = d3.select(path);
                const pathData = JSON.parse(pathSelect.attr('data'));
                const line = d3
                    .line()
                    .x((d) => {
                        const transformScaled = transform.rescaleX(xAxis.scale);
                        const value = transformScaled(d[0]);
                        return value;
                    })
                    .y((d) => d[1]);
                pathSelect.attr('d', line(pathData));
            });
            ...

Here's the values of transform:

k:1.6817928305074288
x:-278.99232789420023
y:
-200.42112372679287

when d[0] = 0 the transformScaled(d[0]) return -133335,..

I don't know why I get these values. When I calculate transformation manually using  x * transform.k + transform.x I get the right values (-79.5), but I would use rescaleX function.


问:
PDF to Excel extraction - How to support more than one block pattern and combine?
I currently have working code that extracts all text from a PDF and exports to a .txt file. From there, it grabs specific block patterns, formats and extracts to an excel sheet. I'm currently running into two issues with the code, however.

With item names that are long enough to require a second line, a new row is being created with the cut-off portion. I know this is because I have the line break specified but I'm not sure how to deal with this issue. After the item name, "Status" is always the next piece of information so I'm trying to figure out a way to end the item name category when it sees "Status" rather than when the line ends.
EDIT: I've found examples of this being the case with the description field as well. Some description fields are empty, some are contained on one line and some spill over to multiple lines. There is always an empty line between the description field and the next data block but when trying to use multiple line breaks as the pattern (\n\n), the pattern doesn't find anything. I'm out of ideas for the longer fields at this point but I'd imagine the same solution would work for both the name field and the description field.

Example:

```<code>Institute 123
Status: Active
Event Category: ABC
Event Sub-Category: ABC
Added Date: 01/07/2021
Update Frequency: Weekly
Language: English
Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit
</code>```

```<code>Institute With Long Name That
Requires Another Line 123
Status: Active
Event Category: ABC
Event Sub-Category: ABC
Added Date: 01/07/2021
Update Frequency: Weekly
Language: English
Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit
</code>```

There are varying block patterns. The majority of the information given is the same but not in all cases. Examples:

Variation 1:

```<code>Institute 123
Status: Active
Event Category: ABC
Event Sub-Category: ABC
Added Date: 01/07/2021
Update Frequency: Weekly
Language: English
Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit
</code>```

Variation 2:

```<code>Institute 123
Status: Deleted
Event Category: ABC
Event Sub-Category: ABC
Last Approved Date: 01/07/2021
Language: English
Date of Deletion: 07/25/2022
</code>```

Code shown here. I currently have everything formatting correctly but need to add support for different variations of data as well as how to handle names that are too long. For the different variations I'd like to just add additional information columns to the excel sheet and fill them in or leave them empty as required but since it's searching for specific patterns, I'm not sure how to do that.

```<code>import pdfplumber
import pandas as pd
import re

# Set pdf location and location for text file to be written.
pdfFilePath = r'/Desktop/test.pdf'
txtFilePath = r'/Desktop/test.txt'

# iterate through all pages of pdf and extract to .txt file before parsing
with pdfplumber.open(pdfFilePath) as pdf:
    k = len(pdf.pages)
    for i in range(1, k):
        page = pdf.pages[i]
        text = (page.extract_text())

        with open(txtFilePath, 'a') as txtFile:
            txtFile.write(text)

with open(txtFilePath, 'r') as f:
    text = "".join(f)

# Establishing block pattern
block_pattern = re.compile(
    r"^(.*)\n"
    r"^Status: (.*)\n"
    r"^Event Category: (.*)\n"
    r"^Event Sub-Category: (.*)\n"
    r"^Added Date: (.*)\n"
    r"^Update Frequency: (.*)\n"
    r"^Language: (.*)\n"
    r"^Description: (.*)\n",
    flags=re.MULTILINE)

columns = ["Item", "Status", "Event Category", "Event Sub-Category",
           "Added Date", "Update Frequency", "Language", "Description"]
df = pd.DataFrame.from_records(re.findall(block_pattern, text), columns=columns)

df.to_excel(r'/desktop/example.xlsx')

</code>```

Body:
I currently have working code that extracts all text from a PDF and exports to a .txt file. From there, it grabs specific block patterns, formats and extracts to an excel sheet. I'm currently running into two issues with the code, however.

With item names that are long enough to require a second line, a new row is being created with the cut-off portion. I know this is because I have the line break specified but I'm not sure how to deal with this issue. After the item name, "Status" is always the next piece of information so I'm trying to figure out a way to end the item name category when it sees "Status" rather than when the line ends.
EDIT: I've found examples of this being the case with the description field as well. Some description fields are empty, some are contained on one line and some spill over to multiple lines. There is always an empty line between the description field and the next data block but when trying to use multiple line breaks as the pattern (\n\n), the pattern doesn't find anything. I'm out of ideas for the longer fields at this point but I'd imagine the same solution would work for both the name field and the description field.

Example:

Institute 123
Status: Active
Event Category: ABC
Event Sub-Category: ABC
Added Date: 01/07/2021
Update Frequency: Weekly
Language: English
Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit

Institute With Long Name That
Requires Another Line 123
Status: Active
Event Category: ABC
Event Sub-Category: ABC
Added Date: 01/07/2021
Update Frequency: Weekly
Language: English
Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit

There are varying block patterns. The majority of the information given is the same but not in all cases. Examples:

Variation 1:

Institute 123
Status: Active
Event Category: ABC
Event Sub-Category: ABC
Added Date: 01/07/2021
Update Frequency: Weekly
Language: English
Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit

Variation 2:

Institute 123
Status: Deleted
Event Category: ABC
Event Sub-Category: ABC
Last Approved Date: 01/07/2021
Language: English
Date of Deletion: 07/25/2022

Code shown here. I currently have everything formatting correctly but need to add support for different variations of data as well as how to handle names that are too long. For the different variations I'd like to just add additional information columns to the excel sheet and fill them in or leave them empty as required but since it's searching for specific patterns, I'm not sure how to do that.

import pdfplumber
import pandas as pd
import re

# Set pdf location and location for text file to be written.
pdfFilePath = r'/Desktop/test.pdf'
txtFilePath = r'/Desktop/test.txt'

# iterate through all pages of pdf and extract to .txt file before parsing
with pdfplumber.open(pdfFilePath) as pdf:
    k = len(pdf.pages)
    for i in range(1, k):
        page = pdf.pages[i]
        text = (page.extract_text())

        with open(txtFilePath, 'a') as txtFile:
            txtFile.write(text)

with open(txtFilePath, 'r') as f:
    text = "".join(f)

# Establishing block pattern
block_pattern = re.compile(
    r"^(.*)\n"
    r"^Status: (.*)\n"
    r"^Event Category: (.*)\n"
    r"^Event Sub-Category: (.*)\n"
    r"^Added Date: (.*)\n"
    r"^Update Frequency: (.*)\n"
    r"^Language: (.*)\n"
    r"^Description: (.*)\n",
    flags=re.MULTILINE)

columns = ["Item", "Status", "Event Category", "Event Sub-Category",
           "Added Date", "Update Frequency", "Language", "Description"]
df = pd.DataFrame.from_records(re.findall(block_pattern, text), columns=columns)

df.to_excel(r'/desktop/example.xlsx')


问:
Creating a CTE dynamically from contents of DataTable C#
I am trying to create a method getSqlCte that accepts a data table and returns a CTE string (for sql query) with the values, desired output is as below

```<code>with cte as
select * from (('LU','88949'),('SU','44657')) AS t (HeadOffice, StoreNo)
\\\\SQL code comes here   xxxxxxxxx JOIN cte ON x=y
</code>```

I accept a DataTable dt  eg. with columns with Head office and Store Numbers
I only have read access to the database. (So no temp Table.)

```<code>string getSqlCte(DataTable dt)
{
  IEnumerable<DataRow> rows = dt.AsEnumerable();

string[] columnNames = dt.Columns.Cast<DataColumn>()
                                             .Select(x => x.ColumnName)
                                             .ToArray();

string cteData = string.Join(",", rows.Select(r => $"('{r["Headoffice"]}', '{r["StoreNo"]}')"));

string query = $"WITH MyCTE AS (SELECT * FROM ({cteData}) AS t({string.Join(", ", columnNames)})) ";

return query;
}
</code>```

How do I dynamically input the row fields inside rows.Select to to make cte data return the the columns in the array columnNames  so as to re-use the method
Or alternatively loop through to produce  the CTE string dynamically based on the columns required .

I am able to produce for one  DataTable but if columns change (or increase), i get errors.

Body:
I am trying to create a method getSqlCte that accepts a data table and returns a CTE string (for sql query) with the values, desired output is as below

with cte as
select * from (('LU','88949'),('SU','44657')) AS t (HeadOffice, StoreNo)
\\\\SQL code comes here   xxxxxxxxx JOIN cte ON x=y

I accept a DataTable dt  eg. with columns with Head office and Store Numbers
I only have read access to the database. (So no temp Table.)

string getSqlCte(DataTable dt)
{
  IEnumerable<DataRow> rows = dt.AsEnumerable();

string[] columnNames = dt.Columns.Cast<DataColumn>()
                                             .Select(x => x.ColumnName)
                                             .ToArray();

string cteData = string.Join(",", rows.Select(r => $"('{r["Headoffice"]}', '{r["StoreNo"]}')"));

string query = $"WITH MyCTE AS (SELECT * FROM ({cteData}) AS t({string.Join(", ", columnNames)})) ";

return query;
}

How do I dynamically input the row fields inside rows.Select to to make cte data return the the columns in the array columnNames  so as to re-use the method
Or alternatively loop through to produce  the CTE string dynamically based on the columns required .

I am able to produce for one  DataTable but if columns change (or increase), i get errors.


问:
Laravel black page - Unable to create configured logger. Using emergency logger
After following the instruction to deploy my Laravel app on 000webhost.com, i got a black page with server error on console and when i look to Laravel logs i see:

```<code>laravel.EMERGENCY: Unable to create configured logger. Using emergency logger. {"exception":"[object] (InvalidArgumentException(code: 0): Log [] is not defined. at /storage/ssd3/245/19242245/vendor/laravel/framework/src/Illuminate/Log/LogManager.php:207)

laravel.ERROR: syntax error, unexpected token ")" {"exception":"[object] (ParseError(code: 0): syntax error, unexpected token \")\" at /storage/ssd3/245/19242245/vendor/symfony/finder/Finder.php:636)
</code>```

All works on local server.

Laravel 9

Use PHP8.0 on 000webhost

Body:
After following the instruction to deploy my Laravel app on 000webhost.com, i got a black page with server error on console and when i look to Laravel logs i see:

laravel.EMERGENCY: Unable to create configured logger. Using emergency logger. {"exception":"[object] (InvalidArgumentException(code: 0): Log [] is not defined. at /storage/ssd3/245/19242245/vendor/laravel/framework/src/Illuminate/Log/LogManager.php:207)

laravel.ERROR: syntax error, unexpected token ")" {"exception":"[object] (ParseError(code: 0): syntax error, unexpected token \")\" at /storage/ssd3/245/19242245/vendor/symfony/finder/Finder.php:636)

All works on local server.

Laravel 9

Use PHP8.0 on 000webhost


问:
Why wont py script write file?
Shouldnt it create a file and write asd in it? When it prints out fgh.</p>

```<code>   <!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
  </head>
  <body>
    <py-script>
        f = open("file.txt", "a", encoding="UTF-8")
        f.write("asd")
        print("fgh")
    </py-script>
  </body>
</html>
</code>```

Title: Why wont py script write file?

Body:
Shouldnt it create a file and write asd in it? When it prints out fgh.

   <!DOCTYPE html>

    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />

    <py-script>
        f = open("file.txt", "a", encoding="UTF-8")
        f.write("asd")
        print("fgh")
    </py-script>


问:
Web scraping (Shopify Blog Post) Not getting the HTML content using Python Selenium
I am trying to web scrape Shopify Blog, to send text from python script which will upload to the blog. I have successfully log into the desired page of the Shopify Blog but when I tried to access the text field (using class, xpath) Python script didn't show at all. But this will exist in the actual HTML page as shown below.
 Actual page

I am getting the content of half of the page (shown in green Box of Figure 2). While the content of red box is absent from the extracted python selenium driver Object/variable.
Figure 2 Blog post

Looking forward to your help.

I tried Selenium Python Library to extract the page contents.


问:
Removing ripple tag from XML crashes the app
I have next xml background file

```<code><?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android">
    <ripple android:color="@color/backgroundColorPrimary">
        <item>
            <selector>
                <item android:state_enabled="false">
                    <shape android:shape="rectangle">
                        <solid android:color="@android:color/transparent" />

                        <stroke
                            android:width="@dimen/button_border_width"
                            android:color="#26E7E7E7" />
                        <corners android:radius="7dp" />
                    </shape>
                </item>
                <item android:state_selected="false">
                    <layer-list>
                        <item
                            android:left="3dp"
                            android:top="1dp">
                            <shape>
                                <corners android:radius="7dp" />
                                <solid android:color="#26E7E7E7" />
                            </shape>
                        </item>
                        <item
                            android:top="2dp"
                            android:bottom="4dp"
                            android:left="2dp"
                            android:right="1dp">
                            <shape>
                                <corners android:radius="7dp" />
                                <solid android:color="@color/white" />
                            </shape>
                        </item>
                    </layer-list>
                </item>
            </selector>
        </item>
    </ripple>
</inset>
</code>```

Ripple effect goes beyond the margins of the button I put this background to. I guess it is because of this part of code:

```<code>                                  android:top="2dp"
                                android:bottom="4dp"
                                android:left="2dp"
                                android:right="1dp">
</code>```

which makes shadow on my button. I would like to make ripple effect only on the original size of button. How should I do this.

Also removing ripple tag crashes my app. I can add  in the place of ripple, but then it does not work as I want it to.
How to solve this?

Body:
I have next xml background file

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android">
    <ripple android:color="@color/backgroundColorPrimary">
        <item>
            <selector>
                <item android:state_enabled="false">
                    <shape android:shape="rectangle">
                        <solid android:color="@android:color/transparent" />

                        <stroke
                            android:width="@dimen/button_border_width"
                            android:color="#26E7E7E7" />
                        <corners android:radius="7dp" />
                    </shape>
                </item>
                <item android:state_selected="false">
                    <layer-list>
                        <item
                            android:left="3dp"
                            android:top="1dp">
                            <shape>
                                <corners android:radius="7dp" />
                                <solid android:color="#26E7E7E7" />
                            </shape>
                        </item>
                        <item
                            android:top="2dp"
                            android:bottom="4dp"
                            android:left="2dp"
                            android:right="1dp">
                            <shape>
                                <corners android:radius="7dp" />
                                <solid android:color="@color/white" />
                            </shape>
                        </item>
                    </layer-list>
                </item>
            </selector>
        </item>
    </ripple>
</inset>

Ripple effect goes beyond the margins of the button I put this background to. I guess it is because of this part of code:

                                  android:top="2dp"
                                android:bottom="4dp"
                                android:left="2dp"
                                android:right="1dp">

which makes shadow on my button. I would like to make ripple effect only on the original size of button. How should I do this.

Also removing ripple tag crashes my app. I can add  in the place of ripple, but then it does not work as I want it to.
How to solve this?


问:
How do I make VSCode outline global (browse entire folder)?
In VS code, there's an outline feature that works for the file currently open. It's great, just what I need!

However, I want to browse the entire class structure of my project, just like you can in qtcreator, and like you can for other programming languages in IntelliJ.

This is super important: browsing the class structure is the fastest way for me to navigate between files. Working with my code in qtcreator is a factor of 2 faster due to the qtcreator "outline" being global.


问:
My first column of a matrix is returning a weird symbol, and not the intended input
I'm new to C and I'm trying to do a simple program where the user inputs a sequence of strings and then it is printed again using Arrays, but the first column of the array always returns with a weird symbol. It's input is stopped using the symbol "#". Can someone find the solution to this problem?

The cmd looks like this:

```<code>Input the Sequence:
morning
hey
#
The sequences are:
   ♥
h e y

-----------------------
Process exited after 10.01 seconds with return value 0
Press any key to continue...
</code>```

The code:

```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int findnumber (char c, char ArrayAlfabeto[27], int Numeracao[26]);
char findchar (int c, char ArrayAlfabeto[27], int Numeracao[26]);

int main(){

    char exit, exit2 = '#';
    char ArrayChar[50];
    char ArrayIni[50] = {0};
    char ArrayCharFinal[50];
    char ArrayAlfabeto[27] = {"abcdefghijklmnopqrstuvwxyz"};
    int Numeracao[26] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26};
    int ArrayNumeroAlfabeto[110];
    int ArrayNumeroAlfabeto2[110];
    int ArrayReverse[110];
    int B=0, G=0,j, i, n, size = 0, size2 = 0, PosicaoPivo, PosicaoSucessor, Encontrou = 0, Pivo, Sucessor, contador;
    char ArrayStrings[G][51];
    int ArrayLength[G];

    //Asks for the input string
    printf("Input the sequences: \n");

    while((ArrayIni[0] != exit2)){

        scanf(" %s^\n", ArrayIni);
        if(ArrayIni[0] != exit2){
            size2 = strlen(ArrayIni);
            for(B;B<size2;B++){
                ArrayStrings[G][B] = ArrayIni[B];
            }
            ArrayLength[G] = B;

        }
        B=0;
        G++;
        //printf("Teste 1: %c\n", ArrayStrings[0][0]);
    }

    printf("The sequences are: \n");
    int U=0;
    for(U;U<=G;U++){
        int I = 0, contador = ArrayLength[U];
        for(I;I<contador;I++){
            printf(" %c", ArrayStrings[U][I]);
        }
        printf("\n");

    }

}

</code>```

Body:
I'm new to C and I'm trying to do a simple program where the user inputs a sequence of strings and then it is printed again using Arrays, but the first column of the array always returns with a weird symbol. It's input is stopped using the symbol "#". Can someone find the solution to this problem?

The cmd looks like this:

Input the Sequence:
morning
hey
#
The sequences are:
   ♥
h e y

-----------------------
Process exited after 10.01 seconds with return value 0
Press any key to continue...

The code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int findnumber (char c, char ArrayAlfabeto[27], int Numeracao[26]);
char findchar (int c, char ArrayAlfabeto[27], int Numeracao[26]);

int main(){

    char exit, exit2 = '#';
    char ArrayChar[50];
    char ArrayIni[50] = {0};
    char ArrayCharFinal[50];
    char ArrayAlfabeto[27] = {"abcdefghijklmnopqrstuvwxyz"};
    int Numeracao[26] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26};
    int ArrayNumeroAlfabeto[110];
    int ArrayNumeroAlfabeto2[110];
    int ArrayReverse[110];
    int B=0, G=0,j, i, n, size = 0, size2 = 0, PosicaoPivo, PosicaoSucessor, Encontrou = 0, Pivo, Sucessor, contador;
    char ArrayStrings[G][51];
    int ArrayLength[G];

    //Asks for the input string
    printf("Input the sequences: \n");

    while((ArrayIni[0] != exit2)){

        scanf(" %s^\n", ArrayIni);
        if(ArrayIni[0] != exit2){
            size2 = strlen(ArrayIni);
            for(B;B<size2;B++){
                ArrayStrings[G][B] = ArrayIni[B];
            }
            ArrayLength[G] = B;

        }
        B=0;
        G++;
        //printf("Teste 1: %c\n", ArrayStrings[0][0]);
    }

    printf("The sequences are: \n");
    int U=0;
    for(U;U<=G;U++){
        int I = 0, contador = ArrayLength[U];
        for(I;I<contador;I++){
            printf(" %c", ArrayStrings[U][I]);
        }
        printf("\n");

    }

}


问:
uncaugth TypeError: Cannot set properties of undefined (setting '20')
when i am taking values into x and y using destructuring its working.
but when I am trying to swap the values using Destructuring its simply showing Typeerror.
I have searched this problem on the internet and found no solution any help would be appreciatable.

```<code>const arr=new Array(2,3,4);
let [x,y,z]=arr;
console.log(x,y)
let a="23";

let b="20";
console.log(a,b)

[a , b] = [b , a];
console.log(a,b)

// [x,y]=[y,x];
console.log(x,y)
</code>```

i am expecting the values of a and b to be sawpped.

Body:
when i am taking values into x and y using destructuring its working.
but when I am trying to swap the values using Destructuring its simply showing Typeerror.
I have searched this problem on the internet and found no solution any help would be appreciatable.

const arr=new Array(2,3,4);
let [x,y,z]=arr;
console.log(x,y)
let a="23";

let b="20";
console.log(a,b)

[a , b] = [b , a];
console.log(a,b)

// [x,y]=[y,x];
console.log(x,y)

i am expecting the values of a and b to be sawpped.


问:
Cant Deserialize LocalDateTime in Quarkus
I'm trying to deserialize an object using Kafka inside a Quarkus Project JDK-17. But It simply won't work. I was having the same issue when serializing the message inside the same project, but using  ObjectMapper().registerModule(new JavaTimeModule()); solved the issue.

Now that I need to consume the same object, inside the same project, It won't work. I've I already tried the following:

```<code>new ObjectMapper().registerModule(new JavaTimeModule());
mapper.readValue(data, BudgetToMarinaOrderDTO.class);
</code>```

2:

```<code>new ObjectMapper().registerModule(new JavaTimeModule()).disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.readValue(data, BudgetToMarinaOrderDTO.class);
</code>```

3:

```<code>Gson gson = new GsonBuilder().create();
gson.fromJson(data, BudgetToMarinaOrderDTO.class);
</code>```

4:

```<code>gsonBuilder.registerTypeAdapter(LocalDateTime.class, new CustomLocalDateTimeDeserializer());
Gson gson = gsonBuilder.setPrettyPrinting().create();
gson.fromJson(data, BudgetToMarinaOrderDTO.class);
</code>```

These are the related dependencies that I'm using:

```<code>        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-smallrye-reactive-messaging-kafka</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.10</version>
        </dependency>
</code>```

Each one of those gives me a different Error, but they all talk about the same thing...
Here's one of these errors:

```<code>com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.time.LocalDateTime` from Object value (
</code>```

Body:
I'm trying to deserialize an object using Kafka inside a Quarkus Project JDK-17. But It simply won't work. I was having the same issue when serializing the message inside the same project, but using  ObjectMapper().registerModule(new JavaTimeModule()); solved the issue.

Now that I need to consume the same object, inside the same project, It won't work. I've I already tried the following:

new ObjectMapper().registerModule(new JavaTimeModule());
mapper.readValue(data, BudgetToMarinaOrderDTO.class);

2:

new ObjectMapper().registerModule(new JavaTimeModule()).disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.readValue(data, BudgetToMarinaOrderDTO.class);

3:

Gson gson = new GsonBuilder().create();
gson.fromJson(data, BudgetToMarinaOrderDTO.class);

4:

gsonBuilder.registerTypeAdapter(LocalDateTime.class, new CustomLocalDateTimeDeserializer());
Gson gson = gsonBuilder.setPrettyPrinting().create();
gson.fromJson(data, BudgetToMarinaOrderDTO.class);

These are the related dependencies that I'm using:

        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-smallrye-reactive-messaging-kafka</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.10</version>
        </dependency>

Each one of those gives me a different Error, but they all talk about the same thing...
Here's one of these errors:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.time.LocalDateTime` from Object value (