答:
The point is pretty simple: You pass a member function to a thread object, but not an object which that function could be called on.

The template only seemingly solves this problem, as you don't instantiate it. As soon as you do so, the same problem will re-appear.

You can fix that by passing an instance as parameter:

```<code>thread_ = std::thread(&BaseThread::worker, this);
</code>```

Additionally, you have to take a member function pointer via appropriate operator and class scope resolution.

Side note: As you have a virtual function, you should consider adding a virtual destructor as well, otherwise deleting a derived class via pointer to base class will fail miserably.

Don't forget to join the thread in the destructor (or wherever that appears appropriate to you) either.

Title: Run thread with derived method from base class without using templates

Body:
The point is pretty simple: You pass a member function to a thread object, but not an object which that function could be called on.

The template only seemingly solves this problem, as you don't instantiate it. As soon as you do so, the same problem will re-appear.

You can fix that by passing an instance as parameter:

thread_ = std::thread(&BaseThread::worker, this);

Additionally, you have to take a member function pointer via appropriate operator and class scope resolution.

Side note: As you have a virtual function, you should consider adding a virtual destructor as well, otherwise deleting a derived class via pointer to base class will fail miserably.

Don't forget to join the thread in the destructor (or wherever that appears appropriate to you) either.


来源: stackexchange

问:
Switching between the networks in android
Hey guys
I am developing an application in which i need to find the latitude
longitude of the user. I am able to find latitude longitude by network providers through following code :-

```<code>LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
loc = lm.getLastKnownLocation(lm.NETWORK_PROVIDER);
Toast.makeText(BaseScreen.this, "Lat: "+loc.getLatitude()+" long: "+loc.getLongitude(), Toast.LENGTH_LONG).show();
</code>```

Now the following are the cases which i need to implement :-

What if user is in a building and he can not retrieve data from GPS

What if the user has GPS switched off and wants to get location from Network

My application has like 20 activities if i place the code of locationlistener in one base screen which is extended by other activities and keep saving the latitude and longitude in some datamanager then will the call back work in that base screen activity even if the activity is not the main UI activity??

答:
a. Usually we should register for both GPS and network provider while requesting updates, this takes care of the line-of-sight problem where we automatically fall back on network provided values.

b. If the GPS is switched off you can check that from the code by using isProviderEnabled(), if not than your only option is to use the Network Provider.

c. Better still have LocationListener as a separate class and in onLocationChanged store the location received which should be available across your application.

To register use android.location.LocationListener.requestLocationUpdates

ContentLicense: CC BY-SA 3.0

Body:
Hey guys
I am developing an application in which i need to find the latitude
longitude of the user. I am able to find latitude longitude by network providers through following code :-

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
loc = lm.getLastKnownLocation(lm.NETWORK_PROVIDER);
Toast.makeText(BaseScreen.this, "Lat: "+loc.getLatitude()+" long: "+loc.getLongitude(), Toast.LENGTH_LONG).show();

Now the following are the cases which i need to implement :-

What if user is in a building and he can not retrieve data from GPS

What if the user has GPS switched off and wants to get location from Network

My application has like 20 activities if i place the code of locationlistener in one base screen which is extended by other activities and keep saving the latitude and longitude in some datamanager then will the call back work in that base screen activity even if the activity is not the main UI activity??


问:
Is there a way to use login/password of login account to reuse in a playbook?
I have created a job with 2 options for the user writes his login/password. This credentials will be used later in a playbook as extra-variables.

But all this credentials are readable in logs !!!

How to workaround that ?

答:
You can use the "Mask Password" Log filter in your inline-playbook or your playbook steps (also, for any Rundeck step), you can check the documentation here. I did a Job Definition example that works:

<joblist>
  <job>
    <context>
      <options preserveOrder='true'>
        <option name='opt1' secure='true' value='12345' valueExposed='true' />
      </options>
    </context>
    <defaultTab>nodes</defaultTab>
    <description></description>
    <dispatch>
      <excludePrecedence>true</excludePrecedence>
      <keepgoing>false</keepgoing>
      <rankOrder>ascending</rankOrder>
      <successOnEmptyNodeFilter>false</successOnEmptyNodeFilter>
      <threadcount>1</threadcount>
    </dispatch>
    <executionEnabled>true</executionEnabled>
    <id>2c9b3903-a545-4dbd-aeac-578889dbb611</id>
    <loglevel>INFO</loglevel>
    <name>HelloWorld</name>
    <nodeFilterEditable>false</nodeFilterEditable>
    <nodefilters>
      <filter>name: 192.168.33.20</filter>
    </nodefilters>
    <nodesSelectedByDefault>true</nodesSelectedByDefault>
    <scheduleEnabled>true</scheduleEnabled>
    <sequence keepgoing='false' strategy='node-first'>
      <command>
        <node-step-plugin type='com.batix.rundeck.plugins.AnsiblePlaybookInlineWorkflowNodeStep'>
          <configuration>
            <entry key='ansible-base-dir-path' value='/home/user/' />
            <entry key='ansible-become' value='false' />
            <entry key='ansible-playbook-inline' value='---
# This playbook prints a simple debug message
- name: Echo
  hosts: all
  connection: local

  tasks:
  - name: Print debug message
    debug:
      msg: ${option.opt1}' />
            <entry key='ansible-ssh-passphrase-option' value='option.password' />
            <entry key='ansible-ssh-use-agent' value='false' />
          </configuration>
        </node-step-plugin>
        <plugins>
          <LogFilter type='LogFilter:mask-passwords'>
            <config>
              <color>red</color>
              <replacement>[SECURE]</replacement>
            </config>
          </LogFilter>
        </plugins>
      </command>
    </sequence>
    <uuid>2c9b3903-a545-4dbd-aeac-578889dbb611</uuid>
  </job>
</joblist>
```

ContentLicense: CC BY-SA 4.0

Body:
You can use the "Mask Password" Log filter in your inline-playbook or your playbook steps (also, for any Rundeck step), you can check the documentation here. I did a Job Definition example that works:

<joblist>
  <job>
    <context>
      <options preserveOrder='true'>
        <option name='opt1' secure='true' value='12345' valueExposed='true' />
      </options>
    </context>
    <defaultTab>nodes</defaultTab>
    <description></description>
    <dispatch>
      <excludePrecedence>true</excludePrecedence>
      <keepgoing>false</keepgoing>
      <rankOrder>ascending</rankOrder>
      <successOnEmptyNodeFilter>false</successOnEmptyNodeFilter>
      <threadcount>1</threadcount>
    </dispatch>
    <executionEnabled>true</executionEnabled>
    <id>2c9b3903-a545-4dbd-aeac-578889dbb611</id>
    <loglevel>INFO</loglevel>
    <name>HelloWorld</name>
    <nodeFilterEditable>false</nodeFilterEditable>
    <nodefilters>
      <filter>name: 192.168.33.20</filter>
    </nodefilters>
    <nodesSelectedByDefault>true</nodesSelectedByDefault>
    <scheduleEnabled>true</scheduleEnabled>
    <sequence keepgoing='false' strategy='node-first'>
      <command>
        <node-step-plugin type='com.batix.rundeck.plugins.AnsiblePlaybookInlineWorkflowNodeStep'>
          <configuration>
            <entry key='ansible-base-dir-path' value='/home/user/' />
            <entry key='ansible-become' value='false' />
            <entry key='ansible-playbook-inline' value='---&#10;# This playbook prints a simple debug message&#10;- name: Echo &#10;  hosts: all&#10;  connection: local&#10;&#10;  tasks:&#10;  - name: Print debug message&#10;    debug:&#10;      msg: ${option.opt1}' />
            <entry key='ansible-ssh-passphrase-option' value='option.password' />
            <entry key='ansible-ssh-use-agent' value='false' />
          </configuration>
        </node-step-plugin>
        <plugins>
          <LogFilter type='LogFilter:mask-passwords'>
            <config>
              <color>red</color>
              <replacement>[SECURE]</replacement>
            </config>
          </LogFilter>
        </plugins>
      </command>
    </sequence>
    <uuid>2c9b3903-a545-4dbd-aeac-578889dbb611</uuid>
  </job>
</joblist>


问:
Two questions about ORDER BY using Prepared Statements
```<code><?php
$what = 'creationdate';

$sql = "SELECT * FROM `accountlist` ORDER BY ? [ASC/DESC]";

$stmt = $conn->stmt_init();

if(!($stmt->prepare($sql)))
{
  echo "Error";
} else {
  $stmt->bind_param("s", $what);
  $check = $stmt->execute();
  $result = $stmt->get_result();
}

for($n=1; $row = $result->fetch_assoc(); $n++)
{
  var_dump($row);echo "<br />";

  echo $n . ':<br />';
  foreach($row as $key => $value) echo $key . ': '. $value . '<br />';
  echo '<br />';
}

echo $check ? 'success' : 'error/no lines'
</code>```

?>

Why does this return the same result when I use either ASC or DESC in my query?

Is there a way to place a placeholder instead of that *? Using a ? and binding it returns a "?" in the $row array...

答:
This is a bit long for a comment.

You cannot replace an identifier in a SQL statement using a parameter.  Examples of identifiers are column and table names.  You also cannot replace SQL keywords or operators, such as INNER or =.

In your case, you are substituting a parameter with a constant value.  It is treated as the value, not as a column reference (or expression).  Hence, ASC and DESC do not differentiate among equal values.

Body:
<?php
$what = 'creationdate';

$sql = "SELECT * FROM `accountlist` ORDER BY ? [ASC/DESC]";

$stmt = $conn->stmt_init();

if(!($stmt->prepare($sql)))
{
  echo "Error";
} else {
  $stmt->bind_param("s", $what);
  $check = $stmt->execute();
  $result = $stmt->get_result();
}

for($n=1; $row = $result->fetch_assoc(); $n++)
{
  var_dump($row);echo "
";

  echo $n . ':
';
  foreach($row as $key => $value) echo $key . ': '. $value . '
';
  echo '
';
}

echo $check ? 'success' : 'error/no lines'

?>

Why does this return the same result when I use either ASC or DESC in my query?

Is there a way to place a placeholder instead of that *? Using a ? and binding it returns a "?" in the $row array...


问:
(15,1): error CS0120: An object reference is required for the non-static field, method, or property 'GameObject.GetComponent(string)'
I am programming

```<code>using UnityEngine;

public class playermove : MonoBehaviour
{
    public float moveSpeed=5f;

    // Update is called once per frame
    void Update()
    {
        jump();
        Vector3 movment = new Vector3(Input.GetAxis("Horizontal"),0f ,0f);
        transform.position += movment * Time.deltaTime * moveSpeed;
    }

    void jump()
    {
        if (Input.GetButtonDown("jump"))
        {
            GameObject.GetComponent("RigidBody2D")().AddForce(new Vector2(0f,5f),ForceMode2D.Impulse);
        }
    }
}
</code>```

and I am getting this problem:

(15,1): error CS0120: An object reference is required for the non-static field, method, or property 'GameObject.GetComponent(string)'

答:
GameObject is the name of a class. The error is telling you that an object is expected, in other words a particular instance of GameObject, such as the player.

eg

```<code>GameObject player = GameObject.Find("player");
player.GetComponent("RigidBody2D").AddForce(new Vector2(0f,5f),ForceMode2D.Impulse);
</code>```

Body:
I am programming

using UnityEngine;

public class playermove : MonoBehaviour
{
    public float moveSpeed=5f;

    // Update is called once per frame
    void Update()
    {
        jump();
        Vector3 movment = new Vector3(Input.GetAxis("Horizontal"),0f ,0f);
        transform.position += movment * Time.deltaTime * moveSpeed;
    }

    void jump()
    {
        if (Input.GetButtonDown("jump"))
        {
            GameObject.GetComponent("RigidBody2D")().AddForce(new Vector2(0f,5f),ForceMode2D.Impulse);
        }
    }
}

and I am getting this problem:

(15,1): error CS0120: An object reference is required for the non-static field, method, or property 'GameObject.GetComponent(string)'

Body:
GameObject is the name of a class. The error is telling you that an object is expected, in other words a particular instance of GameObject, such as the player.

eg

GameObject player = GameObject.Find("player");
player.GetComponent("RigidBody2D").AddForce(new Vector2(0f,5f),ForceMode2D.Impulse);


问:
Hibernate: saving an entity with foreign primary key
I have a database with two entities (Product and Feedback). Feedback has a single foreign key that refers to Product, whose primary key is an integer. They are therefore in a one-to-one relationship.

I want to add a new Feedback entry to the database with my web application.
To do so I'm trying to perform a PUT request to my Spring server from my Angular client application.

The client has an Object of class Feedback with the following attributes (content of Feedback.ts)

```<code>export class Feedback {
  constructor(
    public productId: number,
    public score: number,
    public preferred: boolean,
    public textNote: string
  ) {
  }
}
</code>```

The class Feedback.java, server side:

```<code>@Entity
@Table(name = "feedback")
public class Feedback implements Serializable {
    @Id
    @JoinColumn(name = "product", unique = true)
    @OneToOne(cascade = CascadeType.ALL)
    private Product product;

    @Column(name = "score")
    private double score;

    @Column(name = "preferred")
    private boolean preferred;

    @Column(name = "textnote")
    private String textNote;

    // ... getters, setters, constructor

}
</code>```

As you can see there is a non-matching attribute: productId is a number, while product is of class Product. How can I give the Spring application the correct object in order to save it in the database?

I'm trying to follow the Hibernate guidelines and as far as I understood it would be a bad practice to use an attribute in the java class of type int instead of Product. What should I do?

答:
You can extend a DefaultConversionService and implement a custom converter to convert id to product

```<code> @Configuration
 public static class Config {
   @Bean
   public ConversionService conversionService () {
      DefaultConversionService service = new DefaultConversionService();
      service.addConverter(new IdToProductConverter());
      return service;
   }
 }
</code>```

Then the IdToProductConverter will receive the id and can lookup the product from the DB

```<code>class IdToProductConverter implements Converter<String, Product> {
    @Override
    public Product convert(String source) {
    }
}
</code>```

Body:
I have a database with two entities (Product and Feedback). Feedback has a single foreign key that refers to Product, whose primary key is an integer. They are therefore in a one-to-one relationship.

I want to add a new Feedback entry to the database with my web application.
To do so I'm trying to perform a PUT request to my Spring server from my Angular client application.

The client has an Object of class Feedback with the following attributes (content of Feedback.ts)

export class Feedback {
  constructor(
    public productId: number,
    public score: number,
    public preferred: boolean,
    public textNote: string
  ) {
  }
}

The class Feedback.java, server side:

@Entity
@Table(name = "feedback")
public class Feedback implements Serializable {
    @Id
    @JoinColumn(name = "product", unique = true)
    @OneToOne(cascade = CascadeType.ALL)
    private Product product;

    @Column(name = "score")
    private double score;

    @Column(name = "preferred")
    private boolean preferred;

    @Column(name = "textnote")
    private String textNote;

    // ... getters, setters, constructor

}

As you can see there is a non-matching attribute: productId is a number, while product is of class Product. How can I give the Spring application the correct object in order to save it in the database?

I'm trying to follow the Hibernate guidelines and as far as I understood it would be a bad practice to use an attribute in the java class of type int instead of Product. What should I do?

Body:
You can extend a DefaultConversionService and implement a custom converter to convert id to product

 @Configuration
 public static class Config {
   @Bean
   public ConversionService conversionService () {
      DefaultConversionService service = new DefaultConversionService();
      service.addConverter(new IdToProductConverter());
      return service;
   }
 }

Then the IdToProductConverter will receive the id and can lookup the product from the DB

class IdToProductConverter implements Converter<String, Product> {
    @Override
    public Product convert(String source) {
    }
}


问:
Pygal World Map - mouseover features
I'm using Python's Pygal World Map module.  Put simply, I want "2016" to pop up when the cursor hovers over the United States.  When I hover over the United States, however, I do not get any mouseover effect.  I'm trying to achieve the mouseover effect on Pygal's website: http://www.pygal.org/en/latest/documentation/types/maps/pygal_maps_world.html</p>

```<code>import pygal

wm = pygal.maps.world.World()
wm.title = 'Countries I\'ve Been To'
wm.add('United States',{'us':2016})

wm.render_to_file('myplaces.svg')
</code>```

答: Please open the .svg file with Google Chrome and you will see the mouseover features.

Title: Pygal World Map - mouseover features

Body:
I'm using Python's Pygal World Map module.  Put simply, I want "2016" to pop up when the cursor hovers over the United States.  When I hover over the United States, however, I do not get any mouseover effect.  I'm trying to achieve the mouseover effect on Pygal's website: http://www.pygal.org/en/latest/documentation/types/maps/pygal_maps_world.html

import pygal

wm = pygal.maps.world.World()
wm.title = 'Countries I\'ve Been To'
wm.add('United States',{'us':2016})

wm.render_to_file('myplaces.svg')


问:
R :Fitting survival trees with time-varying covariates in RandomForestSRC
In the package LTRCtrees one can fit a decision tree to the special format of the Surv function :Surv(time, time2, event) as per below example

```<code>set.seed(0)
library(survival)
library(LTRCtrees)
## Create the start-stop-event triplet needed for coxph and LTRC trees
first <- with(pbcseq, c(TRUE, diff(id) !=0)) #first id for each subject
last <- c(first[-1], TRUE) #last id
time1 <- with(pbcseq, ifelse(first, 0, day))
time2 <- with(pbcseq, ifelse(last, futime, c(day[-1], 0)))
event <- with(pbcseq, ifelse(last, status, 0))
event <- 1*(event==2)

pbcseq$time1 <- time1
pbcseq$time2 <- time2
pbcseq$event <-  event

## Fit the Cox model and LTRC trees with time-varying covariates
fit.cox <- coxph(Surv(time1, time2, event) ~ age + sex + log(bili), pbcseq)
LTRCIT.fit <- LTRCIT(Surv(time1, time2, event) ~ age + sex + log(bili), pbcseq)
LTRCART.fit <- LTRCART(Surv(time1, time2, event) ~ age + sex + log(bili), pbcseq)
</code>```

Is it possible to use the same function on a Random Forest using the RandomForestSRC library

```<code>library(randomForestSRC)
RF.fit <- rfsrc(Surv(time1, time2, event) ~ age + sex + log(bili), data=pbcseq, nsplit = 3, ntree = 100, importance = TRUE)
</code>```

Which generates an error:

```<code>Error in parseFormula(formula, data, ytry) :
  Survival formula incorrectly specified.
</code>```

答: This paper by Wongvibulsin, Wu, and Zeger (2019) extends the randomForestSRC package to handle TVC, but you may need to contact the authors for any relevant code. </p>

Body:
In the package LTRCtrees one can fit a decision tree to the special format of the Surv function :Surv(time, time2, event) as per below example

set.seed(0)
library(survival)
library(LTRCtrees)
## Create the start-stop-event triplet needed for coxph and LTRC trees
first <- with(pbcseq, c(TRUE, diff(id) !=0)) #first id for each subject
last <- c(first[-1], TRUE) #last id
time1 <- with(pbcseq, ifelse(first, 0, day))
time2 <- with(pbcseq, ifelse(last, futime, c(day[-1], 0)))
event <- with(pbcseq, ifelse(last, status, 0))
event <- 1*(event==2)

pbcseq$time1 <- time1
pbcseq$time2 <- time2
pbcseq$event <-  event

## Fit the Cox model and LTRC trees with time-varying covariates
fit.cox <- coxph(Surv(time1, time2, event) ~ age + sex + log(bili), pbcseq)
LTRCIT.fit <- LTRCIT(Surv(time1, time2, event) ~ age + sex + log(bili), pbcseq)
LTRCART.fit <- LTRCART(Surv(time1, time2, event) ~ age + sex + log(bili), pbcseq)

Is it possible to use the same function on a Random Forest using the RandomForestSRC library

library(randomForestSRC)
RF.fit <- rfsrc(Surv(time1, time2, event) ~ age + sex + log(bili), data=pbcseq, nsplit = 3, ntree = 100, importance = TRUE)

Which generates an error:

Error in parseFormula(formula, data, ytry) :
  Survival formula incorrectly specified.


问:
Need some help with regular expressions (php)
For example, I have the following code :

```<code>$string  = "adf  gggg  eere value aaaa bbb (10) value
ddttt ggg www (20) value ddttt ggg www dddd (40) ";
preg_match("/(value).*(\(\d+\))/is", $string, $result);
var_dump($result[2]); // outputs 40.
</code>```

I'm trying to get the first value (10). The code above outputs 40 which makes sense, but not what I want. The string pattern is : word "value", then a number of any characters, then "(", integer, ")". It seems that I'm missing something obvious... I haven't worked too much with regular expressions, but I believe it can be solved somehow with ?<!value, no luck so far though.

Thanks for any help.

答:
.* is greedy, so it will match as many characters as possible, you want .*? which will match the minimum characters needed to complete the match:

```<code>/(value).*?(\(\d+\))/
</code>```

Body:
For example, I have the following code :

$string  = "adf  gggg  eere value aaaa bbb (10) value
ddttt ggg www (20) value ddttt ggg www dddd (40) ";
preg_match("/(value).*(\(\d+\))/is", $string, $result);
var_dump($result[2]); // outputs 40.

I'm trying to get the first value (10). The code above outputs 40 which makes sense, but not what I want. The string pattern is : word "value", then a number of any characters, then "(", integer, ")". It seems that I'm missing something obvious... I haven't worked too much with regular expressions, but I believe it can be solved somehow with ?<!value, no luck so far though.

Thanks for any help.

Body:
.* is greedy, so it will match as many characters as possible, you want .*? which will match the minimum characters needed to complete the match:

/(value).*?(\(\d+\))/


问:
How can i export 2 tables in a single excel sheet using reactjs / javascript
I am trying to export 2 tables in a single excel sheet using reactjs , can anyone suggest me any library or any idea how to acheieve this

答:
You can use react-html-table-to-excel to export file using id then implement same id on ReactToExcel

npm i react-html-table-to-excel or if you using yarn yarn add react-html-table-to-excel

```<code> <table id="table-to-xls" >

.....

</table>

 <ReactToExcel
   className="btn "
   table="table-to-xls"
   filename="Name of file"
   sheet="sheet 1"
   buttonText={t("export_report")}
 />
</code>```

Body:
You can use react-html-table-to-excel to export file using id then implement same id on ReactToExcel

npm i react-html-table-to-excel or if you using yarn yarn add react-html-table-to-excel

 <table id="table-to-xls" >

.....

</table>

 <ReactToExcel
   className="btn "
   table="table-to-xls"
   filename="Name of file"
   sheet="sheet 1"
   buttonText={t("export_report")}
 />


问:
(SQFLite) Retrieve data from 2 joined tables and convert result query to list
I have two models in my app, named Basket and Items. Model Basket contains a list of Items. So it's as follows:

Basket:

```<code>int id
string name
string imageUrl
List<Items> items
</code>```

Items:

```<code>string name
string description
int basketId
</code>```

_

My 2 tables:

basket:

```<code>id
name
imageUrl
</code>```

items:

```<code>id
name
description
basketId
</code>```

What I want to do is to retrieve all baskets with all its corresponding items and make a List basketList object. I tried to join the tables, but I ended with 4 baskets with null items instead of a basket with 4 items. I'm using SQFLite for flutter.

答:
You can do it without joining the tables. First, you get the Maplist of basket from sqflite. Next, as you are converting from Map object to Basket() object, for each basket in the list, you get the list of items and add the list of items to the basket. You can have a helper mapping function to map Map objects from sqflite to your object class. </p>

```<code>Future<List<Basket>> getBasketList() async{

var basketMapList = await getBasketMapList();
int count = basketMapList.length;

List<Basket> basketList = List<Basket>();

for (int i=0; i<count; i++){

  basketList.add(Basket.fromMapObject(basketMapList[i]));

  // for each basket, add the list of items...
  Future<List<Item>> itemListFuture = getBasketItemList(basketList[i].basketid);
  itemListFuture.then(
        (itemList) {

          basketList[i].items = itemList;

    },
  );
}

return basketList;
</code>```

<p>}</p>

```<code>// in basket class. Write a similar function for your items object.
   fromMapObject(Map<String, dynamic> map) {
        this.id = map['id'];
        this.name = map['name'];
        this.imageurl = map['imageurl'];
  }
</code>```

Body:
I have two models in my app, named Basket and Items. Model Basket contains a list of Items. So it's as follows:

Basket:

int id
string name
string imageUrl
List<Items> items

Items:

string name
string description
int basketId

_

My 2 tables:

basket:

id
name
imageUrl

items:

id
name
description
basketId

What I want to do is to retrieve all baskets with all its corresponding items and make a List basketList object. I tried to join the tables, but I ended with 4 baskets with null items instead of a basket with 4 items. I'm using SQFLite for flutter.

Body:
You can do it without joining the tables. First, you get the Maplist of basket from sqflite. Next, as you are converting from Map object to Basket() object, for each basket in the list, you get the list of items and add the list of items to the basket. You can have a helper mapping function to map Map objects from sqflite to your object class.

Future<List<Basket>> getBasketList() async{

var basketMapList = await getBasketMapList();
int count = basketMapList.length;

List<Basket> basketList = List<Basket>();

for (int i=0; i<count; i++){

  basketList.add(Basket.fromMapObject(basketMapList[i]));

  // for each basket, add the list of items...
  Future<List<Item>> itemListFuture = getBasketItemList(basketList[i].basketid);
  itemListFuture.then(
        (itemList) {

          basketList[i].items = itemList;

    },
  );
}

return basketList;

}

// in basket class. Write a similar function for your items object.
   fromMapObject(Map<String, dynamic> map) {
        this.id = map['id'];
        this.name = map['name'];
        this.imageurl = map['imageurl'];
  }


问:
Find a value of an element in vector in a std::map < int , std::vector <int >>
Is there a prettier way to get a value from inside a vector in a map without using loops?
For example , How to get the key of the vector which has an element of value 50?

```<code>std::map < int , std::vector < int >> myMap;
std::vector < int > a= {10,20,30};
std::vector < int > b= {50,60,70};
myMap.insert({1000,a});
myMap.insert({2000,b});
</code>```

Can I get the key(s) if the value is in more than one vector ?
For Example if 50 Is in both vectors ?

```<code>std::vector < int > a= {10,20,50};
std::vector < int > b= {50,60,70};
</code>```

答:
Is there a prettier way to get a value from inside a vector in a map without using loops?

You cannot avoid looping the map. But you can avoid writing the loop by using standard algorithm: std::find_if.

I mean more efficient

If you want the lookup to be efficient, then your choice of data structure is not good. You could instead use following:

```<code>std::unordered_multimap<int, int> myMap{
    {10, 1000},
    {20, 1000},
    {30, 1000},
    {50, 2000},
    {60, 2000},
    {70, 2000},
};
</code>```

With this, the lookup has asymptotically constant complexity instead of linear.

Body:
Is there a prettier way to get a value from inside a vector in a map without using loops?
For example , How to get the key of the vector which has an element of value 50?

std::map < int , std::vector < int >> myMap;
std::vector < int > a= {10,20,30};
std::vector < int > b= {50,60,70};
myMap.insert({1000,a});
myMap.insert({2000,b});

Can I get the key(s) if the value is in more than one vector ?
For Example if 50 Is in both vectors ?

std::vector < int > a= {10,20,50};
std::vector < int > b= {50,60,70};

Body:
Is there a prettier way to get a value from inside a vector in a map without using loops?

You cannot avoid looping the map. But you can avoid writing the loop by using standard algorithm: std::find_if.

I mean more efficient

If you want the lookup to be efficient, then your choice of data structure is not good. You could instead use following:

std::unordered_multimap<int, int> myMap{
    {10, 1000},
    {20, 1000},
    {30, 1000},
    {50, 2000},
    {60, 2000},
    {70, 2000},
};

With this, the lookup has asymptotically constant complexity instead of linear.


问:
Why can't local variable be used in GNU C basic inline asm statements?
Why cannot I use local variables from main to be used in basic asm inline? It is only allowed in extended asm, but why so?

(I know local variables are on the stack after return address (and therefore cannot be used once the function return), but that should not be the reason to not use them)

And example of basic asm:

```<code>int a = 10; //global a
int b = 20; //global b
int result;

int main() {
    asm ( "pusha\n\t"
          "movl a, %eax\n\t"
          "movl b, %ebx\n\t"
          "imull %ebx, %eax\n\t"
          "movl %eax, result\n\t"
          "popa");

    printf("the answer is %d\n", result);
    return 0;
}
</code>```

example of extended:

```<code>int main (void) {
    int data1 = 10;  //local var - could be used in extended
    int data2 = 20;
    int result;

    asm ( "imull %%edx, %%ecx\n\t"
          "movl %%ecx, %%eax"
          : "=a"(result)
          : "d"(data1), "c"(data2));

    printf("The result is %d\n",result);
    return 0;
}
</code>```

Compiled with:
gcc -m32 somefile.c

platform:
uname -a:
Linux 5.0.0-32-generic #34-Ubuntu SMP Wed Oct 2 02:06:48 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

答:
This is because asm is a defined language which is common for all compilers on the same processor family. After using the __asm__ keyword, you can reliably use any good manual for the processor to then start writing useful code.

But it does not have a defined interface for C, and lets be honest, if you don't interface your assembler with  your C code then why is it there?

Examples of useful very simple asm: generate a debug interrupt; set the floating point register mode (exceptions/accuracy);

Each compiler writer has invented their own mechanism to interface to C. For example in one old compiler you had to declare the variables you want to share as named registers in the C code. In GCC and clang they allow you to use their quite messy 2-step system to reference an input or output index, then associate that index with a local variable.

This mechanism is the "extension" to the asm standard.

Of course, the asm is not really a standard. Change processor and your asm code is trash. When we talk in general about sticking to the c/c++ standards and not using extensions, we don't talk about asm, because you are already breaking every portability rule there is.

Then, on top of that, if you are going to call C functions, or your asm declares functions that are callable by C then you will have to match to the calling conventions of your compiler. These rules are implicit. They constrain the way you write your asm, but it will still be legal asm, by some criteria.

But if you were just writing your own asm functions, and calling them from asm, you may not be constrained so much by the c/c++ conventions: make up your own register argument rules; return values in any register you want; make stack frames, or don't; preserve the stack frame through exceptions - who cares?

Note that you might still be constrained by the platform's relocatable code conventions (these are not "C" conventions, but are often described using C  syntax), but this is still one way that you can write a chunk of "portable" asm functions, then call them using "extended" embedded asm.

Body:
Why cannot I use local variables from main to be used in basic asm inline? It is only allowed in extended asm, but why so?

(I know local variables are on the stack after return address (and therefore cannot be used once the function return), but that should not be the reason to not use them)

And example of basic asm:

int a = 10; //global a
int b = 20; //global b
int result;

int main() {
    asm ( "pusha\n\t"
          "movl a, %eax\n\t"
          "movl b, %ebx\n\t"
          "imull %ebx, %eax\n\t"
          "movl %eax, result\n\t"
          "popa");

    printf("the answer is %d\n", result);
    return 0;
}

example of extended:

int main (void) {
    int data1 = 10;  //local var - could be used in extended
    int data2 = 20;
    int result;

    asm ( "imull %%edx, %%ecx\n\t"
          "movl %%ecx, %%eax"
          : "=a"(result)
          : "d"(data1), "c"(data2));

    printf("The result is %d\n",result);
    return 0;
}

Compiled with:
gcc -m32 somefile.c

platform:
uname -a:
Linux 5.0.0-32-generic #34-Ubuntu SMP Wed Oct 2 02:06:48 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux


问:
Is it possible to save the text entered into an alert's textfield in SwiftUI and display it in the app like this -> Text("alert text input here")?
So far I was able to handle displaying a textfield in an alert in which a user can input some text, but have not been able to use that text and display it inside the app.

Here's the code for the alert:

```<code>private func alert() {
    let alert = UIAlertController(title: "Enter Name", message: "...or pseudo", preferredStyle: .alert)
    alert.addTextField { (textField) in
        textField.placeholder = "Enter something"
    }
    alert.addAction(UIAlertAction(title: "Done", style: .default) { _ in })
    let textField = alert.textFields![0] as UITextField
    alertInput = textField.text ?? "Name"
    showAlert(alert: alert)
}

func showAlert(alert: UIAlertController) {
    if let controller = topMostViewController() {
        controller.present(alert, animated: true)
    }
}
</code>```

And this is how I'm trying to implement it in the body:

```<code>Section {
    VStack {
        Button(action: {
            withAnimation {
                self.alert()
            }
        }) {
            Text(alertInput)
        }
    }
}
</code>```

alertInput is initialized before the body like so:

```<code>@State private var alertInput = ""
</code>```

答:
You will want to grab the value of the text field from inside the Done button's handler. So all you need to do is move the bracket down:

```<code>alert.addAction(UIAlertAction(title: "Done", style: .default) { _ in
    let textField = alert.textFields![0] as UITextField
    alertInput = textField.text ?? "Name"
})
</code>```

The code inside this closure is called when the user taps this UIAlertAction you have set up.

Note that if the field is left empty, the value of textField.text will be "" and not nil, so in order to use the default value you provide, you may need some additional logic here to check for a blank string as well.

Body:
So far I was able to handle displaying a textfield in an alert in which a user can input some text, but have not been able to use that text and display it inside the app.

Here's the code for the alert:

private func alert() {
    let alert = UIAlertController(title: "Enter Name", message: "...or pseudo", preferredStyle: .alert)
    alert.addTextField { (textField) in
        textField.placeholder = "Enter something"
    }
    alert.addAction(UIAlertAction(title: "Done", style: .default) { _ in })
    let textField = alert.textFields![0] as UITextField
    alertInput = textField.text ?? "Name"
    showAlert(alert: alert)
}

func showAlert(alert: UIAlertController) {
    if let controller = topMostViewController() {
        controller.present(alert, animated: true)
    }
}

And this is how I'm trying to implement it in the body:

Section {
    VStack {
        Button(action: {
            withAnimation {
                self.alert()
            }
        }) {
            Text(alertInput)
        }
    }
}

alertInput is initialized before the body like so:

@State private var alertInput = ""

Body:
You will want to grab the value of the text field from inside the Done button's handler. So all you need to do is move the bracket down:

alert.addAction(UIAlertAction(title: "Done", style: .default) { _ in
    let textField = alert.textFields![0] as UITextField
    alertInput = textField.text ?? "Name"
})

The code inside this closure is called when the user taps this UIAlertAction you have set up.

Note that if the field is left empty, the value of textField.text will be "" and not nil, so in order to use the default value you provide, you may need some additional logic here to check for a blank string as well.


问:
Why am I unable to cd within a dockercontainer?
I would like to automatically execute tasks inside a docker container. The task that should be executed should be run inside a specific, mounted directory. To do this, I am using the this command:

```<code>docker run --rm -v /a/dir/on/my/host:/tmp some_container /bin/bash -c "cd /tmp/dir/inside/volume && echo \"$PWD\""
</code>```

, followed by the actual task, which I omit, due to brevity.

PWD should give me /tmp/dir/inside/volume, but prints /a/dir/on/my/host. Why is that?

答:
$PWD is expanded before you run your container. Use single quotes instead of double quotes to defer expansion. Also it's simpler to use --workdir or -w instead of cd .. && and subshell.

```<code>docker run --rm -v /a/dir/on/my/host:/tmp some_container /bin/bash -c 'cd /tmp/dir/inside/volume && echo "$PWD"'
</code>```

or I suggest:

```<code>docker run --rm -v /a/dir/on/my/host:/tmp -w /tmp/dir/inside/volume /some_container pwd
</code>```

Body:
I would like to automatically execute tasks inside a docker container. The task that should be executed should be run inside a specific, mounted directory. To do this, I am using the this command:

docker run --rm -v /a/dir/on/my/host:/tmp some_container /bin/bash -c "cd /tmp/dir/inside/volume && echo \"$PWD\""

, followed by the actual task, which I omit, due to brevity.

PWD should give me /tmp/dir/inside/volume, but prints /a/dir/on/my/host. Why is that?

Body:
$PWD is expanded before you run your container. Use single quotes instead of double quotes to defer expansion. Also it's simpler to use --workdir or -w instead of cd .. && and subshell.

docker run --rm -v /a/dir/on/my/host:/tmp some_container /bin/bash -c 'cd /tmp/dir/inside/volume && echo "$PWD"'

or I suggest:

docker run --rm -v /a/dir/on/my/host:/tmp -w /tmp/dir/inside/volume /some_container pwd


问:
Istio Virtual Service - can I route traffic based on the calling service
Say I've got three services, ServiceA, ServiceB, and ServiceC. ServiceA and ServiceB both call ServiceC. I want to deploy a new version of ServiceC, but only want to send it traffic from ServiceB for testing. Is there a Route configuration that takes "calling service" into account?

答:
Based on istio documentation

You can do it with virtual service, or virtual service and destination rule.

With labels, example here

Deployments with app and version labels: We recommend adding an explicit app label and version label to deployments. Add the labels to the deployment specification of pods deployed using the Kubernetes Deployment. The app and version labels add contextual information to the metrics and telemetry Istio collects.

The app label: Each deployment specification should have a distinct app label with a meaningful value. The app label is used to add contextual information in distributed tracing.

The version label: This label indicates the version of the application corresponding to the particular deployment.

Each routing rule is associated with one or more service versions (see glossary in beginning of document). Weights associated with the version determine the proportion of traffic it receives. For example, the following rule will route 25% of traffic for the “reviews” service to instances with the “v2” tag and the remaining traffic (i.e., 75%) to “v1”.

```<code>apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews-route
spec:
  hosts:
  - reviews.prod.svc.cluster.local
  http:
  - route:
    - destination:
        host: reviews.prod.svc.cluster.local
        subset: v2
      weight: 25
    - destination:
        host: reviews.prod.svc.cluster.local
        subset: v1
      weight: 75
</code>```

And the associated DestinationRule

```<code>apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: reviews-destination
spec:
  host: reviews.prod.svc.cluster.local
  subsets:
  - name: v1
    labels:
      version: v1
  - name: v2
    labels:
      version: v2
</code>```

OR

Traffic can also be split across two entirely different services without having to define new subsets. For example, the following rule forwards 25% of traffic to reviews.com and 75% to dev.reviews.com

```<code>apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews-route-two-domains
spec:
  hosts:
  - reviews.com
  http:
  - route:
    - destination:
        host: dev.reviews.com
      weight: 25
    - destination:
        host: reviews.com
      weight: 75
</code>```

EDIT

So actually you would have to add labels to your serviceC 1.0 and 2.0 and virtual service would look like this.

```<code>apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews-route-two-domains
spec:
  hosts:
  - reviews.com
  http:
  - match:
    - sourceLabels:
        svc: A
    - route:
      - destination:
          host: serviceC
          label: v1
  - match:
    - sourceLabels:
        svc: B
    - route:
      - destination:
          host: serviceC
          label: v2
</code>```

Check my another answer where I used sourceLabels here

Let me know if you have any more questions.

Body:
Based on istio documentation

You can do it with virtual service, or virtual service and destination rule.

With labels, example here

Deployments with app and version labels: We recommend adding an explicit app label and version label to deployments. Add the labels to the deployment specification of pods deployed using the Kubernetes Deployment. The app and version labels add contextual information to the metrics and telemetry Istio collects.

The app label: Each deployment specification should have a distinct app label with a meaningful value. The app label is used to add contextual information in distributed tracing.

The version label: This label indicates the version of the application corresponding to the particular deployment.

Each routing rule is associated with one or more service versions (see glossary in beginning of document). Weights associated with the version determine the proportion of traffic it receives. For example, the following rule will route 25% of traffic for the “reviews” service to instances with the “v2” tag and the remaining traffic (i.e., 75%) to “v1”.

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews-route
spec:
  hosts:
  - reviews.prod.svc.cluster.local
  http:
  - route:
    - destination:
        host: reviews.prod.svc.cluster.local
        subset: v2
      weight: 25
    - destination:
        host: reviews.prod.svc.cluster.local
        subset: v1
      weight: 75

And the associated DestinationRule

apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: reviews-destination
spec:
  host: reviews.prod.svc.cluster.local
  subsets:
  - name: v1
    labels:
      version: v1
  - name: v2
    labels:
      version: v2

OR

Traffic can also be split across two entirely different services without having to define new subsets. For example, the following rule forwards 25% of traffic to reviews.com and 75% to dev.reviews.com

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews-route-two-domains
spec:
  hosts:
  - reviews.com
  http:
  - route:
    - destination:
        host: dev.reviews.com
      weight: 25
    - destination:
        host: reviews.com
      weight: 75

EDIT

So actually you would have to add labels to your serviceC 1.0 and 2.0 and virtual service would look like this.

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews-route-two-domains
spec:
  hosts:
  - reviews.com
  http:
  - match:
    - sourceLabels:
        svc: A
    - route:
      - destination:
          host: serviceC
          label: v1
  - match:
    - sourceLabels:
        svc: B
    - route:
      - destination:
          host: serviceC
          label: v2

Check my another answer where I used sourceLabels here

Let me know if you have any more questions.


问:
Angular - How to disable mouse click events outside a specific DIV based on a condition?
I'm using a RAD tool that generates angular code, and I want to make some modifications to a specific behaviour.

I have a grid and I can enter "edit" mode for a specific row with a button click, now once in edit mode, I want to disable completely mouse clicks outside the div containing that grid, because if the users clicks on some components outside the grid, before saving his edit, it will cause some bugs.

So I when the "Edit" button is clicked, I want to stop mouse events outside a specific div, and as soon as the "Save" button is clicked, I want to allow again mouse events everywhere.

I have no code to show, as it would be just some html code with some buttons tags.

The solution I'm looking for is just to know what is the correct way to do this, then I Can implement it by myself

答:
If i understood, you want to stop propagation only outside the div... So if you click in div, the click has effects; else the propagation will stopped. You need to use HostListener
(here the official documentation https://angular.io/api/core/HostListener)

Try in this way:

```<code><div #myDIVName (click)="stopEvent($event)"></div>
</code>```

and in your component, declare a variable with the ViewChild decorator

```<code>@ViewChild('myDIVName') myDIVName;
</code>```

and add this function

```<code>@HostListener('document:click', ['$event'])
  public onClick(event) {
    try {
      if (this.disableOutsideClick &&   !this.myDIVName.nativeElement.contains(event.target)) {
        event.stopPropagation():
        }
    } catch (e) {
        console.log(e);
        }
    }
</code>```

Body:
If i understood, you want to stop propagation only outside the div... So if you click in div, the click has effects; else the propagation will stopped. You need to use HostListener
(here the official documentation https://angular.io/api/core/HostListener)

Try in this way:

<div #myDIVName (click)="stopEvent($event)"></div>

and in your component, declare a variable with the ViewChild decorator

@ViewChild('myDIVName') myDIVName;

and add this function

@HostListener('document:click', ['$event'])
  public onClick(event) {
    try {
      if (this.disableOutsideClick &&   !this.myDIVName.nativeElement.contains(event.target)) {
        event.stopPropagation():
        }
    } catch (e) {
        console.log(e);
        }
    }


问:
Random System.NotSupportedException on WP7
Sporadically, I receive an error in my WP7 Silverlight application. The error is a random "System.NotSupportedException". This error is thrown occassionally when the following code is executed:

```<code>// 1. Build the url
string serviceURL = "http://www.mydomain.com/service.svc/param1/param2";

// 2. Asynchronously execute the query using HttpWebRequest instead of WebClient. There is a UI performance issue with the WebClient currently
WebRequest request = HttpWebRequest.Create(serviceUrl);
request.BeginGetResponse(new AsyncCallback(MyService_Completed), request);

...

private void MyService_Completed(IAsyncResult result)
{
  // Do stuff
}
</code>```

I have verified that the URL I am sending is correct. Please note, that this request is part of my view model, which may have other network requests fired off at the same time. I have no idea why this happens ocassionally. Can anybody point out any potential reasons?

Thank you!

答:
A similar question has been asked previously. If you look at the comments the original poster added to the answer, he claims to have solved the problem by replacing </p>

```<code>request.BeginGetResponse(new AsyncCallback(MyService_Completed), request);
</code>```

<p>with </p>

```<code>request.BeginGetResponse( MyService_Completed, request);
</code>```

Body:
Sporadically, I receive an error in my WP7 Silverlight application. The error is a random "System.NotSupportedException". This error is thrown occassionally when the following code is executed:

// 1. Build the url
string serviceURL = "http://www.mydomain.com/service.svc/param1/param2";

// 2. Asynchronously execute the query using HttpWebRequest instead of WebClient. There is a UI performance issue with the WebClient currently
WebRequest request = HttpWebRequest.Create(serviceUrl);
request.BeginGetResponse(new AsyncCallback(MyService_Completed), request);

...

private void MyService_Completed(IAsyncResult result)
{
  // Do stuff
}

I have verified that the URL I am sending is correct. Please note, that this request is part of my view model, which may have other network requests fired off at the same time. I have no idea why this happens ocassionally. Can anybody point out any potential reasons?

Thank you!

Body:
A similar question has been asked previously. If you look at the comments the original poster added to the answer, he claims to have solved the problem by replacing

request.BeginGetResponse(new AsyncCallback(MyService_Completed), request);

with

request.BeginGetResponse( MyService_Completed, request);


答:
Here works for every map, value and inner container:</p>

```<code>#include <iostream>

#include <map>
#include <vector>
#include <algorithm>
#include <iterator>
#include <optional>

template <typename ValueT, typename MapT>
std::optional<typename MapT::key_type> find_key_for_value_contained_in_intern_container(const ValueT& value, const MapT& map) {
    auto key_it = std::find_if(std::begin(map), std::end(map), [&value] (const auto & element) {
        return std::find(std::begin(element.second), std::end(element.second), value) != std::end(element.second);
    });
    return (key_it != std::end(map)) ? key_it->first : std::optional<typename MapT::key_type>();
}

int main() {
    std::map<int, std::vector<int >> myMap;
    std::vector<int> a = {10, 20, 30};
    std::vector<int> b = {50, 60, 70};
    myMap.insert({1000, a});
    myMap.insert({2000, b});

    int value_to_search{50};

    auto key = find_key_for_value_contained_in_intern_container(value_to_search, myMap);

    if (key)
    std::cout << "Value " << value_to_search << " is at key " << *key << "\n";
}
</code>```

Title: Find a value of an element in vector in a std::map < int , std::vector <int >>

Body:
Here works for every map, value and inner container:

#include <iostream>

#include <map>
#include <vector>
#include <algorithm>
#include <iterator>
#include <optional>

template <typename ValueT, typename MapT>
std::optional<typename MapT::key_type> find_key_for_value_contained_in_intern_container(const ValueT& value, const MapT& map) {
    auto key_it = std::find_if(std::begin(map), std::end(map), [&value] (const auto & element) {
        return std::find(std::begin(element.second), std::end(element.second), value) != std::end(element.second);
    });
    return (key_it != std::end(map)) ? key_it->first : std::optional<typename MapT::key_type>();
}

int main() {
    std::map<int, std::vector<int >> myMap;
    std::vector<int> a = {10, 20, 30};
    std::vector<int> b = {50, 60, 70};
    myMap.insert({1000, a});
    myMap.insert({2000, b});

    int value_to_search{50};

    auto key = find_key_for_value_contained_in_intern_container(value_to_search, myMap);

    if (key)
    std::cout << "Value " << value_to_search << " is at key " << *key << "\n";
}


问:
How does Smalltalk image handle IO?
I just started to learn Smalltalk, went through its syntax, but hasn't done any real coding with it. While reading some introductory articles and some SO questions like:

What gives Smalltalk the ability to do image persistence, and why
can't languages like Ruby/Python serialize
themselves?

What is a Smalltalk “image”?

One question always comes into my mind: How does Smalltalk image handle IO?

A smalltalk program can resume from where it exits, using information stored in the image. Say I have some opened TCP connections(not to mention all sorts of buffer), how do they get recovered? There seems to be no way other than reopening them(confirmed by this answer). And if Smalltalk does reopen those connections, isn't it going against the idea of "resume execution of the program at a later time exactly from where you left off"? Or is there some magic behind it?

I don't mind if the answer is specific to certain dialects, say Pharo.

Also would be interested to know some resources to learn more about this topic.

答: For some practical code dealing with image startUp and shutDown, take a look at the class side of ZnServer. SessionManager is the class providing all the functionality you need to deal with giving up system resources on shutdown and re-aquiring them again on startup.

Title: How does Smalltalk image handle IO?


问:
Timeout on Google Home using Dialogflow
I'm developing my own bot and in one instance I prompt the user to take a measurement, and then wait for their reply. Currently, my bot times out before the user even has time to take the measurement. Suggestions on how to extend the timeout period?</p>

答:
You can use <break time="5" /> in SSML.

conv.ask(`<speak><break time="5" /></speak>`);

https://developers.google.com/assistant/actions/reference/ssml

Title: Timeout on Google Home using Dialogflow


问:
Handling fcm notification click
I am using fcm to send messages. The messages arrive to the app, but when the user clicks on the notification, t it supposed to open a link but it just opens the app. My manifest is like this

```<code><service android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="@string/default_notification_channel_id"/>
</code>```

Where the notification is supposed to be handled :

```<code>Bundle extras = getIntent().getExtras();
    if (extras != null && extras.containsKey("rateUpdate")) {
        try {
            startActivity(new Intent("android.intent.action.VIEW", Uri.parse("market://details?id=tino.varconn.com.fastnetworks")));
        } catch (ActivityNotFoundException unused) {
            startActivity(new Intent("android.intent.action.VIEW", Uri.parse("http://play.google.com/store/apps/details?id=tino.varconn.com.fastnetworks")));
        }
    }
</code>```

When sending the message, I always make sure that in the key, value text boxes I put rateUpdate. Where am I going wrong here?

答:
Inside FirebaseMessagingService class you can get content from push notification and build your own Notification

```<code>    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Notification notification = remoteMessage.getNotification()
        String title = notification.getTitle()
        String body = notification.getBody();
        //now you can build and show your own notification
    }
</code>```

with .setContentIntent() method, where you can set any Activity you want to start.

```<code>        NotificationCompat.Builder builder = ...
        Intent intent = new Intent(context, destinationClass);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent,
            0);
        builder.setContentIntent(contentIntent);
</code>```

Title: Handling fcm notification click

Body:
I am using fcm to send messages. The messages arrive to the app, but when the user clicks on the notification, t it supposed to open a link but it just opens the app. My manifest is like this

<service android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="@string/default_notification_channel_id"/>

Where the notification is supposed to be handled :

Bundle extras = getIntent().getExtras();
    if (extras != null && extras.containsKey("rateUpdate")) {
        try {
            startActivity(new Intent("android.intent.action.VIEW", Uri.parse("market://details?id=tino.varconn.com.fastnetworks")));
        } catch (ActivityNotFoundException unused) {
            startActivity(new Intent("android.intent.action.VIEW", Uri.parse("http://play.google.com/store/apps/details?id=tino.varconn.com.fastnetworks")));
        }
    }

When sending the message, I always make sure that in the key, value text boxes I put rateUpdate. Where am I going wrong here?

Body:
Inside FirebaseMessagingService class you can get content from push notification and build your own Notification

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Notification notification = remoteMessage.getNotification()
        String title = notification.getTitle()
        String body = notification.getBody();
        //now you can build and show your own notification
    }

with .setContentIntent() method, where you can set any Activity you want to start.

        NotificationCompat.Builder builder = ...
        Intent intent = new Intent(context, destinationClass);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent,
            0);
        builder.setContentIntent(contentIntent);


问:
Selective USB UMS-Mode
is there a way to regulate the UMS-mode? I would like to implement a feature, that lets the user select which files he wants to share with a pc. Say you only want the pc see the picture subfolder, but not all the other folders on your sd. I am not sure if this is possible and most likely I will require root access when possible.

I know this will bring no real security, because you can always remove the sd card and read all the files on it. I thought of this feature mainly because of my crappy car radio. It can read mp3 files from a usb stick. But the many different folders and strange files on a android sd card seems to kill it. Furthermore I think there are a lot of other situation when you would prefer only to show a smaller part of your sd memory to a pc.

Can you imagine any other way to simulate the described behaviour? Can I generate completely new usb modes and implement my own UMS?

Every idea is welcome.

Sincerely Erik

答:
is there a way to regulate the UMS-mode?

Not from an SDK application. Also, bear in mind that UMS mode is being deprecated in favor of MTP.

I am not sure if this is possible and most likely I will require root access when possible.

No, you will need to write your own custom firmware.

Can I generate completely new usb modes and implement my own UMS?

By writing your own firmware, presumably, yes.

Title: Selective USB UMS-Mode


问:
Python Flask: Creating redirect to another website function
I have this problem, where I try to redirect to another URL using FLASK. My HTML form uses POST to get the input to backend:

```<code> if request.method == 'POST' and 'redirectButton' in request.form:
    createRedirect(request.form['redirectButton'])
</code>```

And then using my createRedirect func. I would like to redirect them, to URL I have assembled:

```<code>def createRedirect(videoName):
   redirectLink = "https://www.youtube.com/watch?v={}".format(VIDEOID[videoname])
   print(redirectLink)
   return redirect(redirectLink, code=302)
</code>```

If I click on the printed link, new tab opens on my explorer and it works fine, but the redirect does not happen -> the URL is right

Also I have no problem with formatting

答:
How about</p>

```<code> if request.method == 'POST' and 'redirectButton' in request.form:
    redirect_data = createRedirect(request.form['redirectButton']
    return redirect(redirect_data["link"], code=redirect_data["code"])

def createRedirect(videoName):
   redirectLink = "https://www.youtube.com/watch?v={}".format(VIDEOID[videoname])
   print(redirectLink)
   return {"link": redirectLink, "code": 302}
</code>```

Body:
I have this problem, where I try to redirect to another URL using FLASK. My HTML form uses POST to get the input to backend:

 if request.method == 'POST' and 'redirectButton' in request.form:
    createRedirect(request.form['redirectButton'])

And then using my createRedirect func. I would like to redirect them, to URL I have assembled:

def createRedirect(videoName):
   redirectLink = "https://www.youtube.com/watch?v={}".format(VIDEOID[videoname])
   print(redirectLink)
   return redirect(redirectLink, code=302)

If I click on the printed link, new tab opens on my explorer and it works fine, but the redirect does not happen -> the URL is right

Also I have no problem with formatting

Body:
How about

 if request.method == 'POST' and 'redirectButton' in request.form:
    redirect_data = createRedirect(request.form['redirectButton']
    return redirect(redirect_data["link"], code=redirect_data["code"])

def createRedirect(videoName):
   redirectLink = "https://www.youtube.com/watch?v={}".format(VIDEOID[videoname])
   print(redirectLink)
   return {"link": redirectLink, "code": 302}


问:
Prevent default link behaviour when click somewhere in  element
Lets say we have a like this structure:

document.querySelector(".container").addEventListener("click", e => {
  e.stopImmediatePropagation();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  <div class="preventGoToLinkWhenClick">
    button for open video modal
  </div>
</code>```

When I click on the div inside, it should not go to the link. Is this possible? I have tried stopImmediatePropagation() but does not works.

But should work  element when click outside the div

答:
Use an event listener to prevent default action if the clicked element contains class preventGoToLinkWhenClick (or any criterium you define), otherwise just return

document.addEventListener("click", evt => {
  if (evt.target.classList.contains("preventGoToLinkWhenClick")) {
   evt.preventDefault();
  }
  return;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  <div class="preventGoToLinkWhenClick">
    button for open video modal
  </div>
  [click to open]
</code>```

Title: Prevent default link behaviour when click somewhere in <a> element

Body:
Lets say we have a like this structure:

document.querySelector(".container").addEventListener("click", e => {
  e.stopImmediatePropagation();
}

    button for open video modal

When I click on the div inside, it should not go to the link. Is this possible? I have tried stopImmediatePropagation() but does not works.

But should work  element when click outside the div

Body:
Use an event listener to prevent default action if the clicked element contains class preventGoToLinkWhenClick (or any criterium you define), otherwise just return

document.addEventListener("click", evt => {
  if (evt.target.classList.contains("preventGoToLinkWhenClick")) {
   evt.preventDefault();
  }
  return;
});

<a href=//www.google.com" class="container">
  <div class="preventGoToLinkWhenClick">
    button for open video modal
  </div>
  [click to open]
</a>


问:
EXIF-JS data is getting undefined outside of the method
I am developing a web application using Angular 8. I just want to access the exif data of an input image outside the getData method by assigning the obtained data to a global variable. If i tried to access the global variable after executing function it is showing undefined.
here is the function for extracting the exif data:

```<code>photodata: any; // global variable
getPhotodata(file) {
    EXIF.getData(file, function() {
      const data = EXIF.getAllTags(this);
      console.log(data); // working
      console.log(data.Make); // working
      console.log(data.Model); // working
      console.log(data.DateTimeOriginal); // working
      this.photodata = data;
      console.log(this.photodata) // working
  });
  }
  console.log(this.photodata) // here it is showing undefined
</code>```

i have tried to return the data. But it also does not worked

```<code>getPhotodata(file) {
    EXIF.getData(file, function() {
      const data = EXIF.getAllTags(this);
      console.log(data); // working
      console.log(data.Make); // working
      console.log(data.Model); // working
      console.log(data.DateTimeOriginal); // working
      return data;
  });
  }
console.log(getPhotodata(file)) // undefined
</code>```

答:
I'm aware you probably solved this by now, but in case async programming got you curious, you might enjoy my library exifr. I've written it because exif-js is effectively dead now (not maintained for over 2 years), it's pretty ineffective. Exifr is built around promises and async/await syntax, so you can do this:

```<code>async function getExif() {
  let output = await exifr.parse(file)
  console.log(data.Make)
  console.log(data.Model)
}
</code>```

You can also try out the library's playground and experiment with images and their output, or check out the repository and docs.

Body:
I am developing a web application using Angular 8. I just want to access the exif data of an input image outside the getData method by assigning the obtained data to a global variable. If i tried to access the global variable after executing function it is showing undefined.
here is the function for extracting the exif data:

photodata: any; // global variable
getPhotodata(file) {
    EXIF.getData(file, function() {
      const data = EXIF.getAllTags(this);
      console.log(data); // working
      console.log(data.Make); // working
      console.log(data.Model); // working
      console.log(data.DateTimeOriginal); // working
      this.photodata = data;
      console.log(this.photodata) // working
  });
  }
  console.log(this.photodata) // here it is showing undefined

i have tried to return the data. But it also does not worked

getPhotodata(file) {
    EXIF.getData(file, function() {
      const data = EXIF.getAllTags(this);
      console.log(data); // working
      console.log(data.Make); // working
      console.log(data.Model); // working
      console.log(data.DateTimeOriginal); // working
      return data;
  });
  }
console.log(getPhotodata(file)) // undefined

Body:
I'm aware you probably solved this by now, but in case async programming got you curious, you might enjoy my library exifr. I've written it because exif-js is effectively dead now (not maintained for over 2 years), it's pretty ineffective. Exifr is built around promises and async/await syntax, so you can do this:

async function getExif() {
  let output = await exifr.parse(file)
  console.log(data.Make)
  console.log(data.Model)
}

You can also try out the library's playground and experiment with images and their output, or check out the repository and docs.


问:
Simple script with an error, variable is not defined
im trying to write a very basic sleep interval script and a starter script
but for some reason that I can't understand I get an error message

CODE:

```<code>def intervals():
    while True:
        try:
            interval = input('[?] Intervals in seconds [default = 0s]:\t') or 0
            interval = int(interval)
            print(f'[+] Sleep for: {interval} seconds after each message Sent')
            return interval
        except:
            print(f'[!] Error: {interval} Not a number')

def intervals_start(interval):
    sleep(interval)

intervals()
intervals_start(interval)
</code>```

ERROR:

```<code>[?] Intervals in seconds [default = 0s]:    5
[+] Sleep for: 5 seconds after each message Sent
Traceback (most recent call last):
  File "***********/testing.py", line 49, in <module>
    intervals_start(interval)
NameError: name 'interval' is not defined
Process finished with exit code 1
</code>```

答:
You are passing a variable interval into a function intervals_start(), but nowhere in the code did you assign interval a value.

You need to capture the result of intervals()

interval = intervals()

then you can safely pass the user selected interval into intervals_start()

Body:
im trying to write a very basic sleep interval script and a starter script
but for some reason that I can't understand I get an error message

CODE:

def intervals():
    while True:
        try:
            interval = input('[?] Intervals in seconds [default = 0s]:\t') or 0
            interval = int(interval)
            print(f'[+] Sleep for: {interval} seconds after each message Sent')
            return interval
        except:
            print(f'[!] Error: {interval} Not a number')

def intervals_start(interval):
    sleep(interval)

intervals()
intervals_start(interval)

ERROR:

[?] Intervals in seconds [default = 0s]:    5
[+] Sleep for: 5 seconds after each message Sent
Traceback (most recent call last):
  File "***********/testing.py", line 49, in <module>
    intervals_start(interval)
NameError: name 'interval' is not defined
Process finished with exit code 1


问:
How to get the duplicate key values in freemarker?
my input is :

```<code>someMap = { "item": "first" , "item": "second" }
</code>```

template:

```<code><#list someMap?keys as k>
  ${k}
</#list>
</code>```

output:

```<code>item
</code>```

but the expected output is :

```<code>item
item
</code>```

How to get the duplicate keys in freemarker?

Thank you!

答: That is not possible. A Map only stores one element for each key.</p>

Body:
my input is :

someMap = { "item": "first" , "item": "second" }

template:

<#list someMap?keys as k>
  ${k}
</#list>

output:

item

but the expected output is :

item
item

How to get the duplicate keys in freemarker?

Thank you!


问:
Swfitmailer Scope in Function
I've got a small function that implements use of Swift_Mailer to handle sending emails:

```<code>public function send(string $subject, $to, string $msg, $from = '')
{
    if (!empty($to)) {
        if (empty($from)) {
            $smtpSettings = $this->loadSettings();

            $from = [$smtpSettings['from_email'] => $smtpSettings['from_name']];
        }

        var_dump($to);

        $email = (new \Swift_Message($subject))
            ->setFrom($from)
            ->setTo($to)
            ->setBody($msg);

        // Send the message
        $result = $this->swift->send($email);
    } else {
        var_dump('nein');
    }
}
</code>```

Which gets used here:

```<code>$mailer->send(
    'Some Subject',
    [$email],
    'Hello, world'
);
</code>```

This returns this message:

0: Address in mailbox given [] does not comply with RFC 2822, 3.6.2.

After a quick Googles, it seems the Swift_Message instance isn't getting the $to value properly.

I added the var_dump($to) to the script to see what's actually in it, and I get:

```<code>array(1) {
  string(19) "someemail@domain.com"
}
</code>```

The email above is psuedo for my real email, which I copy/pasted into thunderbird and sent an email to - all good, so I know the email is valid.

However, the error message seems to show that no email was passed. My code more or less mirrors the documentation but for some reason, my email isn't getting passed.

Does Swift_Message have some weird scope issues? It doesn't seem like $subject or $from are going wrong, so why is the $to potentially not in-scope?

答:
AbraCadaver led me towards the right path, more so than the error message returned to me.

I copied the original code from the documentation and replaced the values one-by-one with the corresponding $var, all worked, even $to - the message was a red herring.

The $from variable however, is what broke the script. The value was incorrectly formatted, fixing the format fixed the script.

I set $from to ['theemail@domain.com' => 'Some Name'] and all was well.

Title: Swfitmailer Scope in Function

Body:
I've got a small function that implements use of Swift_Mailer to handle sending emails:

public function send(string $subject, $to, string $msg, $from = '')
{
    if (!empty($to)) {
        if (empty($from)) {
            $smtpSettings = $this->loadSettings();

            $from = [$smtpSettings['from_email'] => $smtpSettings['from_name']];
        }

        var_dump($to);

        $email = (new \Swift_Message($subject))
            ->setFrom($from)
            ->setTo($to)
            ->setBody($msg);

        // Send the message
        $result = $this->swift->send($email);
    } else {
        var_dump('nein');
    }
}

Which gets used here:

$mailer->send(
    'Some Subject',
    [$email],
    'Hello, world'
);

This returns this message:

0: Address in mailbox given [] does not comply with RFC 2822, 3.6.2.

After a quick Googles, it seems the Swift_Message instance isn't getting the $to value properly.

I added the var_dump($to) to the script to see what's actually in it, and I get:

array(1) {
  string(19) "someemail@domain.com"
}

The email above is psuedo for my real email, which I copy/pasted into thunderbird and sent an email to - all good, so I know the email is valid.

However, the error message seems to show that no email was passed. My code more or less mirrors the documentation but for some reason, my email isn't getting passed.

Does Swift_Message have some weird scope issues? It doesn't seem like $subject or $from are going wrong, so why is the $to potentially not in-scope?


问:
Should I normalize this table?
I have a table Items which stores fetched book data from Amazon.  This Amazon data is inserted into Items as users browse the site, so any INSERT that occurs needs to be efficient.

Here's the table:

```<code>CREATE TABLE IF NOT EXISTS `items` (
  `Item_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Item_ISBN` char(13) DEFAULT NULL,
  `Title` varchar(255) NOT NULL,
  `Edition` varchar(20) DEFAULT NULL,
  `Authors` varchar(255) DEFAULT NULL,
  `Year` char(4) DEFAULT NULL,
  `Publisher` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`Item_ID`),
  UNIQUE KEY `Item_Data` (`Item_ISBN`,`Title`,`Edition`,`Authors`,`Year`,`Publisher`),
  KEY `ISBN` (`Item_ISBN`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT AUTO_INCREMENT=1 ;
</code>```

Normalizing this table would presumably mean creating tables for Titles, Authors, and Publishers.  My concern with doing this is that the insert would become too complex.. To insert a single Item, I'd have to:

Check for the Publisher in Publishers to SELECT Publisher_ID, otherwise insert it and use mysql_insert_id() to get Publisher_ID.

Check for the Authors in Authors to SELECT Authors_ID, otherwise insert it and use mysql_insert_id() to get Authors_ID.

Check for the Title in Titles to SELECT Title_ID, otherwise insert it and use mysql_insert_id() to get Title_ID.

Use those ID's to finally insert the Item (which may in fact be a duplicate, so this whole process would have been a waste..)

Does that argue against normalization for this table?

Note: The goal of Items is not to create a comprehensive database of books, so that a user would say "Show me all the books by Publisher X."  The Items table is just used to cache Items for my users' search results.

答:
YES you should normalize it if you don't think it is already. However, as far as I can tell it's already in 5th Normal Form anyway - at least it seems to be based on the "obvious" interpretation of those column names and if you ignore the nullable columns. Why do you doubt it? Not sure why you want to allow nulls for some of those columns though.

1.Check for the Publisher in Publishers to SELECT Publisher_ID,
  otherwise insert it and use
  mysql_insert_id() to get Publisher_ID

There is no "Publisher_ID" in your table. Normalization has nothing to do with inventing a new "Publisher_ID" attribute. Substituting a "Publisher_ID" in place of Publisher certainly wouldn't make it any more normalized than it already is.

Title: Should I normalize this table?

Body:
I have a table Items which stores fetched book data from Amazon.  This Amazon data is inserted into Items as users browse the site, so any INSERT that occurs needs to be efficient.

Here's the table:

CREATE TABLE IF NOT EXISTS `items` (
  `Item_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Item_ISBN` char(13) DEFAULT NULL,
  `Title` varchar(255) NOT NULL,
  `Edition` varchar(20) DEFAULT NULL,
  `Authors` varchar(255) DEFAULT NULL,
  `Year` char(4) DEFAULT NULL,
  `Publisher` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`Item_ID`),
  UNIQUE KEY `Item_Data` (`Item_ISBN`,`Title`,`Edition`,`Authors`,`Year`,`Publisher`),
  KEY `ISBN` (`Item_ISBN`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT AUTO_INCREMENT=1 ;

Normalizing this table would presumably mean creating tables for Titles, Authors, and Publishers.  My concern with doing this is that the insert would become too complex.. To insert a single Item, I'd have to:

Check for the Publisher in Publishers to SELECT Publisher_ID, otherwise insert it and use mysql_insert_id() to get Publisher_ID.

Check for the Authors in Authors to SELECT Authors_ID, otherwise insert it and use mysql_insert_id() to get Authors_ID.

Check for the Title in Titles to SELECT Title_ID, otherwise insert it and use mysql_insert_id() to get Title_ID.

Use those ID's to finally insert the Item (which may in fact be a duplicate, so this whole process would have been a waste..)

Does that argue against normalization for this table?

Note: The goal of Items is not to create a comprehensive database of books, so that a user would say "Show me all the books by Publisher X."  The Items table is just used to cache Items for my users' search results.


问:
login as a user and admin at the same time in laravel
I am working on a laravel project in which from ADMIN panel I can log in in the user module, but when I want to go back from the browser the admin panel is not working means admin is logout. is there any method in which I can log in in both module admin and user.</p>

答:
You could solve your problem with two possible ways that laravel provide and you could google about "laravel multi auth example".

Multiple authentications using "middleware"

Multiple authentications using auth "guards"

Here are two articles will help you to understand and show you the implement with an example:

Laravel 6 Multi Auth (Authentication) Tutorial

How to use multiple authentication guards in a Laravel app


问:
SQL select without showing joining columns in Joins
How do I exclude duplicate columns of joining keys when we do a join?</p>

答:
It depends on the nature of your query. If you need to use the joined table as a filter then don't join it on the main query, do it as a sub-query.</p>

```<code>SELECT *
FROM A
WHERE A.SEQ IN (SELECT B.FKEY_SEQ
                    FROM B
                    LEFT JOIN B WITH (NOLOCK) ON B.FKEY_SEQ = A.SEQ
                    WHERE B.SOMECOLUMN IN ('1234','5678'))
</code>```

Body:
It depends on the nature of your query. If you need to use the joined table as a filter then don't join it on the main query, do it as a sub-query.

SELECT *
FROM A
WHERE A.SEQ IN (SELECT B.FKEY_SEQ
                    FROM B
                    LEFT JOIN B WITH (NOLOCK) ON B.FKEY_SEQ = A.SEQ
                    WHERE B.SOMECOLUMN IN ('1234','5678'))


问:
C64 Assembly Rendering a Sprite
I have written a short program in 6502 assembler for the Commodore 64 using the ca65 assembler and ld65 linker. The program should render a solid square sprite somewhere near the center of the display, but I don't see anything being rendered.

This is my assembly:

```<code>    .segment "CODE"

    ; set sprite pointer index
    ; this, multiplied by $40, is the address
    ; in this case, the address is $2000
    ; $80 * $40 = $2000
    lda #$80
    sta $07f8

    ; enable sprite 0
    lda #$01
    sta $d015

    ; set x and y position
    lda #$80
    sta $d001
    sta $d002

loop:
    jmp loop

    .segment "GFXDATA"

    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
</code>```

This is my linker script, adapted from ca65's recommended linker script for hand-written assembler on the c64. The only change I made was to add the "GFXDATA" segment, so that I could store my sprites at address $2000.

```<code>FEATURES {
    STARTADDRESS: default = $0801;
}
SYMBOLS {
    __LOADADDR__: type = import;
}
MEMORY {
    ZP:       file = "", start = $0002,  size = $00FE,      define = yes;
    LOADADDR: file = %O, start = %S - 2, size = $0002;
    MAIN:     file = %O, start = %S,     size = $D000 - %S;
}
SEGMENTS {
    ZEROPAGE: load = ZP,       type = zp,  optional = yes;
    LOADADDR: load = LOADADDR, type = ro;
    EXEHDR:   load = MAIN,     type = ro,  optional = yes;
    CODE:     load = MAIN,     type = rw;
    RODATA:   load = MAIN,     type = ro,  optional = yes;
    DATA:     load = MAIN,     type = rw,  optional = yes;
    GFXDATA:  load = MAIN, type = ro, optional = yes, start = $2000;
    BSS:      load = MAIN,     type = bss, optional = yes, define = yes;
}
</code>```

This is the command I am using to compile and link:

```<code>cl65 -o graphics.prg --mapfile graphics.map -u __EXEHDR__ -t c64 -C linker.cfg graphics.asm
</code>```

This is the contents of the mapfile after compiling:

```<code>Modules list:
-------------
graphics.o:
    CODE              Offs=000000  Size=000015  Align=00001  Fill=0000
    GFXDATA           Offs=000000  Size=000040  Align=00001  Fill=0000
/usr/share/cc65/lib/c64.lib(exehdr.o):
    EXEHDR            Offs=000000  Size=00000C  Align=00001  Fill=0000
/usr/share/cc65/lib/c64.lib(loadaddr.o):
    LOADADDR          Offs=000000  Size=000002  Align=00001  Fill=0000

Segment list:
-------------
Name                   Start     End    Size  Align
----------------------------------------------------
LOADADDR              0007FF  000800  000002  00001
EXEHDR                000801  00080C  00000C  00001
CODE                  00080D  000821  000015  00001
GFXDATA               002000  00203F  000040  00001

Exports list by name:
---------------------
__EXEHDR__                000001 REA    __LOADADDR__              000001 REA

Exports list by value:
----------------------
__EXEHDR__                000001 REA    __LOADADDR__              000001 REA

Imports list:
-------------
__EXEHDR__ (exehdr.o):
    [linker generated]
__LOADADDR__ (loadaddr.o):
    [linker generated]        linker.cfg(5)
</code>```

And a hexdump of the final binary file:

```<code>0000000 0801 080b 0320 329e 3630 0031 0000 80a9
0000010 f88d a907 8d01 d015 80a9 018d 8dd0 d002
0000020 1f4c 0008 0000 0000 0000 0000 0000 0000
0000030 0000 0000 0000 0000 0000 0000 0000 0000
*
0001800 ff00 ffff ffff ffff ffff ffff ffff ffff
0001810 ffff ffff ffff ffff ffff ffff ffff ffff
*
0001840 00ff
0001841
</code>```

The "GFXDATA" segment is my sprite. The sprite is 64 bytes of $FF, so it should look like a solid square. This sprite data is located at address $2000.

The "CODE" segment is starts at the usual BASIC start location, and ca65 is inserting a BASIC loader for me so I can just type run after loading the program.

I have not switched the VIC's bank, so the screen is still at its default address range ($0400-$07FF), with the last 8 bytes of this range being my sprite pointers. I'm only using sprite pointer 0 ($07f8) because I only have one sprite.

When I run the program, everything locks up -- which is to be expected, because the program ends in an infinite loop. But I don't see the sprite anywhere on screen:

What am I missing?

答:
As @Jester pointed out in the comments, the X-position and Y-position memory addresses are wrong. The correct addresses are $d000 and $d001:

```<code>; set x and y position
lda #$80
sta $d000
sta $d001
</code>```

This is the corrected code:

```<code>    .segment "CODE"

    ; set sprite pointer index
    ; this, multiplied by $40, is the address
    ; in this case, the address is $2000
    ; $80 * $40 = $2000
    lda #$80
    sta $07f8

    ; enable sprite 0
    lda #$01
    sta $d015

    ; set x and y position
    lda #$80
    sta $d000
    sta $d001

loop:
    jmp loop

    .segment "GFXDATA"

    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
</code>```

And here's a picture of it in action:

Title: C64 Assembly Rendering a Sprite

Body:
I have written a short program in 6502 assembler for the Commodore 64 using the ca65 assembler and ld65 linker. The program should render a solid square sprite somewhere near the center of the display, but I don't see anything being rendered.

This is my assembly:

    .segment "CODE"

    ; set sprite pointer index
    ; this, multiplied by $40, is the address
    ; in this case, the address is $2000
    ; $80 * $40 = $2000
    lda #$80
    sta $07f8

    ; enable sprite 0
    lda #$01
    sta $d015

    ; set x and y position
    lda #$80
    sta $d001
    sta $d002

loop:
    jmp loop

    .segment "GFXDATA"

    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF

This is my linker script, adapted from ca65's recommended linker script for hand-written assembler on the c64. The only change I made was to add the "GFXDATA" segment, so that I could store my sprites at address $2000.

FEATURES {
    STARTADDRESS: default = $0801;
}
SYMBOLS {
    __LOADADDR__: type = import;
}
MEMORY {
    ZP:       file = "", start = $0002,  size = $00FE,      define = yes;
    LOADADDR: file = %O, start = %S - 2, size = $0002;
    MAIN:     file = %O, start = %S,     size = $D000 - %S;
}
SEGMENTS {
    ZEROPAGE: load = ZP,       type = zp,  optional = yes;
    LOADADDR: load = LOADADDR, type = ro;
    EXEHDR:   load = MAIN,     type = ro,  optional = yes;
    CODE:     load = MAIN,     type = rw;
    RODATA:   load = MAIN,     type = ro,  optional = yes;
    DATA:     load = MAIN,     type = rw,  optional = yes;
    GFXDATA:  load = MAIN, type = ro, optional = yes, start = $2000;
    BSS:      load = MAIN,     type = bss, optional = yes, define = yes;
}

This is the command I am using to compile and link:

cl65 -o graphics.prg --mapfile graphics.map -u __EXEHDR__ -t c64 -C linker.cfg graphics.asm

This is the contents of the mapfile after compiling:

Modules list:
-------------
graphics.o:
    CODE              Offs=000000  Size=000015  Align=00001  Fill=0000
    GFXDATA           Offs=000000  Size=000040  Align=00001  Fill=0000
/usr/share/cc65/lib/c64.lib(exehdr.o):
    EXEHDR            Offs=000000  Size=00000C  Align=00001  Fill=0000
/usr/share/cc65/lib/c64.lib(loadaddr.o):
    LOADADDR          Offs=000000  Size=000002  Align=00001  Fill=0000

Segment list:
-------------
Name                   Start     End    Size  Align
----------------------------------------------------
LOADADDR              0007FF  000800  000002  00001
EXEHDR                000801  00080C  00000C  00001
CODE                  00080D  000821  000015  00001
GFXDATA               002000  00203F  000040  00001

Exports list by name:
---------------------
__EXEHDR__                000001 REA    __LOADADDR__              000001 REA

Exports list by value:
----------------------
__EXEHDR__                000001 REA    __LOADADDR__              000001 REA

Imports list:
-------------
__EXEHDR__ (exehdr.o):
    [linker generated]
__LOADADDR__ (loadaddr.o):
    [linker generated]        linker.cfg(5)

And a hexdump of the final binary file:

0000000 0801 080b 0320 329e 3630 0031 0000 80a9
0000010 f88d a907 8d01 d015 80a9 018d 8dd0 d002
0000020 1f4c 0008 0000 0000 0000 0000 0000 0000
0000030 0000 0000 0000 0000 0000 0000 0000 0000
*
0001800 ff00 ffff ffff ffff ffff ffff ffff ffff
0001810 ffff ffff ffff ffff ffff ffff ffff ffff
*
0001840 00ff
0001841

The "GFXDATA" segment is my sprite. The sprite is 64 bytes of $FF, so it should look like a solid square. This sprite data is located at address $2000.

The "CODE" segment is starts at the usual BASIC start location, and ca65 is inserting a BASIC loader for me so I can just type run after loading the program.

I have not switched the VIC's bank, so the screen is still at its default address range ($0400-$07FF), with the last 8 bytes of this range being my sprite pointers. I'm only using sprite pointer 0 ($07f8) because I only have one sprite.

When I run the program, everything locks up -- which is to be expected, because the program ends in an infinite loop. But I don't see the sprite anywhere on screen:

What am I missing?

Body:
As @Jester pointed out in the comments, the X-position and Y-position memory addresses are wrong. The correct addresses are $d000 and $d001:

; set x and y position
lda #$80
sta $d000
sta $d001

This is the corrected code:

    .segment "CODE"

    ; set sprite pointer index
    ; this, multiplied by $40, is the address
    ; in this case, the address is $2000
    ; $80 * $40 = $2000
    lda #$80
    sta $07f8

    ; enable sprite 0
    lda #$01
    sta $d015

    ; set x and y position
    lda #$80
    sta $d000
    sta $d001

loop:
    jmp loop

    .segment "GFXDATA"

    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
    .byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF

And here's a picture of it in action: