问:
Python Selenium to Download File to Memory
I have a number of scripts that scrape the web, grab files, then read them using pandas. This procedure must be deployed under a new architecture in which downloading files from disc is not acceptable; instead, the file should be saved in memory and read with pandas from there.

The Websites doesn't provide a direct link to the file rather it has provided with a button that uses form submission to download it.

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.wait import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager

chrome_options = webdriver.ChromeOptions()
prefs = {'download': {'default_directory': #a link to memory}}
chrome_options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(options=chrome_options,service=Service(ChromeDriverManager().install()))

driver.get("https://www.speedchex.com/")
driver = login(driver)

WebDriverWait(driver,15).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,"#CSVButton")))
driver.find_element(By.CSS_SELECTOR,'#CSVButton').click()   #This button Downloads the file.
download_wait()  # a function to check if download is finished or not
driver.quit()
</code>```

Donwload_wait is just a function that will check the directory if there are any .crdownload files.

```<code>def download_wait():
    path_to_downloads = OUTPUT_FOLDER
    seconds = 0
    dl_wait = True
    while dl_wait and seconds < 200:
        time.sleep(1)
        dl_wait = False
        for fname in os.walk.files(filter=['*.crdownload']):
                dl_wait = True
        seconds += 1
    return seconds
</code>```

The input tag that downloads the file is as follows.

```<code><input name="CSVButton" type="button" id="CSVButton"  onclick="javascript: this.form.OutputType.value = 'CSV'; this.form.submit(); this.form.OutputType.value = 'HTML'; " value="CSV">
</code>```

答:
Selenium actually just pass commands down to the browser, in a different process than your Python program - so the usual approach of creating an object that emulates a file (io.BytesIO) can't work in this case.

Your only approach is to create an in-memory filesystem, and set the browser dwonload directory to have it as its target.How to create an in memory filesystem and were it is located will vary with your Operating System, but on Linux it is as easy as sudo mount -t tmpfs -o size=1024m myramdisk <mountpoint> (Use subprocess or plain os.system to issue that command). You can e even use  "/home/user/Downloads" as the mountpoint, and then you won't need to worry about changing any config in the browser.

It will work as a normal filesystem both from your browser and from your selenium script program - the normal file operation calls will work on it - You just have to arrange to de-create the filesystem upon program exit

For that, the "atexit" handler Python has can be usefull - https://docs.python.org/3/library/atexit.html

Body:
I have a number of scripts that scrape the web, grab files, then read them using pandas. This procedure must be deployed under a new architecture in which downloading files from disc is not acceptable; instead, the file should be saved in memory and read with pandas from there.

The Websites doesn't provide a direct link to the file rather it has provided with a button that uses form submission to download it.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.wait import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager

chrome_options = webdriver.ChromeOptions()
prefs = {'download': {'default_directory': #a link to memory}}
chrome_options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(options=chrome_options,service=Service(ChromeDriverManager().install()))

driver.get("https://www.speedchex.com/")
driver = login(driver)

WebDriverWait(driver,15).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,"#CSVButton")))
driver.find_element(By.CSS_SELECTOR,'#CSVButton').click()   #This button Downloads the file.
download_wait()  # a function to check if download is finished or not
driver.quit()

Donwload_wait is just a function that will check the directory if there are any .crdownload files.

def download_wait():
    path_to_downloads = OUTPUT_FOLDER
    seconds = 0
    dl_wait = True
    while dl_wait and seconds < 200:
        time.sleep(1)
        dl_wait = False
        for fname in os.walk.files(filter=['*.crdownload']):
                dl_wait = True
        seconds += 1
    return seconds

The input tag that downloads the file is as follows.

<input name="CSVButton" type="button" id="CSVButton"  onclick="javascript: this.form.OutputType.value = 'CSV'; this.form.submit(); this.form.OutputType.value = 'HTML'; " value="CSV">


来源: stackexchange

问:
What Did I Do Wrong Here With Shopware 6 Product.Loaded Event
I created a bare minimum Shopware 6 plugin to display product ID when the product is loaded. It worked fine. Below is my code.

```<code>   PATH: src/Resources/config/services.xml

<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>

        <service id="TestPlugin\Listener\ProductLoadedListener" >
            <tag  name="kernel.event_listener" event="product.loaded" />
        </service>

    </services>
</container>
</code>```

Below is the ProductLoadedListener.php codes

```<code>PATH: src/Listener/ProductLoadedListener.php

<?php declare(strict_types=1);

namespace TestPlugin\Listener;

use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;

class ProductLoadedListener{

    public function onProductLoaded(EntityLoadedEvent $entityLoadedEvent){

        print_r($entityLoadedEvent->getIds());

    }

}
</code>```

The above codes did the job it was created to do.
So I updated the ProductLoadedListener.php codes

```<code><?php declare(strict_types=1);

namespace TestPlugin\Listener;

use Shopware\Core\Framework\DataAbstractionLayer\Pricing\Price;

class ProductLoadedListener{

    public function onProductLoaded(Price $price){

        print_r($price->getNet());

    }

}
</code>```

I go an error

```<code>Argument 1 passed to TestPlugin\Listener\ProductLoadedListener::onProductLoaded() must be an instance of Shopware\Core\Framework\DataAbstractionLayer\Pricing\Price, instance of Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent given, called in /var/www/html/vendor/symfony/event-dispatcher/EventDispatcher.php on line 270
</code>```

So I am asking why I got the above error, I was expecting it to echo the net price?

答:
Shopware will inject in the onProductLoaded function an EntityLoadedEvent object, not a Price object. That's why PHP throws this error.

If you want the get the price of the loaded product, then you should get the product from the $entityLoadedEvent and then get the price:

class ProductLoadedListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            ProductEvents::PRODUCT_LOADED_EVENT => 'onProductLoaded'
        ];
    }

    public function onProductLoaded(EntityLoadedEvent $entityLoadedEvent)
    {
        /** @var ProductCollection $loadedProducts */
        $loadedProducts = $event->getEntities();
        $firstProduct = $loadedProducts->first();
        $productNetPrice = $firstProduct->getPrice()->first()->getNet();
        dd($productNetPrice);
    }
}
```

ContentLicense: CC BY-SA 4.0

Body:
I created a bare minimum Shopware 6 plugin to display product ID when the product is loaded. It worked fine. Below is my code.

   PATH: src/Resources/config/services.xml

<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>

        <service id="TestPlugin\Listener\ProductLoadedListener" >
            <tag  name="kernel.event_listener" event="product.loaded" />
        </service>

    </services>
</container>

Below is the ProductLoadedListener.php codes

PATH: src/Listener/ProductLoadedListener.php

<?php declare(strict_types=1);

namespace TestPlugin\Listener;

use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;

class ProductLoadedListener{

    public function onProductLoaded(EntityLoadedEvent $entityLoadedEvent){

        print_r($entityLoadedEvent->getIds());

    }

}

The above codes did the job it was created to do.
So I updated the ProductLoadedListener.php codes

<?php declare(strict_types=1);

namespace TestPlugin\Listener;

use Shopware\Core\Framework\DataAbstractionLayer\Pricing\Price;

class ProductLoadedListener{

    public function onProductLoaded(Price $price){

        print_r($price->getNet());

    }

}

I go an error

Argument 1 passed to TestPlugin\Listener\ProductLoadedListener::onProductLoaded() must be an instance of Shopware\Core\Framework\DataAbstractionLayer\Pricing\Price, instance of Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent given, called in /var/www/html/vendor/symfony/event-dispatcher/EventDispatcher.php on line 270

So I am asking why I got the above error, I was expecting it to echo the net price?


问:
Angular 2 SimpleChanges Object throws error at first npm start
In my angular 2 application there is a component containing an array of objects that is passing the chosen (clicked) one to it's direct child component. This does display the data more detailed. I'm using the "SimpleChanges" feature to watch in this child component if the object given changed to make another http request to get the related comments from a database.

If I try to build it with npm I get an error, saying :

app/displayEntry.component.ts(23,41): error TS2339: Property 'entry' does not exist on type 'SimpleChanges'

If I just comment this part out, start npm and finally put it in there again and save it, there is no Problem anymore ( no erro and it works ).
My question is, is there a way to work around this behavior and can this cause any trouble later I don't foresee or should I just ignore it? Thanks for your help

Parent component:

```<code>import { Component, OnInit } from '@angular/core';
import { entry } from './Objekte/entry';
import { entryService } from './entry.service'

@Component({
templateUrl: 'app/Html_Templates/displayLastEntrys.template.html'
})

export class displayLastEntrys implements OnInit{

public entrys : entry[];
private entryChoosen: boolean;
private ChoosenEntry : entry;

constructor ( private entryservice : entryService){
    this.entryChoosen = false;
}

ngOnInit() : void  {
    this.getData();
}

getData() {
    this.entryservice.getFirstEntrys().then(entrys => this.entrys = entrys);
}

entryClicked(ent: entry){
    this.entryChoosen = true;
    this.ChoosenEntry = ent;
}

leaveEntry () {
    this.entryChoosen = false;
}

voted( upordown : boolean ) {

}
}
</code>```

Child component:

```<code>import { Component, Input, Injectable, OnChanges , SimpleChanges, Output,                    EventEmitter} from '@angular/core';
import { entry} from './Objekte/entry';
import { entryService } from './entry.service';
import { comment } from './Objekte/comments';

@Component({
selector: 'display-entry',
templateUrl: 'app/Html_Templates/displayEntry.template.html'
})

export class displayComponent implements OnChanges{
@Input() public entry : entry;
public comments : comment[];

private changecounter : number;

constructor(private service : entryService) {
    this.changecounter  = 0;
}

ngOnChanges(changes : SimpleChanges){

   this.service.getComments(changes.entry.currentValue.id)
            .then(com => this.comments = com )
            .catch();

    this.entry.viewed++;
    // To implement :: change database
}

votedUp () : void {
    this.entry.votes ++;
    // To implement :: change database
}

votedDown () : void  {
    this.entry.votes --;
    // To implement :: change database
}
}
</code>```

答: If you are completely dependent on the IDE's auto-completion, make sure to actually use SimpleChanges instead of just SimpleChange. A very thing to be overlooked at.

ContentLicense: CC BY-SA 3.0

Body:
In my angular 2 application there is a component containing an array of objects that is passing the chosen (clicked) one to it's direct child component. This does display the data more detailed. I'm using the "SimpleChanges" feature to watch in this child component if the object given changed to make another http request to get the related comments from a database.

If I try to build it with npm I get an error, saying :

app/displayEntry.component.ts(23,41): error TS2339: Property 'entry' does not exist on type 'SimpleChanges'

If I just comment this part out, start npm and finally put it in there again and save it, there is no Problem anymore ( no erro and it works ).
My question is, is there a way to work around this behavior and can this cause any trouble later I don't foresee or should I just ignore it? Thanks for your help

Parent component:

import { Component, OnInit } from '@angular/core';
import { entry } from './Objekte/entry';
import { entryService } from './entry.service'

@Component({
templateUrl: 'app/Html_Templates/displayLastEntrys.template.html'
})

export class displayLastEntrys implements OnInit{

public entrys : entry[];
private entryChoosen: boolean;
private ChoosenEntry : entry;

constructor ( private entryservice : entryService){
    this.entryChoosen = false;
}

ngOnInit() : void  {
    this.getData();
}

getData() {
    this.entryservice.getFirstEntrys().then(entrys => this.entrys = entrys);
}

entryClicked(ent: entry){
    this.entryChoosen = true;
    this.ChoosenEntry = ent;
}

leaveEntry () {
    this.entryChoosen = false;
}

voted( upordown : boolean ) {

}
}

Child component:

import { Component, Input, Injectable, OnChanges , SimpleChanges, Output,                    EventEmitter} from '@angular/core';
import { entry} from './Objekte/entry';
import { entryService } from './entry.service';
import { comment } from './Objekte/comments';

@Component({
selector: 'display-entry',
templateUrl: 'app/Html_Templates/displayEntry.template.html'
})

export class displayComponent implements OnChanges{
@Input() public entry : entry;
public comments : comment[];

private changecounter : number;

constructor(private service : entryService) {
    this.changecounter  = 0;
}

ngOnChanges(changes : SimpleChanges){

   this.service.getComments(changes.entry.currentValue.id)
            .then(com => this.comments = com )
            .catch();

    this.entry.viewed++;
    // To implement :: change database
}

votedUp () : void {
    this.entry.votes ++;
    // To implement :: change database
}

votedDown () : void  {
    this.entry.votes --;
    // To implement :: change database
}
}


问:
Networkx dfs_edges not functioning as intended by professor
The expected output from dfs_edges(G, 4) is correct, but it's off by the position of one edges and I can't figure out why

Input:

```<code>G = nx.Graph()
edges = [(1,2),(1,3),(1,5),(2,5),(2,6),(3,4),(3,5),(4,5),(4,6),(4,7),(5,6)]
root = 4
G.add_edges_from(edges)
printGraph(G)
</code>```

Expected Output:

```<code>DFS traversal from from 4 = [(4, 3), (4, 7), (3, 1), (1, 2), (2, 5), (5, 6)]
</code>```

My Code:

```<code>import networkx as nx
def printGraph(G):
    print("DFS traversal from from 4 =", list(nx.dfs_edges(G,4)))
</code>```

Result from code:

```<code>DFS traversal from from 4 = [(4, 3), (3, 1), (1, 2), (2, 5), (5, 6), (4, 7)]
</code>```

The problem is the position of the (4, 7) edge, while I can manually place it where it should be, but that would mean it wouldn't work on the hidden text cases (Moodle)

答:
This is your graph:

In a depth-first search starting at node 4, I would expect node 7 be be visited either first or last, not right after node 3. The output you're getting is valid for dfs_edges. The expected output is what's incorrect.

Body:
The expected output from dfs_edges(G, 4) is correct, but it's off by the position of one edges and I can't figure out why

Input:

G = nx.Graph()
edges = [(1,2),(1,3),(1,5),(2,5),(2,6),(3,4),(3,5),(4,5),(4,6),(4,7),(5,6)]
root = 4
G.add_edges_from(edges)
printGraph(G)

Expected Output:

DFS traversal from from 4 = [(4, 3), (4, 7), (3, 1), (1, 2), (2, 5), (5, 6)]

My Code:

import networkx as nx
def printGraph(G):
    print("DFS traversal from from 4 =", list(nx.dfs_edges(G,4)))

Result from code:

DFS traversal from from 4 = [(4, 3), (3, 1), (1, 2), (2, 5), (5, 6), (4, 7)]

The problem is the position of the (4, 7) edge, while I can manually place it where it should be, but that would mean it wouldn't work on the hidden text cases (Moodle)


问:
JavaScript/DOM - Is there a difference between a "CSS Selector" and an attribute?
Excluding declarative event handlers:

href='#' onclick=<handler> ... />

Is there any material difference between an Attribute and a CSS Selector?  If I provide my own attribute:

href='#' my-data-node-type='1'/>

Is "my-data-node-type" an attribute, a CSS Selector or both?  I think what I'm really asking here is, are the terms "attribute" and "css selector" synonymous?  Or is a "css selector" only an attribute recognized by CSS as eligible for styling?

答:
CSS selectors are not attributes.  They're patterns used to decide which elements to apply styles to in the document.

From the w3c: http://www.w3.org/TR/CSS2/selector.html

"In CSS, pattern matching rules determine which style rules apply to elements in the document tree. These patterns, called selectors, may range from simple element names to rich contextual patterns. If all conditions in the pattern are true for a certain element, the selector matches the element."

In your case, the attribute name "my-data-node-type" may be used as part of a CSS selector to reference your link, but a CSS selector is not an attribute.  Attributes aren't part of CSS, they're the name/value pairs of data you'll find within element tags in HTML and other like markup languages, for example.

```<code><element my-attribute-name="my-attribute-value" />
</code>```

It's not the standard, but the HTML Wikipedia page has a nice plain language description of attributes: http://en.wikipedia.org/wiki/Html

For example, given the HTML:

```<code><div id="foo">
  <a data-node-type="foo" href="bar">Click me!</a>
</div>
</code>```

"data-node-type" and "href" are the attributes of the  tag,

```<code># while:
div#foo a[data-node-type=foo]

# or:
div a[href]

# or simply:
a
</code>```

...are CSS selectors which would target that , with the first two making use of its attributes.

Body:
Excluding declarative event handlers:

<a href='#' onclick=<handler> ... />

Is there any material difference between an Attribute and a CSS Selector?  If I provide my own attribute:

Is "my-data-node-type" an attribute, a CSS Selector or both?  I think what I'm really asking here is, are the terms "attribute" and "css selector" synonymous?  Or is a "css selector" only an attribute recognized by CSS as eligible for styling?

Body:
CSS selectors are not attributes.  They're patterns used to decide which elements to apply styles to in the document.

From the w3c: http://www.w3.org/TR/CSS2/selector.html

"In CSS, pattern matching rules determine which style rules apply to elements in the document tree. These patterns, called selectors, may range from simple element names to rich contextual patterns. If all conditions in the pattern are true for a certain element, the selector matches the element."

In your case, the attribute name "my-data-node-type" may be used as part of a CSS selector to reference your link, but a CSS selector is not an attribute.  Attributes aren't part of CSS, they're the name/value pairs of data you'll find within element tags in HTML and other like markup languages, for example.

<element my-attribute-name="my-attribute-value" />

It's not the standard, but the HTML Wikipedia page has a nice plain language description of attributes: http://en.wikipedia.org/wiki/Html

For example, given the HTML:

<div id="foo">
  <a data-node-type="foo" href="bar">Click me!</a>
</div>

"data-node-type" and "href" are the attributes of the <a> tag,

# while:
div#foo a[data-node-type=foo]

# or:
div a[href]

# or simply:
a

...are CSS selectors which would target that <a>, with the first two making use of its attributes.


问:
gcloud CLI: running bq mk command requires a step using the browser
I am running the following command from a local terminal:

bq mk --transfer_config --target_dataset=mydataset --display_name='mytransfer' --params='{
"data_path": "s3://mys3path/*",
"destination_table_name_template": "mytable",
"file_format": "JSON",
"max_bad_records":"0",
"ignore_unknown_values":"true",
"access_key_id": "myaccessid",
"secret_access_key": "myaccesskey"
}' --data_source=amazon_s3

```
<p>Now, every time I run this, I get the following:</p>
```/opt/google-cloud-sdk/platform/bq/bq.py:41: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses
  import imp
Table '<mytablehere>' successfully created.
/opt/google-cloud-sdk/platform/bq/bq.py:41: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses
  import imp

https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=***********.apps.googleusercontent.com&scope=https://www.googleapis.com/auth/bigquery&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=version_info
Please copy and paste the above URL into your web browser and follow the instructions to retrieve a version_info.
Enter your version_info here:
```

So, every time I run this, I need to open this link, sign-in my account, authorize Google data transfer service to "View and manage your data in Google BigQuery and see the email address for your Google Account" and then copy/paste back to the terminal a string that I get in the browser.

Is there any way to persist the version configuration so that I don't have to perform this step every time?

Thank you in advance

答:
In order to have your Service Account’s credentials to persist within the BigQuery command line tool, so that you can use it after logging out then logging in again, you will need to set the CLOUDSDK_PYTHON_SITEPACKAGES environment variable by running the following command:

export CLOUDSDK_PYTHON_SITEPACKAGES=1

You can then run the following command to see the accounts the tool has credentials for, which should include your Service Account:

gcloud auth list

I hope that the above information would be helpful. If it does not, make sure that you try out the steps followed in the Stackoverflow case.

Make sure to try out the .bigqueryrc solution provided by Michael Sheldon.

Body:
I am running the following command from a local terminal:

bq mk --transfer_config --target_dataset=mydataset --display_name='mytransfer' --params='{
"data_path": "s3://mys3path/*",
"destination_table_name_template": "mytable",
"file_format": "JSON",
"max_bad_records":"0",
"ignore_unknown_values":"true",
"access_key_id": "myaccessid",
"secret_access_key": "myaccesskey"
}' --data_source=amazon_s3

Now, every time I run this, I get the following:

/opt/google-cloud-sdk/platform/bq/bq.py:41: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses
  import imp
Table '<mytablehere>' successfully created.
/opt/google-cloud-sdk/platform/bq/bq.py:41: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses
  import imp

https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=***********.apps.googleusercontent.com&scope=https://www.googleapis.com/auth/bigquery&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=version_info
Please copy and paste the above URL into your web browser and follow the instructions to retrieve a version_info.
Enter your version_info here:

So, every time I run this, I need to open this link, sign-in my account, authorize Google data transfer service to "View and manage your data in Google BigQuery and see the email address for your Google Account" and then copy/paste back to the terminal a string that I get in the browser.

Is there any way to persist the version configuration so that I don't have to perform this step every time?

Thank you in advance


问:
Problems trying to use Project Loom/Virtual Threads with OpenJDK 19-loom JAVA
I'm trying to test the virtual threads reference loom project in Java and I'm using the following JDK 19-loom version:

```<code>  package com;

import java.util.concurrent.ThreadFactory;

    public class a {

        public static void main (String [] args) throws Exception{
            Runnable printThread = () -> System.out.println(Thread.currentThread());

            ThreadFactory virtualThreadFactory = Thread.builder().virtual().factory();
            ThreadFactory kernelThreadFactory = Thread.builder().factory();

            Thread virtualThread = virtualThreadFactory.newThread(printThread);
            Thread kernelThread = kernelThreadFactory.newThread(printThread);

            virtualThread.start();
            kernelThread.start();

        }
    }
</code>```

And I have the following IntelliJ configuration:

But I am having the following error:

And it seems that the builder of the thread is not identified

I would like to know what else do I need?

答:
You are using an outdated example.

With the current state of Loom, your example has to look like

public static void main(String[] args) throws InterruptedException {
    Runnable printThread = () -> System.out.println(Thread.currentThread());

    ThreadFactory virtualThreadFactory = Thread.ofVirtual().factory();
    ThreadFactory kernelThreadFactory = Thread.ofPlatform().factory();

    Thread virtualThread = virtualThreadFactory.newThread(printThread);
    Thread kernelThread = kernelThreadFactory.newThread(printThread);

    virtualThread.start();
    kernelThread.start();

    virtualThread.join();
    kernelThread.join();
}
```
<p>but you can also use the simplified</p>
```public static void main(String[] args) throws InterruptedException {
    Runnable printThread = () -> System.out.println(Thread.currentThread());

    Thread virtualThread = Thread.startVirtualThread(printThread);
    Thread kernelThread = Thread.ofPlatform().start(printThread);

    virtualThread.join();
    kernelThread.join();
}
```

Keep in mind that this is work in progress and documents can become outdated quite fast.

Body:
I'm trying to test the virtual threads reference loom project in Java and I'm using the following JDK 19-loom version:

  package com;

import java.util.concurrent.ThreadFactory;

    public class a {

        public static void main (String [] args) throws Exception{
            Runnable printThread = () -> System.out.println(Thread.currentThread());

            ThreadFactory virtualThreadFactory = Thread.builder().virtual().factory();
            ThreadFactory kernelThreadFactory = Thread.builder().factory();

            Thread virtualThread = virtualThreadFactory.newThread(printThread);
            Thread kernelThread = kernelThreadFactory.newThread(printThread);

            virtualThread.start();
            kernelThread.start();

        }
    }

And I have the following IntelliJ configuration:

But I am having the following error:

And it seems that the builder of the thread is not identified

I would like to know what else do I need?

Body:
You are using an outdated example.

With the current state of Loom, your example has to look like

public static void main(String[] args) throws InterruptedException {
    Runnable printThread = () -> System.out.println(Thread.currentThread());

    ThreadFactory virtualThreadFactory = Thread.ofVirtual().factory();
    ThreadFactory kernelThreadFactory = Thread.ofPlatform().factory();

    Thread virtualThread = virtualThreadFactory.newThread(printThread);
    Thread kernelThread = kernelThreadFactory.newThread(printThread);

    virtualThread.start();
    kernelThread.start();

    virtualThread.join();
    kernelThread.join();
}

but you can also use the simplified

public static void main(String[] args) throws InterruptedException {
    Runnable printThread = () -> System.out.println(Thread.currentThread());

    Thread virtualThread = Thread.startVirtualThread(printThread);
    Thread kernelThread = Thread.ofPlatform().start(printThread);

    virtualThread.join();
    kernelThread.join();
}

Keep in mind that this is work in progress and documents can become outdated quite fast.


问:
OpenGL ES 2.0 PNG alpha channel
I am just learning to work with OpenGL ES 2.0 for Android.  I have been trying to simply display a texture on the middle of the screen, which was easy enough, but I cannot seem to get the PNG alpha to work properly.  The image will either show with a black background, or the entire image will be blended into the background color slightly, depending on the settings I use.

The actual tutorials I have followed to get to this point never worked with transparency, so I have tried to work in code I have found by searching around, and likely have just missed one important step.  I have searched quite a lot to figure this problem out though, and I have not seen any answers that had something my setup does not.  I have tried every combination of glBlendFunc and what not with no luck.

I figured if I tried to paste in all of the code that may be related to this, the question would seem very bloated, so I will be happy to post any bits of code you guys ask for.  I'd greatly appreciate any ideas for what I should try next.

EDIT ::  Here is my fragment shader, which is what I believe to be the cause.  This is the only part that I have never really found a decent example for working with transparency, and everything else matches what I have seen elsewhere.

```<code>        final String fragmentShader =
        "precision mediump float;       \n"
        + "varying vec2 v_Color;          \n"
        + "uniform sampler2D s_baseMap;   \n"
        + "void main()                    \n"
        + "{                              \n"
        + "  vec4 baseColor;              \n"
        + "  baseColor = texture2D( s_baseMap, v_Color );   \n"
        + "   gl_FragColor = baseColor;     \n"
        + "}                              \n";
</code>```

It never does anything with the alpha explicitly, it is from an example that doesn't use it after all, but I still don't know much about fragment shaders and because it seemed to "sort of" work when it blends the image into the background, I figured it was working with the alpha in some form and I just had something set wrong.

EDIT ::  Here is the "loadTexture" method.  It is roughly the same as the example from the openGL ES 2.0 book that I am trying to learn from, with a few alterations that seem to get the image closer to working properly.

```<code>    private int loadTexture ( InputStream is )
{
    int[] textureId = new int[1];
    Bitmap bitmap;
    bitmap = BitmapFactory.decodeStream(is);
    byte[] buffer = new byte[bitmap.getWidth() * bitmap.getHeight() * 4];

    for ( int y = 0; y < bitmap.getHeight(); y++ )
        for ( int x = 0; x < bitmap.getWidth(); x++ )
        {
            int pixel = bitmap.getPixel(x, y);
            buffer[(y * bitmap.getWidth() + x) * 4 + 0] = (byte)((pixel >> 16) & 0xFF);
            buffer[(y * bitmap.getWidth() + x) * 4 + 1] = (byte)((pixel >> 8) & 0xFF);
            buffer[(y * bitmap.getWidth() + x) * 4 + 2] = (byte)((pixel >> 0) & 0xFF);
        }

    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(bitmap.getWidth() * bitmap.getHeight() * 4);
    byteBuffer.put(buffer).position(0);

    GLES20.glGenTextures ( 1, textureId, 0 );
    GLES20.glBindTexture ( GLES20.GL_TEXTURE_2D, textureId[0] );

    GLES20.glTexImage2D ( GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, bitmap.getWidth(), bitmap.getHeight(), 0,
                          GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer );

    GLES20.glTexParameteri ( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR );
    GLES20.glTexParameteri ( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR );
    GLES20.glTexParameteri ( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE );
    GLES20.glTexParameteri ( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE );

    return textureId[0];
}
</code>```

I understand what the code is doing, but admittedly it still confuses me a bit so I may just be missing something obvious due to my lack of knowledge.

I don't see any other parts of my code that seem like they could cause the kind of problems I am having, but programming is always full of the unexpected (Especially in the world of OpenGL it seems) so if you think something else is the cause I'll be sure to post that for you as well.  Sorry for all the trouble!

答:
your initial shader is fine.  alpha is inherent in color ops, it just may not be applied depending on blend/mode/etc.

given that your texture comes out black if you do fragcolor = base.aaa, that implies your texture data is 'bad'.

looking at your texture load, yeah, it's wrong.  you never copy over the alpha, just the rgb.  assuming java clears the byte array to 0s, all alpha will be zero, that would get you your black box, that would cause the image to 'vanish' when you enable alpha blending.

To simplify your life, instead of all the hand copying and stuff, you can simply load the bitmap normally and use the GLUtils helper to upload instead of directly using glTexImage2d:

```<code>  bitmap = BitmapFactory.decodeStream(is);
  GLES20.glGenTextures ( 1, textureId, 0 );
  GLES20.glBindTexture ( GLES20.GL_TEXTURE_2D, textureId[0] );
  GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
</code>```

Something like that.  Then enable blending, use src+invsrc blend mode if not premultiplied, and render, you should get the result desired.

Title: OpenGL ES 2.0 PNG alpha channel

Body:
I am just learning to work with OpenGL ES 2.0 for Android.  I have been trying to simply display a texture on the middle of the screen, which was easy enough, but I cannot seem to get the PNG alpha to work properly.  The image will either show with a black background, or the entire image will be blended into the background color slightly, depending on the settings I use.

The actual tutorials I have followed to get to this point never worked with transparency, so I have tried to work in code I have found by searching around, and likely have just missed one important step.  I have searched quite a lot to figure this problem out though, and I have not seen any answers that had something my setup does not.  I have tried every combination of glBlendFunc and what not with no luck.

I figured if I tried to paste in all of the code that may be related to this, the question would seem very bloated, so I will be happy to post any bits of code you guys ask for.  I'd greatly appreciate any ideas for what I should try next.

EDIT ::  Here is my fragment shader, which is what I believe to be the cause.  This is the only part that I have never really found a decent example for working with transparency, and everything else matches what I have seen elsewhere.

        final String fragmentShader =
        "precision mediump float;       \n"
        + "varying vec2 v_Color;          \n"
        + "uniform sampler2D s_baseMap;   \n"
        + "void main()                    \n"
        + "{                              \n"
        + "  vec4 baseColor;              \n"
        + "  baseColor = texture2D( s_baseMap, v_Color );   \n"
        + "   gl_FragColor = baseColor;     \n"
        + "}                              \n";

It never does anything with the alpha explicitly, it is from an example that doesn't use it after all, but I still don't know much about fragment shaders and because it seemed to "sort of" work when it blends the image into the background, I figured it was working with the alpha in some form and I just had something set wrong.

EDIT ::  Here is the "loadTexture" method.  It is roughly the same as the example from the openGL ES 2.0 book that I am trying to learn from, with a few alterations that seem to get the image closer to working properly.

    private int loadTexture ( InputStream is )
{
    int[] textureId = new int[1];
    Bitmap bitmap;
    bitmap = BitmapFactory.decodeStream(is);
    byte[] buffer = new byte[bitmap.getWidth() * bitmap.getHeight() * 4];

    for ( int y = 0; y < bitmap.getHeight(); y++ )
        for ( int x = 0; x < bitmap.getWidth(); x++ )
        {
            int pixel = bitmap.getPixel(x, y);
            buffer[(y * bitmap.getWidth() + x) * 4 + 0] = (byte)((pixel >> 16) & 0xFF);
            buffer[(y * bitmap.getWidth() + x) * 4 + 1] = (byte)((pixel >> 8) & 0xFF);
            buffer[(y * bitmap.getWidth() + x) * 4 + 2] = (byte)((pixel >> 0) & 0xFF);
        }

    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(bitmap.getWidth() * bitmap.getHeight() * 4);
    byteBuffer.put(buffer).position(0);

    GLES20.glGenTextures ( 1, textureId, 0 );
    GLES20.glBindTexture ( GLES20.GL_TEXTURE_2D, textureId[0] );

    GLES20.glTexImage2D ( GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, bitmap.getWidth(), bitmap.getHeight(), 0,
                          GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer );

    GLES20.glTexParameteri ( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR );
    GLES20.glTexParameteri ( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR );
    GLES20.glTexParameteri ( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE );
    GLES20.glTexParameteri ( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE );

    return textureId[0];
}

I understand what the code is doing, but admittedly it still confuses me a bit so I may just be missing something obvious due to my lack of knowledge.

I don't see any other parts of my code that seem like they could cause the kind of problems I am having, but programming is always full of the unexpected (Especially in the world of OpenGL it seems) so if you think something else is the cause I'll be sure to post that for you as well.  Sorry for all the trouble!

Body:
your initial shader is fine.  alpha is inherent in color ops, it just may not be applied depending on blend/mode/etc.

given that your texture comes out black if you do fragcolor = base.aaa, that implies your texture data is 'bad'.

looking at your texture load, yeah, it's wrong.  you never copy over the alpha, just the rgb.  assuming java clears the byte array to 0s, all alpha will be zero, that would get you your black box, that would cause the image to 'vanish' when you enable alpha blending.

To simplify your life, instead of all the hand copying and stuff, you can simply load the bitmap normally and use the GLUtils helper to upload instead of directly using glTexImage2d:

  bitmap = BitmapFactory.decodeStream(is);
  GLES20.glGenTextures ( 1, textureId, 0 );
  GLES20.glBindTexture ( GLES20.GL_TEXTURE_2D, textureId[0] );
  GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);

Something like that.  Then enable blending, use src+invsrc blend mode if not premultiplied, and render, you should get the result desired.


问:
Visual studio code not showing output, java programming
I'm learning to code Java...
I just installed the Java runtime environment and Visual Studio Code, and wrote this:

```<code>public class IterationDemo

{
    public static void main(String[] args)
    {
        System.out.println('x');
    }
}
</code>```

However, I don't see any output, both under output or terminal. Only kind of a rectangle (▯) under terminal.
I've tried to find a solution googling, stack and so on but no answer yet...
what can I do?
Thanks!

答:
OK; got solved on its own - I ended up clearing the cache and then the output came :)
Thanks myself!</p>

Body:
I'm learning to code Java...
I just installed the Java runtime environment and Visual Studio Code, and wrote this:

public class IterationDemo

{
    public static void main(String[] args)
    {
        System.out.println('x');
    }
}

However, I don't see any output, both under output or terminal. Only kind of a rectangle (▯) under terminal.
I've tried to find a solution googling, stack and so on but no answer yet...
what can I do?
Thanks!


问:
Cannot apply count() or collecr() on RDD from textfile(Spark)
I am new at Spark and I have Databricks Community Edition account. Right now I'm doing Lab and encountered with following error:

!rm README.md* -f
!wget https://raw.githubusercontent.com/carloapp2/SparkPOT/master/README.md

textfile_rdd = sc.textFile("README.md")
textfile_rdd.count()
```
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code>IllegalArgumentException: Path must be absolute: dbfs:/../dbfs/README.md
</code>```

答:
By default, wget will download your file to /databricks/driver
You have to store it in the DataBricks File System (dbfs) in order to be able to read it with the -P option. See wget manual for reference.
It also seems that the !wget magic creates a file that is not available with the dbfs:/ path. On Databricks Community, !wget leads to a file not found as you mentionned.

You can do the following in a %sh cell first:

%sh
rm README.md* -f
wget https://raw.githubusercontent.com/carloapp2/SparkPOT/master/README.md -P /dbfs/downloads/
```
<p>And then in a second python cell, you can access the file throug the Files API (note the path starting with <code>file:/</code></p>
<pre class="lang-py prettyprint-override"><code>textfile_rdd = sc.textFile("file:/dbfs/downloads/README.md")
textfile_rdd.count()
</code>```

--2022-02-11 13:48:19--  https://raw.githubusercontent.com/carloapp2/SparkPOT/master/README.md
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.110.133, 185.199.109.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 3624 (3.5K) [text/plain]
Saving to: ‘/dbfs/FileStore/README.md.1’

README.md.1         100%[===================>]   3.54K  --.-KB/s    in 0.001s

2022-02-11 13:48:19 (4.10 MB/s) - ‘/dbfs/FileStore/README.md.1’ saved [3624/3624]

Out[25]: 98
```

The following solution has been tested on a Databricks Community Edition with a 7.1 LTS ML and a 9.1 LTS ML Databricks Runtime.

Body:
I am new at Spark and I have Databricks Community Edition account. Right now I'm doing Lab and encountered with following error:

!rm README.md* -f
!wget https://raw.githubusercontent.com/carloapp2/SparkPOT/master/README.md

textfile_rdd = sc.textFile("README.md")
textfile_rdd.count()

Output:

IllegalArgumentException: Path must be absolute: dbfs:/../dbfs/README.md

Body:
By default, wget will download your file to /databricks/driver
You have to store it in the DataBricks File System (dbfs) in order to be able to read it with the -P option. See wget manual for reference.
It also seems that the !wget magic creates a file that is not available with the dbfs:/ path. On Databricks Community, !wget leads to a file not found as you mentionned.

You can do the following in a %sh cell first:

%sh
rm README.md* -f
wget https://raw.githubusercontent.com/carloapp2/SparkPOT/master/README.md -P /dbfs/downloads/

And then in a second python cell, you can access the file throug the Files API (note the path starting with file:/

textfile_rdd = sc.textFile("file:/dbfs/downloads/README.md")
textfile_rdd.count()

--2022-02-11 13:48:19--  https://raw.githubusercontent.com/carloapp2/SparkPOT/master/README.md
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.110.133, 185.199.109.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 3624 (3.5K) [text/plain]
Saving to: ‘/dbfs/FileStore/README.md.1’

README.md.1         100%[===================>]   3.54K  --.-KB/s    in 0.001s

2022-02-11 13:48:19 (4.10 MB/s) - ‘/dbfs/FileStore/README.md.1’ saved [3624/3624]

Out[25]: 98

The following solution has been tested on a Databricks Community Edition with a 7.1 LTS ML and a 9.1 LTS ML Databricks Runtime.


问:
How to compare the content of 2 columns in functions on object?
I am trying to build a query to match two columns and I have tried the following:

```<code>obj= obj.filter(e => e.colOne.exactMatch(e.colTwo))
</code>```

I am not be able to get this working, is there any way to filter by comparing the content of 2 columns?

答:
The filter() method can't dynamically grab the value to filter based on each object, but can be used to filter on a static value.

You can filter a smaller object set (<100K rows) named myUnfilteredObjects of type ObjectType this way:

```<code>let myFilteredObjects = new Set<ObjectType>();

for (const unfilteredObj of myUnfilteredObjects) {
    if (unfilteredObj.colOne === unfilteredObj.colTwo) {
        myFilteredObjects.add(unfilteredObj);
    }
}
</code>```

Edit: updating with a solution for larger-scale object sets:

You can create a new boolean column in your object's underlying dataset that is true if colOne and colTwo match, and false otherwise. Filtering on this new column via the filter() method will then work as you expect.

Body:
I am trying to build a query to match two columns and I have tried the following:

obj= obj.filter(e => e.colOne.exactMatch(e.colTwo))

I am not be able to get this working, is there any way to filter by comparing the content of 2 columns?

Body:
The filter() method can't dynamically grab the value to filter based on each object, but can be used to filter on a static value.

You can filter a smaller object set (<100K rows) named myUnfilteredObjects of type ObjectType this way:

let myFilteredObjects = new Set<ObjectType>();

for (const unfilteredObj of myUnfilteredObjects) {
    if (unfilteredObj.colOne === unfilteredObj.colTwo) {
        myFilteredObjects.add(unfilteredObj);
    }
}

Edit: updating with a solution for larger-scale object sets:

You can create a new boolean column in your object's underlying dataset that is true if colOne and colTwo match, and false otherwise. Filtering on this new column via the filter() method will then work as you expect.


问:
Maven update dependencies in POM
Are there any preexisting Maven plugins or commands to update the dependencies in the POM?
Example: (if this was in my POM)

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.3</version>
</dependency>
```

<p>Is there a command or plugin I can run to get it to update the dependency to: </p>

<pre class="lang-xml prettyprint-override"><code><dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.4</version>
</dependency>
</code>```

答:
I had the same kind of problem and finally solved it by writing a bash script.

GitHub repository - Update POM Shell

This is a shell script that allows you to update a dependency on different modules directly from the command line.

It is particularly useful when you need to update one or more dependencies on different modules at once.

Title: Maven update dependencies in POM

Body:
Are there any preexisting Maven plugins or commands to update the dependencies in the POM?
Example: (if this was in my POM)

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.3</version>
</dependency>

Is there a command or plugin I can run to get it to update the dependency to:

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.4</version>
</dependency>


问:
Reading a string of words into for loop from env file
I want to loop through a list of words like so:

words="hello world"
for w in $words; do
    echo $w
done
```

but I want the list of words (words="hello world") to come from a .env file placed in a directory and then reading the env file with export $(grep -v '^#' .env | xargs).

I am able to do the above however, the for loop is only looping through the first word, as if the whitespace in words is stopping the loop. Why is that?

I literally copied the variable from the .sh script into the .env file and it is not working the same way.

答:
An easy solve is to separate words with comma instead of whitespace:

.env file

```<code>words=hello,world
</code>```

script

Then the loop would work:

```<code>export $(grep -v '^#' .env | xargs)

for w in $words; do
    echo $w
done
</code>```

Body:
I want to loop through a list of words like so:

words="hello world"
for w in $words; do
    echo $w
done

but I want the list of words (words="hello world") to come from a .env file placed in a directory and then reading the env file with export $(grep -v '^#' .env | xargs).

I am able to do the above however, the for loop is only looping through the first word, as if the whitespace in words is stopping the loop. Why is that?

I literally copied the variable from the .sh script into the .env file and it is not working the same way.

Body:
An easy solve is to separate words with comma instead of whitespace:

.env file

words=hello,world

script

Then the loop would work:

export $(grep -v '^#' .env | xargs)

for w in $words; do
    echo $w
done


问:
iText7: Adding a PDF inside a Cell (cutoff at end of page)
We are creating a PDF, it contains a large table, with headers (bold), sub-headers (non bold), rows and cells.

One of the requirements is to add an already existing PDF (can be multiple pages) inside the cell (under the sub-header). And this is where we are struggling. What we have tried so far:

Converting the PDF to a FormXObject, and adding that into the cell.

```<code>FontProvider fontProvider = new FontProvider();
ConverterProperties props = new ConverterProperties();
props.SetFontProvider(fontProvider);

var historyId = text.Replace("=Spectec_template", "");

var pdfTemplate = templateToPdfClient.GetPdf(historyId, "HI").Result;
PdfDocument srcDoc = new PdfDocument(new PdfReader(pdfTemplate.FileStream));
for (int i = 1; i < srcDoc.GetNumberOfPages() + 1; i++)
{
    Cell newCell = new Cell(1, columnInfo.ColumnSpan).SetFont(PdfFontFactory.CreateFont(_fontName));
    PdfPage origPage = srcDoc.GetPage(i);

    Rectangle rect = origPage.GetPageSize();
    PdfFormXObject pageCopy = origPage.CopyAsFormXObject(pdf);
    Image image = new Image(pageCopy);
    image.SetBorder(Border.NO_BORDER);
    image.SetMaxWidth(UnitValue.CreatePercentValue(100));
    image.SetMaxHeight(UnitValue.CreatePercentValue(50));

    Div div = new Div();
    div.Add(image.SetMaxWidth(UnitValue.CreatePercentValue(100)));

    newCell.Add(div);
    newCell = ApplyLayoutsToCell(newCell, cellStyles);
    table.AddCell(newCell);
}
</code>```

But the end result is that we only see 1 page and it's completely overlapping at the end of the page.

When we set image.SetAutoScale(true); the PDF is visible but it's extremely small.
When adding the Image to a Paragraph instead of a DIV the PDF pages display next to each other.

Any ideas, suggestions?

Thank you

答:
Thanks to @mkl and @KJ I figured this out.

I ended up adding each PDF page in a new Cell, and setting the scaling of image to 0.6f.

```<code>for (int i = 1; i < srcDoc.GetNumberOfPages() + 1; i++)
{
    newCell = new Cell(1, columnInfo.ColumnSpan).SetFont(PdfFontFactory.CreateFont(_fontName));

    PdfPage origPage = srcDoc.GetPage(i);

    PdfFormXObject pageCopy = origPage.CopyAsFormXObject(pdf);
    Image image = new Image(pageCopy);
    image.SetBorder(Border.NO_BORDER);
    image.Scale(0.6f, 0.6f);

    newCell.Add(image);
    newCell = ApplyLayoutsToCell(newCell, cellStyles);

    table.AddCell(newCell);
}
</code>```

Body:
We are creating a PDF, it contains a large table, with headers (bold), sub-headers (non bold), rows and cells.

One of the requirements is to add an already existing PDF (can be multiple pages) inside the cell (under the sub-header). And this is where we are struggling. What we have tried so far:

Converting the PDF to a FormXObject, and adding that into the cell.

FontProvider fontProvider = new FontProvider();
ConverterProperties props = new ConverterProperties();
props.SetFontProvider(fontProvider);

var historyId = text.Replace("=Spectec_template", "");

var pdfTemplate = templateToPdfClient.GetPdf(historyId, "HI").Result;
PdfDocument srcDoc = new PdfDocument(new PdfReader(pdfTemplate.FileStream));
for (int i = 1; i < srcDoc.GetNumberOfPages() + 1; i++)
{
    Cell newCell = new Cell(1, columnInfo.ColumnSpan).SetFont(PdfFontFactory.CreateFont(_fontName));
    PdfPage origPage = srcDoc.GetPage(i);

    Rectangle rect = origPage.GetPageSize();
    PdfFormXObject pageCopy = origPage.CopyAsFormXObject(pdf);
    Image image = new Image(pageCopy);
    image.SetBorder(Border.NO_BORDER);
    image.SetMaxWidth(UnitValue.CreatePercentValue(100));
    image.SetMaxHeight(UnitValue.CreatePercentValue(50));

    Div div = new Div();
    div.Add(image.SetMaxWidth(UnitValue.CreatePercentValue(100)));

    newCell.Add(div);
    newCell = ApplyLayoutsToCell(newCell, cellStyles);
    table.AddCell(newCell);
}

But the end result is that we only see 1 page and it's completely overlapping at the end of the page.

When we set image.SetAutoScale(true); the PDF is visible but it's extremely small.
When adding the Image to a Paragraph instead of a DIV the PDF pages display next to each other.

Any ideas, suggestions?

Thank you

Body:
Thanks to @mkl and @KJ I figured this out.

I ended up adding each PDF page in a new Cell, and setting the scaling of image to 0.6f.

for (int i = 1; i < srcDoc.GetNumberOfPages() + 1; i++)
{
    newCell = new Cell(1, columnInfo.ColumnSpan).SetFont(PdfFontFactory.CreateFont(_fontName));

    PdfPage origPage = srcDoc.GetPage(i);

    PdfFormXObject pageCopy = origPage.CopyAsFormXObject(pdf);
    Image image = new Image(pageCopy);
    image.SetBorder(Border.NO_BORDER);
    image.Scale(0.6f, 0.6f);

    newCell.Add(image);
    newCell = ApplyLayoutsToCell(newCell, cellStyles);

    table.AddCell(newCell);
}


问:
Converting existing site to React JS (Adding ReactJS to existing webpage)
I am kinda new to front web development, but there is one interesting question for me.

I got a simple vanila html+css+js website, in which I want to integrate a few actions (profile page, custom e-commerce, checkout, etc) using React.

As I followed this tutorial (Add React in One Minute),
I had successfully "inserted" react component into the webpage. But the normal reactjs applications are able to use installed libraries, use props to pass data.

So, basically, the question is how to run this webpage the way that react will be able to handle libraries installation (common npm i example) in order to be able to import them and work like with normal react application created by npx create-react-app my-app

答:
You could use libraries via a CDN link, the same way you added React via a script-tag to your site. Ultimately i think you're looking for the developer experience one gets while using JSX-syntax and this would require you to rewrite your exitsing app, achieved trough setting up a node project with your mentioned command npx create-react-app <app-name>.

JSX must be compiled to regular JavaScript so that browsers can interpret them correctly, much like you would compile a C++ program to a binary file.


问:
Filtering data with selections and checkboxes in Flexdashboard
In a flexdashboard, I want to allow a selection by having selectInput() combined with a checkboxGroupInput(). But the data is not updated correctly and I cannot figure out what is wrong.

I used the toy example from this SO-example [LINK] and included a checkbox. It seems that the Checkbox is still ignored and messes up the other parts of the code.

It would be great if someone could adjust the code so that selection can be based on one of the three columns Team, Name or Year.

```<code>---
title: "example"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
    runtime: shiny
---

```{r setup, include=FALSE}
library(DT)
library(shiny)

users <- data.frame(
  Name = c("Allan A","Barbara B","Charles C","Darwin D","Evelyn E","Frank F","Greg G","Hans H"),
  Team = c(1,2,3,3,2,1,2,2),
  Year = c(1999,1999,1999,2000,2000,2000,2003,2003),
  stringsAsFactors = FALSE)
```

Inputs {.sidebar}
=======================================================================
### Input Variables

```{r global_input}

### selection Input based on columns Team and Name
selectInput("teaminput","Team",c("All", unique(users$Team)), selected="All")
selectInput("userinput","User Name", c("All", unique(users$Name) ), selected="All")

### Add Input from CheckboxGroup based on Year starting with all
checkboxGroupInput("yearinput", label = "Year",choices =  unique(users$Year), selected=unique(users$Year), inline = TRUE)

### Filter Team based on one of the three choices (Team, Name, Year)
teamFiltered <- reactive(users[input$teaminput=="All" |
                                 users$Team==input$teaminput |
                                 users$Year ==input$yearinput,])

### Observe if userinput changes based on SELECTION
observe(updateSelectInput(session,"userinput",
                          choices = c( unique(teamFiltered()$Name)),
                          selected="All"))

### Observe if yearinput changes based on CHECK BOX
observe(updateCheckboxGroupInput(session,"yearinput",
                                  choices =  teamFiltered()$Year,
                                  selected="All"))

```

Results
=======================================================================
### Intake Coordinator KPIs

```{r daily_table}
userFiltered <- reactive(teamFiltered()[input$userinput=="All" |
                         teamFiltered()$Name==input$userinput |
                         teamFiltered()$Year==input$yearinput,])

renderDataTable(userFiltered())
```
</code>```

答:
Try this

```<code>library(DT)
library(shiny)

users <- data.frame(
  Name = c("Allan A","Barbara B","Charles C","Darwin D","Evelyn E","Frank F","Greg G","Hans H"),
  Team = c(1,2,3,3,2,1,2,2),
  Year = c(1999,1999,1999,2000,2000,2000,2003,2003),
  stringsAsFactors = FALSE)

ui <- fluidPage(

### selection Input based on columns Team and Name
selectInput("teaminput","Team",c("All", unique(users$Team)), selected= "All", multiple = TRUE),
selectInput("userinput","User Name", c("All", unique(users$Name) ), selected="All", multiple = TRUE),

### Add Input from CheckboxGroup based on Year starting with all
checkboxGroupInput("yearinput", label = "Year",choices =  unique(users$Year), selected=unique(users$Year), inline = TRUE),
DTOutput("t1")

)

server <- function(input, output, session) {
### Filter Team based on one of the three choices (Team, Name, Year)
teamFiltered <- reactive(users["All" %in% input$teaminput |
                                 users$Team %in% input$teaminput,])

### Observe if userinput changes based on SELECTION
observeEvent(c(input$yearinput,input$teaminput), {
  updateSelectInput(session,"userinput", choices = c( unique(teamFiltered()$Name)), selected=unique(teamFiltered()$Name)
                    )
  })

### Observe if yearinput changes based on CHECK BOX
observeEvent(c(input$userinput,input$teaminput), {
  updateCheckboxGroupInput(session,"yearinput", choices =  unique(teamFiltered()$Year),
                                 selected=unique(teamFiltered()$Year))
  })

  ### Intake Coordinator KPIs

userFiltered <- reactive(teamFiltered()[ "All" %in% input$userinput |
                                          teamFiltered()$Name %in% input$userinput &
                                          teamFiltered()$Year %in% input$yearinput,])

output$t1 <- renderDT(userFiltered())

}

shinyApp(ui, server)
</code>```

Body:
In a flexdashboard, I want to allow a selection by having selectInput() combined with a checkboxGroupInput(). But the data is not updated correctly and I cannot figure out what is wrong.

I used the toy example from this SO-example [LINK] and included a checkbox. It seems that the Checkbox is still ignored and messes up the other parts of the code.

It would be great if someone could adjust the code so that selection can be based on one of the three columns Team, Name or Year.

---
title: "example"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
    runtime: shiny
---

```{r setup, include=FALSE}
library(DT)
library(shiny)

users <- data.frame(
  Name = c("Allan A","Barbara B","Charles C","Darwin D","Evelyn E","Frank F","Greg G","Hans H"),
  Team = c(1,2,3,3,2,1,2,2),
  Year = c(1999,1999,1999,2000,2000,2000,2003,2003),
  stringsAsFactors = FALSE)
```

Inputs {.sidebar}
=======================================================================
### Input Variables

```{r global_input}

### selection Input based on columns Team and Name
selectInput("teaminput","Team",c("All", unique(users$Team)), selected="All")
selectInput("userinput","User Name", c("All", unique(users$Name) ), selected="All")

### Add Input from CheckboxGroup based on Year starting with all
checkboxGroupInput("yearinput", label = "Year",choices =  unique(users$Year), selected=unique(users$Year), inline = TRUE)

### Filter Team based on one of the three choices (Team, Name, Year)
teamFiltered <- reactive(users[input$teaminput=="All" |
                                 users$Team==input$teaminput |
                                 users$Year ==input$yearinput,])

### Observe if userinput changes based on SELECTION
observe(updateSelectInput(session,"userinput",
                          choices = c( unique(teamFiltered()$Name)),
                          selected="All"))

### Observe if yearinput changes based on CHECK BOX
observe(updateCheckboxGroupInput(session,"yearinput",
                                  choices =  teamFiltered()$Year,
                                  selected="All"))

```

Results
=======================================================================
### Intake Coordinator KPIs

```{r daily_table}
userFiltered <- reactive(teamFiltered()[input$userinput=="All" |
                         teamFiltered()$Name==input$userinput |
                         teamFiltered()$Year==input$yearinput,])

renderDataTable(userFiltered())
```

Body:
Try this

library(DT)
library(shiny)

users <- data.frame(
  Name = c("Allan A","Barbara B","Charles C","Darwin D","Evelyn E","Frank F","Greg G","Hans H"),
  Team = c(1,2,3,3,2,1,2,2),
  Year = c(1999,1999,1999,2000,2000,2000,2003,2003),
  stringsAsFactors = FALSE)

ui <- fluidPage(

### selection Input based on columns Team and Name
selectInput("teaminput","Team",c("All", unique(users$Team)), selected= "All", multiple = TRUE),
selectInput("userinput","User Name", c("All", unique(users$Name) ), selected="All", multiple = TRUE),

### Add Input from CheckboxGroup based on Year starting with all
checkboxGroupInput("yearinput", label = "Year",choices =  unique(users$Year), selected=unique(users$Year), inline = TRUE),
DTOutput("t1")

)

server <- function(input, output, session) {
### Filter Team based on one of the three choices (Team, Name, Year)
teamFiltered <- reactive(users["All" %in% input$teaminput |
                                 users$Team %in% input$teaminput,])

### Observe if userinput changes based on SELECTION
observeEvent(c(input$yearinput,input$teaminput), {
  updateSelectInput(session,"userinput", choices = c( unique(teamFiltered()$Name)), selected=unique(teamFiltered()$Name)
                    )
  })

### Observe if yearinput changes based on CHECK BOX
observeEvent(c(input$userinput,input$teaminput), {
  updateCheckboxGroupInput(session,"yearinput", choices =  unique(teamFiltered()$Year),
                                 selected=unique(teamFiltered()$Year))
  })

  ### Intake Coordinator KPIs

userFiltered <- reactive(teamFiltered()[ "All" %in% input$userinput |
                                          teamFiltered()$Name %in% input$userinput &
                                          teamFiltered()$Year %in% input$yearinput,])

output$t1 <- renderDT(userFiltered())

}

shinyApp(ui, server)


问:
WindowChrome/title bar theme not syncing with loaded PresentationFramework/XAML
I'm attempting to build a WPF app which uses the Royale theme from XP Media Center. I've correctly referenced the PresentationFramework.Royale DLL and the corresponding XAML resources into my App.xaml, and can confirm that the controls are very much Royale-themed:

However, the window itself fails to be, and the WindowChrome/title bar/window border theme fails to sync up, remaining the standard presentation style for Windows 10. This, of course, is what I'm trying to replicate, at least visually:

Relevant XAML, if useful (all *.cs files are default):

App.xaml:

```<code><Application x:Class="ExampleRoyale.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Ariadne"
    StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/PresentationFramework.Royale;component/themes/Royale.NormalColor.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
</code>```

MainWindow.xaml:

```<code><Window x:Class="ExampleRoyale.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ExampleRoyale"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" Margin="94,39,0,0" VerticalAlignment="Top" Width="120"/>
        <ComboBox HorizontalAlignment="Left" Margin="94,12,0,0" VerticalAlignment="Top" Width="120"/>
        <Label Content="Label" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="79"/>
        <Label Content="Label 2" HorizontalAlignment="Left" Margin="10,39,0,0" VerticalAlignment="Top" Width="79"/>
        <RadioButton Content="RadioButton" HorizontalAlignment="Left" Margin="228,15,0,0" VerticalAlignment="Top" Width="102"/>
        <RadioButton Content="RadioButton 2" HorizontalAlignment="Left" Margin="228,44,0,0" VerticalAlignment="Top" Width="102"/>
        <TabControl Margin="82,72,82,71">
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>
</code>```

Is there a manner to apply the Royale theme to the window container itself, or is Royale controls the closest I will get?

答:
Is there a manner to apply the Royale theme to the window container itself

Unfortunately (?) the window container itself is not part of WPF so there is no custom style for it. It's part of the operating system.

You may be able to make Windows 10 look like Vista by changing the OS settings as a user (I haven't tried) but this is not related to WPF.

Body:
I'm attempting to build a WPF app which uses the Royale theme from XP Media Center. I've correctly referenced the PresentationFramework.Royale DLL and the corresponding XAML resources into my App.xaml, and can confirm that the controls are very much Royale-themed:

However, the window itself fails to be, and the WindowChrome/title bar/window border theme fails to sync up, remaining the standard presentation style for Windows 10. This, of course, is what I'm trying to replicate, at least visually:

Relevant XAML, if useful (all *.cs files are default):

App.xaml:

<Application x:Class="ExampleRoyale.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Ariadne"
    StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/PresentationFramework.Royale;component/themes/Royale.NormalColor.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

MainWindow.xaml:

<Window x:Class="ExampleRoyale.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ExampleRoyale"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" Margin="94,39,0,0" VerticalAlignment="Top" Width="120"/>
        <ComboBox HorizontalAlignment="Left" Margin="94,12,0,0" VerticalAlignment="Top" Width="120"/>

        <RadioButton Content="RadioButton" HorizontalAlignment="Left" Margin="228,15,0,0" VerticalAlignment="Top" Width="102"/>
        <RadioButton Content="RadioButton 2" HorizontalAlignment="Left" Margin="228,44,0,0" VerticalAlignment="Top" Width="102"/>
        <TabControl Margin="82,72,82,71">
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

Is there a manner to apply the Royale theme to the window container itself, or is Royale controls the closest I will get?


问:
Template Specialization VS Function Overloading
A textbook I have notes that you can provide your own implementation for standard library functions like swap(x,y) via template specialization or function overloading.  This would be useful for any types which can benefit from something other than an assignment swap, like STL containers for example (which already have swaps written, I know).

My questions are the following:

What's better: template specialization to give your specialized
swap implementation, or function overloading providing the exact
parameters you wish to use without a template?

Why is it better? Or if they're equal, why is this?

答:
Short story: overload when you can, specialise when you need to.

Long story: C++ treats specialisation and overloads very differently. This is best explained with an example.

```<code>template <typename T> void foo(T);
template <typename T> void foo(T*); // overload of foo(T)
template <>           void foo<int>(int*); // specialisation of foo(T*)

foo(new int); // calls foo<int>(int*);
</code>```

Now let's swap the last two.

```<code>template <typename T> void foo(T);
template <>           void foo<int*>(int*); // specialisation of foo(T)
template <typename T> void foo(T*); // overload of foo(T)

foo(new int); // calls foo(T*) !!!
</code>```

The compiler does overload resolution before it even looks at specialisations. So, in both cases, overload resolution chooses foo(T*). However, only in the first case does it find foo<int*>(int*) because in the second case the int* specialisation is a specialisation of foo(T), not foo(T*).

You mentioned std::swap. This makes things even more complicated.

The standard says that you can add specialisations to the std namespace. Great, so you have some Foo type and it has a performant swap then you just specialise swap(Foo&, Foo&) in the std namespace. No problems.

But what if Foo is a template class? C++ doesn't have partial specialisation of functions, so you can't specialise swap. Your only choice is overloading, but the standard says that you aren't allowed to add overloads into the std namespace!

You have two options at this point:

Create a swap(Foo<T>&, Foo<T>&) function in your own namespace, and hope that it gets found via ADL. I say "hope" because if the standard library calls swap like std::swap(a, b); then ADL simply won't work.

Ignore the part of the standard that says not to add overloads and do it anyway. Honestly, even though it's technically not allowed, in all realistic scenarios it's going to work.

One thing to remember though is that there's no guarantee that the standard library uses swap at all. Most algorithms use std::iter_swap and in some implementations that I've looked at, it doesn't always forward to std::swap.

Body:
Short story: overload when you can, specialise when you need to.

Long story: C++ treats specialisation and overloads very differently. This is best explained with an example.

template <typename T> void foo(T);
template <typename T> void foo(T*); // overload of foo(T)
template <>           void foo<int>(int*); // specialisation of foo(T*)

foo(new int); // calls foo<int>(int*);

Now let's swap the last two.

template <typename T> void foo(T);
template <>           void foo<int*>(int*); // specialisation of foo(T)
template <typename T> void foo(T*); // overload of foo(T)

foo(new int); // calls foo(T*) !!!

The compiler does overload resolution before it even looks at specialisations. So, in both cases, overload resolution chooses foo(T*). However, only in the first case does it find foo<int*>(int*) because in the second case the int* specialisation is a specialisation of foo(T), not foo(T*).

You mentioned std::swap. This makes things even more complicated.

The standard says that you can add specialisations to the std namespace. Great, so you have some Foo type and it has a performant swap then you just specialise swap(Foo&, Foo&) in the std namespace. No problems.

But what if Foo is a template class? C++ doesn't have partial specialisation of functions, so you can't specialise swap. Your only choice is overloading, but the standard says that you aren't allowed to add overloads into the std namespace!

You have two options at this point:

Create a swap(Foo<T>&, Foo<T>&) function in your own namespace, and hope that it gets found via ADL. I say "hope" because if the standard library calls swap like std::swap(a, b); then ADL simply won't work.

Ignore the part of the standard that says not to add overloads and do it anyway. Honestly, even though it's technically not allowed, in all realistic scenarios it's going to work.

One thing to remember though is that there's no guarantee that the standard library uses swap at all. Most algorithms use std::iter_swap and in some implementations that I've looked at, it doesn't always forward to std::swap.


问:
Unrecognized selector sent to instance 0x7fecc7011000" In Swift
I cannot figure it out why this error is happening  unrecognized selector sent to instance 0x7fecc7011000" . I added the all the necessary code but cannot find which selector actually is messing .

Screenshot of the project structure with  story board .

The network Manager code .

```<code>class NetworkManager {

    func getCoins(from url: String, completion: @escaping (Result<VanueResponse, NetworkError>) -> Void ) {

        guard let url = URL(string: url) else {
            completion(.failure(.badURL))
            return
        }

        URLSession.shared.dataTask(with: url) { data, response, error in

            if let error = error {
                completion(.failure(.other(error)))
                return
            }

            if let data = data {
                //decode
                do {
                    let response = try JSONDecoder().decode(VanueResponse.self, from: data)
                    completion(.success(response))
                } catch let error {
                    completion(.failure(.other(error)))
                }
            }
        }
        .resume()
    }

}
</code>```

Presenter  code ..

```<code>class VenuePresenter : VanueProtocol{

    // creating instance of the class
    private let view : VanueViewProtocol
    private let networkManager: NetworkManager
    private var vanues = [Venue]()
    var rows: Int{
        return vanues.count
    }
    // initilanize the class
    init(view:VanueViewProtocol , networkmanager:NetworkManager = NetworkManager()){
        self.view = view
        self.networkManager = networkmanager
    }

    func getVanue(){

        let url  = "https://coinmap.org/api/v1/venues/"

        networkManager.getCoins(from: url) { result in

            switch result {
            case.success(let respone):
                self.vanues = respone.results
                DispatchQueue.main.async {
                    self.view.resfreshTableView()
                }
            case .failure(let error):
                DispatchQueue.main.async {
                    self.view.displayError(error.localizedDescription)
                    print(Thread.callStackSymbols)
                }
            }

        }
    }

    func getId(by row: Int) -> Int {
        return vanues[row].id
    }

    func getLat(by row: Int) -> Double {
        return vanues[row].lat
    }

    func getCreated(by row: Int) -> Int {
        return vanues[row].createdOn
    }

    func getLon(by row: Int) -> Double? {
        return vanues[row].lon
    }

}
</code>```

Protocol code ..

```<code>import Foundation

protocol VanueProtocol {
    func getVanue()
    func getId(by row: Int) -> Int
    func getLat(by row: Int) -> Double
    func getLon(by row: Int) -> Double?
    func getCreated(by row: Int) -> Int
    var rows: Int { get }
}

protocol VanueViewProtocol {
    func resfreshTableView()
   func displayError(_ message: String)
}
</code>```

Here is the code in view controller .

```<code>class ViewController: UIViewController{

    private var presenter : VenuePresenter!
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self
        presenter = VenuePresenter(view: self)
        presenter.getVanue()

    }

}

extension ViewController : VanueViewProtocol{
    func resfreshTableView() {
        tableView.reloadData()

    }
       func displayError(_ message: String) {
            let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
            let doneButton = UIAlertAction(title: "Done", style: .default, handler: nil)
            alert.addAction(doneButton)
            present(alert, animated: true, completion: nil)
        }
    }
extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        presenter.rows
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        guard let cell = tableView.dequeueReusableCell(withIdentifier: DisplayView.identifier, for: indexPath) as? DisplayView
          else { return UITableViewCell() }

        let row = indexPath.row
        let id   = presenter.getId(by: row)
        let lat = presenter.getLat(by: row)
         guard let lon = presenter.getLon(by: row) else { return UITableViewCell() }
        let createdon = presenter.getCreated(by: row)
        cell.configureCell(id: id, lat: lat, lon: lon, createdon: createdon)
        return cell
    }
}
extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
}

</code>```

Here is the code in custom view controller named is display view .

```<code>import UIKit

class DisplayView: UITableViewCell{

    static let identifier = "DisplayView"

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!
    @IBOutlet weak var label4: UILabel!

    func configureCell(id: Int ,lat : Double , lon : Double , createdon: Int){
        label1.text = String(id)
        label2.text = String(lat)
        label3.text = String(lon)
        label4.text = String(createdon)

    }

}

</code>```

Here is my model .

```<code>struct Coin: Codable {
    let venues: [Venue]
}

// MARK: - Venue
struct Venue: Codable {
    let id: Int
    let lat, lon: Double
    let category, name: String
    let createdOn: Int
    let geolocationDegrees: String

    enum CodingKeys: String, CodingKey {
        case id, lat, lon, category, name
        case createdOn = "created_on"
        case geolocationDegrees = "geolocation_degrees"
    }
}
</code>```

I added the break point but it retuning nil and it needs to return the data from API . Here is the API link .https://coinmap.org/api/v1/venues/

Here is the screenshot of the error .

Here is the console window .

答:
The problem is this outlet:

```<code>IBOutlet weak var tableView: UITableView!
</code>```

You have hooked it up in the storyboard to the wrong object. It is hooked to the cell, not the table view. It looks like you must have hooked it up and then changed the class of the thing it is hooked to.

Body:
I cannot figure it out why this error is happening  unrecognized selector sent to instance 0x7fecc7011000" . I added the all the necessary code but cannot find which selector actually is messing .

Screenshot of the project structure with  story board .

The network Manager code .

class NetworkManager {

    func getCoins(from url: String, completion: @escaping (Result<VanueResponse, NetworkError>) -> Void ) {

        guard let url = URL(string: url) else {
            completion(.failure(.badURL))
            return
        }

        URLSession.shared.dataTask(with: url) { data, response, error in

            if let error = error {
                completion(.failure(.other(error)))
                return
            }

            if let data = data {
                //decode
                do {
                    let response = try JSONDecoder().decode(VanueResponse.self, from: data)
                    completion(.success(response))
                } catch let error {
                    completion(.failure(.other(error)))
                }
            }
        }
        .resume()
    }

}

Presenter  code ..

class VenuePresenter : VanueProtocol{

    // creating instance of the class
    private let view : VanueViewProtocol
    private let networkManager: NetworkManager
    private var vanues = [Venue]()
    var rows: Int{
        return vanues.count
    }
    // initilanize the class
    init(view:VanueViewProtocol , networkmanager:NetworkManager = NetworkManager()){
        self.view = view
        self.networkManager = networkmanager
    }

    func getVanue(){

        let url  = "https://coinmap.org/api/v1/venues/"

        networkManager.getCoins(from: url) { result in

            switch result {
            case.success(let respone):
                self.vanues = respone.results
                DispatchQueue.main.async {
                    self.view.resfreshTableView()
                }
            case .failure(let error):
                DispatchQueue.main.async {
                    self.view.displayError(error.localizedDescription)
                    print(Thread.callStackSymbols)
                }
            }

        }
    }

    func getId(by row: Int) -> Int {
        return vanues[row].id
    }

    func getLat(by row: Int) -> Double {
        return vanues[row].lat
    }

    func getCreated(by row: Int) -> Int {
        return vanues[row].createdOn
    }

    func getLon(by row: Int) -> Double? {
        return vanues[row].lon
    }

}

Protocol code ..

import Foundation

protocol VanueProtocol {
    func getVanue()
    func getId(by row: Int) -> Int
    func getLat(by row: Int) -> Double
    func getLon(by row: Int) -> Double?
    func getCreated(by row: Int) -> Int
    var rows: Int { get }
}

protocol VanueViewProtocol {
    func resfreshTableView()
   func displayError(_ message: String)
}

Here is the code in view controller .

class ViewController: UIViewController{

    private var presenter : VenuePresenter!
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self
        presenter = VenuePresenter(view: self)
        presenter.getVanue()

    }

}

extension ViewController : VanueViewProtocol{
    func resfreshTableView() {
        tableView.reloadData()

    }
       func displayError(_ message: String) {
            let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
            let doneButton = UIAlertAction(title: "Done", style: .default, handler: nil)
            alert.addAction(doneButton)
            present(alert, animated: true, completion: nil)
        }
    }
extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        presenter.rows
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        guard let cell = tableView.dequeueReusableCell(withIdentifier: DisplayView.identifier, for: indexPath) as? DisplayView
          else { return UITableViewCell() }

        let row = indexPath.row
        let id   = presenter.getId(by: row)
        let lat = presenter.getLat(by: row)
         guard let lon = presenter.getLon(by: row) else { return UITableViewCell() }
        let createdon = presenter.getCreated(by: row)
        cell.configureCell(id: id, lat: lat, lon: lon, createdon: createdon)
        return cell
    }
}
extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
}

Here is the code in custom view controller named is display view .

import UIKit

class DisplayView: UITableViewCell{

    static let identifier = "DisplayView"

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!
    @IBOutlet weak var label4: UILabel!

    func configureCell(id: Int ,lat : Double , lon : Double , createdon: Int){
        label1.text = String(id)
        label2.text = String(lat)
        label3.text = String(lon)
        label4.text = String(createdon)

    }

}

Here is my model .

struct Coin: Codable {
    let venues: [Venue]
}

// MARK: - Venue
struct Venue: Codable {
    let id: Int
    let lat, lon: Double
    let category, name: String
    let createdOn: Int
    let geolocationDegrees: String

    enum CodingKeys: String, CodingKey {
        case id, lat, lon, category, name
        case createdOn = "created_on"
        case geolocationDegrees = "geolocation_degrees"
    }
}

I added the break point but it retuning nil and it needs to return the data from API . Here is the API link .https://coinmap.org/api/v1/venues/

Here is the screenshot of the error .

Here is the console window .

Body:
The problem is this outlet:

IBOutlet weak var tableView: UITableView!

You have hooked it up in the storyboard to the wrong object. It is hooked to the cell, not the table view. It looks like you must have hooked it up and then changed the class of the thing it is hooked to.


问:
DevExtrem Angular - DataGrid - How to use raw template with server side data processing
I am integrating the DevExtrem datagrid with Angular and Server side processing : https://js.devexpress.com/Documentation/Guide/Data_Binding/Specify_a_Data_Source/Custom_Data_Sources/

I would like to know if it is possible de have a custom raw template with server side processing ?
The API will return an object "Currency" -> {"Symbol","Code"} but the actual data source display "Object" in the raw, so I need to tell to the datagrid to display in the row currency.code .

答:
You can do it by using dxTemplate =</p>
```<code><dx-data-grid
                [dataSource]="customDataSource"
                dataRowTemplate="dataRowTemplateName"
            >
                <ng-container *dxTemplate="let test of 'dataRowTemplateName'">
                    <tr class="main-row">
                        <td>{{ test.data.id }}</td>
                        <td>{{ test.data.base_price }}</td>
                    </tr>
                </ng-container>
</code>```

Body:
You can do it by using dxTemplate =

<dx-data-grid
                [dataSource]="customDataSource"
                dataRowTemplate="dataRowTemplateName"
            >
                <ng-container *dxTemplate="let test of 'dataRowTemplateName'">
                    <tr class="main-row">
                        <td>{{ test.data.id }}</td>
                        <td>{{ test.data.base_price }}</td>
                    </tr>
                </ng-container>


问:
Serializing lambdas and functions with dill. Is there a better (faster) way?
Im writing a aio scrapper called scrubber upon lxml, httpx and asyncio. From beginning I wanted to outsource the cpu bounded parsing duty to a separate process.
After failing several times, learning about pickle and other issues concerning multiprocessing, I now found a way to let the process consume all that work. And Im a little proud of this solution also.

But it turns out, that the serialization I need is "terrible" slow, and at the end im not sure if this will have any advantage (I know - everybody warned me that serialization for mp could be a show stopper)
One of the problems is now of course the serialization with dill. dill package is needed because of serialization of lambdas. This I need to keep the namespace clear and give s smart and easy to use interface.

The test Ive done looks like this

```<code>import pickle
import dill
import timeit

# emulates the lambda a bit
def serialize_me(x):
    return 42 + x

p_t = timeit.timeit("pickle.dumps(serialize_me)",globals=globals(),number=10_000)
d_t = timeit.timeit("dill.dumps(serialize_me)",globals=globals(),number=10_000)
dl_t = timeit.timeit("dill.dumps(lambda x: 42)", globals=globals(), number=10_000)

dumped_p = pickle.dumps(serialize_me)
dumped_d = dill.dumps(serialize_me)
dumped_dl = dill.dumps(lambda x: 42)

ls_p = timeit.timeit("pickle.loads(dumped_p)", globals=globals(), number=10_000)
ls_d = timeit.timeit("dill.loads(dumped_d)", globals=globals(), number=10_000)
ls_dl = timeit.timeit("dill.loads(dumped_dl)", globals=globals(), number=10_000)

print("--serialize a function--")
print("pickle: ",p_t)
print("dill: ", d_t)
print("dill pure lambda: ", dl_t)
print("relative p/d: ", str(d_t/p_t))

print("--Compose that function--")
print("pickle: ", ls_p)
print("dill: ", ls_d)
print("dill lambda: ", ls_dl)

</code>```

Resulting to

```<code>--serialize a function--
pickle:  0.018466599998646416
dill:  5.7938681000014185
dill pure lambda:  5.5841117999989365
relative p/d:  313.7485027252501
--Compose that function--
pickle:  0.017203299998072907
dill:  0.19668400000227848
dill lambda:  0.1924564000000828

</code>```

Now, under real condition using pytest-benchmark the gap is not that big and lays 3-10 times slower but will not scale better than this.

But still far away from what one could await?
Yes I read this Why is dill slow? and yes this was clear from the beginning, thats why I avoided dill, but at the very end the lambdas kicked in and become very useful.

Now the question is if I should kick that and hope, that parsing will not hang the event loop, dive down to realms of python to write a pickler for lambdas or what else?

Meanwhile Im using the `asyncio.run_in_executor` and removed the producer/consumer design.

I also found a solution to serialize lambdas but did not find a way to register it at pickle.

I will update this post as soon as I have it ready on github.

Possible Answer

I made a small package. Available through github at the moment only.
This package works like a proxy using pythons marshall serializer.
It is about 100 times faster than using dill for this isolated case.

https://github.com/cloasdata/lambdser

pip install lambdser

答:
I'm the dill author.  Writing a new "python" serializer isn't the answer.  In fact, when you compare dill to python's pickle, the speed is roughly the same.

As you can see, they are about the same:

```<code>Python 3.9.10 (main, Jan 15 2022, 12:09:07)
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> import dill
>>> import timeit
>>>
>>> def doit(x): return x
...
>>> timeit.timeit("dill.dumps(doit)", globals=globals(), number=10000)
1.315841937000016
>>> timeit.timeit("pickle._dumps(doit)", globals=globals(), number=10000)
1.1476000689999637
</code>```

You'll note that I've used pickle._dumps which uses the python-based pickler.  In recent versions of python, pickle uses a C-based pickler by default (formerly known as cPickle)... and it's roughly 100x faster, as you experienced.

```<code>>>> timeit.timeit("pickle.dumps(doit)", globals=globals(), number=10000)
0.01674603300000399
</code>```

So, you'll need to write a C-based pickler to compete with the speed of pickle.  That also means, that all of the registered pickling solutions need to be written in C as well, if you want roughly the same speed-up.  And then, you'll need to modify/fork multiprocessing to use your new serializer instead of pickle.

There is currently an effort in dill (and other serializers like cloudpickle) to better leverage the C pickling interface.  If you'd like to contribute to either, you are more than welcome to do so.

Body:
Im writing a aio scrapper called scrubber upon lxml, httpx and asyncio. From beginning I wanted to outsource the cpu bounded parsing duty to a separate process.
After failing several times, learning about pickle and other issues concerning multiprocessing, I now found a way to let the process consume all that work. And Im a little proud of this solution also.

But it turns out, that the serialization I need is "terrible" slow, and at the end im not sure if this will have any advantage (I know - everybody warned me that serialization for mp could be a show stopper)
One of the problems is now of course the serialization with dill. dill package is needed because of serialization of lambdas. This I need to keep the namespace clear and give s smart and easy to use interface.

The test Ive done looks like this

import pickle
import dill
import timeit

# emulates the lambda a bit
def serialize_me(x):
    return 42 + x

p_t = timeit.timeit("pickle.dumps(serialize_me)",globals=globals(),number=10_000)
d_t = timeit.timeit("dill.dumps(serialize_me)",globals=globals(),number=10_000)
dl_t = timeit.timeit("dill.dumps(lambda x: 42)", globals=globals(), number=10_000)

dumped_p = pickle.dumps(serialize_me)
dumped_d = dill.dumps(serialize_me)
dumped_dl = dill.dumps(lambda x: 42)

ls_p = timeit.timeit("pickle.loads(dumped_p)", globals=globals(), number=10_000)
ls_d = timeit.timeit("dill.loads(dumped_d)", globals=globals(), number=10_000)
ls_dl = timeit.timeit("dill.loads(dumped_dl)", globals=globals(), number=10_000)

print("--serialize a function--")
print("pickle: ",p_t)
print("dill: ", d_t)
print("dill pure lambda: ", dl_t)
print("relative p/d: ", str(d_t/p_t))

print("--Compose that function--")
print("pickle: ", ls_p)
print("dill: ", ls_d)
print("dill lambda: ", ls_dl)

Resulting to

--serialize a function--
pickle:  0.018466599998646416
dill:  5.7938681000014185
dill pure lambda:  5.5841117999989365
relative p/d:  313.7485027252501
--Compose that function--
pickle:  0.017203299998072907
dill:  0.19668400000227848
dill lambda:  0.1924564000000828

Now, under real condition using pytest-benchmark the gap is not that big and lays 3-10 times slower but will not scale better than this.

But still far away from what one could await?
Yes I read this Why is dill slow? and yes this was clear from the beginning, thats why I avoided dill, but at the very end the lambdas kicked in and become very useful.

Now the question is if I should kick that and hope, that parsing will not hang the event loop, dive down to realms of python to write a pickler for lambdas or what else?

Meanwhile Im using the `asyncio.run_in_executor` and removed the producer/consumer design.

I also found a solution to serialize lambdas but did not find a way to register it at pickle.

I will update this post as soon as I have it ready on github.

Possible Answer

I made a small package. Available through github at the moment only.
This package works like a proxy using pythons marshall serializer.
It is about 100 times faster than using dill for this isolated case.

https://github.com/cloasdata/lambdser

pip install lambdser

Body:
I'm the dill author.  Writing a new "python" serializer isn't the answer.  In fact, when you compare dill to python's pickle, the speed is roughly the same.

As you can see, they are about the same:

Python 3.9.10 (main, Jan 15 2022, 12:09:07)
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> import dill
>>> import timeit
>>>
>>> def doit(x): return x
...
>>> timeit.timeit("dill.dumps(doit)", globals=globals(), number=10000)
1.315841937000016
>>> timeit.timeit("pickle._dumps(doit)", globals=globals(), number=10000)
1.1476000689999637

You'll note that I've used pickle._dumps which uses the python-based pickler.  In recent versions of python, pickle uses a C-based pickler by default (formerly known as cPickle)... and it's roughly 100x faster, as you experienced.

>>> timeit.timeit("pickle.dumps(doit)", globals=globals(), number=10000)
0.01674603300000399

So, you'll need to write a C-based pickler to compete with the speed of pickle.  That also means, that all of the registered pickling solutions need to be written in C as well, if you want roughly the same speed-up.  And then, you'll need to modify/fork multiprocessing to use your new serializer instead of pickle.

There is currently an effort in dill (and other serializers like cloudpickle) to better leverage the C pickling interface.  If you'd like to contribute to either, you are more than welcome to do so.