问:
Error while creating a SOAP document: IllegalArgumentException saying local part cannot be "null" when creating a QName
I have a piece of code that is trying to create a new Soap message and adding a fault document in it.

```<code>public static SOAPMessage getMessage() throws SOAPException {
    SOAPMessage message = newSoapMessage((XmlObject) null);
    SOAPBody respBody = message.getSOAPBody();
    respBody.addDocument(newFaultDocument("soap:Server","faultText"));
    message.saveChanges();
    return message;
}

public static Document newFaultDocument(String faultCode, String faultString) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    try {
        Document doc = factory.newDocumentBuilder().newDocument();
        Element fault = doc.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "Fault:abc");
        doc.appendChild(fault);

        Element faultCodeElement = doc.createElement("faultcode");
        faultCodeElement.setTextContent(StringEscapeUtils.escapeXml(faultCode));
        fault.appendChild(faultCodeElement);

        Element faultStringElement = doc.createElement("faultstring");
        faultStringElement.setTextContent(StringEscapeUtils.escapeXml(faultString));
        fault.appendChild(faultStringElement);

        return doc;
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException("Unexpected exception while creating Fault document", e);
    }
}

public static <T extends XmlObject> SOAPMessage newSoapMessage(T soapBody) {
    try {
        MessageFactory mf = MessageFactory.newInstance();
        SOAPMessage message = mf.createMessage();
        SOAPBody respBody = message.getSOAPBody();

        if (soapBody != null) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            respBody.addDocument(factory.newDocumentBuilder().parse(soapBody.newInputStream()));
            message.saveChanges();
        }

        return message;
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new IllegalStateException("Unexpected exception while creating SOAP message", e);
    }
}
</code>```

I am calling the getMessage() function to get the document but it fails with the following stacktrace

```<code>Exception in thread "main" java.lang.IllegalArgumentException: local part cannot be "null" when creating a QName
    at javax.xml.namespace.QName.<init>(QName.java:244)
    at javax.xml.namespace.QName.<init>(QName.java:188)
    at com.sun.xml.messaging.saaj.soap.impl.ElementImpl.<init>(ElementImpl.java:156)
    at com.sun.xml.messaging.saaj.soap.impl.ElementFactory.createElement(ElementFactory.java:119)
    at com.sun.xml.messaging.saaj.soap.SOAPDocumentImpl.registerChildNodes(SOAPDocumentImpl.java:230)
    at com.sun.xml.messaging.saaj.soap.SOAPDocumentImpl.registerChildNodes(SOAPDocumentImpl.java:251)
    at com.sun.xml.messaging.saaj.soap.SOAPDocumentImpl.registerChildNodes(SOAPDocumentImpl.java:251)
    at com.sun.xml.messaging.saaj.soap.SOAPDocumentImpl.importNode(SOAPDocumentImpl.java:217)
    at com.sun.xml.messaging.saaj.soap.impl.BodyImpl.addDocument(BodyImpl.java:259)
    at com.example.demo.Demo1Application.getMessage(Demo1Application.java:29)
    at com.example.demo.Demo1Application.main(Demo1Application.java:23)

Process finished with exit code 1
</code>```

I tried figuring out how the local part is to be set in QName but couldn't figure out where and how it is to be done. Any help will be highly appreciated.

Body:
I have a piece of code that is trying to create a new Soap message and adding a fault document in it.

public static SOAPMessage getMessage() throws SOAPException {
    SOAPMessage message = newSoapMessage((XmlObject) null);
    SOAPBody respBody = message.getSOAPBody();
    respBody.addDocument(newFaultDocument("soap:Server","faultText"));
    message.saveChanges();
    return message;
}

public static Document newFaultDocument(String faultCode, String faultString) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    try {
        Document doc = factory.newDocumentBuilder().newDocument();
        Element fault = doc.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "Fault:abc");
        doc.appendChild(fault);

        Element faultCodeElement = doc.createElement("faultcode");
        faultCodeElement.setTextContent(StringEscapeUtils.escapeXml(faultCode));
        fault.appendChild(faultCodeElement);

        Element faultStringElement = doc.createElement("faultstring");
        faultStringElement.setTextContent(StringEscapeUtils.escapeXml(faultString));
        fault.appendChild(faultStringElement);

        return doc;
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException("Unexpected exception while creating Fault document", e);
    }
}

public static <T extends XmlObject> SOAPMessage newSoapMessage(T soapBody) {
    try {
        MessageFactory mf = MessageFactory.newInstance();
        SOAPMessage message = mf.createMessage();
        SOAPBody respBody = message.getSOAPBody();

        if (soapBody != null) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            respBody.addDocument(factory.newDocumentBuilder().parse(soapBody.newInputStream()));
            message.saveChanges();
        }

        return message;
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new IllegalStateException("Unexpected exception while creating SOAP message", e);
    }
}

I am calling the getMessage() function to get the document but it fails with the following stacktrace

Exception in thread "main" java.lang.IllegalArgumentException: local part cannot be "null" when creating a QName
    at javax.xml.namespace.QName.<init>(QName.java:244)
    at javax.xml.namespace.QName.<init>(QName.java:188)
    at com.sun.xml.messaging.saaj.soap.impl.ElementImpl.<init>(ElementImpl.java:156)
    at com.sun.xml.messaging.saaj.soap.impl.ElementFactory.createElement(ElementFactory.java:119)
    at com.sun.xml.messaging.saaj.soap.SOAPDocumentImpl.registerChildNodes(SOAPDocumentImpl.java:230)
    at com.sun.xml.messaging.saaj.soap.SOAPDocumentImpl.registerChildNodes(SOAPDocumentImpl.java:251)
    at com.sun.xml.messaging.saaj.soap.SOAPDocumentImpl.registerChildNodes(SOAPDocumentImpl.java:251)
    at com.sun.xml.messaging.saaj.soap.SOAPDocumentImpl.importNode(SOAPDocumentImpl.java:217)
    at com.sun.xml.messaging.saaj.soap.impl.BodyImpl.addDocument(BodyImpl.java:259)
    at com.example.demo.Demo1Application.getMessage(Demo1Application.java:29)
    at com.example.demo.Demo1Application.main(Demo1Application.java:23)

Process finished with exit code 1

I tried figuring out how the local part is to be set in QName but couldn't figure out where and how it is to be done. Any help will be highly appreciated.


来源: stackexchange

问:
How to write in GCS using spark java in dataproc?
I am trying to use GCP to run spark application, i am using dataproc to trigger application and want to write output in Google Cloud Storage for this i have GCS connector added in my pom.xml

```<code> <!-- https://mvnrepository.com/artifact/com.google.cloud.bigdataoss/gcs-connector -->
    <dependency>
        <groupId>com.google.cloud.bigdataoss</groupId>
        <artifactId>gcs-connector</artifactId>
        <version>hadoop3-2.2.4</version>
    </dependency>
</code>```

It help's me to read CSV from GCS but when i try to write result in GCS it throws a very annoying error:

```<code>Exception in thread "main" java.lang.IllegalArgumentException: Pathname /user/root/gs/2022-12-27 12:08:48 from hdfs://dm-service-metanome-m/user/root/gs/2022-12-27 12:08:48 is not a valid DFS filename.
</code>```

Can anyone help me ?

i use the following code to write output in GCS.

```<code>javaRDDString.coalesce(1).saveAsTextFile(location+"/"+(DATE_FORMAT.format(new Date(System.currentTimeMillis())).toString()));
</code>```

Thanks in Advance :)

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use GCP to run spark application, i am using dataproc to trigger application and want to write output in Google Cloud Storage for this i have GCS connector added in my pom.xml

    <dependency>
        <groupId>com.google.cloud.bigdataoss</groupId>
        <artifactId>gcs-connector</artifactId>
        <version>hadoop3-2.2.4</version>
    </dependency>

It help's me to read CSV from GCS but when i try to write result in GCS it throws a very annoying error:

Exception in thread "main" java.lang.IllegalArgumentException: Pathname /user/root/gs/2022-12-27 12:08:48 from hdfs://dm-service-metanome-m/user/root/gs/2022-12-27 12:08:48 is not a valid DFS filename.

Can anyone help me ?

i use the following code to write output in GCS.

javaRDDString.coalesce(1).saveAsTextFile(location+"/"+(DATE_FORMAT.format(new Date(System.currentTimeMillis())).toString()));

Thanks in Advance :)


问:
Invalid attempt to call Read when reader is closed
I tried every way but not fixed. I am using ASP.NET Core MVC and DevExpress.

I try to get value into DataTable and insert List<DataRow>, and these datarows to IEnumerable and pass and show to a report in view

```<code>DataTable table = new DataTable();
List<DataRow> rows = new List<DataRow>();

try
{
    SqlBaglantisi.Db2ConnectionOpen();

    OleDbCommand odbcmd = new OleDbCommand();
    odbcmd.CommandText = db2Get;
    odbcmd.CommandTimeout = 700000;
    odbcmd.CommandType = CommandType.Text;
    odbcmd.Connection = SqlBaglantisi.db2connection;

    OleDbDataReader oleDr = odbcmd.ExecuteReader();

    while (oleDr.Read())
    {
        table.Load(oleDr);
    }
    oleDr.Close();

    SqlBaglantisi.Db2ConnectionClose();

    foreach(DataRow dr in table.Rows)
    {
        rows.Add(dr);
    }
    return rows;
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
    return rows;
}
</code>```

AND

```<code>public object GetSelectedValue(DataSourceLoadOptions loadOptions)
{
    IEnumerable<DataRow> reqModel = SqlDataProcess.GetDepo();
    return DataSourceLoader.Load(reqModel, loadOptions);
}
</code>```

Search every solution every web site but not working, not fixed.

IF YOU HAVE ANOTHER ANSWER OR ANOTHER TYPE, ANOTHER WAY, PLEASE WRITE PLEASEEE!!!!!

Body:
I tried every way but not fixed. I am using ASP.NET Core MVC and DevExpress.

I try to get value into DataTable and insert List<DataRow>, and these datarows to IEnumerable and pass and show to a report in view

DataTable table = new DataTable();
List<DataRow> rows = new List<DataRow>();

try
{
    SqlBaglantisi.Db2ConnectionOpen();

    OleDbCommand odbcmd = new OleDbCommand();
    odbcmd.CommandText = db2Get;
    odbcmd.CommandTimeout = 700000;
    odbcmd.CommandType = CommandType.Text;
    odbcmd.Connection = SqlBaglantisi.db2connection;

    OleDbDataReader oleDr = odbcmd.ExecuteReader();

    while (oleDr.Read())
    {
        table.Load(oleDr);
    }
    oleDr.Close();

    SqlBaglantisi.Db2ConnectionClose();

    foreach(DataRow dr in table.Rows)
    {
        rows.Add(dr);
    }
    return rows;
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
    return rows;
}

AND

public object GetSelectedValue(DataSourceLoadOptions loadOptions)
{
    IEnumerable<DataRow> reqModel = SqlDataProcess.GetDepo();
    return DataSourceLoader.Load(reqModel, loadOptions);
}

Search every solution every web site but not working, not fixed.

IF YOU HAVE ANOTHER ANSWER OR ANOTHER TYPE, ANOTHER WAY, PLEASE WRITE PLEASEEE!!!!!


问:
Clicking an item in listview of home screen widget not working
I have a few items in the list view of my home screen widget. I want to find the id of the item which is being clicked. Hence I am trying pass a value in the intent and trying to retrieve that value where the click is received. But I am not able to access the value which was being passed. My code:

```<code>class WidgetProvider : HomeWidgetProvider() {

    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray,
        widgetData: SharedPreferences
    ) {
        Log.d("debugging", "widget loaded")

        appWidgetIds.forEach { widgetId ->
            val views = RemoteViews(context.packageName, R.layout.widget_layout).apply {

                val todosRemoteView = RemoteViews.RemoteCollectionItems.Builder()

                val view = RemoteViews(context.packageName, R.layout.each_todo).apply {
                    setTextViewText(R.id.each_todo_container_text, "test")
                    setCompoundButtonChecked(R.id.each_todo_container_checkbox, false)

                    val fillInIntent = Intent().apply {
                        Bundle().also { extras ->
                            extras.putInt("taskId", 4242)
                            putExtras(extras)
                        }
                    }
                    setOnCheckedChangeResponse(
                        R.id.each_todo_container_checkbox,
                        RemoteViews.RemoteResponse.fromFillInIntent(fillInIntent)
                    )
                    setOnClickFillInIntent(R.id.each_todo_container_text, fillInIntent)
                }

                todosRemoteView.addItem(69696969, view)
                setRemoteAdapter(
                    R.id.todos_list,
                    todosRemoteView
                        .build()
                )

                val pendingIntentx: PendingIntent = Intent(
                    context,
                    WidgetProvider::class.java
                ).run {
                    PendingIntent.getBroadcast(context, 0, this, PendingIntent.FLAG_IMMUTABLE)
                }
                setPendingIntentTemplate(R.id.todos_list, pendingIntentx)
            }

            appWidgetManager.updateAppWidget(widgetId, views)
        }

    }

    override fun onReceive(context: Context?, intent: Intent?) {
        val viewIndex: Int = intent!!.getIntExtra(
            "taskId",
            0
        )//i am expecting 4242 but 0(the default value) is getting received here
        Log.d("debugging", "an item is clicked $viewIndex")
        super.onReceive(context, intent)
    }

}
</code>```

These are the docs I referred to using remote collections and enabling click functionality for remote collections

Body:
I have a few items in the list view of my home screen widget. I want to find the id of the item which is being clicked. Hence I am trying pass a value in the intent and trying to retrieve that value where the click is received. But I am not able to access the value which was being passed. My code:

class WidgetProvider : HomeWidgetProvider() {

    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray,
        widgetData: SharedPreferences
    ) {
        Log.d("debugging", "widget loaded")

        appWidgetIds.forEach { widgetId ->
            val views = RemoteViews(context.packageName, R.layout.widget_layout).apply {

                val todosRemoteView = RemoteViews.RemoteCollectionItems.Builder()

                val view = RemoteViews(context.packageName, R.layout.each_todo).apply {
                    setTextViewText(R.id.each_todo_container_text, "test")
                    setCompoundButtonChecked(R.id.each_todo_container_checkbox, false)

                    val fillInIntent = Intent().apply {
                        Bundle().also { extras ->
                            extras.putInt("taskId", 4242)
                            putExtras(extras)
                        }
                    }
                    setOnCheckedChangeResponse(
                        R.id.each_todo_container_checkbox,
                        RemoteViews.RemoteResponse.fromFillInIntent(fillInIntent)
                    )
                    setOnClickFillInIntent(R.id.each_todo_container_text, fillInIntent)
                }

                todosRemoteView.addItem(69696969, view)
                setRemoteAdapter(
                    R.id.todos_list,
                    todosRemoteView
                        .build()
                )

                val pendingIntentx: PendingIntent = Intent(
                    context,
                    WidgetProvider::class.java
                ).run {
                    PendingIntent.getBroadcast(context, 0, this, PendingIntent.FLAG_IMMUTABLE)
                }
                setPendingIntentTemplate(R.id.todos_list, pendingIntentx)
            }

            appWidgetManager.updateAppWidget(widgetId, views)
        }

    }

    override fun onReceive(context: Context?, intent: Intent?) {
        val viewIndex: Int = intent!!.getIntExtra(
            "taskId",
            0
        )//i am expecting 4242 but 0(the default value) is getting received here
        Log.d("debugging", "an item is clicked $viewIndex")
        super.onReceive(context, intent)
    }

}

These are the docs I referred to using remote collections and enabling click functionality for remote collections


问:
Monitoring using Prometheus alert
I am very new at Prometheus and I need to How create an alert when Http code status !=200 using Prometheus ?

Please I need help and thanks

Title: Monitoring using Prometheus alert


问:
How to set custom assembly attributes dynamically in C#
As the title says, i am looking for an API (preferably .NET Core or Roslyn) that lets me set CustomAttributes on a dynamically created Assembly. Since AssemblyBuilder no longer lets you save an Assembly to file, i moved to Roslyn for the generation, that's why i need another way to set those attributes.

In .NET Framework, the equivalent to this was the AssemblyBuilder.SetCustomAttribute() method.

In addtition, i am also looking for a way to replace the .NET Framework method AssemblyBuilder.DefineVersionInfoResource().

ab.SetCustomAttribute(
  new CustomAttributeBuilder(
    typeof(AssemblyTitleAttribute).GetConstructor(new[] { typeof(string) }), new object[] { assemblyName.Name.Trim() }));
```


问:
Change event not triggering when calling matslider toggle function in unit test cases
I have a matslider toggle in my page and onload since its checked and giving true value. But when I change toggle it should call a method and then give false value. In my test case its calling method but giving only true value for toggle. Its not rendering false after calling the function.

html

```<code><mat-slide-toggle class="toggles" [checked]="true" (change)="OnToggle($event)">Toggle</mat-slide-toggle>
</code>```

ts

```<code>@Input() currtoggleval=true;
@Output() togglechange=new EventEmitter<boolean>();

ngAfterViewInit():void {
this.togglechange.emit(this.currtoggleval);
}

public OnToggle(event): any {
this.currtoggleval=event.checked;
this.togglechange.emit(this.currtoggleval)
}
</code>```

test cases

```<code>it('Should call ontoggle ', async () => {

const slider = fixture.debugElement.query(By.css('.toggles'));
spyOn(component, 'onToggle');
slider.triggerEventHandler('change', null);
expect(component.onToggle).toHaveBeenCalled();
expect(component.currtoggleval).toBe(false);

});
</code>```

Body:
I have a matslider toggle in my page and onload since its checked and giving true value. But when I change toggle it should call a method and then give false value. In my test case its calling method but giving only true value for toggle. Its not rendering false after calling the function.

html

<mat-slide-toggle class="toggles" [checked]="true" (change)="OnToggle($event)">Toggle</mat-slide-toggle>

ts

@Input() currtoggleval=true;
@Output() togglechange=new EventEmitter<boolean>();

ngAfterViewInit():void {
this.togglechange.emit(this.currtoggleval);
}

public OnToggle(event): any {
this.currtoggleval=event.checked;
this.togglechange.emit(this.currtoggleval)
}

test cases

it('Should call ontoggle ', async () => {

const slider = fixture.debugElement.query(By.css('.toggles'));
spyOn(component, 'onToggle');
slider.triggerEventHandler('change', null);
expect(component.onToggle).toHaveBeenCalled();
expect(component.currtoggleval).toBe(false);

});


问:
react natvie not redirecting when axios is success
i am doing a axios post request the api call is sucess but the issue here is that i have to click on the sceen of emulator for the    props.navigation.navigate('Home_scrren', {data: Data56});  to redirect to the next screen i dont know why this is happening

```<code> axios({
     method: 'POST',
     url: 'http://127.0.0.1:8000/api/register',
     data: Data56,
   })
  .then(res => {
       if (res.status == 200) {
         props.navigation.navigate('Home_scrren', {data: Data56});
       }
     })
     .catch(error => {
       alert(JSON.stringify(error));
     });
 }
</code>```

Body:
i am doing a axios post request the api call is sucess but the issue here is that i have to click on the sceen of emulator for the    props.navigation.navigate('Home_scrren', {data: Data56});  to redirect to the next screen i dont know why this is happening

 axios({
     method: 'POST',
     url: 'http://127.0.0.1:8000/api/register',
     data: Data56,
   })
  .then(res => {
       if (res.status == 200) {
         props.navigation.navigate('Home_scrren', {data: Data56});
       }
     })
     .catch(error => {
       alert(JSON.stringify(error));
     });
 }


问:
Count Distinct is counting all instances
Hi I have a field called Document.id I am trying to count distinct occurrences of this by grouping another field. It is counting all occurrences against the all the group.

Document.id
Orgdoctype.id

10
1234

6
7876

SELECT `OrderDocumentType`.`orderId` AS `orderId`
    , `OrderDocumentType`.`status` AS `status`
    , `Orgdocumenttype`.`name` AS `Orgdocumenttype__name`
    , `Orgdocumenttype`.`needsApproval` AS `Orgdocumenttype__needsApproval`
    , `Order`.`status` AS `Order__status`
    , Group_concat(`Annotation`.`text`) AS `Annotation__text`
    , Count (distinct `Document`.`id`)
    , `Orgdocumenttype`.`id`
FROM `OrderDocumentType`
    LEFT JOIN `OrgDocumentType` AS `Orgdocumenttype` ON `OrderDocumentType`.`orgDocumentTypeId` = `Orgdocumenttype`.`id`
    LEFT JOIN `Order` AS `Order` ON `OrderDocumentType`.`orderId` = `Order`.`id`
    LEFT JOIN `Document` AS `Document` ON `Orgdocumenttype`.`id`= `Document`.`orgDocumentTypeId`
    LEFT JOIN `DocumentImage` AS `Documentimage` ON `Document`.`id` = `Documentimage`.`documentId`
    LEFT JOIN `Annotation` AS `Annotation` ON `Documentimage`.`id` = `Annotation`.`documentImageId`
WHERE `OrderDocumentType`.`orgId` = 2556
    AND (`Order`.`status` <> 'CANCELLED_BY_HAVEN' OR `Order`.`status` IS NULL)
    AND (`Order`.`status` <> 'CANCELLATION_REQUESTED_BY_SHIPPER' OR `Order`.`status` IS NULL)
    AND (`Order`.`status` <> 'CANCELLED_BY_PROVIDER' OR `Order`.`status` IS NULL)
    AND (`Order`.`status` <> 'CANCELLED_BY_SHIPPER' OR `Order`.`status` IS NULL)
    AND (`Order`.`status` <> 'EXPIRED' OR `Order`.`status` IS NULL)
    AND `Orgdocumenttype`.`needsApproval` = TRUE
    AND `OrderDocumentType`.`orderId` = 474019
GROUP BY `Orgdocumenttype`.`id`
```
<p>I have tried different <code>GROUP BY</code>'s but it then shows all rows.</p>
<p>Sorry here is update I can't attach but above is the current code and below tables show what is happening and also what should happen.</p>
<p>I used below code to get what should happen</p>
<pre class="lang-sql prettyprint-override"><code>SELECT `Document`.`orgDocumentTypeId` AS `orgDocumentTypeId`
    , `Orgdocumenttype`.`name` AS `Orgdocumenttype__name`
    , Count (distinct `Document`.`id`) AS `count`
FROM `Document`
    LEFT JOIN `OrgDocumentType` AS `Orgdocumenttype` ON `Document`.`OrgdocumentTypeId` = `Orgdocumenttype`.`id`
WHERE `Document`.`orderId` = 474019
GROUP BY `Document`.`orgDocumentTypeId`
    , `Orgdocumenttype`.`name`
ORDER BY `Document`.`orgDocumentTypeId` ASC
    , `Orgdocumenttype`.`name` ASC
</code>```

current

Orgdoctype__name
Count `Document`.`id`
orgDocTypeId

Bill of Lading
10
2720

PL-Packing List
6
2841

Certificate of Origin
8
2863

Commercial Invoice
6
2864

What I get with the other code and what I need

Orgdoctype__name
Count `Document`.`id`
orgDocTypeId

Bill of Lading
3
2720

PL-Packing List
3
2841

Certificate of Origin
1
2863

Commercial Invoice
2
2864

Booking Confirmation
1
2742

Body:
Hi I have a field called Document.id I am trying to count distinct occurrences of this by grouping another field. It is counting all occurrences against the all the group.

Document.id
Orgdoctype.id

10
1234

6
7876

SELECT `OrderDocumentType`.`orderId` AS `orderId`
    , `OrderDocumentType`.`status` AS `status`
    , `Orgdocumenttype`.`name` AS `Orgdocumenttype__name`
    , `Orgdocumenttype`.`needsApproval` AS `Orgdocumenttype__needsApproval`
    , `Order`.`status` AS `Order__status`
    , Group_concat(`Annotation`.`text`) AS `Annotation__text`
    , Count (distinct `Document`.`id`)
    , `Orgdocumenttype`.`id`
FROM `OrderDocumentType`
    LEFT JOIN `OrgDocumentType` AS `Orgdocumenttype` ON `OrderDocumentType`.`orgDocumentTypeId` = `Orgdocumenttype`.`id`
    LEFT JOIN `Order` AS `Order` ON `OrderDocumentType`.`orderId` = `Order`.`id`
    LEFT JOIN `Document` AS `Document` ON `Orgdocumenttype`.`id`= `Document`.`orgDocumentTypeId`
    LEFT JOIN `DocumentImage` AS `Documentimage` ON `Document`.`id` = `Documentimage`.`documentId`
    LEFT JOIN `Annotation` AS `Annotation` ON `Documentimage`.`id` = `Annotation`.`documentImageId`
WHERE `OrderDocumentType`.`orgId` = 2556
    AND (`Order`.`status` <> 'CANCELLED_BY_HAVEN' OR `Order`.`status` IS NULL)
    AND (`Order`.`status` <> 'CANCELLATION_REQUESTED_BY_SHIPPER' OR `Order`.`status` IS NULL)
    AND (`Order`.`status` <> 'CANCELLED_BY_PROVIDER' OR `Order`.`status` IS NULL)
    AND (`Order`.`status` <> 'CANCELLED_BY_SHIPPER' OR `Order`.`status` IS NULL)
    AND (`Order`.`status` <> 'EXPIRED' OR `Order`.`status` IS NULL)
    AND `Orgdocumenttype`.`needsApproval` = TRUE
    AND `OrderDocumentType`.`orderId` = 474019
GROUP BY `Orgdocumenttype`.`id`

I have tried different GROUP BY's but it then shows all rows.

Sorry here is update I can't attach but above is the current code and below tables show what is happening and also what should happen.

I used below code to get what should happen

SELECT `Document`.`orgDocumentTypeId` AS `orgDocumentTypeId`
    , `Orgdocumenttype`.`name` AS `Orgdocumenttype__name`
    , Count (distinct `Document`.`id`) AS `count`
FROM `Document`
    LEFT JOIN `OrgDocumentType` AS `Orgdocumenttype` ON `Document`.`OrgdocumentTypeId` = `Orgdocumenttype`.`id`
WHERE `Document`.`orderId` = 474019
GROUP BY `Document`.`orgDocumentTypeId`
    , `Orgdocumenttype`.`name`
ORDER BY `Document`.`orgDocumentTypeId` ASC
    , `Orgdocumenttype`.`name` ASC

current

Orgdoctype__name
Count `Document`.`id`
orgDocTypeId

Bill of Lading
10
2720

PL-Packing List
6
2841

Certificate of Origin
8
2863

Commercial Invoice
6
2864

What I get with the other code and what I need

Orgdoctype__name
Count `Document`.`id`
orgDocTypeId

Bill of Lading
3
2720

PL-Packing List
3
2841

Certificate of Origin
1
2863

Commercial Invoice
2
2864

Booking Confirmation
1
2742


问:
how to override security-constraints in web.xml for jsp servlet web application java
I have an already running web application in jsp/servlet where its security constraints are written in web.xml descriptor file. The application works based on Forms authentication.
Now, i would like to introduce another login option on the home page of application to do the auth using Azure AD. I am getting successful redirection in application after getting authenticated from Azure AD but the issue i am facing is, that after the redirection the redirected url to the dashboard landing page (which comes after login) is not included in the exclusion list of the web.xml so even after successful auth from Azure i am going back to login.jsp (login page)
So the idea is i would like to keep forms authentication and Azure AD auth both on the same page with two seperate buttons but since forms auth validates each redirection in security-constraints inclusion and if the url matches with the inclusion list urls then i will go back to login page as if i am not authenticated.
Just a thought, if there is a way to have the redirect urls in the exclusion at the runtime means, if i can disable forms auth when i come from Azure AD redirection may be using some filters or something..
Please help with some directions here</p>


问:
How to disable all images from isotope gallery on page reload
if page is reloaded then all images are displayed and then after clicking other categories and then click on first category then that category images are shown.</p>


问:
How to continue TensorBoardLogger from previous works
I am training my model with percent of data with percent of epoch for example I divide 10000 data in 5 folders with sizes of 2000 data and I divided 100 epoch in 10 epoch for each 2000 data for example in the first session I run model with 2000 data and 10 epoch and the next step I run saved model(with load_from_checkpoint) with other 2000 data in 10 epoch.....

my source for checkpoint and tensorboard_logger and trainer isin below.

```<code>checkpoint_callback=ModelCheckpoint(dirpath="model",filename="newmodel_2",save_last=True,verbose=True,monitor="val_ce_loss",mode="min")
logger=TensorBoardLogger("training-logs",name="test_2")
    trainer = pl.Trainer(
        callbacks=[checkpoint_callback],
        max_epochs=N_EPOCHS,
        gpus=1,
        max_steps = max_steps,
        logger=logger,
    )
</code>```

And my source code for run is

```<code>base_path_ckpt = '/home/tt/model/last.ckpt'
config_model= model(config, max_steps= max_steps)
model_with_previous = config_model.load_from_checkpoint(base_path_ckpt)
trainer.fit(model_with_previous , datamodule)
</code>```

My question is ,I know how to continue my training model with .load_from_checkpoint but How can I continue showing training_logs with tensorboard?(because when I run again my model for next 10 epoch and 2000 next data I can't see any previous tensorboard_logs)

Body:
I am training my model with percent of data with percent of epoch for example I divide 10000 data in 5 folders with sizes of 2000 data and I divided 100 epoch in 10 epoch for each 2000 data for example in the first session I run model with 2000 data and 10 epoch and the next step I run saved model(with load_from_checkpoint) with other 2000 data in 10 epoch.....

my source for checkpoint and tensorboard_logger and trainer isin below.

checkpoint_callback=ModelCheckpoint(dirpath="model",filename="newmodel_2",save_last=True,verbose=True,monitor="val_ce_loss",mode="min")
logger=TensorBoardLogger("training-logs",name="test_2")
    trainer = pl.Trainer(
        callbacks=[checkpoint_callback],
        max_epochs=N_EPOCHS,
        gpus=1,
        max_steps = max_steps,
        logger=logger,
    )

And my source code for run is

base_path_ckpt = '/home/tt/model/last.ckpt'
config_model= model(config, max_steps= max_steps)
model_with_previous = config_model.load_from_checkpoint(base_path_ckpt)
trainer.fit(model_with_previous , datamodule)

My question is ,I know how to continue my training model with .load_from_checkpoint but How can I continue showing training_logs with tensorboard?(because when I run again my model for next 10 epoch and 2000 next data I can't see any previous tensorboard_logs)


问:
Cannot open ASCII filename aarch64 assembly mach-o
I am trying to open a file in aarch64 assembly on an M1 mac. I am able to open the file if I define a short name in the ASCII format, but for longer filenames, I need to define the string as .string. Why is this and is it possible to open a longer ASCII-filename?

Works: FILENAME: .ascii "day2.in"

Works: FILENAME: .string "day25.in"

Does not work: FILENAME: .ascii "day25.in"

```<code>.globl _start
.align 2

_start:
    adr x0, FILENAME
    mov x1, 0
    mov x2, 0
    mov x16, 5
    svc 0x80

    mov x16, 1
    svc 0x80
</code>```

I am able to write the text out to STDOUT for all three cases with:

```<code>    mov x0, 1
    adr x1, FILENAME
    mov x2, 8
    mov x16, 4
    svc 0x80
</code>```

Body:
I am trying to open a file in aarch64 assembly on an M1 mac. I am able to open the file if I define a short name in the ASCII format, but for longer filenames, I need to define the string as .string. Why is this and is it possible to open a longer ASCII-filename?

Works: FILENAME: .ascii "day2.in"

Works: FILENAME: .string "day25.in"

Does not work: FILENAME: .ascii "day25.in"

.globl _start
.align 2

_start:
    adr x0, FILENAME
    mov x1, 0
    mov x2, 0
    mov x16, 5
    svc 0x80

    mov x16, 1
    svc 0x80

I am able to write the text out to STDOUT for all three cases with:

    mov x0, 1
    adr x1, FILENAME
    mov x2, 8
    mov x16, 4
    svc 0x80


问:
Dask and PyInstaller not working after exe creation
dask_runner.py

import dask

in dask.spec file:

 hiddenimports=['dask','distributed'],

hooks file:

```<code>from PyInstaller.utils.hooks import collect_submodules
from PyInstaller.utils.hooks import get_package_paths

datas = [(get_package_paths('dask')[1],"dask"), (get_package_paths('distributed')[1],"distributed")]
</code>```

I have included dask.yaml, distributed.yaml so I dont see errors regarding that.
But when I try to run dask.exe no output is seen

I am using:
python3.8
pyinstaller==4.7

Body:
dask_runner.py

import dask

in dask.spec file:

 hiddenimports=['dask','distributed'],

hooks file:

from PyInstaller.utils.hooks import collect_submodules
from PyInstaller.utils.hooks import get_package_paths

datas = [(get_package_paths('dask')[1],"dask"), (get_package_paths('distributed')[1],"distributed")]

I have included dask.yaml, distributed.yaml so I dont see errors regarding that.
But when I try to run dask.exe no output is seen

I am using:
python3.8
pyinstaller==4.7


问:
Adding Search Bar to find the required variable's plot in Plotly
I want to add search bar for this graph,I am dealing with datasets having 50-500 Variables

```<code>from plotly import animation
data1=go.Bar(x=vas,y=nan,name='Non-Null%',text=nan,textposition='outside',texttemplate='%{text:.3}',marker=dict(color='#00ADB5'))
data2=go.Bar(x=vas,y=na,name=' Null%',text=na,textposition='inside',texttemplate='%{text:.3}',marker=dict(color='#393E46'))
data=[data1,data2]
layout=go.Layout(title="Nulls and Non-Nulls",barmode='stack')
fig=go.Figure(data=data,layout=layout)
fig.update_layout(showlegend=True,
                    plot_bgcolor='#EAFDFC',
                    font=dict(family='Arial', size=12,
                              color='black'),title=dict(font=dict(family='Arial',
                                       size=18,
                                       color='black'),x=0.5,y=0.9,xanchor='center',
                             yanchor='top'))
#drop-down for bar and scatter plot
fig.update_layout(
    updatemenus=[
        dict(
            buttons=list([
                dict(
                    args=["type", "scatter"],
                    label="Scatter Plot",
                    method="restyle"
                ),
                dict(
                    args=["type", "bar"],
                    label="Bar Chart",
                    method="restyle"
                )
            ]),
            direction="down",
        ),
    ]
)
#slider
fig.update_layout(
    xaxis=dict(
        rangeselector=dict(
            buttons=list([
                dict(count=1,
                     step="day",
                     stepmode="backward"),
            ])
        ),
        rangeslider=dict(
            visible=True
        ),
    )
)
</code>```

I tried with slider but its cumbersome to slider over 500 variables.If it is possible to add search bar,please help me out.TIA

Body:
I want to add search bar for this graph,I am dealing with datasets having 50-500 Variables

from plotly import animation
data1=go.Bar(x=vas,y=nan,name='Non-Null%',text=nan,textposition='outside',texttemplate='%{text:.3}',marker=dict(color='#00ADB5'))
data2=go.Bar(x=vas,y=na,name=' Null%',text=na,textposition='inside',texttemplate='%{text:.3}',marker=dict(color='#393E46'))
data=[data1,data2]
layout=go.Layout(title="Nulls and Non-Nulls",barmode='stack')
fig=go.Figure(data=data,layout=layout)
fig.update_layout(showlegend=True,
                    plot_bgcolor='#EAFDFC',
                    font=dict(family='Arial', size=12,
                              color='black'),title=dict(font=dict(family='Arial',
                                       size=18,
                                       color='black'),x=0.5,y=0.9,xanchor='center',
                             yanchor='top'))
#drop-down for bar and scatter plot
fig.update_layout(
    updatemenus=[
        dict(
            buttons=list([
                dict(
                    args=["type", "scatter"],
                    label="Scatter Plot",
                    method="restyle"
                ),
                dict(
                    args=["type", "bar"],
                    label="Bar Chart",
                    method="restyle"
                )
            ]),
            direction="down",
        ),
    ]
)
#slider
fig.update_layout(
    xaxis=dict(
        rangeselector=dict(
            buttons=list([
                dict(count=1,
                     step="day",
                     stepmode="backward"),
            ])
        ),
        rangeslider=dict(
            visible=True
        ),
    )
)

I tried with slider but its cumbersome to slider over 500 variables.If it is possible to add search bar,please help me out.TIA


问:
Number Pattern & Number Detection in Python
Suppose the below dataset is given

1,5,7,20,43

2,7,8,11,14,15,20,43

1,5,6,9,15,21,22,25,28,29,43,45

3,5,8,15,21,25,26,35,40,43,46,47,48,49

2,5,8,12,20,28,30,33,38,43,48,50,51,55,58,59

Also, number 43 is given as a “main” number

Now I have to predict the number pattern and also find the relationship in between that “main” number (e.g., 43) and rest of the number in that number series, so that in future any similar dataset has given then I have to recognize the “main” number in that dataset. What is the best way to do this using Python?


问:
Is it possible to create Discord scheduled events with a Webhook?
Is it possible to create Discord scheduled events with a Webhook or is there a need of an bot available in this Server?

If searched but found only an API doc to create those Events with an bot.

I would love to use this on firebase cloud functions without an auth flow.


问:
Scala object mapper exception while creating delta sharing rest client in Java
I am trying to create a delta sharing rest client which is accessing shares located in azure blob storage. It's throwing this exception : java.lang.NoClassDefFoundError: com/fasterxml/jackson/module/scala/ScalaObjectMapper

Below is my client code
`

```<code>String profileFile = "./profile.share";
Configuration config = new Configuration();
config.set("fs.AbstractFileSystem.wasb.Impl", "org.apache.hadoop.fs.azure.Wasb");
config.set("fs.azure.block.blob.with.compaction.dir", "/hbase/WALs,/data/myblobfiles");
config.set("fs.azure", "org.apache.hadoop.fs.azure.NativeAzureFileSystem");
config.set("fs.azure.enable.append.support", "true");
DeltaSharingProfileProvider profileProvider = new DeltaSharingFileProfileProvider(config, profileFile);
DeltaSharingClient restClient = new DeltaSharingRestClient(profileProvider, 40, 5, true, false);
restClient.listAllTables();
</code>```

`

I have placed my account name and account key in the config as well (removed here). Have added all these dependencies in my gradle build

```<code>implementation 'org.projectlombok:lombok:1.18.22'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
implementation"org.springframework.boot:spring-boot-starter:2.3.1.RELEASE"
implementation"org.springframework.boot:spring-boot-devtools:2.3.1.RELEASE"
implementation"org.springframework.boot:spring-boot-starter-test:2.3.1.RELEASE"
implementation"org.springframework.boot:spring-boot-starter-web:2.3.1.RELEASE"
implementation("io.delta:delta-standalone_2.12:0.6.0")
implementation("org.apache.hadoop:hadoop-client:3.3.1")
implementation("org.apache.parquet:parquet-hadoop:1.10.1")
implementation("io.delta:delta-sharing-spark_2.12:0.6.0")
implementation 'io.delta:delta-core_2.12:2.1.0'
</code>```

Can anyone please help with this?

Body:
I am trying to create a delta sharing rest client which is accessing shares located in azure blob storage. It's throwing this exception : java.lang.NoClassDefFoundError: com/fasterxml/jackson/module/scala/ScalaObjectMapper

Below is my client code
`

String profileFile = "./profile.share";
Configuration config = new Configuration();
config.set("fs.AbstractFileSystem.wasb.Impl", "org.apache.hadoop.fs.azure.Wasb");
config.set("fs.azure.block.blob.with.compaction.dir", "/hbase/WALs,/data/myblobfiles");
config.set("fs.azure", "org.apache.hadoop.fs.azure.NativeAzureFileSystem");
config.set("fs.azure.enable.append.support", "true");
DeltaSharingProfileProvider profileProvider = new DeltaSharingFileProfileProvider(config, profileFile);
DeltaSharingClient restClient = new DeltaSharingRestClient(profileProvider, 40, 5, true, false);
restClient.listAllTables();

`

I have placed my account name and account key in the config as well (removed here). Have added all these dependencies in my gradle build

implementation 'org.projectlombok:lombok:1.18.22'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
implementation"org.springframework.boot:spring-boot-starter:2.3.1.RELEASE"
implementation"org.springframework.boot:spring-boot-devtools:2.3.1.RELEASE"
implementation"org.springframework.boot:spring-boot-starter-test:2.3.1.RELEASE"
implementation"org.springframework.boot:spring-boot-starter-web:2.3.1.RELEASE"
implementation("io.delta:delta-standalone_2.12:0.6.0")
implementation("org.apache.hadoop:hadoop-client:3.3.1")
implementation("org.apache.parquet:parquet-hadoop:1.10.1")
implementation("io.delta:delta-sharing-spark_2.12:0.6.0")
implementation 'io.delta:delta-core_2.12:2.1.0'

Can anyone please help with this?


问:
Airship Block Notification on A Page
So, we're building a chat functionality in our react-native app. What we want to achieve, is to block notification when the app is in foreground and the chat page is open. We can't seem to find anything that we can use for this.

We're using the following sdk for our app : https://github.com/urbanairship/react-native-module

We've tried the PushReceived event listener like this :

```<code>UrbanAirship.addListener(EventType.PushReceived, event => {
     setTimeout(() => {
        console.log('push received', JSON.stringify(event));
     }, 2000);
});

</code>```

But the console.log seems to trigger after the notification was shown, instead of showing the notification after the delayed console.log. Is there something that we're missing or is blocking notification by shown page is just not possible with Airship?

Title: Airship Block Notification on A Page

Body:
So, we're building a chat functionality in our react-native app. What we want to achieve, is to block notification when the app is in foreground and the chat page is open. We can't seem to find anything that we can use for this.

We're using the following sdk for our app : https://github.com/urbanairship/react-native-module

We've tried the PushReceived event listener like this :

UrbanAirship.addListener(EventType.PushReceived, event => {
     setTimeout(() => {
        console.log('push received', JSON.stringify(event));
     }, 2000);
});

But the console.log seems to trigger after the notification was shown, instead of showing the notification after the delayed console.log. Is there something that we're missing or is blocking notification by shown page is just not possible with Airship?


问:
Converting to desired format in json file
I'm quite new to coding and recently I'm doing a tinder project splitting both male and female data, with Python pandas.

enter image description here

This is my code in splitting both female and male.

```<code>outputJSON = pd.read_json('output.json')
temp_male = []
temp_female = []
for x in range (len(outputJSON)):
    if outputJSON['user'][x]['gender'] == 'M':
        temp_male.append(outputJSON.loc[x])
    else:
        temp_female.append(outputJSON.loc[x])
temp_male
</code>```

The outcome data :
enter image description here

and later on i convert them to dataframe and then to separate json file

```<code>
temp_male = pd.DataFrame(temp_male_df)
temp_male
temp_male = temp_male.to_json('male.json')
male = pd.read_json('male.json')
male
</code>```

However, the structure of 'male.json' is not what I expected
The one Im expecting:
enter image description here
The one Im getting:
enter image description here

Basically, I expect one whole data include userID, conversations and etc from one id followed by another id, however seems like the json file display all id then only proceed to other dataset.

Will appreciate much if anyone could help me with this !!

I have mentioned above

Body:
I'm quite new to coding and recently I'm doing a tinder project splitting both male and female data, with Python pandas.

enter image description here

This is my code in splitting both female and male.

outputJSON = pd.read_json('output.json')
temp_male = []
temp_female = []
for x in range (len(outputJSON)):
    if outputJSON['user'][x]['gender'] == 'M':
        temp_male.append(outputJSON.loc[x])
    else:
        temp_female.append(outputJSON.loc[x])
temp_male

The outcome data :
enter image description here

and later on i convert them to dataframe and then to separate json file

temp_male = pd.DataFrame(temp_male_df)
temp_male
temp_male = temp_male.to_json('male.json')
male = pd.read_json('male.json')
male

However, the structure of 'male.json' is not what I expected
The one Im expecting:
enter image description here
The one Im getting:
enter image description here

Basically, I expect one whole data include userID, conversations and etc from one id followed by another id, however seems like the json file display all id then only proceed to other dataset.

Will appreciate much if anyone could help me with this !!

I have mentioned above


问:
C++ struct initialization with colon ":"
Within our team's code review I found out a strange usage of struct initialization under C++17 and I'm surprised that it works:

```<code>struct TestStruct {
  std::string test_str1;
  std::string test_str2;
  std::string test_str3;
};

TestStruct t{test_str1 : "col1", test_str3 : "col3"};
std::cout << "str1: " << t.test_str1 << "\nstr2:" << t.test_str2 << "\nstr3:" << t.test_str3;

</code>```

and here's the result as follow:

```<code>str1: col1
str2:
str3: col3
</code>```

I couldn't find references for such usage but it looks like Constructors and member initializer lists with some ellision.

Can someone explain why it works?
Thanks :)

Body:
Within our team's code review I found out a strange usage of struct initialization under C++17 and I'm surprised that it works:

struct TestStruct {
  std::string test_str1;
  std::string test_str2;
  std::string test_str3;
};

TestStruct t{test_str1 : "col1", test_str3 : "col3"};
std::cout << "str1: " << t.test_str1 << "\nstr2:" << t.test_str2 << "\nstr3:" << t.test_str3;

and here's the result as follow:

str1: col1
str2:
str3: col3

I couldn't find references for such usage but it looks like Constructors and member initializer lists with some ellision.

Can someone explain why it works?
Thanks :)


问:
Attempting to start Next using require failed. Unable to find moduble
I am attempting to combine a package called find-free-port that finds a port if 3000, 3001, 3002, etc... are taken.

When it does, it will start NextJS development, like this:

```<code>const findFreePort = require("find-free-port");

findFreePort(3000, 3005, (err, freePort) => {
  if (err) {
    console.error(err);
  } else {
    console.log(`Free port found: ${freePort}`);
    process.env.PORT = freePort;
    require("next/dist/server/next-dev").default();
  }
});

</code>```

The issue is, when I do, I get this error:

```<code>> node start-server.js

Free port found: 3001
internal/modules/cjs/loader.js:905
  throw err;
  ^

Error: Cannot find module 'next/dist/server/next-dev'
Require stack:
- C:\Users\Raddy\Desktop\LocalProjects\screenrecordme\start-server.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
    at Function.Module._load (internal/modules/cjs/loader.js:746:27)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:101:18)
</code>```

How would I make my code work?

I deleted my node_modules and .next folder and reinstalled everything

Body:
I am attempting to combine a package called find-free-port that finds a port if 3000, 3001, 3002, etc... are taken.

When it does, it will start NextJS development, like this:

const findFreePort = require("find-free-port");

findFreePort(3000, 3005, (err, freePort) => {
  if (err) {
    console.error(err);
  } else {
    console.log(`Free port found: ${freePort}`);
    process.env.PORT = freePort;
    require("next/dist/server/next-dev").default();
  }
});

The issue is, when I do, I get this error:

> node start-server.js

Free port found: 3001
internal/modules/cjs/loader.js:905
  throw err;
  ^

Error: Cannot find module 'next/dist/server/next-dev'
Require stack:
- C:\Users\Raddy\Desktop\LocalProjects\screenrecordme\start-server.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
    at Function.Module._load (internal/modules/cjs/loader.js:746:27)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:101:18)

How would I make my code work?

I deleted my node_modules and .next folder and reinstalled everything


问:
Kubectl get Object upto a limit
Is there a way in the Kubectl client to specify the number of objects we want in the get command?

Requirement: kubectl get pods --limit=100

I can work around and pipe o/p from get command as kubectl get pods --no-headers=true -o custom-columns=NAME:.metadata.name,NAMESPACE:.metadata.namespace | head -n 5 to get 5 rows.

But that will still get all items from the Kubernetes API Server.

Is there any native kubectl way to limit the number of objects retrieved from the API Server?

Title: Kubectl get Object upto a limit


问:
How to solve App Crash on StickerView on some devices?
I get many errors of this kind displayed in the firebase

```<code>Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo android.view.InflateException: Binary XML
</code>```

when using this StickerView code:

```<code><com.test.new.ExampleSticker.StickerView
    android:id="@+id/sticker_view"
    android:visibility="visible"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    app:showBorder="true"
    app:showIcons="true">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</com.test.new.ExampleSticker.StickerView>
</code>```

What might be the reason? Any help would be appreciated.

Body:
I get many errors of this kind displayed in the firebase

Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo android.view.InflateException: Binary XML

when using this StickerView code:

<com.test.new.ExampleSticker.StickerView
    android:id="@+id/sticker_view"
    android:visibility="visible"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    app:showBorder="true"
    app:showIcons="true">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</com.test.new.ExampleSticker.StickerView>

What might be the reason? Any help would be appreciated.


问:
aiohttp can't work in docker container on AWS
aiohttp works fine on local machine, but can't work when deployment in AWS cluster.

`

```<code>    async def _get_file_size(self):
        async with aiohttp.ClientSession(auth=self.auth) as client:
            async with client.get(self.asf_url) as size_session:
                self.file_size = size_session.content_length
</code>```

`
Different client object is obtained when on local machine and AWS cluster

Body:
aiohttp works fine on local machine, but can't work when deployment in AWS cluster.

`

    async def _get_file_size(self):
        async with aiohttp.ClientSession(auth=self.auth) as client:
            async with client.get(self.asf_url) as size_session:
                self.file_size = size_session.content_length

`
Different client object is obtained when on local machine and AWS cluster


问:
Can't bind to 'grid-columns' since it isn't a known property of 'grid-ui'
grid-columns is showing error in app.Customer.html and in app.CustomerComponent.ts

app.Customer.html

```<code><form [formGroup]="CustomerModel.formCustomerGroup">
Customer Code :<input formControlName="CustomerCodeControl"
[(ngModel)]="CustomerModel.CustomerCode" type=text/><br>
Customer Name :<input formControlName="CustomerNameControl"
 [(ngModel)]="CustomerModel.CustomerName" type=text/><br>
Customer Amount :<input [(ngModel)]="CustomerModel.CustomerAmount"
[ngModelOptions]="{standalone: true}"
type=text/><br>
<input [disabled]="!(CustomerModel.formCustomerGroup.valid)" (click)="Add()" type=button value="Add"/><br>
</form>
<div *ngIf="CustomerModel.formCustomerGroup.dirty"
            [hidden]="!(hasError('pattern','CustomerCodeControl'))" >Customer Code format is not proper</div><br>
<div *ngIf="CustomerModel.formCustomerGroup.dirty"
            [hidden]="!(hasError('required','CustomerCodeControl'))" >Customer Code is required</div><br>
<div *ngIf="CustomerModel.formCustomerGroup.dirty"
            [hidden]="!(hasError('required','CustomerCodeControl'))" >Customer name is required</div><br>

<grid-ui [grid-columns]="[{'colName':'CustomerCode'},{'colName':'CustomerName'},{'colName':'CustomerAmount'}]"
[grid-data]="CustomerModels"
(grid-selected)="SelectCustomer($event)"
></grid-ui>

</code>```

app.CustomerComponent.ts

```<code>import { Component, Injector } from '@angular/core';
import {Customer} from "./app.model";
import {BaseLogger} from "../Utility/app.Logger"
@Component({
  templateUrl: './app.CustomerView.html',
})
export class CustomerComponent {
  title = 'MyApp';
  CustomerModel : Customer = new Customer();
  CustomerModels :Array<Customer>=new Array<Customer>();
  Logobj !: BaseLogger;
  constructor(_injector : Injector){
    this.Logobj = _injector.get("1");
    this.Logobj.Log;
  }
  SelectCustomer(_selected:Customer){
     this.CustomerModel = _selected;
  }
  Add(){
      this.CustomerModels.push(this.CustomerModel);
      this.CustomerModel=new Customer(); //clear UI
  }
  hasError(typeofvalidator:string,
        controlname:string) : boolean{
          return this.CustomerModel
                .formCustomerGroup
                .controls[controlname]
                .hasError(typeofvalidator);
  }
}
</code>```

Can't bind to 'grid-columns' since it isn't a known property of 'grid-ui'.

1. If 'grid-ui' is an Angular component and it has 'grid-columns' input, then verify that it is part of this module.

2. If 'grid-ui' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.ngtsc(-998002)

app.CustomerComponent.ts(3, 55): Error occurs in the template of component CustomerComponent.

Body:
grid-columns is showing error in app.Customer.html and in app.CustomerComponent.ts

app.Customer.html

<form [formGroup]="CustomerModel.formCustomerGroup">
Customer Code :<input formControlName="CustomerCodeControl"
[(ngModel)]="CustomerModel.CustomerCode" type=text/>

Customer Name :<input formControlName="CustomerNameControl"
 [(ngModel)]="CustomerModel.CustomerName" type=text/>

Customer Amount :<input [(ngModel)]="CustomerModel.CustomerAmount"
[ngModelOptions]="{standalone: true}"
type=text/>

<input [disabled]="!(CustomerModel.formCustomerGroup.valid)" (click)="Add()" type=button value="Add"/>

</form>

Customer Code format is not proper

Customer Code is required

Customer name is required

<grid-ui [grid-columns]="[{'colName':'CustomerCode'},{'colName':'CustomerName'},{'colName':'CustomerAmount'}]"
[grid-data]="CustomerModels"
(grid-selected)="SelectCustomer($event)"
></grid-ui>

app.CustomerComponent.ts

import { Component, Injector } from '@angular/core';
import {Customer} from "./app.model";
import {BaseLogger} from "../Utility/app.Logger"
@Component({
  templateUrl: './app.CustomerView.html',
})
export class CustomerComponent {
  title = 'MyApp';
  CustomerModel : Customer = new Customer();
  CustomerModels :Array<Customer>=new Array<Customer>();
  Logobj !: BaseLogger;
  constructor(_injector : Injector){
    this.Logobj = _injector.get("1");
    this.Logobj.Log;
  }
  SelectCustomer(_selected:Customer){
     this.CustomerModel = _selected;
  }
  Add(){
      this.CustomerModels.push(this.CustomerModel);
      this.CustomerModel=new Customer(); //clear UI
  }
  hasError(typeofvalidator:string,
        controlname:string) : boolean{
          return this.CustomerModel
                .formCustomerGroup
                .controls[controlname]
                .hasError(typeofvalidator);
  }
}

Can't bind to 'grid-columns' since it isn't a known property of 'grid-ui'.

1. If 'grid-ui' is an Angular component and it has 'grid-columns' input, then verify that it is part of this module.

2. If 'grid-ui' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.ngtsc(-998002)

app.CustomerComponent.ts(3, 55): Error occurs in the template of component CustomerComponent.


问:
UITextView making isScrolledEnabled removes right contentInset
I have a very simple implementation of a UITextView in my app. I have applied contentInset from all four sides, but when I make isScrolledEnabled false right contentInset goes away. With isScrolledEnabled true contentInset works fine. Can you please help me solve this ?
I am aware about textContainerInset and it works just fine but I don't want to use it. It is causing other things to break in my app.
Here is the sample code:</p>
```<code>class ViewController: UIViewController {

    var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .lightGray
        setupTextView()
        setupContraints()
    }

    private func setupTextView() {
        textView = UITextView()
        textView.text = "Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, tvOS, and watchOS."
        textView.font = .boldSystemFont(ofSize: 24)
        textView.contentInset = .init(top: 25, left: 25, bottom: 25, right: 25)
        textView.isScrollEnabled = false
        textView.layer.borderColor = UIColor.red.cgColor
        textView.layer.borderWidth = 2
        view.addSubview(textView)
    }

    private func setupContraints() {
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.heightAnchor.constraint(equalToConstant: 250).isActive = true
        textView.widthAnchor.constraint(equalToConstant: 350).isActive = true
        textView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        textView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    }
}
</code>```

Body:
I have a very simple implementation of a UITextView in my app. I have applied contentInset from all four sides, but when I make isScrolledEnabled false right contentInset goes away. With isScrolledEnabled true contentInset works fine. Can you please help me solve this ?
I am aware about textContainerInset and it works just fine but I don't want to use it. It is causing other things to break in my app.
Here is the sample code:

class ViewController: UIViewController {

    var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .lightGray
        setupTextView()
        setupContraints()
    }

    private func setupTextView() {
        textView = UITextView()
        textView.text = "Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, tvOS, and watchOS."
        textView.font = .boldSystemFont(ofSize: 24)
        textView.contentInset = .init(top: 25, left: 25, bottom: 25, right: 25)
        textView.isScrollEnabled = false
        textView.layer.borderColor = UIColor.red.cgColor
        textView.layer.borderWidth = 2
        view.addSubview(textView)
    }

    private func setupContraints() {
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.heightAnchor.constraint(equalToConstant: 250).isActive = true
        textView.widthAnchor.constraint(equalToConstant: 350).isActive = true
        textView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        textView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    }
}


问:
WooCommerce with Apple Pay and Authorize.net Integration
I have implemented apple pay on my WordPress Website using Authorize.net as my Payment Gateway. I am also using WooCommerce and successfully setup the certificate requirements of Apple. I can also see apple pay button on the website but when I try to try a test purchase the error says "An error occurred, please try again or try an alternate form of payment". I can't even see error on hosting error logs/authorize.net logs/transactions.

Staging site - https://staging-ojaienergetics2019-staging0906.kinsta.cloud/

```<code>add_filter( 'wc_payment_gateway_authorize_net_cim_activate_apple_pay', '__return_true' );
</code>```

Body:
I have implemented apple pay on my WordPress Website using Authorize.net as my Payment Gateway. I am also using WooCommerce and successfully setup the certificate requirements of Apple. I can also see apple pay button on the website but when I try to try a test purchase the error says "An error occurred, please try again or try an alternate form of payment". I can't even see error on hosting error logs/authorize.net logs/transactions.

Staging site - https://staging-ojaienergetics2019-staging0906.kinsta.cloud/

add_filter( 'wc_payment_gateway_authorize_net_cim_activate_apple_pay', '__return_true' );


问:
Importing CSV files always fail
My problem is failing to import any csv file from my laptop
I always get errors ( 2068, 1083,or 3948 )
I have tried Changing in my.ini text file ,but editing is prevented
I wrote this code

```<code>SHOW VARIABLES LIKE "secure_file_priv";
</code>```

I get this result

```<code>'C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\'
</code>```

so transferred csv files to this pass -- another failure also
My codes are:

```<code>LOAD DATA LOCAL INFILE '/ProgramData/MySQL/MySQL Server 8.0/Uploads/covid_death.CSV'
INTO TABLE death
FIELDS TERMINATED BY ','
TERMINATED BY'\n'
IGNORE 1 LINES;
</code>```

these lines applied for workbench and command lines too(MySQL 8.0)
*When I use "Import Data Wizard" loads error in integer or Truncated values error"

Title: Importing CSV files always fail

Body:
My problem is failing to import any csv file from my laptop
I always get errors ( 2068, 1083,or 3948 )
I have tried Changing in my.ini text file ,but editing is prevented
I wrote this code

SHOW VARIABLES LIKE "secure_file_priv";

I get this result

'C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\'

so transferred csv files to this pass -- another failure also
My codes are:

LOAD DATA LOCAL INFILE '/ProgramData/MySQL/MySQL Server 8.0/Uploads/covid_death.CSV'
INTO TABLE death
FIELDS TERMINATED BY ','
TERMINATED BY'\n'
IGNORE 1 LINES;

these lines applied for workbench and command lines too(MySQL 8.0)
*When I use "Import Data Wizard" loads error in integer or Truncated values error"


问:
set default directory of "Open Workspace from File" in vs code
When I open a workspace in vscode, I always have to navigate to ~/vscode-workspaces.  I wonder if I can choose the default directory it looks for workspace files in.

(I checked in settings and searched for 'folder' and 'directory' but didn't find anything appropriate.)


问:
Rails 6: Getting warning: previous definition of Socket was here rails aborted! NameError: uninitialized constant Rack::Cors
When I try rails db:create I get
warning: previous definition of Socket was here
rails aborted!
NameError: uninitialized constant Rack::Cors

I am trying to create db . I am new to rails so am not sure what to do. I am trying to setup the project on my local.


问:
Filtered products don't appear on the first page after pagination in Reactjs
Basically, after filtering through a set of products, depending on the current page I am on, I get demonstrated with the corresponding product cards. However, a problem occurs: after filtering, the selected products don't show up on the first page, but on the second page while the first has nothing there.

For example, I have two categories of products: "Hi, World" and "Horoscope". If I select both, everything works perfectly fine and I get all the products well-paginated, with "Hi, World" appearing on the first page and followed by "Horoscope" products on the second page. But, if I only want to select "Horoscope", the products don't appear on the first page, but on the second page.

Product showcasing page:

```<code>{/*pagination setting: I divide the products into 10 for each page and so for the first page, only products at index 0 to 10 get demonstrated and the logic follows for the other pages*/}
const [currentPage,setCurrentPage]=useState<number>(1);
const [postsPerPage,setPostsPerPage]=useState<number>(10);
const indexOfLastPost=currentPage*postsPerPage;
const indexOfFirstPost=indexOfLastPost-postsPerPage;

{/*product array getting paginated/sliced*/}
{
                            (productData?.map((product)=>{
                                if(product.theme=== "Horoscope"&&horoscopeFilter){
                                    currentProductRendered.push(product);
                                    return(
                                        <ProductCard productData={product} setAddToShoppingCartStatus={setAddToShoppingCartStatus} setShoppingCartIsClicked={setShoppingCartIsClicked}/>
                                    )
                                }else if(product.theme==="Hi, World"&&hiWorldFilter){
                                    currentProductRendered.push(product);
                                    return(
                                        <ProductCard productData={product} setAddToShoppingCartStatus={setAddToShoppingCartStatus} setShoppingCartIsClicked={setShoppingCartIsClicked}/>
                                    )
                                }
                                else{
                                    return;
                                }
                            }).slice(indexOfFirstPost,indexOfLastPost)
                            )
                        }

{/*Pagination component*/}
<Pagination postsPerPage={postsPerPage} totalPosts={currentProductRendered?.length as number} currentPage={currentPage} setCurrentPage={setCurrentPage}></Pagination>
</code>```

Pagination component:

```<code>type Props={
    postsPerPage: number;
    totalPosts:number;
    currentPage:number;
    setCurrentPage:(currentPage:number)=>void;
}

export default function Pagination(props:Props){
    const pageNumbers=[];

    for(let i=1;i<=Math.ceil(props.totalPosts/props.postsPerPage);i++){
        pageNumbers.push(i);
    }

    const handlePrevOnClick=()=>{
        let currentPage=props.currentPage;
        props.setCurrentPage(currentPage-1);
    }

    const handleNextOnClick=()=>{
        let currentPage=props.currentPage;
        props.setCurrentPage(currentPage+1);
    }
    let tempPageNumbers:(number | string)[];
    {/*depending on the length of pageNumbers, pagination numbers get shown visually accordingly*/}
    if(pageNumbers.length===1){
        tempPageNumbers=[1];
    }else if(pageNumbers.length===2){
        tempPageNumbers=[1,2];
    }else if(pageNumbers.length===3){
        tempPageNumbers=[1,2,3];
    }else if(pageNumbers.length===4){
        tempPageNumbers=[1,2,3,4];
    }else if(pageNumbers.length===5){
        tempPageNumbers=[1,2,3,4,5];
    }else if(pageNumbers.length===6){
        tempPageNumbers=[1,2,3,4,5,6];
    }else if(pageNumbers.length>=7&&props.currentPage>=1&&props.currentPage<=4){
        tempPageNumbers=[1,2,3,4,5,"...",pageNumbers.length];
    }else if(props.currentPage>=5&&props.currentPage+4<=pageNumbers.length){
        tempPageNumbers=["1...",props.currentPage-2,props.currentPage-1,props.currentPage,props.currentPage+1,props.currentPage+2,"...",pageNumbers.length];
    }else{
        tempPageNumbers=["1...",pageNumbers.length-4,pageNumbers.length-3,pageNumbers.length-2,pageNumbers.length-1,pageNumbers.length];
    }

    return(
        <div className={"pagination-container"}>
            <div className={"pages-container"}>
                <div className={"each-page"} onClick={handlePrevOnClick}>
                    <div className={"page-number"}>
                        Prev
                    </div>
                </div>
                {tempPageNumbers.map((page)=>{
                    if(page==="1..."){
                        return(
                            <div className={"each-page"} onClick={()=>{props.setCurrentPage(1)}}>
                                <div className={"page-number"}>
                                    {page}
                                </div>
                            </div>
                        )
                    }else if(page===props.currentPage){
                        return(
                            <div className={"current-page"} onClick={()=>{props.setCurrentPage(page as number)}}>
                                <div className={"current-page-number"}>
                                    {page}
                                </div>
                            </div>
                        )
                    }else if(page==="..."){
                        return(
                            <div className={"dot-dot-page"}>
                                <div className={"page-number"}>
                                    {page}
                                </div>
                            </div>
                        )
                    }
                    else{
                        return(
                            <div className={"each-page"} onClick={()=>{props.setCurrentPage(page as number)}}>
                                <div className={"page-number"}>
                                    {page}
                                </div>
                            </div>
                        )
                    }
            })}
                <div className={"each-page"} onClick={handleNextOnClick}>
                    <div className={"page-number"}>
                        Next
                    </div>
                </div>
            </div>
        </div>
    )

}
</code>```

I expect to see products get shown starting from the first page. I think the problem is mainly with wrong pagination. The pagination doesn't start with the first page.

I will appreciate anyone who can help me with this problem! I have been stuck for several days... Million thanks in advance!

Body:
Basically, after filtering through a set of products, depending on the current page I am on, I get demonstrated with the corresponding product cards. However, a problem occurs: after filtering, the selected products don't show up on the first page, but on the second page while the first has nothing there.

For example, I have two categories of products: "Hi, World" and "Horoscope". If I select both, everything works perfectly fine and I get all the products well-paginated, with "Hi, World" appearing on the first page and followed by "Horoscope" products on the second page. But, if I only want to select "Horoscope", the products don't appear on the first page, but on the second page.

Product showcasing page:

{/*pagination setting: I divide the products into 10 for each page and so for the first page, only products at index 0 to 10 get demonstrated and the logic follows for the other pages*/}
const [currentPage,setCurrentPage]=useState<number>(1);
const [postsPerPage,setPostsPerPage]=useState<number>(10);
const indexOfLastPost=currentPage*postsPerPage;
const indexOfFirstPost=indexOfLastPost-postsPerPage;

{/*product array getting paginated/sliced*/}
{
                            (productData?.map((product)=>{
                                if(product.theme=== "Horoscope"&&horoscopeFilter){
                                    currentProductRendered.push(product);
                                    return(
                                        <ProductCard productData={product} setAddToShoppingCartStatus={setAddToShoppingCartStatus} setShoppingCartIsClicked={setShoppingCartIsClicked}/>
                                    )
                                }else if(product.theme==="Hi, World"&&hiWorldFilter){
                                    currentProductRendered.push(product);
                                    return(
                                        <ProductCard productData={product} setAddToShoppingCartStatus={setAddToShoppingCartStatus} setShoppingCartIsClicked={setShoppingCartIsClicked}/>
                                    )
                                }
                                else{
                                    return;
                                }
                            }).slice(indexOfFirstPost,indexOfLastPost)
                            )
                        }

{/*Pagination component*/}
<Pagination postsPerPage={postsPerPage} totalPosts={currentProductRendered?.length as number} currentPage={currentPage} setCurrentPage={setCurrentPage}></Pagination>

Pagination component:

type Props={
    postsPerPage: number;
    totalPosts:number;
    currentPage:number;
    setCurrentPage:(currentPage:number)=>void;
}

export default function Pagination(props:Props){
    const pageNumbers=[];

    for(let i=1;i<=Math.ceil(props.totalPosts/props.postsPerPage);i++){
        pageNumbers.push(i);
    }

    const handlePrevOnClick=()=>{
        let currentPage=props.currentPage;
        props.setCurrentPage(currentPage-1);
    }

    const handleNextOnClick=()=>{
        let currentPage=props.currentPage;
        props.setCurrentPage(currentPage+1);
    }
    let tempPageNumbers:(number | string)[];
    {/*depending on the length of pageNumbers, pagination numbers get shown visually accordingly*/}
    if(pageNumbers.length===1){
        tempPageNumbers=[1];
    }else if(pageNumbers.length===2){
        tempPageNumbers=[1,2];
    }else if(pageNumbers.length===3){
        tempPageNumbers=[1,2,3];
    }else if(pageNumbers.length===4){
        tempPageNumbers=[1,2,3,4];
    }else if(pageNumbers.length===5){
        tempPageNumbers=[1,2,3,4,5];
    }else if(pageNumbers.length===6){
        tempPageNumbers=[1,2,3,4,5,6];
    }else if(pageNumbers.length>=7&&props.currentPage>=1&&props.currentPage<=4){
        tempPageNumbers=[1,2,3,4,5,"...",pageNumbers.length];
    }else if(props.currentPage>=5&&props.currentPage+4<=pageNumbers.length){
        tempPageNumbers=["1...",props.currentPage-2,props.currentPage-1,props.currentPage,props.currentPage+1,props.currentPage+2,"...",pageNumbers.length];
    }else{
        tempPageNumbers=["1...",pageNumbers.length-4,pageNumbers.length-3,pageNumbers.length-2,pageNumbers.length-1,pageNumbers.length];
    }

    return(

                        Prev

                {tempPageNumbers.map((page)=>{
                    if(page==="1..."){
                        return(

{props.setCurrentPage(1)}}>

                                    {page}

                        )
                    }else if(page===props.currentPage){
                        return(

{props.setCurrentPage(page as number)}}>

                                    {page}

                        )
                    }else if(page==="..."){
                        return(

                                    {page}

                        )
                    }
                    else{
                        return(

{props.setCurrentPage(page as number)}}>

                                    {page}

                        )
                    }
            })}

                        Next

    )

}

I expect to see products get shown starting from the first page. I think the problem is mainly with wrong pagination. The pagination doesn't start with the first page.

I will appreciate anyone who can help me with this problem! I have been stuck for several days... Million thanks in advance!


问:
Yarn install error. "getaddrinfo ENOTFOUND bnpm.byted.org"."
when I run yarn install, there are many info
"There appears to be trouble with your network connection. Retrying..." to me, and an error:
An unexpected error occurred:

```<code>"http://bnpm.byted.org/follow-redirects/-/follow-redirects-1.14.9.tgz: getaddrinfo ENOTFOUND bnpm.byted.org".
</code>```

I have changed the mirror source, but it don't work.

Body:
when I run yarn install, there are many info
"There appears to be trouble with your network connection. Retrying..." to me, and an error:
An unexpected error occurred:

"http://bnpm.byted.org/follow-redirects/-/follow-redirects-1.14.9.tgz: getaddrinfo ENOTFOUND bnpm.byted.org".

I have changed the mirror source, but it don't work.


问:
How to save an object arrayList which have Pair value in file android
I want to save an arraylist of connections which have Pairs value in file but it showing NotSerializableException.

I also implemented the serializable interface .
i thought it occur from Pair class. If you have any solution for save these array of connections and also retrieve from file.

Connection.kt

```<code>data class Connection(
//    @Transient
    var firstPair: Pair<CircuitComponent, Int>,
//    @Transient
    var secondPair: Pair<CircuitComponent, Int>
) :Serializable{

    var pathOfLine: NamedPath = NamedPath("")

    data class State(
        val firstComponentCode: String,
        val secondComponentCode: String,
        val firstTouchPointIndex: Int,
        val secondTouchPointIndex: Int,
        val pathName: String,
    ): Serializable

     fun getState() = State(
        firstPair.first.getCode(),
        secondPair.first.getCode(),
        firstPair.second,
        secondPair.second,
        pathOfLine.name
    )
}
</code>```

saving arraylist of connection

```<code>val projectsDirectory = File("${requireActivity().filesDir}/projects")
projectsDirectory.mkdir()
val thisProjectDirectory = File("${projectsDirectory}/${args.project.customerName}")
thisProjectDirectory.mkdir()
val file = File(thisProjectDirectory, "/image.jpg")
val out = FileOutputStream(file)
args.project.image = file.absolutePath
args.project.dateModified = SimpleDateFormat("MMMM dd yyyy", Locale.getDefault()).format(Date())
args.project.size = "${thisProjectDirectory.length() / 1000} kb"
serialize(thisProjectDirectory.absolutePath,"list_con.ser", connectionsList)
designBitmap.compress(Bitmap.CompressFormat.JPEG, 50, out)
out.close()
</code>```

serialize method

```<code>fun serialize(location:String,fileName:String,obj:Any){
 val fileOutputStream = FileOutputStream("$location/$fileName")
 val objectOutputStream = ObjectOutputStream(fileOutputStream)
 objectOutputStream.writeObject(obj)
 objectOutputStream.close()
}
</code>```

fetch connections

```<code>val projectLocation = "${requireActivity().filesDir}/projects/${args.project.customerName}"
val projectDirectory = File(projectLocation)
val connectionsList= deserialize(File(projectDirectory , "list_con.ser"))
</code>```

deserialize

```<code>fun deserialize(file: File): Any? {
    val fileInputStream = FileInputStream(file)
    val objectInputStream = ObjectInputStream(fileInputStream)
    return objectInputStream.readObject()
}
</code>```

Body:
I want to save an arraylist of connections which have Pairs value in file but it showing NotSerializableException.

I also implemented the serializable interface .
i thought it occur from Pair class. If you have any solution for save these array of connections and also retrieve from file.

Connection.kt

data class Connection(
//    @Transient
    var firstPair: Pair<CircuitComponent, Int>,
//    @Transient
    var secondPair: Pair<CircuitComponent, Int>
) :Serializable{

    var pathOfLine: NamedPath = NamedPath("")

    data class State(
        val firstComponentCode: String,
        val secondComponentCode: String,
        val firstTouchPointIndex: Int,
        val secondTouchPointIndex: Int,
        val pathName: String,
    ): Serializable

     fun getState() = State(
        firstPair.first.getCode(),
        secondPair.first.getCode(),
        firstPair.second,
        secondPair.second,
        pathOfLine.name
    )
}

saving arraylist of connection

val projectsDirectory = File("${requireActivity().filesDir}/projects")
projectsDirectory.mkdir()
val thisProjectDirectory = File("${projectsDirectory}/${args.project.customerName}")
thisProjectDirectory.mkdir()
val file = File(thisProjectDirectory, "/image.jpg")
val out = FileOutputStream(file)
args.project.image = file.absolutePath
args.project.dateModified = SimpleDateFormat("MMMM dd yyyy", Locale.getDefault()).format(Date())
args.project.size = "${thisProjectDirectory.length() / 1000} kb"
serialize(thisProjectDirectory.absolutePath,"list_con.ser", connectionsList)
designBitmap.compress(Bitmap.CompressFormat.JPEG, 50, out)
out.close()

serialize method

fun serialize(location:String,fileName:String,obj:Any){
 val fileOutputStream = FileOutputStream("$location/$fileName")
 val objectOutputStream = ObjectOutputStream(fileOutputStream)
 objectOutputStream.writeObject(obj)
 objectOutputStream.close()
}

fetch connections

val projectLocation = "${requireActivity().filesDir}/projects/${args.project.customerName}"
val projectDirectory = File(projectLocation)
val connectionsList= deserialize(File(projectDirectory , "list_con.ser"))

deserialize

fun deserialize(file: File): Any? {
    val fileInputStream = FileInputStream(file)
    val objectInputStream = ObjectInputStream(fileInputStream)
    return objectInputStream.readObject()
}


问:
I want to use _msize alternative but I don't know
First of all, I am practicing C language in VScode on m2 Mac.
I want to use _msize like got used it on Windows.
I tried to use the alternative malloc_usable_size() that I found.
When I use it, it fails.

My native language is Korean. Please excuse my English.

I want to know the allocated buffer size. I want to use something like msize on Windows.


问:
CORS error with GraphQL Apollo and NextJS
I'll do my best to explain my issue.

I'm building a NextJS site and using Apollo to handle Graph QL, and it's been working perfectly fine when I test the API using Postman, but when I try to run in dev I get CORS errors:

This operation has been blocked as a potential Cross-Site Request Forgery (CSRF). Please either specify a 'content-type' header (with a type that is not one of application/x-www-form-urlencoded, multipart/form-data, text/plain) or provide a non-empty value for one of the following headers: x-apollo-operation-name, apollo-require-preflight

This is my code that runs the Apollo code.

index.ts:

```<code>import { ApolloServer } from '@apollo/server';
import { startServerAndCreateNextHandler } from '@as-integrations/next';
import { applyMiddleware } from 'graphql-middleware';
import { makeExecutableSchema } from '@graphql-tools/schema';

import { getUserFromToken } from './../../../server/security/jwt';
import typeDefs from './schema';

import { resolvers } from './resolvers';
import { permissions } from './permissions';

const schema = applyMiddleware(
    makeExecutableSchema({
        typeDefs: typeDefs,
        resolvers,
    }),
    permissions
);

const server = new ApolloServer({
    schema,
    includeStacktraceInErrorResponses: false,
});

export default startServerAndCreateNextHandler(server, {
    context: async (req, res) => {
        const cookies = req.cookies;
        const token = cookies.titanAuthToken || '';
        var user;
        if (token) {
            user = getUserFromToken(token);
        }

        return { req, res, user, token };
    },
});
</code>```

I have tried a few suggestions from google including this:

```<code>const server = new ApolloServer({
    schema,
    includeStacktraceInErrorResponses: false,
    cors: {
        origin: true,
        credentials: true, // true if you need cookies/authentication
        methods: ['GET', 'POST', 'OPTIONS'],
    }
});
</code>```

But when I try the above I get this error:

```<code>Argument of type '{ schema: GraphQLSchemaWithFragmentReplacements; includeStacktraceInErrorResponses: false; cors: { origin: boolean; credentials: boolean; methods: string[]; }; }' is not assignable to parameter of type 'ApolloServerOptions<BaseContext>'.
  Object literal may only specify known properties, and 'cors' does not exist in type 'ApolloServerOptionsWithSchema<BaseContext>
</code>```

Any help to fix this CORS error would be greatly appreciated.

Body:
I'll do my best to explain my issue.

I'm building a NextJS site and using Apollo to handle Graph QL, and it's been working perfectly fine when I test the API using Postman, but when I try to run in dev I get CORS errors:

This operation has been blocked as a potential Cross-Site Request Forgery (CSRF). Please either specify a 'content-type' header (with a type that is not one of application/x-www-form-urlencoded, multipart/form-data, text/plain) or provide a non-empty value for one of the following headers: x-apollo-operation-name, apollo-require-preflight

This is my code that runs the Apollo code.

index.ts:

import { ApolloServer } from '@apollo/server';
import { startServerAndCreateNextHandler } from '@as-integrations/next';
import { applyMiddleware } from 'graphql-middleware';
import { makeExecutableSchema } from '@graphql-tools/schema';

import { getUserFromToken } from './../../../server/security/jwt';
import typeDefs from './schema';

import { resolvers } from './resolvers';
import { permissions } from './permissions';

const schema = applyMiddleware(
    makeExecutableSchema({
        typeDefs: typeDefs,
        resolvers,
    }),
    permissions
);

const server = new ApolloServer({
    schema,
    includeStacktraceInErrorResponses: false,
});

export default startServerAndCreateNextHandler(server, {
    context: async (req, res) => {
        const cookies = req.cookies;
        const token = cookies.titanAuthToken || '';
        var user;
        if (token) {
            user = getUserFromToken(token);
        }

        return { req, res, user, token };
    },
});

I have tried a few suggestions from google including this:

const server = new ApolloServer({
    schema,
    includeStacktraceInErrorResponses: false,
    cors: {
        origin: true,
        credentials: true, // true if you need cookies/authentication
        methods: ['GET', 'POST', 'OPTIONS'],
    }
});

But when I try the above I get this error:

Argument of type '{ schema: GraphQLSchemaWithFragmentReplacements; includeStacktraceInErrorResponses: false; cors: { origin: boolean; credentials: boolean; methods: string[]; }; }' is not assignable to parameter of type 'ApolloServerOptions<BaseContext>'.
  Object literal may only specify known properties, and 'cors' does not exist in type 'ApolloServerOptionsWithSchema<BaseContext>

Any help to fix this CORS error would be greatly appreciated.


问:
Module Federation Angular in React Shell
I want to use angular app inside react app using module federation.
I found a way to use angular's app.component in React. But I can't use other components.
I am sharing the codes below.

Angular webpack config

```<code>const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const mf = require("@angular-architects/module-federation/webpack");
const path = require("path");
const share = mf.share;

const sharedMappings = new mf.SharedMappings();
sharedMappings.register(path.join(__dirname, "tsconfig.json"), [
]);

module.exports = {
  output: {
    uniqueName: "mfeRemote",
    publicPath: "auto",
    scriptType: "text/javascript",
  },
  optimization: {
    runtimeChunk: false,
  },
  resolve: {
    alias: {
      ...sharedMappings.getAliases(),
    },
  },
  experiments: {
    outputModule: true,
  },
  plugins: [
    new ModuleFederationPlugin({
      name: "mfeRemote",
      filename: "remoteEntry.js",
      exposes: {
        "./AppModule": "./src/loadApp.ts",
        "./DashComp": "./src/app/external/dashboard/dashboard.component.ts",
      },

      shared: share({
        "@angular/core": {
          singleton: true,
          strictVersion: true,
          requiredVersion: "auto",
        },
        "@angular/common": {
          singleton: true,
          strictVersion: true,
          requiredVersion: "auto",
        },
        "@angular/common/http": {
          singleton: true,
          strictVersion: true,
          requiredVersion: "auto",
        },
        "@angular/router": {
          singleton: true,
          strictVersion: true,
          requiredVersion: "auto",
        },

        ...sharedMappings.getDescriptors(),
      }),
    }),
    sharedMappings.getPlugin(),
  ],
};
</code>```

loadApp.ts

```<code>import 'zone.js';

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';

const mount = () => {
  platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .catch((err) => console.error(err));
};

export { mount };
</code>```

React Craco config

```<code>const ModuleFederationPlugin = require("webpack").container.ModuleFederationPlugin;
const deps = require("./package.json").dependencies;

module.exports = {
  plugins: [
    {
      plugin: {
        overrideCracoConfig: ({ cracoConfig, pluginOptions, context: { env, paths } }) => {
          return cracoConfig;
        },
        overrideWebpackConfig: ({ webpackConfig, cracoConfig, pluginOptions, context: { env, paths } }) => {
          webpackConfig.plugins = [
            ...webpackConfig.plugins,
            new ModuleFederationPlugin({
              name: "app",
              remotes: {
                appModule: "mfeRemote@http://localhost:3002/remoteEntry.js",
              },
              shared: {
                ...deps,
                "react-dom": {
                  singleton: true,
                  eager: true,
                },
                react: {
                  singleton: true,
                  eager: true,
                },
              },
            }),
          ];
          return webpackConfig;
        },
        overrideDevServerConfig: ({
          devServerConfig,
          cracoConfig,
          pluginOptions,
          context: { env, paths, proxy, allowedHost },
        }) => {
          return devServerConfig;
        },
        overrideJestConfig: ({ jestConfig, cracoConfig, pluginOptions, context: { env, paths, resolve, rootDir } }) => {
          return jestConfig;
        },
      },
    },
  ],
};

</code>```

React using App-Component (is Work)

```<code>import React, { useEffect, useRef } from "react";
import { mount } from "appModule/AppModule";

const RemoteAppModule = () => {
  const ref = useRef(null);
  useEffect(() => {
    mount();
  }, []);
  return (
    <div className="remote-module">
      <app-root></app-root>
    </div>
  );
};

export default RemoteAppModule;
</code>```

React using Other Comp (not Work)

```<code>import React from "react";

let DashComp = React.lazy(() =>
  import("appModule/DashComp").then((module) => {

     // this row for -> class component without new
    let ExtModule = new module.DashboardComponent();
    return { default: ExtModule };
  })

  );

const RemoteExtModule = () => {
  return (
    <div>
      <React.Suspense fallback="...loading">
        <DashComp />
      </React.Suspense>
    </div>
  );
};

export default RemoteExtModule;
</code>```

Error

enter image description here

------------------UPDATE ------------------------------------------

i solved my problem different way. I used multiple bootstrap module .

check my repo :

https://github.com/scerci/mfe-angular-react

Body:
I want to use angular app inside react app using module federation.
I found a way to use angular's app.component in React. But I can't use other components.
I am sharing the codes below.

Angular webpack config

const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const mf = require("@angular-architects/module-federation/webpack");
const path = require("path");
const share = mf.share;

const sharedMappings = new mf.SharedMappings();
sharedMappings.register(path.join(__dirname, "tsconfig.json"), [
]);

module.exports = {
  output: {
    uniqueName: "mfeRemote",
    publicPath: "auto",
    scriptType: "text/javascript",
  },
  optimization: {
    runtimeChunk: false,
  },
  resolve: {
    alias: {
      ...sharedMappings.getAliases(),
    },
  },
  experiments: {
    outputModule: true,
  },
  plugins: [
    new ModuleFederationPlugin({
      name: "mfeRemote",
      filename: "remoteEntry.js",
      exposes: {
        "./AppModule": "./src/loadApp.ts",
        "./DashComp": "./src/app/external/dashboard/dashboard.component.ts",
      },

      shared: share({
        "@angular/core": {
          singleton: true,
          strictVersion: true,
          requiredVersion: "auto",
        },
        "@angular/common": {
          singleton: true,
          strictVersion: true,
          requiredVersion: "auto",
        },
        "@angular/common/http": {
          singleton: true,
          strictVersion: true,
          requiredVersion: "auto",
        },
        "@angular/router": {
          singleton: true,
          strictVersion: true,
          requiredVersion: "auto",
        },

        ...sharedMappings.getDescriptors(),
      }),
    }),
    sharedMappings.getPlugin(),
  ],
};

loadApp.ts

import 'zone.js';

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';

const mount = () => {
  platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .catch((err) => console.error(err));
};

export { mount };

React Craco config

const ModuleFederationPlugin = require("webpack").container.ModuleFederationPlugin;
const deps = require("./package.json").dependencies;

module.exports = {
  plugins: [
    {
      plugin: {
        overrideCracoConfig: ({ cracoConfig, pluginOptions, context: { env, paths } }) => {
          return cracoConfig;
        },
        overrideWebpackConfig: ({ webpackConfig, cracoConfig, pluginOptions, context: { env, paths } }) => {
          webpackConfig.plugins = [
            ...webpackConfig.plugins,
            new ModuleFederationPlugin({
              name: "app",
              remotes: {
                appModule: "mfeRemote@http://localhost:3002/remoteEntry.js",
              },
              shared: {
                ...deps,
                "react-dom": {
                  singleton: true,
                  eager: true,
                },
                react: {
                  singleton: true,
                  eager: true,
                },
              },
            }),
          ];
          return webpackConfig;
        },
        overrideDevServerConfig: ({
          devServerConfig,
          cracoConfig,
          pluginOptions,
          context: { env, paths, proxy, allowedHost },
        }) => {
          return devServerConfig;
        },
        overrideJestConfig: ({ jestConfig, cracoConfig, pluginOptions, context: { env, paths, resolve, rootDir } }) => {
          return jestConfig;
        },
      },
    },
  ],
};

React using App-Component (is Work)

import React, { useEffect, useRef } from "react";
import { mount } from "appModule/AppModule";

const RemoteAppModule = () => {
  const ref = useRef(null);
  useEffect(() => {
    mount();
  }, []);
  return (

      <app-root></app-root>

  );
};

export default RemoteAppModule;

React using Other Comp (not Work)

import React from "react";

let DashComp = React.lazy(() =>
  import("appModule/DashComp").then((module) => {

     // this row for -> class component without new
    let ExtModule = new module.DashboardComponent();
    return { default: ExtModule };
  })

  );

const RemoteExtModule = () => {
  return (

      <React.Suspense fallback="...loading">
        <DashComp />
      </React.Suspense>

  );
};

export default RemoteExtModule;

Error

enter image description here

------------------UPDATE ------------------------------------------

i solved my problem different way. I used multiple bootstrap module .

check my repo :

https://github.com/scerci/mfe-angular-react