问:
How do you escape the ~ character in a Batch script?
I am trying to replace a (~) in a string with a comma (,) but using the (~) during string replacement means display all characters from that index (e.g. %a:~2%).

My string is 1,2,3~4~5~6,7~8,9,10

I have already tried using a caret (^) which doesn't do the job.

With the caret (^) %a:^~=,% I get the echo of 1,2,3~4~5~6,7~8,9,10

Without the caret (^) %a:~=,% I get a:~=,

Input:

```<code>1,2,3~4~5~6,7~8,9,10
</code>```

code:

```<code>SET a=1,2,3~4~5~6,7~8,9,10
SET a=%a:^~=,%
echo !a!
</code>```

Expected Output:

```<code>1,2,3,4,5,6,7,8,9,10
</code>```

Actual Output:

a:~=, OR 1,2,3~4~5~6,7~8,9,10

What is the escape character for the (~) so I can replace it in a string?

EDIT: Add more detail about the wider project

I have an excel sheet which contains some cells that contain items like data, data this excel sheet is then exported as csv so I can iterate through the data. When the excel is converted the cells that contain data, data are converted to "data, data". I have found a work around for keeping that data as one cell when iterating through the .csv with commas (,) by first looping through the line looking for double quotes (") and when they have been found I take the data within the quotes and replace the commas (,) with tildes (~) and remove the double quotes ("). This changes the data to data~ data. I then reform the original line with this change. Later I access the data based on input from the user telling me which column of data they want. At this stage I'd like to be able to convert the tildes (~) back to commas (,) so as to return the data exactly as it is shown in the excel sheet i.e. converting data~ data into data, data

答:
There is no way to escape the ~ character, so you can only work around it.

What about this approach:

@echo off
set "STR=1,2,3~4~5~6,7~8,9,10"
set "NEW=,"
:LOOP
if not defined STR goto :END
rem // Get part left from first `~`:
for /F "delims=~ eol=~" %%I in (",%STR%") do set "PRT=%%I"
set "PRT=%PRT:~1%"
rem // Get part right from first `~`:
set "CMP=%STR:*~=%"
if "%CMP%" == "%STR%" (set "STR=") else (set "STR=%CMP%")
rem // Replace a single `~` by `,`:
set "NEW=%NEW%%PRT%,"
goto :LOOP
:END
echo(%NEW:~1,-1%
```

Body:
I am trying to replace a (~) in a string with a comma (,) but using the (~) during string replacement means display all characters from that index (e.g. %a:~2%).

My string is 1,2,3~4~5~6,7~8,9,10

I have already tried using a caret (^) which doesn't do the job.

With the caret (^) %a:^~=,% I get the echo of 1,2,3~4~5~6,7~8,9,10

Without the caret (^) %a:~=,% I get a:~=,

Input:

1,2,3~4~5~6,7~8,9,10

code:

SET a=1,2,3~4~5~6,7~8,9,10
SET a=%a:^~=,%
echo !a!

Expected Output:

1,2,3,4,5,6,7,8,9,10

Actual Output:

a:~=, OR 1,2,3~4~5~6,7~8,9,10

What is the escape character for the (~) so I can replace it in a string?

EDIT: Add more detail about the wider project

I have an excel sheet which contains some cells that contain items like data, data this excel sheet is then exported as csv so I can iterate through the data. When the excel is converted the cells that contain data, data are converted to "data, data". I have found a work around for keeping that data as one cell when iterating through the .csv with commas (,) by first looping through the line looking for double quotes (") and when they have been found I take the data within the quotes and replace the commas (,) with tildes (~) and remove the double quotes ("). This changes the data to data~ data. I then reform the original line with this change. Later I access the data based on input from the user telling me which column of data they want. At this stage I'd like to be able to convert the tildes (~) back to commas (,) so as to return the data exactly as it is shown in the excel sheet i.e. converting data~ data into data, data


来源: stackexchange

问:
Accessing this pointer in static function in cpp
I have a cpp class and few methods defined in it.
One of the static methods needs to call the non static method of the same class. I cant do this using "this" pointer as in static function "this" pointer cant be used.

I need someway to access the pointer to the same class in the static method in cpp...can someone pls help

答:
Assuming any instance of the class will do, why can't the static function just create its own temporary class instance ? Especially if there is a default constructor.
For example, the code below compiles correctly:

```<code>class Circle
{
public:
    Circle(double centerX, double centerY, double radius);
    Circle() : Circle(0.0, 0.0, 1.0)  // unit circle by default
    {}

    inline double  getRadius()  { return radius; };
    inline double  getArea()    { return area; };

    static  double computePi();   // HERE

private:
    double   centerX, centerY, radius, area;
};

Circle::Circle(double centerX, double centerY, double radius)
    : centerX(centerX), centerY(centerY), radius(radius)
{
    area = 3.14159*radius*radius;
}

double Circle::computePi()  // static class function, no "this" allowed
{
    Circle   tmpC1;  // temporary instance here !
    Circle*  tmpThis = &tmpC1;

    double  radius = tmpThis->getRadius();
    double  area   = tmpThis->getArea();
    double  pi     = area / (radius*radius);

    return pi;
}
</code>```

OK, the semantics looks a bit hairy, but maybe it looks better in your own context.

ContentLicense: CC BY-SA 4.0

Body:
Assuming any instance of the class will do, why can't the static function just create its own temporary class instance ? Especially if there is a default constructor.
For example, the code below compiles correctly:

class Circle
{
public:
    Circle(double centerX, double centerY, double radius);
    Circle() : Circle(0.0, 0.0, 1.0)  // unit circle by default
    {}

    inline double  getRadius()  { return radius; };
    inline double  getArea()    { return area; };

    static  double computePi();   // HERE

private:
    double   centerX, centerY, radius, area;
};

Circle::Circle(double centerX, double centerY, double radius)
    : centerX(centerX), centerY(centerY), radius(radius)
{
    area = 3.14159*radius*radius;
}

double Circle::computePi()  // static class function, no "this" allowed
{
    Circle   tmpC1;  // temporary instance here !
    Circle*  tmpThis = &tmpC1;

    double  radius = tmpThis->getRadius();
    double  area   = tmpThis->getArea();
    double  pi     = area / (radius*radius);

    return pi;
}

OK, the semantics looks a bit hairy, but maybe it looks better in your own context.


问:
nothing fires after fetch data from DB react native
i have index.js contain's Tabs each tab render the same component (animate.js)  but with different props, the code as the following:

index.js

```<code>categoryList.map((item,index) => {
    if(item.head_category == category_id)
      return (
          <Tab heading={item.category_name} key={index}>
            <Animate category_id={item.category_id}/>
          </Tab>
        )
    });
</code>```

in the animate.js i receive the category_id number and fetch the data using redux , and the data gets back

for first animate.js rendering nothing fires after the data returns but if i switch the tabs everything works grate

animate.js

```<code>import React from 'react';
import { InteractionManager, StyleSheet, Text, View, Button } from 'react-native';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import {LineDotsLoader} from 'react-native-indicator';

import {goodsAction} from './redux/actions'

class animate extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      category_id:'',
      loading:true,
    };
    console.log('constructor');
  }
componentDidMount(){
  const { category_id, category_name } = this.props;
  this.props.goodsAction({category_id}); // My fetching Action
  console.log(`componentDidMount `);
}
componentWillReceiveProps(nextProps){
    console.log(`componentWillReceiveProps`)
}
static getDerivedStateFromProps(props, state){
  console.log(` getDerivedStateFromProps `);
  return null;
  }
componentDidUpdate(prevProps, prevState) {
    console.log(` componentDidUpdate `);
  }

  renderPage() {
    return (
      <View style={{ flex: 1 }}>
        // anything
      </View>
    );
  }
  render(props) {
    console.log(`render`);
if (this.props.loading) {
// if redux still fetching return loading:true else return false
  return(<View style={styles.container}><LineDotsLoader /></View>)}
return (
        <View style={styles.container}>
          {this.renderPage()} // or anything
        </View>
    );
  }
}

const mapStateToProps = state => {
  return {
    error: state.goods.error,
    loading: state.goods.loading,
    goods: state.goods.goods
  }
}

export default connect(mapStateToProps, { goodsAction })(animate);
</code>```

my console image

Edit

and this is my goodsRedusers.js

```<code>import {
  GOODS_LOADING_ATTEMPT,
  GOODS_REFRESH_ATTEMPT,
  GOODS_LOADED,
  GOODS_FAILED
} from '../actions/types';

const INITIAL_STATE = { goods:[], loading: true, error: '', }

export default (state = INITIAL_STATE, action) => {
  switch(action.type) {
    case GOODS_LOADING_ATTEMPT://dispatch before connecting to db
      return {...INITIAL_STATE, loading: true }
    case GOODS_FAILED:
      return {...INITIAL_STATE, loading: false, error: action.error  }
    case GOODS_LOADED://dispatch after data gets back
      return {...INITIAL_STATE, loading: false, goods: action.goods  }
    default:
      return state;
  }
}
</code>```

答:
```<code>static getDerivedStateFromProps(props, state){
  console.log(` getDerivedStateFromProps `);
  return null;
  }
</code>```

Returning null won't update the state when props change, if that's what you want.
Try removing this code.

Body:
i have index.js contain's Tabs each tab render the same component (animate.js)  but with different props, the code as the following:

index.js

categoryList.map((item,index) => {
    if(item.head_category == category_id)
      return (
          <Tab heading={item.category_name} key={index}>
            <Animate category_id={item.category_id}/>
          </Tab>
        )
    });

in the animate.js i receive the category_id number and fetch the data using redux , and the data gets back

for first animate.js rendering nothing fires after the data returns but if i switch the tabs everything works grate

animate.js

import React from 'react';
import { InteractionManager, StyleSheet, Text, View, Button } from 'react-native';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import {LineDotsLoader} from 'react-native-indicator';

import {goodsAction} from './redux/actions'

class animate extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      category_id:'',
      loading:true,
    };
    console.log('constructor');
  }
componentDidMount(){
  const { category_id, category_name } = this.props;
  this.props.goodsAction({category_id}); // My fetching Action
  console.log(`componentDidMount `);
}
componentWillReceiveProps(nextProps){
    console.log(`componentWillReceiveProps`)
}
static getDerivedStateFromProps(props, state){
  console.log(` getDerivedStateFromProps `);
  return null;
  }
componentDidUpdate(prevProps, prevState) {
    console.log(` componentDidUpdate `);
  }

  renderPage() {
    return (
      <View style={{ flex: 1 }}>
        // anything
      </View>
    );
  }
  render(props) {
    console.log(`render`);
if (this.props.loading) {
// if redux still fetching return loading:true else return false
  return(<View style={styles.container}><LineDotsLoader /></View>)}
return (
        <View style={styles.container}>
          {this.renderPage()} // or anything
        </View>
    );
  }
}

const mapStateToProps = state => {
  return {
    error: state.goods.error,
    loading: state.goods.loading,
    goods: state.goods.goods
  }
}

export default connect(mapStateToProps, { goodsAction })(animate);

my console image

Edit

and this is my goodsRedusers.js

import {
  GOODS_LOADING_ATTEMPT,
  GOODS_REFRESH_ATTEMPT,
  GOODS_LOADED,
  GOODS_FAILED
} from '../actions/types';

const INITIAL_STATE = { goods:[], loading: true, error: '', }

export default (state = INITIAL_STATE, action) => {
  switch(action.type) {
    case GOODS_LOADING_ATTEMPT://dispatch before connecting to db
      return {...INITIAL_STATE, loading: true }
    case GOODS_FAILED:
      return {...INITIAL_STATE, loading: false, error: action.error  }
    case GOODS_LOADED://dispatch after data gets back
      return {...INITIAL_STATE, loading: false, goods: action.goods  }
    default:
      return state;
  }
}

Body:
static getDerivedStateFromProps(props, state){
  console.log(` getDerivedStateFromProps `);
  return null;
  }

Returning null won't update the state when props change, if that's what you want.
Try removing this code.


问:
Is there a way to use javascript variable as part of PHP SQL page?
I have a variable within a laravel PHP page, held within Javascript. I currently print / output this as:

```<code>${data.id}
</code>```

I now want to connect to PHPMyAdmin to check to see if the ID is within a table. However, I realise I can't use the ID number in PHP - as this is done on the server side and JS on the client side. A little stuck.

Unfortunately, I'm on a shared hosting package so node.js isn't a solution I can use.

Any help would be great! I think I can use AJAX, but unsure on how this would look.

答:
here the AJAX sample.

$.ajax({
  method: "POST",
  url: "some.php",
  data: { id: data.id}
})
  .done(function( response) {
    console.log(response);
    //TODO:process your response here if receive response from php file.

  });```

Body:
I have a variable within a laravel PHP page, held within Javascript. I currently print / output this as:

${data.id}

I now want to connect to PHPMyAdmin to check to see if the ID is within a table. However, I realise I can't use the ID number in PHP - as this is done on the server side and JS on the client side. A little stuck.

Unfortunately, I'm on a shared hosting package so node.js isn't a solution I can use.

Any help would be great! I think I can use AJAX, but unsure on how this would look.


问:
libc6: comma operator in assert macro definition
My system uses libc6 2.29. In /usr/include/assert.h I can find the definition of assert() macro:

```<code>/* The first occurrence of EXPR is not evaluated due to the sizeof,
   but will trigger any pedantic warnings masked by the __extension__
   for the second occurrence.  The ternary operator is required to
   support function pointers and bit fields in this context, and to
   suppress the evaluation of variable length arrays.  */
#  define assert(expr)                          \
  ((void) sizeof ((expr) ? 1 : 0), __extension__ ({         \
      if (expr)                             \
        ; /* empty */                           \
      else                              \
        __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION);   \
    }))
</code>```

I wonder why to use the comma operator, and what is meant by 'The first occurrence of EXPR is not evaluated due to the sizeof'.

What problem there would be using the following definition:

```<code>#  define assert(expr)                      \
  ({                                        \
      if (expr)                             \
           ; /* empty */                            \
      else                              \
           __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION);    \
    })
</code>```

Edit:

what value does the operator ({ }) get if expr is true?

Is it possible to rewrite the definition of assert() as follows?

```<code>#  define assert(expr)                          \
  ((void) sizeof ((expr) ? 1 : 0), __extension__ ({         \
      if (!expr)                                \
          __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION); \
    }))
</code>```

Where are the problems with this last definition?

答:
({ is not standard C and will trigger warnings or errors in standard C compilation modes.

So they are using __extension__, which will disable any such diagnostics.

However __extension__ will also mask non-standard constructs in expr, which you do want diagnosed.

Which is why they need expr repeated twice, once inside __extension__ and once outside.

However expr only needs to be evaluated once.

So they inhibit another evaluation by placing the other occurrence of expr inside sizeof.

Just sizeof(expr) is not enough though, because it won't work for things like function names.

So sizeof((expr) ? 1 : 0) is used instead, which doesn't have this problem.

So the two parts of the generated expression are (a) sizeof((expr) ? 1 : 0) and (b) the __extension__(...) part .

The first part is only needed to produce diagnostics if something is wrong with the expr.

The second part does the actual assertion.

Finally, the two parts are connected with the comma operator.

Body:
My system uses libc6 2.29. In /usr/include/assert.h I can find the definition of assert() macro:

/* The first occurrence of EXPR is not evaluated due to the sizeof,
   but will trigger any pedantic warnings masked by the __extension__
   for the second occurrence.  The ternary operator is required to
   support function pointers and bit fields in this context, and to
   suppress the evaluation of variable length arrays.  */
#  define assert(expr)                          \
  ((void) sizeof ((expr) ? 1 : 0), __extension__ ({         \
      if (expr)                             \
        ; /* empty */                           \
      else                              \
        __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION);   \
    }))

I wonder why to use the comma operator, and what is meant by 'The first occurrence of EXPR is not evaluated due to the sizeof'.

What problem there would be using the following definition:

#  define assert(expr)                      \
  ({                                        \
      if (expr)                             \
           ; /* empty */                            \
      else                              \
           __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION);    \
    })

Edit:

what value does the operator ({ }) get if expr is true?

Is it possible to rewrite the definition of assert() as follows?

#  define assert(expr)                          \
  ((void) sizeof ((expr) ? 1 : 0), __extension__ ({         \
      if (!expr)                                \
          __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION); \
    }))

Where are the problems with this last definition?


问:
Angular - Display table list based on a list
I'm new to Angular and trying to display multiple tables based on a list of values. For each rule refNo there has to be a separate rule conditions table displayed one after the other. At the moment all the tables are displaying the same values.

RuleComponent.html

```<code>  <div  *ngFor="let x of automation_rules_list">

    <table class="table">
      <thead>
        <tr>
          <th>Ticket Field</th>
          <th>Operator</th>
          <th>Expected Value</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <tr  *ngFor="let o of automation_rules_conditions_list">
          <td>{{o.ticketField}}</td>
          <td>{{o.ticketField}}</td>
          <td>{{o.operator}}</td>
          <td>{{o.expectedValue}}</td>
          <td><span class="pointer text-danger"><i class="fas fa-trash-alt"></i></span></td>
        </tr>
      </tbody>

    </table>
</code>```

RuleComponent.ts

```<code>ngOnInit() {

  this.loadAutomationRules();
}

loadAutomationRules() {

  this.ars.getAutomationRules().subscribe(res => {

    this.automation_rules_list = res;

    for (var i = 0; i < this.automation_rules_list.length; i++) {

      this.loadAutomationRuleConditions(res[i]["refNo"]);

    }

  });

}

loadAutomationRuleConditions(ruleRefNo) {

  this.ars.getAutomationConditions(ruleRefNo).subscribe(res => {

    this.automation_rules_conditions_list = res;

  });

}
</code>```

答:
You should add automation_rules_condition property in each automation_rule.
    loadAutomationRules() {

```<code>  this.ars.getAutomationRules().subscribe(res => {

    this.automation_rules_list = res;

    for (var i = 0; i < this.automation_rules_list.length; i++) {

      this.loadAutomationRuleConditions(res[i]);

    }

  });

}

loadAutomationRuleConditions(rule) {

  this.ars.getAutomationConditions(rule["refNo"]).subscribe(res => {

    rule.automation_rules_condition = res;

  });

}
</code>```

And you should use x.automation_rules_condition to display the table.

```<code><div  *ngFor="let x of automation_rules_list">

    <table class="table">
      <thead>
        <tr>
          <th>Ticket Field</th>
          <th>Operator</th>
          <th>Expected Value</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <tr  *ngFor="let o of x.automation_rules_condition">
          <td>{{o.ticketField}}</td>
          <td>{{o.ticketField}}</td>
          <td>{{o.operator}}</td>
          <td>{{o.expectedValue}}</td>
          <td><span class="pointer text-danger"><i class="fas fa-trash-alt"></i></span></td>
        </tr>
      </tbody>

    </table>
</div>
</code>```

Body:
I'm new to Angular and trying to display multiple tables based on a list of values. For each rule refNo there has to be a separate rule conditions table displayed one after the other. At the moment all the tables are displaying the same values.

RuleComponent.html

          Ticket Field
          Operator
          Expected Value
          Action

          {{o.ticketField}}
          {{o.ticketField}}
          {{o.operator}}
          {{o.expectedValue}}

RuleComponent.ts

ngOnInit() {

  this.loadAutomationRules();
}

loadAutomationRules() {

  this.ars.getAutomationRules().subscribe(res => {

    this.automation_rules_list = res;

    for (var i = 0; i < this.automation_rules_list.length; i++) {

      this.loadAutomationRuleConditions(res[i]["refNo"]);

    }

  });

}

loadAutomationRuleConditions(ruleRefNo) {

  this.ars.getAutomationConditions(ruleRefNo).subscribe(res => {

    this.automation_rules_conditions_list = res;

  });

}

Body:
You should add automation_rules_condition property in each automation_rule.
    loadAutomationRules() {

  this.ars.getAutomationRules().subscribe(res => {

    this.automation_rules_list = res;

    for (var i = 0; i < this.automation_rules_list.length; i++) {

      this.loadAutomationRuleConditions(res[i]);

    }

  });

}

loadAutomationRuleConditions(rule) {

  this.ars.getAutomationConditions(rule["refNo"]).subscribe(res => {

    rule.automation_rules_condition = res;

  });

}

And you should use x.automation_rules_condition to display the table.

<div  *ngFor="let x of automation_rules_list">

    <table class="table">
      <thead>
        <tr>
          <th>Ticket Field</th>
          <th>Operator</th>
          <th>Expected Value</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <tr  *ngFor="let o of x.automation_rules_condition">
          <td>{{o.ticketField}}</td>
          <td>{{o.ticketField}}</td>
          <td>{{o.operator}}</td>
          <td>{{o.expectedValue}}</td>
          <td><span class="pointer text-danger"><i class="fas fa-trash-alt"></i></span></td>
        </tr>
      </tbody>

    </table>
</div>


问:
How we run a .NET 32-bit application in a 64-bit Windows server?
We are installing a third party application in one of our 64-bit Windows servers.  This application apparently was build with the compiler option set to choose the platform at run time.  When we run the application it gives us an error:

```<code>System.BadImageFormatException: is not a valid Win32 application.
</code>```

I have seen in MSDN forums that in order to fix this error I have to build the application set to 32-bit, and that way it will run fine on a 64-bit server.  I check on other StackOverflow links Other Posts.

How to get around this situation?  For everyone that wants to know more information:

The application is running fine in a 32-bit test server.

IIS version 6

using SQL Server Express 2005

On the Web Service Extension there are both Framework64\v2.0.50727\aspnet_isapi.dll

and Framework\v2.0.50727\aspnet_isapi.dll

答:
I'm not sure this will help, but check it out:

http://msdn.microsoft.com/en-us/library/ms164699(VS.80).aspx

OwnerDisplayName: Geo

ContentLicense: CC BY-SA 2.5

Body:
We are installing a third party application in one of our 64-bit Windows servers.  This application apparently was build with the compiler option set to choose the platform at run time.  When we run the application it gives us an error:

System.BadImageFormatException: is not a valid Win32 application.

I have seen in MSDN forums that in order to fix this error I have to build the application set to 32-bit, and that way it will run fine on a 64-bit server.  I check on other StackOverflow links Other Posts.

How to get around this situation?  For everyone that wants to know more information:

The application is running fine in a 32-bit test server.

IIS version 6

using SQL Server Express 2005

On the Web Service Extension there are both Framework64\v2.0.50727\aspnet_isapi.dll

and Framework\v2.0.50727\aspnet_isapi.dll

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: Lars Mæhlum


问:
Multiple content_for on the same page
I have large block of HTML in my application that I would like to move into a shared template and then use content_for with yields to insert the necessary content. However, if I use it more than once in the same layout file the content_for just appends to the previous making that idea not work so well. Is there a solution to this?

```<code><div class="block side">
    <div class="block_head">
        <div class="bheadl"></div>
        <div class="bheadr"></div>
        <h2><%= yield :block_head %></h2>
    </div>
    <div class="block_content">
        <%= yield :block_content %>
    </div>
    <div class="bendl"></div>
    <div class="bendr"></div>
</div>
</code>```

and I use the following code to set the content for the block

```<code>    <%= overwrite_content_for :block_head do -%>
        My Block
    <% end -%>
    <%= overwrite_content_for :block_content do -%>
        <p>My Block Content</p>
    <% end -%>
    <%= render :file => "shared/_blockside" %>
</code>```

The problem is if I use this multiple times on the same layout the content from the original block is appended to the secondary block

I have tried creating a custom helper method to get around it, however it does not return any content

```<code>  def overwrite_content_for(name, content = nil, &block)
    @_content_for[name] = ""
    content_for(name, content &block)
  end
</code>```

I may also be going about this completely wrong and if there are any better methods for getting content to work like this I would like to know. Thanks.

答:
I am not sure if I really understand your question - here is one approach in code that works:

view:

```<code><% content_for :one do %>
  Test one
<% end %>

<% content_for :two do %>
  Test two
<% end %>

<p>Hi</p>
</code>```

application.html.erb

```<code><%= yield :one %>
<%= yield %>
<%= yield :two %>
</code>```

Railsguides: http://guides.rubyonrails.org/layouts_and_rendering.html#using-content_for

ContentLicense: CC BY-SA 3.0

Title: Multiple content_for on the same page

Body:
I have large block of HTML in my application that I would like to move into a shared template and then use content_for with yields to insert the necessary content. However, if I use it more than once in the same layout file the content_for just appends to the previous making that idea not work so well. Is there a solution to this?

<%= yield :block_head %>

        <%= yield :block_content %>

and I use the following code to set the content for the block

    <%= overwrite_content_for :block_head do -%>
        My Block
    <% end -%>
    <%= overwrite_content_for :block_content do -%>

My Block Content

    <% end -%>
    <%= render :file => "shared/_blockside" %>

The problem is if I use this multiple times on the same layout the content from the original block is appended to the secondary block

I have tried creating a custom helper method to get around it, however it does not return any content

  def overwrite_content_for(name, content = nil, &block)
    @_content_for[name] = ""
    content_for(name, content &block)
  end

I may also be going about this completely wrong and if there are any better methods for getting content to work like this I would like to know. Thanks.

Body:
I am not sure if I really understand your question - here is one approach in code that works:

view:

<% content_for :one do %>
  Test one
<% end %>

<% content_for :two do %>
  Test two
<% end %>

<p>Hi</p>

application.html.erb

<%= yield :one %>
<%= yield %>
<%= yield :two %>

Railsguides: http://guides.rubyonrails.org/layouts_and_rendering.html#using-content_for


问:
How do I send data to a Racket server?
Modifying an online example I have the following code which allows a http request to be made to this Racket webserver;

```<code>#lang racket

(require web-server/servlet)
(require web-server/servlet-env)

(define (http-response content)
  (response/full
    200                  ; HTTP response code.
    #"OK"                ; HTTP response message.
    (current-seconds)    ; Timestamp.
    TEXT/HTML-MIME-TYPE  ; MIME type for content.
    '()                  ; Additional HTTP headers.
    (list                ; Content (in bytes) to send to the browser.
      (string->bytes/utf-8 content))))

(define (show-time-page request)
  (http-response (number->string (current-seconds))))

(define (greeting-page request)
  (http-response (list-ref '("Hi" "Hello") (random 2))))

 (define get-data ...)

;; URL routing table (URL dispatcher).
(define-values (dispatch generate-url)
  (dispatch-rules
    [("time") show-time-page]
    [("hello") greeting-page]  ; Notice this line.
    [else (error "There is no procedure to handle the url.")]))

(define (request-handler request)
  (dispatch request))

;; Start the server.
(serve/servlet
  request-handler
  #:launch-browser? #f
  #:quit? #f
  #:listen-ip "127.0.0.1"
  #:port 8001
  #:servlet-regexp #rx"")
</code>```

How do I change the above code to allow it to receive data (such as a string) posted to the Racket webserver via a http-request and display it in the console? Please can you help?

答:
Define a request handler for the POST request. Have it extract the posted data from the request:

```<code>(define (example-post request)
  (define data (request-post-data/raw request))
  (define str (format "got post data: ~v" data))
  (displayln str)
  (http-response str))
</code>```

Add the handler to dispatch-rules. Be sure to specify it's handling a POST (not the default GET) request:

```<code>;; URL routing table (URL dispatcher).
(define-values (dispatch generate-url)
  (dispatch-rules
    [("time") show-time-page]
    [("hello") greeting-page]
    [("example-post") #:method "post" example-post] ; <=== NEW
    [else (error "There is no procedure to handle the url.")]))
</code>```

Now, in a shell if you do

```<code>curl --data "hi" http://127.0.0.1:8001/example-post
</code>```

it will show the response data got post data: #"hi" --- as will the Racket console.

Title: How do I send data to a Racket server?

Body:
Modifying an online example I have the following code which allows a http request to be made to this Racket webserver;

#lang racket

(require web-server/servlet)
(require web-server/servlet-env)

(define (http-response content)
  (response/full
    200                  ; HTTP response code.
    #"OK"                ; HTTP response message.
    (current-seconds)    ; Timestamp.
    TEXT/HTML-MIME-TYPE  ; MIME type for content.
    '()                  ; Additional HTTP headers.
    (list                ; Content (in bytes) to send to the browser.
      (string->bytes/utf-8 content))))

(define (show-time-page request)
  (http-response (number->string (current-seconds))))

(define (greeting-page request)
  (http-response (list-ref '("Hi" "Hello") (random 2))))

 (define get-data ...)

;; URL routing table (URL dispatcher).
(define-values (dispatch generate-url)
  (dispatch-rules
    [("time") show-time-page]
    [("hello") greeting-page]  ; Notice this line.
    [else (error "There is no procedure to handle the url.")]))

(define (request-handler request)
  (dispatch request))

;; Start the server.
(serve/servlet
  request-handler
  #:launch-browser? #f
  #:quit? #f
  #:listen-ip "127.0.0.1"
  #:port 8001
  #:servlet-regexp #rx"")

How do I change the above code to allow it to receive data (such as a string) posted to the Racket webserver via a http-request and display it in the console? Please can you help?

Body:
Define a request handler for the POST request. Have it extract the posted data from the request:

(define (example-post request)
  (define data (request-post-data/raw request))
  (define str (format "got post data: ~v" data))
  (displayln str)
  (http-response str))

Add the handler to dispatch-rules. Be sure to specify it's handling a POST (not the default GET) request:

;; URL routing table (URL dispatcher).
(define-values (dispatch generate-url)
  (dispatch-rules
    [("time") show-time-page]
    [("hello") greeting-page]
    [("example-post") #:method "post" example-post] ; <=== NEW
    [else (error "There is no procedure to handle the url.")]))

Now, in a shell if you do

curl --data "hi" http://127.0.0.1:8001/example-post

it will show the response data got post data: #"hi" --- as will the Racket console.


问:
Update input "value" attribute with data returned from ajax request...passing in [object, Object]. - Django/Python
I have a ajax script which takes a field from my django form and retrieves a price field - Working Fine

I have a paypal form which I need to update the "amount" value with this retrieved value price. But when I pass it in it is returning as an object.

Would really appreciate any help or better way to accomplish this.

HTML:

```<code><h1>Pay using PayPal</h1><form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="amount" value="0" id="id_amount">
</form>

<script>
$("#id_membership_title").change(function () {
  var url = $("#regForm").attr("data-member-url");
  var membership_title = $(this).val();

  $.ajax({
    url: url,
    data: {
      'membership_title': membership_title
    },
    success: function (data) {
      $("#id_amount").html(data);
      $("#id_price").html(data);
    }
  });
      price = document.getElementById("id_amount");
      price.setAttribute("value", $("id_amount"));
});
</code>```

View To Retrieve Price:

```<code>def ajax_load_price(request):
    membership = request.GET.get('membership_title')
    mem_id = ClubMemberships.objects.filter(pk=membership)
    return render(request, 'load_price_value.html', {'mem_id': mem_id})
</code>```

HTML to render price:

```<code>{% for id in mem_id %}
   {{ id.price }}
{% endfor %}
</code>```

答:
try updating this line:
$("#id_amount").html(data);

to instead:
$("#id_amount").val(data);

Body:
I have a ajax script which takes a field from my django form and retrieves a price field - Working Fine

I have a paypal form which I need to update the "amount" value with this retrieved value price. But when I pass it in it is returning as an object.

Would really appreciate any help or better way to accomplish this.

HTML:

Pay using PayPal
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="amount" value="0" id="id_amount">
</form>


问:
WIndows Git-bash run docker.sock

Problem

OS: Windows 10
I cannot run code bellow in git bash.

Tried using it with winpty but does not help. If I run it from cmd, it has no issues, but that is not a solution because I have a lot of commands in .sh format, so I need bash functionality. I googled the problem, but solutions are only to run from cmd.

Code below is one line

```<code>docker run  -v /var/run/docker.sock:/var/run/docker.sock -d --
publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout
</code>```

Results

I expect something similar to that:

docker run  -v /var/run/docker.sock:/var/run/docker.sock -d --publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout

249a69afcdb3d80e4783c439083ec1ffd30946ccec77f2b64f66a0b41afe29e7

I get that:

docker run  -v /var/run/docker.sock:/var/run/docker.sock -d --publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout

C:/Program Files/Docker/Docker/Resources/bin/docker.exe: Error response from daemon: Mount denied:
The source path "C:/Program Files/Git/var/run/docker.sock;C"
doesn't exist and is not known to Docker.
See 'C:/Program Files/Docker/Docker/Resources/bin/docker.exe run --help'.

答:
Check the error. Your gitbash tried to be smart and appended path to your git at the begging : C:/Program Files/Git/var/run/docker.sock. It is a bug/feature discussed here. A quick workaround would be to mount docker.sock like this :

```<code>-v //var/run/docker.sock:/var/run/docker.sock
</code>```

So your full command will be :

```<code>docker run -v //var/run/docker.sock:/var/run/docker.sock -d --publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout
</code>```

Title: WIndows Git-bash run docker.sock

Body:
Problem

OS: Windows 10
I cannot run code bellow in git bash.

Tried using it with winpty but does not help. If I run it from cmd, it has no issues, but that is not a solution because I have a lot of commands in .sh format, so I need bash functionality. I googled the problem, but solutions are only to run from cmd.

Code below is one line

docker run  -v /var/run/docker.sock:/var/run/docker.sock -d --
publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout

Results

I expect something similar to that:

docker run  -v /var/run/docker.sock:/var/run/docker.sock -d --publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout

249a69afcdb3d80e4783c439083ec1ffd30946ccec77f2b64f66a0b41afe29e7

I get that:

docker run  -v /var/run/docker.sock:/var/run/docker.sock -d --publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout

C:/Program Files/Docker/Docker/Resources/bin/docker.exe: Error response from daemon: Mount denied:
The source path "C:/Program Files/Git/var/run/docker.sock;C"
doesn't exist and is not known to Docker.
See 'C:/Program Files/Docker/Docker/Resources/bin/docker.exe run --help'.

Body:
Check the error. Your gitbash tried to be smart and appended path to your git at the begging : C:/Program Files/Git/var/run/docker.sock. It is a bug/feature discussed here. A quick workaround would be to mount docker.sock like this :

-v //var/run/docker.sock:/var/run/docker.sock

So your full command will be :

docker run -v //var/run/docker.sock:/var/run/docker.sock -d --publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout


问:
Collection Group permissions for Firestore
I have these rules:

```<code>match /suuntoAppAccessTokens/{userName} {
      allow create: if request.auth.uid != null && request.auth.token.firebase.sign_in_provider != 'anonymous';
      match /tokens/{userID} {
        allow read, write, create, update, delete: if request.auth.uid == userID && request.auth.token.firebase.sign_in_provider != 'anonymous';
      }
    }

match /{path=**}/tokens/{userID} {
            allow read, write, create, update, delete: if request.auth.uid == userID;
    }

</code>```

That means that for the path /suuntoAppAccessTokens/dimitrioskanellopoulos/tokens/{userID} the current user should have access.

However, when I query the collection group like so:

```<code>return this.afs.collectionGroup('tokens').snapshotChanges();
</code>```

I get a permission error.

Getting directly the document under tokes/{userID} works as expected.

What can I do so that the current user can run a collectionGroup query and get the items he is permitted to get based on my rules?

答:
Your rule is expecting that the security rule will filter all the documents from all of the tokens collection so that only the current user's documents will be read.  This is not possible with security rules.  Security rules are not filters.  From the documentation:

When writing queries to retrieve documents, keep in mind that security
  rules are not filters—queries are all or nothing. To save you time and
  resources, Cloud Firestore evaluates a query against its potential
  result set instead of the actual field values for all of your
  documents. If a query could potentially return documents that the
  client does not have permission to read, the entire request fails.

You will need to change your query to that the client is only requesting documents that are fully expected to be readable by the current user.  Unfortunately, it's not possible for me tell if this is possible with your current schema.  The ID of the document {userId} can't be used in a collection group query to filter the documents.  So, both you must ensure that both of the following criteria are met:

You will need some field in the document that you can filter on to get this job done.

You will need to adjust your security rule to match exactly what the client is asking for.

I suggest storing the uid of the user in the document with the token, the same as {userId} in the rule.  You can query it like this:

```<code>collectionGroup('tokens').where("uid", "==", uid)
</code>```

Be sure that the client passes in the uid correctly

Also, you will need to make sure that the rule is granting access by the exact same criteria:

```<code>match /{path=**}/tokens/{userID} {
  allow read, write, create, update, delete:
    if request.auth.uid == resource.data.uid;
}
</code>```

This will only allow access to the document if its uid field is the same as the auth uid, which is exactly what the client is asking for.

Body:
I have these rules:

match /suuntoAppAccessTokens/{userName} {
      allow create: if request.auth.uid != null && request.auth.token.firebase.sign_in_provider != 'anonymous';
      match /tokens/{userID} {
        allow read, write, create, update, delete: if request.auth.uid == userID && request.auth.token.firebase.sign_in_provider != 'anonymous';
      }
    }

match /{path=**}/tokens/{userID} {
            allow read, write, create, update, delete: if request.auth.uid == userID;
    }

That means that for the path /suuntoAppAccessTokens/dimitrioskanellopoulos/tokens/{userID} the current user should have access.

However, when I query the collection group like so:

return this.afs.collectionGroup('tokens').snapshotChanges();

I get a permission error.

Getting directly the document under tokes/{userID} works as expected.

What can I do so that the current user can run a collectionGroup query and get the items he is permitted to get based on my rules?

Body:
Your rule is expecting that the security rule will filter all the documents from all of the tokens collection so that only the current user's documents will be read.  This is not possible with security rules.  Security rules are not filters.  From the documentation:

When writing queries to retrieve documents, keep in mind that security
  rules are not filters—queries are all or nothing. To save you time and
  resources, Cloud Firestore evaluates a query against its potential
  result set instead of the actual field values for all of your
  documents. If a query could potentially return documents that the
  client does not have permission to read, the entire request fails.

You will need to change your query to that the client is only requesting documents that are fully expected to be readable by the current user.  Unfortunately, it's not possible for me tell if this is possible with your current schema.  The ID of the document {userId} can't be used in a collection group query to filter the documents.  So, both you must ensure that both of the following criteria are met:

You will need some field in the document that you can filter on to get this job done.

You will need to adjust your security rule to match exactly what the client is asking for.

I suggest storing the uid of the user in the document with the token, the same as {userId} in the rule.  You can query it like this:

collectionGroup('tokens').where("uid", "==", uid)

Be sure that the client passes in the uid correctly

Also, you will need to make sure that the rule is granting access by the exact same criteria:

match /{path=**}/tokens/{userID} {
  allow read, write, create, update, delete:
    if request.auth.uid == resource.data.uid;
}

This will only allow access to the document if its uid field is the same as the auth uid, which is exactly what the client is asking for.


问:
How to correctly make Indy TIdHttp use SSL libraries from a specific folder?
I am successfully using Indy's TIdHttp (version 10 with Delphi 2009) to send data over https using the code below

```<code>var
  HttpClient: TIdHttp;
  IdSSLIOHandler: TIdSSLIOHandlerSocketOpenSSL;
  FormData : TIdMultiPartFormDataStream;

begin
  FormData := TIdMultiPartFormDataStream.Create;
  HttpClient:= TIdHttp.Create;
  IdSSLIOHandler:= TIdSSLIOHandlerSocketOpenSSL.Create;
  HttpClient.IOHandler := IdSSLIOHandler;
  ...
  <the rest of the code that uses HttpClient in the normal way>
  ...
</code>```

However this appears to only work if the SSL files libeay32.dll and  ssleay32.dll are in the same folder as my exe. I need them to be loaded from a ProgramData sub folder instead.

If I copy libeay32.dll and  ssleay32.dll from the exe's folder and place them in a folder C:\ProgramData\CommonData\ and then set the SSL path using IdOpenSSLSetLibPath (see below) the I get an error saying it cannot load the SLL libraries.

```<code>var
  HttpClient: TIdHttp;
  IdSSLIOHandler: TIdSSLIOHandlerSocketOpenSSL;
  FormData : TIdMultiPartFormDataStream;

begin
  FormData := TIdMultiPartFormDataStream.Create;
  HttpClient:= TIdHttp.Create;
  IdSSLIOHandler:= TIdSSLIOHandlerSocketOpenSSL.Create;
  IdOpenSSLSetLibPath('C:\ProgramData\CommonData');  //set path to libeay32.dll and  ssleay32.dll
  HttpClient.IOHandler := IdSSLIOHandler;
   ...
  <the rest of the code that uses HttpClient in the normal way>
  ...
</code>```

Using showmessage(whichfailedtoload ) in the exception handler seems to confirm that it is C:\ProgramData\CommonData\libeay32.dll that is the first to fail to load. So Indy is looking in the right place where it should find the identical file.

I don't know if I should call IdOpenSSLSetLibPath before or after creating HttpClient, or before or after assigning the IdSSLIOHandler but it doesn't seem to make much difference anyway.

I've checked these posts here and here and also a forum post here

Can anyone tell me why the identical SSL libraries load and work correctly when in the exe folder but not when they are in a ProgramData sub folder that is assigned using IdOpenSSLSetLibPath? - Better still how to make it work!

BTW I've even used a binary file comparison utility to ensure that the SSL files in the two locations are identical and also used PE to make sure that when it does work it is really using the DLLs in the exe folder and not from elsewhere.

答:
I believe I have might found the answer. The SSL files I had came from
 openssl-1.0.0j-win32-vc.zip. When I tried again using openssl-1.0.2r-i386-win32.zip, downloaded from https://indy.fulgan.com/SSL/ it worked correctly when the files were in the ProgramData sub folder. So it looks like the 1.0.0j files might have included some sort of dependency with other files that the 1.0.2r don't.

It isn't easy though, although the fulgan site for download is mentioned in some SO posts as if its obvious we are supposed to know about it, not all posts mention it and some just say 'get the latest' libraries. Trying to find out which are the latest and where they are is quite hard. Even the fulgan site has both 1.0.2r and 1.0.2q and there is no indication as to which is the latest (unless the letter is some sort of alphabetical version number)

Body:
I am successfully using Indy's TIdHttp (version 10 with Delphi 2009) to send data over https using the code below

var
  HttpClient: TIdHttp;
  IdSSLIOHandler: TIdSSLIOHandlerSocketOpenSSL;
  FormData : TIdMultiPartFormDataStream;

begin
  FormData := TIdMultiPartFormDataStream.Create;
  HttpClient:= TIdHttp.Create;
  IdSSLIOHandler:= TIdSSLIOHandlerSocketOpenSSL.Create;
  HttpClient.IOHandler := IdSSLIOHandler;
  ...
  <the rest of the code that uses HttpClient in the normal way>
  ...

However this appears to only work if the SSL files libeay32.dll and  ssleay32.dll are in the same folder as my exe. I need them to be loaded from a ProgramData sub folder instead.

If I copy libeay32.dll and  ssleay32.dll from the exe's folder and place them in a folder C:\ProgramData\CommonData\ and then set the SSL path using IdOpenSSLSetLibPath (see below) the I get an error saying it cannot load the SLL libraries.

var
  HttpClient: TIdHttp;
  IdSSLIOHandler: TIdSSLIOHandlerSocketOpenSSL;
  FormData : TIdMultiPartFormDataStream;

begin
  FormData := TIdMultiPartFormDataStream.Create;
  HttpClient:= TIdHttp.Create;
  IdSSLIOHandler:= TIdSSLIOHandlerSocketOpenSSL.Create;
  IdOpenSSLSetLibPath('C:\ProgramData\CommonData');  //set path to libeay32.dll and  ssleay32.dll
  HttpClient.IOHandler := IdSSLIOHandler;
   ...
  <the rest of the code that uses HttpClient in the normal way>
  ...

Using showmessage(whichfailedtoload ) in the exception handler seems to confirm that it is C:\ProgramData\CommonData\libeay32.dll that is the first to fail to load. So Indy is looking in the right place where it should find the identical file.

I don't know if I should call IdOpenSSLSetLibPath before or after creating HttpClient, or before or after assigning the IdSSLIOHandler but it doesn't seem to make much difference anyway.

I've checked these posts here and here and also a forum post here

Can anyone tell me why the identical SSL libraries load and work correctly when in the exe folder but not when they are in a ProgramData sub folder that is assigned using IdOpenSSLSetLibPath? - Better still how to make it work!

BTW I've even used a binary file comparison utility to ensure that the SSL files in the two locations are identical and also used PE to make sure that when it does work it is really using the DLLs in the exe folder and not from elsewhere.


问:
how to create a generic procedure in VHDL?
I have already written code for a generic Carry Look-Ahead Adder. but I can't convert this code to be a procedure in a package. can anyone help me do it?

when I try to compile this code, it does not register n as a generic number.

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity Carry_Look_Ahead is

    Generic(n:integer:=4);

Port ( A : in STD_LOGIC_VECTOR (n-1 downto 0);
B : in STD_LOGIC_VECTOR (n-1 downto 0);
Cin : in STD_LOGIC;
S : out STD_LOGIC_VECTOR (n-1 downto 0);
Cout : out STD_LOGIC);
end Carry_Look_Ahead;

architecture Behavioral of Carry_Look_Ahead is

begin

process(A,B,Cin)

variable ci :STD_LOGIC_VECTOR(n downto 0);
variable P: STD_LOGIC_VECTOR(n-1 downto 0);
variable G: STD_LOGIC_VECTOR(n-1 downto 0);
variable si :STD_LOGIC_VECTOR(n-1 downto 0);
          begin
       ci(0) := Cin;

FOR i IN 0 TO n-1 LOOP

  P(i) := A(i) xor B(i);
  G(i) := A(i) and B(i);
  ci(i+1) := G(i) or (P(i) and G(i));
  si(i) := P(i) xor ci(i);

 END LOOP;
    S<=si;
    Cout<=ci(n);
end process;

end Behavioral;
</code>```

This is the error I get when I try to compile this code:

```<code>Unknown identifier "n".
</code>```

答:
my friend found a solution for this:

you can take an integer as a generic number. here is the finished PROCEDURE:

```<code>PROCEDURE cla (
      SIGNAL n               : IN  INTEGER; -- generic number
      SIGNAL Cin             : IN  STD_LOGIC;
      SIGNAL input1 , input2 : IN  STD_LOGIC_VECTOR;
      SIGNAL Sum             : OUT STD_LOGIC_VECTOR;
      SIGNAL Cout            : OUT STD_LOGIC
   ) IS
      VARIABLE c :STD_LOGIC_VECTOR(n downto 0);
      VARIABLE P: STD_LOGIC_VECTOR(n-1 DOWNTO 0);
      VARIABLE G: STD_LOGIC_VECTOR(n-1 DOWNTO 0);
      VARIABLE s :STD_LOGIC_VECTOR(n-1 DOWNTO 0);
   BEGIN
      c(0) := Cin;
      FOR i IN 0 TO n-1 LOOP
         P(i) := input1(i) XOR input2(i);
         G(i) := input1(i) AND input2(i);
         c(i+1) := G(i) OR (P(i) AND G(i));
         s(i) := P(i) XOR c(i);
      END LOOP;
      Sum<=s;
      Cout<=c(n);
   END cla;
</code>```

Body:
I have already written code for a generic Carry Look-Ahead Adder. but I can't convert this code to be a procedure in a package. can anyone help me do it?

when I try to compile this code, it does not register n as a generic number.

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity Carry_Look_Ahead is

    Generic(n:integer:=4);

Port ( A : in STD_LOGIC_VECTOR (n-1 downto 0);
B : in STD_LOGIC_VECTOR (n-1 downto 0);
Cin : in STD_LOGIC;
S : out STD_LOGIC_VECTOR (n-1 downto 0);
Cout : out STD_LOGIC);
end Carry_Look_Ahead;

architecture Behavioral of Carry_Look_Ahead is

begin

process(A,B,Cin)

variable ci :STD_LOGIC_VECTOR(n downto 0);
variable P: STD_LOGIC_VECTOR(n-1 downto 0);
variable G: STD_LOGIC_VECTOR(n-1 downto 0);
variable si :STD_LOGIC_VECTOR(n-1 downto 0);
          begin
       ci(0) := Cin;

FOR i IN 0 TO n-1 LOOP

  P(i) := A(i) xor B(i);
  G(i) := A(i) and B(i);
  ci(i+1) := G(i) or (P(i) and G(i));
  si(i) := P(i) xor ci(i);

 END LOOP;
    S<=si;
    Cout<=ci(n);
end process;

end Behavioral;

This is the error I get when I try to compile this code:

Unknown identifier "n".

Body:
my friend found a solution for this:

you can take an integer as a generic number. here is the finished PROCEDURE:

PROCEDURE cla (
      SIGNAL n               : IN  INTEGER; -- generic number
      SIGNAL Cin             : IN  STD_LOGIC;
      SIGNAL input1 , input2 : IN  STD_LOGIC_VECTOR;
      SIGNAL Sum             : OUT STD_LOGIC_VECTOR;
      SIGNAL Cout            : OUT STD_LOGIC
   ) IS
      VARIABLE c :STD_LOGIC_VECTOR(n downto 0);
      VARIABLE P: STD_LOGIC_VECTOR(n-1 DOWNTO 0);
      VARIABLE G: STD_LOGIC_VECTOR(n-1 DOWNTO 0);
      VARIABLE s :STD_LOGIC_VECTOR(n-1 DOWNTO 0);
   BEGIN
      c(0) := Cin;
      FOR i IN 0 TO n-1 LOOP
         P(i) := input1(i) XOR input2(i);
         G(i) := input1(i) AND input2(i);
         c(i+1) := G(i) OR (P(i) AND G(i));
         s(i) := P(i) XOR c(i);
      END LOOP;
      Sum<=s;
      Cout<=c(n);
   END cla;


问:
lib dependencies and their order
at times if we don't list libs in certain order inside a makefile, it fails.

The reason being - definition should come before its use.

How to determine the correct order?

答:
Actually, when linking libraries, the use should come before the definition. Any unresolved symbols need to be known before a library file providing their definitions is processed.

What comes to the order, I'm afraid you have to do this manually. If libA depends on libB (i.e. libA uses symbols from libB), then you have to link in this order: -lA -lB.

This is mostly a matter of documentation. A well-documented library clearly states what other libraries it depends on, so you can figure out the correct linking order.

If you don't want to read documentation or there is no documentation available, trial and error is always an option :)

Title: lib dependencies and their order


问:
How to normalize a relative path using pathlib
I'm trying to use relative paths in Python, and I want to put my csv files in a separate folder from my python code.

My python program is in the following folder:

```<code>G:\projects\code
</code>```

I want to read this file which is one level up:

```<code>G:\projects\data\sales.csv
</code>```

How do I specify a path using pathlib that is one level up from my current working folder? I don't want to change the current working folder.

I tried this:

```<code>from pathlib import Path
file = Path.cwd() /'..'/'data'/'sales.csv'
</code>```

But now the 'file' variable equals this:

```<code>'G:/projects/code/../data/sales.csv'
</code>```

I read through the docs and either it isn't explained there or I'm just missing it.

答:
Although it's not a problem that your path includes '..' (you can still use this path to open files, etc. in Python), you can normalize the path using resolve():

from pathlib import Path
path = Path.cwd() / '..' / 'data' / 'sales.csv'
print(path)  # WindowsPath('G:/projects/code/../data/sales.csv')
print(path.resolve())  # WindowsPath('G:/projects/data/sales.csv')
```

NB: I personally would name a variable that contains a path path, not file. So you could later on do file = open(path).

Body:
I'm trying to use relative paths in Python, and I want to put my csv files in a separate folder from my python code.

My python program is in the following folder:

G:\projects\code

I want to read this file which is one level up:

G:\projects\data\sales.csv

How do I specify a path using pathlib that is one level up from my current working folder? I don't want to change the current working folder.

I tried this:

from pathlib import Path
file = Path.cwd() /'..'/'data'/'sales.csv'

But now the 'file' variable equals this:

'G:/projects/code/../data/sales.csv'

I read through the docs and either it isn't explained there or I'm just missing it.

Body:
Although it's not a problem that your path includes '..' (you can still use this path to open files, etc. in Python), you can normalize the path using resolve():

from pathlib import Path
path = Path.cwd() / '..' / 'data' / 'sales.csv'
print(path)  # WindowsPath('G:/projects/code/../data/sales.csv')
print(path.resolve())  # WindowsPath('G:/projects/data/sales.csv')

NB: I personally would name a variable that contains a path path, not file. So you could later on do file = open(path).


问:
How to display data from Firebase faster?
I have label and data from Firebase. I need to get the data, count it and update Label. But I have problem. I get the data later than I start counting it.

```<code> let uid = Auth.auth().currentUser?.uid
        let ref = Database.database().reference()
        ref.child("users").child(uid!).child("weight").observe(.value) { (snapshot) in
            self.userWeight = snapshot.value as! Float
            print(self.userWeight)
        }
</code>```

Than I should count it and display.

```<code>self.maxAmountOfWater = (self.userWeight * 4) / 100
maxWaterLabel.text = String(maxAmountOfWater)
</code>```

Value of Label is 0 because I fetch data slow.
I do it all in viewDidLoad

答:
Data is loaded from Firebase asynchronously, since it may take some time to come down from the server/network. Your main application code continues to run while the data is being loaded. Then once the data is available, your completion handler is called.

For this reason, any code that requires data from the database, must be inside the completion handler, or called from there. Putting it anywhere else makes it uncertain that the data will have loaded by the time the code needs it.

So for example:

```<code>let uid = Auth.auth().currentUser?.uid
let ref = Database.database().reference()
ref.child("users").child(uid!).child("weight").observe(.value) { (snapshot) in
    self.userWeight = snapshot.value as! Float
    print(self.userWeight)

    self.maxAmountOfWater = (self.userWeight * 4) / 100
    maxWaterLabel.text = String(maxAmountOfWater)
}
</code>```

Not the use of self.userWeight is inside the callback, so it has access to the value from the database as soon as it's loaded.

If you want you can also define your own completion handler, that you then call from within the Firebase completion handler, or use a dispatch group. For some examples of this, see:

Finish all asynchronous requests before loading data?

Returning method object from inside block

Is this a good way to display asynchronous data?

Edit:

Just a note that UI updates within a Firebase Closure are called on the main thread. So for example, if you load a tableView dataSource within the closure, you can call tableView.reloadData() within the closure as well without having to use a dispatch group or other thread.

Body:
I have label and data from Firebase. I need to get the data, count it and update Label. But I have problem. I get the data later than I start counting it.

 let uid = Auth.auth().currentUser?.uid
        let ref = Database.database().reference()
        ref.child("users").child(uid!).child("weight").observe(.value) { (snapshot) in
            self.userWeight = snapshot.value as! Float
            print(self.userWeight)
        }

Than I should count it and display.

self.maxAmountOfWater = (self.userWeight * 4) / 100
maxWaterLabel.text = String(maxAmountOfWater)

Value of Label is 0 because I fetch data slow.
I do it all in viewDidLoad

Body:
Data is loaded from Firebase asynchronously, since it may take some time to come down from the server/network. Your main application code continues to run while the data is being loaded. Then once the data is available, your completion handler is called.

For this reason, any code that requires data from the database, must be inside the completion handler, or called from there. Putting it anywhere else makes it uncertain that the data will have loaded by the time the code needs it.

So for example:

let uid = Auth.auth().currentUser?.uid
let ref = Database.database().reference()
ref.child("users").child(uid!).child("weight").observe(.value) { (snapshot) in
    self.userWeight = snapshot.value as! Float
    print(self.userWeight)

    self.maxAmountOfWater = (self.userWeight * 4) / 100
    maxWaterLabel.text = String(maxAmountOfWater)
}

Not the use of self.userWeight is inside the callback, so it has access to the value from the database as soon as it's loaded.

If you want you can also define your own completion handler, that you then call from within the Firebase completion handler, or use a dispatch group. For some examples of this, see:

Finish all asynchronous requests before loading data?

Returning method object from inside block

Is this a good way to display asynchronous data?

Edit:

Just a note that UI updates within a Firebase Closure are called on the main thread. So for example, if you load a tableView dataSource within the closure, you can call tableView.reloadData() within the closure as well without having to use a dispatch group or other thread.


答:
I'm not 100% certain on this but I'll give it a go.

First, let's review a few things being used here.

The comma operator discards the first n-1 expression results and returns the nth result. It's often used as a sequence point, as it's guaranteed that the expressions will be evaluated in order.

The use of __extension__ here, which is a GNU LibC macro, is used to mask any warnings about GNU-specific extensions in headers under compilation environments that specify pedantic warnings, either via -ansi or -pedantic, etc. Usually under such compilers, using a compiler-specific extension would throw a warning (or an error if you're running under -Werror, which is quite common), but since in cases where GNU libraries and compilers are being used, libc allows itself to use some extensions where it can safely do so.

Now, since the actual assertion logic might use a GNU extension (as is indicated by the use of __extension__, any real warnings that the expression itself might have raised given its semantics (that is, the expression passed to assert(expr)) would be masked since that expression would be semantically located within the __extension__ block and thus masked.

Therefore, there needed to be a way to allow the compiler the chance to show those warnings, but without evaluating the actual expression (since the expression could have side effects and a double-evaluation could cause undesired behaviour).

You can do this by using the sizeof operator, which takes an expression, looks at its type, and finds the number of chars it takes up - without actually evaluating the expression.

For example, if we have a function int blow_up_the_world(), then the expression sizeof(blow_up_the_world()) would find the size of the result of the expression (in this case, int) without actually evaluating the expression. Using sizeof() in this case meant the world would, in fact, not be blown up.

However, if the expr passed to assert(expr) contained code that would otherwise trigger a compiler warning (e.g. using an extension under -pedantic or -ansi modes), the compiler would still show those warnings even though the code was inside the sizeof() - warnings that would otherwise be masked inside the __extension__ block.

Next, we see that instead of passing expr directly to sizeof, they instead use a ternary. That's because the type of a ternary is whatever type both resulting expressions have - in this case is int or something equivalent. This is because passing certain things to sizeof will result in a runtime value - namely in the case of variable length arrays - which could have undesired effects, or might produce an error, such as when passing sizeof a function name.

Lastly, they wanted all of that, but before the actual evaluation and wanted to keep assert() as an expression, so instead of using a do{}while() block or something similar, which would ultimately result in assert() being a statement, they instead used the comma operator to discard the result of the first sizeof() trick.

Title: libc6: comma operator in assert macro definition

Body:
My system uses libc6 2.29. In /usr/include/assert.h I can find the definition of assert() macro:

/* The first occurrence of EXPR is not evaluated due to the sizeof,
   but will trigger any pedantic warnings masked by the __extension__
   for the second occurrence.  The ternary operator is required to
   support function pointers and bit fields in this context, and to
   suppress the evaluation of variable length arrays.  */
#  define assert(expr)                          \
  ((void) sizeof ((expr) ? 1 : 0), __extension__ ({         \
      if (expr)                             \
        ; /* empty */                           \
      else                              \
        __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION);   \
    }))

I wonder why to use the comma operator, and what is meant by 'The first occurrence of EXPR is not evaluated due to the sizeof'.

What problem there would be using the following definition:

#  define assert(expr)                      \
  ({                                        \
      if (expr)                             \
           ; /* empty */                            \
      else                              \
           __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION);    \
    })

Edit:

what value does the operator ({ }) get if expr is true?

Is it possible to rewrite the definition of assert() as follows?

#  define assert(expr)                          \
  ((void) sizeof ((expr) ? 1 : 0), __extension__ ({         \
      if (!expr)                                \
          __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION); \
    }))

Where are the problems with this last definition?


问:
Observatory server failed to start - Fails to create Socket Server
I'm building some internal tooling for myself to generate Flutter apps using some templates that I've setup along with some additional functionality that I can share between apps.

At the moment the code compiles, builds fine and deploys but it gets stuck on the first view (blank white screen) and retries to start the Observatory server 11 times before failing. There are no other errors besides the one below.

```<code>Launching lib\main.dart on Android SDK built for x86 in debug mode...
Built build\app\outputs\apk\debug\app-debug.apk.
I/flutter ( 7011): Observatory server failed to start after 1 tries
I/flutter ( 7011): Observatory server failed to start after 2 tries
I/flutter ( 7011): Observatory server failed to start after 3 tries
I/flutter ( 7011): Observatory server failed to start after 4 tries
I/flutter ( 7011): Observatory server failed to start after 5 tries
I/flutter ( 7011): Observatory server failed to start after 6 tries
I/flutter ( 7011): Observatory server failed to start after 7 tries
I/flutter ( 7011): Observatory server failed to start after 8 tries
I/flutter ( 7011): Observatory server failed to start after 9 tries
I/flutter ( 7011): Observatory server failed to start after 10 tries
I/flutter ( 7011): Observatory server failed to start after 11 tries
I/flutter ( 7011): Could not start Observatory HTTP server:
I/flutter ( 7011): SocketException: Failed to create server socket (OS Error: Permission denied, errno = 13), address = 127.0.0.1, port = 0
I/flutter ( 7011): #0      _NativeSocket.bind (dart:io/runtime/bin/socket_patch.dart:591:7)
I/flutter ( 7011): <asynchronous suspension>
I/flutter ( 7011): #1      _RawServerSocket.bind (dart:io/runtime/bin/socket_patch.dart:1206:26)
I/flutter ( 7011): #2      _ServerSocket.bind (dart:io/runtime/bin/socket_patch.dart:1466:29)
I/flutter ( 7011): #3      ServerSocket.bind (dart:io/runtime/bin/socket_patch.dart:1457:26)
I/flutter ( 7011): #4      _HttpServer.bind (dart:_http/http_impl.dart:2520:25)
I/flutter ( 7011): #5      HttpServer.bind (dart:_http/http.dart:227:19)
I/flutter ( 7011): #6      Server.startup.poll (dart:vmservice_io/server.dart:355:36)
I/flutter ( 7011): <asynchronous suspension>
I/flutter ( 7011): #7      Server.startup (dart:vmservice_io/server.dart:367:23)
I/flutter ( 7011): <asynchronous suspension>
I/flutter ( 7011): #8      main (dart:vmservice_io/vmservice_io.dart:253:12)
I/flutter ( 7011):
</code>```

My question's are:

how do I go about debugging this problem?

Do you have an idea of what can cause this?

The code looks the same as the template I'm working off (that works) with the only difference being the package name is different.

Edit 1

Here is the link to the project that hangs for reproduction.

答:
In Android Manifest file add Internet Permission.
I'm also facing this problem. after adding this permission now working fine.

```<code><uses-permission android:name="android.permission.INTERNET"/>
</code>```

Problem is Internet permission is needed in release mode.

Android Manifest file have description for this

The INTERNET permission is required for development. Specifically,
flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.

Body:
I'm building some internal tooling for myself to generate Flutter apps using some templates that I've setup along with some additional functionality that I can share between apps.

At the moment the code compiles, builds fine and deploys but it gets stuck on the first view (blank white screen) and retries to start the Observatory server 11 times before failing. There are no other errors besides the one below.

Launching lib\main.dart on Android SDK built for x86 in debug mode...
Built build\app\outputs\apk\debug\app-debug.apk.
I/flutter ( 7011): Observatory server failed to start after 1 tries
I/flutter ( 7011): Observatory server failed to start after 2 tries
I/flutter ( 7011): Observatory server failed to start after 3 tries
I/flutter ( 7011): Observatory server failed to start after 4 tries
I/flutter ( 7011): Observatory server failed to start after 5 tries
I/flutter ( 7011): Observatory server failed to start after 6 tries
I/flutter ( 7011): Observatory server failed to start after 7 tries
I/flutter ( 7011): Observatory server failed to start after 8 tries
I/flutter ( 7011): Observatory server failed to start after 9 tries
I/flutter ( 7011): Observatory server failed to start after 10 tries
I/flutter ( 7011): Observatory server failed to start after 11 tries
I/flutter ( 7011): Could not start Observatory HTTP server:
I/flutter ( 7011): SocketException: Failed to create server socket (OS Error: Permission denied, errno = 13), address = 127.0.0.1, port = 0
I/flutter ( 7011): #0      _NativeSocket.bind (dart:io/runtime/bin/socket_patch.dart:591:7)
I/flutter ( 7011): <asynchronous suspension>
I/flutter ( 7011): #1      _RawServerSocket.bind (dart:io/runtime/bin/socket_patch.dart:1206:26)
I/flutter ( 7011): #2      _ServerSocket.bind (dart:io/runtime/bin/socket_patch.dart:1466:29)
I/flutter ( 7011): #3      ServerSocket.bind (dart:io/runtime/bin/socket_patch.dart:1457:26)
I/flutter ( 7011): #4      _HttpServer.bind (dart:_http/http_impl.dart:2520:25)
I/flutter ( 7011): #5      HttpServer.bind (dart:_http/http.dart:227:19)
I/flutter ( 7011): #6      Server.startup.poll (dart:vmservice_io/server.dart:355:36)
I/flutter ( 7011): <asynchronous suspension>
I/flutter ( 7011): #7      Server.startup (dart:vmservice_io/server.dart:367:23)
I/flutter ( 7011): <asynchronous suspension>
I/flutter ( 7011): #8      main (dart:vmservice_io/vmservice_io.dart:253:12)
I/flutter ( 7011):

My question's are:

how do I go about debugging this problem?

Do you have an idea of what can cause this?

The code looks the same as the template I'm working off (that works) with the only difference being the package name is different.

Edit 1

Here is the link to the project that hangs for reproduction.

Body:
In Android Manifest file add Internet Permission.
I'm also facing this problem. after adding this permission now working fine.

<uses-permission android:name="android.permission.INTERNET"/>

Problem is Internet permission is needed in release mode.

Android Manifest file have description for this

The INTERNET permission is required for development. Specifically,
flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.


问:
Templates and dependency injection
I have a class template ResourceManager and it is intended to be used something like this:

```<code>ResourceManager<Image>* rm =
    ResourceManager<Image>::Instance();

Image* img = rm->acquire("picture.jpg");
rm->release(img);
</code>```

I'd like to use dependency injection (pass the ResourceManager as a parameter to functions that are supposed to use it instead of having it used globally), however given that it's a template I don't know how to do this. Do you have any suggestions?

My game is only at the beginning of the development and I already have four resource types (Image, Font, Animation and Sound) so making a single ResourceManager (i.e. not a template) with an acquire function for each type of resource is not an option.

Edit: Some clarifications.

What I'm looking for is not how to do dependency injection for one type of ResourceManager, but for all of them at once.

My GameState objects need to load resources when they are initialized/opened; they do so through the ResourceManagers. However, GameStates may need to load any number of types of resources: animations, fonts, images, sounds, etc — that's a lot of function parameters for each kind of ResourceManager! What do you suggest I do?

答:
Well, if the function needs a particular kind of resource (most will, probably), just define the specific template instance as parameter:

```<code>function(ResourceManager<Image> *rm, ...);
</code>```

If the function needs any kind of resource than it can either

Be a template itself, like:

```<code>template <typename T>
function(ResourceManager<T> *rm, ...);
</code>```

It will probably need to refer to the resource obtained from resource manager, so it will need the template argument in more places anyway.

Use a polymorphic base class. That would mean you'd have to define something like

```<code>class ResourceManagerBase { /* methods you need to call via the base class */ };
template <typename T>
class ResourceManager : ResourceManagerBase { ... };

function(ResourceManagerBase *rm, ...)
</code>```

The function can call any methods defined in the base class. If the methods depend on resource-type internally, they will be declared abstract virtual (virtual returnType method(...) = 0) in the base and defined in the template class itself. You can also use dynamic_cast to check which particular instantiation of ResourceManager you've got.

Note, that if the function needs to refer to the resource, you will similarly need a ResourceBase abstract base class of all resources, so you can refer to any kind of resource.

The choice is matter of trade-off between faster but very large code with template function (the function will be compiled for each specialization separately) or slower but smaller code with virtual methods (call to virtual method is slower, but there is no code duplication). Also the template variant will compile slower, because most compilers will generate the code for each object file that uses it and than merge identical copies at link time.

Title: Templates and dependency injection

Body:
I have a class template ResourceManager and it is intended to be used something like this:

ResourceManager<Image>* rm =
    ResourceManager<Image>::Instance();

Image* img = rm->acquire("picture.jpg");
rm->release(img);

I'd like to use dependency injection (pass the ResourceManager as a parameter to functions that are supposed to use it instead of having it used globally), however given that it's a template I don't know how to do this. Do you have any suggestions?

My game is only at the beginning of the development and I already have four resource types (Image, Font, Animation and Sound) so making a single ResourceManager (i.e. not a template) with an acquire function for each type of resource is not an option.

Edit: Some clarifications.

What I'm looking for is not how to do dependency injection for one type of ResourceManager, but for all of them at once.

My GameState objects need to load resources when they are initialized/opened; they do so through the ResourceManagers. However, GameStates may need to load any number of types of resources: animations, fonts, images, sounds, etc — that's a lot of function parameters for each kind of ResourceManager! What do you suggest I do?

Body:
Well, if the function needs a particular kind of resource (most will, probably), just define the specific template instance as parameter:

function(ResourceManager<Image> *rm, ...);

If the function needs any kind of resource than it can either

Be a template itself, like:

template <typename T>
function(ResourceManager<T> *rm, ...);

It will probably need to refer to the resource obtained from resource manager, so it will need the template argument in more places anyway.

Use a polymorphic base class. That would mean you'd have to define something like

class ResourceManagerBase { /* methods you need to call via the base class */ };
template <typename T>
class ResourceManager : ResourceManagerBase { ... };

function(ResourceManagerBase *rm, ...)

The function can call any methods defined in the base class. If the methods depend on resource-type internally, they will be declared abstract virtual (virtual returnType method(...) = 0) in the base and defined in the template class itself. You can also use dynamic_cast to check which particular instantiation of ResourceManager you've got.

Note, that if the function needs to refer to the resource, you will similarly need a ResourceBase abstract base class of all resources, so you can refer to any kind of resource.

The choice is matter of trade-off between faster but very large code with template function (the function will be compiled for each specialization separately) or slower but smaller code with virtual methods (call to virtual method is slower, but there is no code duplication). Also the template variant will compile slower, because most compilers will generate the code for each object file that uses it and than merge identical copies at link time.


问:
Execute action when back bar button of UINavigationController is pressed
I need to execute an action (emptying an array), when the back button of a UINavigationController is pressed, while the button still causes the previous ViewController on the stack to appear. How could I accomplish this using swift?

答:
Here is the simplest possible Swift 5 solution that doesn't require you to create a custom back button and give up all that UINavigationController left button functionality you get for free.

As Brandon A recommends above, you need need to implement UINavigationControllerDelegate in the view controller you want to interact with before returning to it. A good way is to create an unwind segue that you can perform manually or automatically and reuse the same code from a custom done button or the back button.

First, make your view controller of interest (the one you want to detect returning to) a delegate of the navigation controller in its viewDidLoad:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    navigationController?.delegate = self
}
</code>```

Second, add an extension at the bottom of the file that overrides navigationController(willShow:animated:)

```<code>extension PickerTableViewController: UINavigationControllerDelegate {

    func navigationController(_ navigationController: UINavigationController,
                              willShow viewController: UIViewController,
                              animated: Bool) {

        if let _ = viewController as? EditComicBookViewController {

            let selectedItemRow = itemList.firstIndex(of: selectedItemName)
            selectedItemIndex = IndexPath(row: selectedItemRow!, section: 0)

            if let selectedCell = tableView.cellForRow(at: selectedItemIndex) {
                performSegue(withIdentifier: "PickedItem", sender: selectedCell)
            }
        }
    }
}
</code>```

Since your question included a UITableViewController, I included a way to get the index path of the row the user tapped.

Body:
Here is the simplest possible Swift 5 solution that doesn't require you to create a custom back button and give up all that UINavigationController left button functionality you get for free.

As Brandon A recommends above, you need need to implement UINavigationControllerDelegate in the view controller you want to interact with before returning to it. A good way is to create an unwind segue that you can perform manually or automatically and reuse the same code from a custom done button or the back button.

First, make your view controller of interest (the one you want to detect returning to) a delegate of the navigation controller in its viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    navigationController?.delegate = self
}

Second, add an extension at the bottom of the file that overrides navigationController(willShow:animated:)

extension PickerTableViewController: UINavigationControllerDelegate {

    func navigationController(_ navigationController: UINavigationController,
                              willShow viewController: UIViewController,
                              animated: Bool) {

        if let _ = viewController as? EditComicBookViewController {

            let selectedItemRow = itemList.firstIndex(of: selectedItemName)
            selectedItemIndex = IndexPath(row: selectedItemRow!, section: 0)

            if let selectedCell = tableView.cellForRow(at: selectedItemIndex) {
                performSegue(withIdentifier: "PickedItem", sender: selectedCell)
            }
        }
    }
}

Since your question included a UITableViewController, I included a way to get the index path of the row the user tapped.


问:
How to show Markers in google maps from Firebase in flutter?
I am trying to make markers appear on google maps flutter plugin but i dont know what i am doing wrong.

I dont get an error, not one that i can see.

I am using google maps flutter plugin and cloud firestore, this is how i have the data in the cloud firestore:

Here is the code:

```<code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() => runApp(Lugares());

class Lugares extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Lugares',
      home: MapSample(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MapSample extends StatefulWidget {
  @override
  State<MapSample> createState() => MapSampleState();
}

class MapSampleState extends State<MapSample> {
  final Firestore _database = Firestore.instance;
  Completer<GoogleMapController> _controller = Completer();
  Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

  crearmarcadores(){
    _database.collection('Lugares')
              .where('tipo', isEqualTo: 'café')
              .where('tipo', isEqualTo: 'negocio')
              .where('tipo', isEqualTo: 'parque')
              .where('tipo', isEqualTo: 'peluqueria')
              .where('tipo', isEqualTo: 'plaza')
              .where('tipo', isEqualTo: 'restaurant')
              .where('tipo', isEqualTo: 'tienda')
              .getDocuments().then((docs) {
                if(docs.documents.isNotEmpty){
                  for(int i= 0; i < docs.documents.length; i++) {
                    initMarker(docs.documents[i].data, docs.documents[i].documentID);
                  }
                }
              });
  }
  void initMarker(lugar, lugaresid) {
    var markerIdVal = lugaresid;
    final MarkerId markerId = MarkerId(markerIdVal);

    // creating a new MARKER
    final Marker marker = Marker(
      markerId: markerId,
      position: LatLng(lugar['Latitud'], lugar['Longitud']),
      infoWindow: InfoWindow(title: lugar['Lugar'], snippet: lugar['tipo']),
    );

    setState(() {
      // adding a new marker to map
      markers[markerId] = marker;
    });
    }

  static final CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(37.42796133580664, -122.085749655962),
    zoom: 14.4746,
  );

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: GoogleMap(
        mapType: MapType.hybrid,
        initialCameraPosition: _kGooglePlex,
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
        myLocationEnabled: true,
         markers: Set<Marker>.of(markers.values),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _currentLocation,
        label: Text('Ir a mi Ubicacion!'),
        icon: Icon(Icons.location_on),
      ),
    );
  }

void _currentLocation() async {
   final GoogleMapController controller = await _controller.future;
   LocationData currentLocation;
   var location = new Location();
   try {
     currentLocation = await location.getLocation();
     } on Exception {
       currentLocation = null;
       }

    controller.animateCamera(CameraUpdate.newCameraPosition(
      CameraPosition(
        bearing: 0,
        target: LatLng(currentLocation.latitude, currentLocation.longitude),
        zoom: 17.0,
      ),
    ));
  }

}
</code>```

Hope some one could tell me what i am missing.

答: Try removing the where clauses in your Firestone query. It seems like you're trying to apply them as OR logic, but chained where clauses acts as AND. This would result in an empty data list and your markers not showing up.</p>

Body:
I am trying to make markers appear on google maps flutter plugin but i dont know what i am doing wrong.

I dont get an error, not one that i can see.

I am using google maps flutter plugin and cloud firestore, this is how i have the data in the cloud firestore:

Here is the code:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() => runApp(Lugares());

class Lugares extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Lugares',
      home: MapSample(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MapSample extends StatefulWidget {
  @override
  State<MapSample> createState() => MapSampleState();
}

class MapSampleState extends State<MapSample> {
  final Firestore _database = Firestore.instance;
  Completer<GoogleMapController> _controller = Completer();
  Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

  crearmarcadores(){
    _database.collection('Lugares')
              .where('tipo', isEqualTo: 'café')
              .where('tipo', isEqualTo: 'negocio')
              .where('tipo', isEqualTo: 'parque')
              .where('tipo', isEqualTo: 'peluqueria')
              .where('tipo', isEqualTo: 'plaza')
              .where('tipo', isEqualTo: 'restaurant')
              .where('tipo', isEqualTo: 'tienda')
              .getDocuments().then((docs) {
                if(docs.documents.isNotEmpty){
                  for(int i= 0; i < docs.documents.length; i++) {
                    initMarker(docs.documents[i].data, docs.documents[i].documentID);
                  }
                }
              });
  }
  void initMarker(lugar, lugaresid) {
    var markerIdVal = lugaresid;
    final MarkerId markerId = MarkerId(markerIdVal);

    // creating a new MARKER
    final Marker marker = Marker(
      markerId: markerId,
      position: LatLng(lugar['Latitud'], lugar['Longitud']),
      infoWindow: InfoWindow(title: lugar['Lugar'], snippet: lugar['tipo']),
    );

    setState(() {
      // adding a new marker to map
      markers[markerId] = marker;
    });
    }

  static final CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(37.42796133580664, -122.085749655962),
    zoom: 14.4746,
  );

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: GoogleMap(
        mapType: MapType.hybrid,
        initialCameraPosition: _kGooglePlex,
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
        myLocationEnabled: true,
         markers: Set<Marker>.of(markers.values),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _currentLocation,
        label: Text('Ir a mi Ubicacion!'),
        icon: Icon(Icons.location_on),
      ),
    );
  }

void _currentLocation() async {
   final GoogleMapController controller = await _controller.future;
   LocationData currentLocation;
   var location = new Location();
   try {
     currentLocation = await location.getLocation();
     } on Exception {
       currentLocation = null;
       }

    controller.animateCamera(CameraUpdate.newCameraPosition(
      CameraPosition(
        bearing: 0,
        target: LatLng(currentLocation.latitude, currentLocation.longitude),
        zoom: 17.0,
      ),
    ));
  }

}

Hope some one could tell me what i am missing.


问:
How can I count the number of days that match between a data frame with two vectors (start date and end date) and a vector of dates?
I have a very large data set (>12,000 rows) that contains two vectors of the start and end date of a measurement (relative growth rate). Each row has an individual, the date of the initial measurement, the date of the final measurement, and then the growth rate associated with that window. I want to count the number of days within each growth measurement that match dates that are in a separate vector. So ideally I would be adding a vector to the data frame that gives me a count of the number of matching days between the dates in the df and the external vector for each individual's growth rate.

Sample of what the data frame looks like, but in actuality it is much, much larger

```<code>individual <- c(1:5)
initialdate <- c("1990-03-01", "1991-05-07", "1992-05-02",
                 "1994-03-02", "1995-03-08")
enddate <- c("1991-08-05", "1993-02-17", "1995-06-22",
             "1995-09-12", "1997-08-18")
RGR <- c(0.25, 0.3, 0.09, 0.48, 0.34)
df <- data.frame(individual, initialdate, enddate, RGR)

DaysToMatch <- c("1991-03-30", "1993-12-18", ... )

countDays <- function(df$initialdate, df$enddate, DaysToMatch) {
    measurementwindow <- seq(as.Date(initialdate), as.Date(enddate), by="days")
    commonDays <- length(intersect(measurementwindow, DaysToMatch))
    return(commonDays)
}
</code>```

Error in seq.Date(as.Date(InitialDate), as.Date(ObsrvnDate), by = "days") :
    'from' must be of length 1

I also suspect that I am not indexing the vectors properly to calculate the commonDays for each row of the data frame.

答:
You could convert DaysToMatch to date and call countDays function using mapply

```<code>DaysToMatch <- as.Date(c("1991-03-30", "1993-12-18"))

countDays <- function(initialdate, enddate, DaysToMatch) {
   measurementwindow <- seq(as.Date(initialdate), as.Date(enddate), by="days")
   commonDays <- length(intersect(measurementwindow, DaysToMatch))
   #Or sum(DaysToMatch %in% measurementwindow)
   return(commonDays)
}

df$commonDays <- mapply(countDays, df$initialdate, df$enddate,
                 MoreArgs = list(DaysToMatch = DaysToMatch))

df
#  individual initialdate    enddate  RGR commonDays
#1          1  1990-03-01 1991-08-05 0.25          1
#2          2  1991-05-07 1993-02-17 0.30          0
#3          3  1992-05-02 1995-06-22 0.09          1
#4          4  1994-03-02 1995-09-12 0.48          0
#5          5  1995-03-08 1997-08-18 0.34          0
</code>```

However, we can also use dplyr::between to calculate number of values between two boundaries.

```<code>library(dplyr)
library(purrr)

df %>%
  mutate_at(vars(ends_with("Date")), as.Date) %>%
  mutate(commonDays = map2_int(initialdate, enddate,
                      ~sum(dplyr::between(DaysToMatch, .x, .y))))
</code>```

Body:
I have a very large data set (>12,000 rows) that contains two vectors of the start and end date of a measurement (relative growth rate). Each row has an individual, the date of the initial measurement, the date of the final measurement, and then the growth rate associated with that window. I want to count the number of days within each growth measurement that match dates that are in a separate vector. So ideally I would be adding a vector to the data frame that gives me a count of the number of matching days between the dates in the df and the external vector for each individual's growth rate.

Sample of what the data frame looks like, but in actuality it is much, much larger

individual <- c(1:5)
initialdate <- c("1990-03-01", "1991-05-07", "1992-05-02",
                 "1994-03-02", "1995-03-08")
enddate <- c("1991-08-05", "1993-02-17", "1995-06-22",
             "1995-09-12", "1997-08-18")
RGR <- c(0.25, 0.3, 0.09, 0.48, 0.34)
df <- data.frame(individual, initialdate, enddate, RGR)

DaysToMatch <- c("1991-03-30", "1993-12-18", ... )

countDays <- function(df$initialdate, df$enddate, DaysToMatch) {
    measurementwindow <- seq(as.Date(initialdate), as.Date(enddate), by="days")
    commonDays <- length(intersect(measurementwindow, DaysToMatch))
    return(commonDays)
}

Error in seq.Date(as.Date(InitialDate), as.Date(ObsrvnDate), by = "days") :
    'from' must be of length 1

I also suspect that I am not indexing the vectors properly to calculate the commonDays for each row of the data frame.

Body:
You could convert DaysToMatch to date and call countDays function using mapply

DaysToMatch <- as.Date(c("1991-03-30", "1993-12-18"))

countDays <- function(initialdate, enddate, DaysToMatch) {
   measurementwindow <- seq(as.Date(initialdate), as.Date(enddate), by="days")
   commonDays <- length(intersect(measurementwindow, DaysToMatch))
   #Or sum(DaysToMatch %in% measurementwindow)
   return(commonDays)
}

df$commonDays <- mapply(countDays, df$initialdate, df$enddate,
                 MoreArgs = list(DaysToMatch = DaysToMatch))

df
#  individual initialdate    enddate  RGR commonDays
#1          1  1990-03-01 1991-08-05 0.25          1
#2          2  1991-05-07 1993-02-17 0.30          0
#3          3  1992-05-02 1995-06-22 0.09          1
#4          4  1994-03-02 1995-09-12 0.48          0
#5          5  1995-03-08 1997-08-18 0.34          0

However, we can also use dplyr::between to calculate number of values between two boundaries.

library(dplyr)
library(purrr)

df %>%
  mutate_at(vars(ends_with("Date")), as.Date) %>%
  mutate(commonDays = map2_int(initialdate, enddate,
                      ~sum(dplyr::between(DaysToMatch, .x, .y))))