问:
How to get the bounds of a collection of markers with React-Leaflet
How can I get the bounds of a collection of markers, so that these bounds can be used to show all markers on a react-leaflet map?
This is my render function:

```<code>render() {
    const position = [51.505, 4.12];

    return (
        <Map center={position} zoom={3} style={{width: '100%', height: '600px'}} >
            <TileLayer
                attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
            />
            {this.state.markers || null}
        </Map>
    );
}
</code>```

The markers are added to this.state.markers with:

```<code>this.state.markers.push(
    <Marker position={position}>
        <Popup>
            <span>Hello</span>
        </Popup>
    </Marker>
);
this.setState({markers: this.state.markers});
</code>```

The markers are getting displayed, but I want the bounds and centre of the map to be adjusted so the markers fit nicely within the viewport of the map with a certain amount of padding.

Any ideas on how to do this?

Edit: This is my import statement: import {Map, Marker, Popup, TileLayer} from 'react-leaflet';

答:
I'm using the following function in Angular, but I believe it should work for you as well.</p>

```<code>fitMapBounds() {
    // Get all visible Markers
    const visibleMarkers = [];
    this.map.eachLayer(function (layer) {
        if (layer instanceof L.Marker) {
            visibleMarkers.push(layer);
        }
    });

    // Ensure there's at least one visible Marker
    if (visibleMarkers.length > 0) {

        // Create bounds from first Marker then extend it with the rest
        const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]);
        visibleMarkers.forEach((marker) => {
            markersBounds.extend(marker.getLatLng());
        });

        // Fit the map with the visible markers bounds
        this.map.flyToBounds(markersBounds, {
            padding: L.point(36, 36), animate: true,
        });
    }
}
</code>```

Body:
How can I get the bounds of a collection of markers, so that these bounds can be used to show all markers on a react-leaflet map?
This is my render function:

render() {
    const position = [51.505, 4.12];

    return (
        <Map center={position} zoom={3} style={{width: '100%', height: '600px'}} >
            <TileLayer
                attribution='&copy OpenStreetMap contributors'
                url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
            />
            {this.state.markers || null}
        </Map>
    );
}

The markers are added to this.state.markers with:

this.state.markers.push(
    <Marker position={position}>
        <Popup>
            Hello
        </Popup>
    </Marker>
);
this.setState({markers: this.state.markers});

The markers are getting displayed, but I want the bounds and centre of the map to be adjusted so the markers fit nicely within the viewport of the map with a certain amount of padding.

Any ideas on how to do this?

Edit: This is my import statement: import {Map, Marker, Popup, TileLayer} from 'react-leaflet';

Body:
I'm using the following function in Angular, but I believe it should work for you as well.

fitMapBounds() {
    // Get all visible Markers
    const visibleMarkers = [];
    this.map.eachLayer(function (layer) {
        if (layer instanceof L.Marker) {
            visibleMarkers.push(layer);
        }
    });

    // Ensure there's at least one visible Marker
    if (visibleMarkers.length > 0) {

        // Create bounds from first Marker then extend it with the rest
        const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]);
        visibleMarkers.forEach((marker) => {
            markersBounds.extend(marker.getLatLng());
        });

        // Fit the map with the visible markers bounds
        this.map.flyToBounds(markersBounds, {
            padding: L.point(36, 36), animate: true,
        });
    }
}


来源: stackexchange

问:
How to create webhook for telegram bot with heroku?
I am trying to deploy a simple echo2 bot using webhook. It's working fine with polling. But, I want to use the bot using webhook. I didn't find any easy to understand answer for this question on internet.
What changes do I need to make in the below code to make the bot work using webhook..?  </p>

```<code>import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
    """Send a message when the command /start is issued."""
    update.message.reply_text('Hi!')

def help(update, context):
    """Send a message when the command /help is issued."""
    update.message.reply_text('Help!')

def echo(update, context):
    """Echo the user message."""
    update.message.reply_text(update.message.text)

def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)

def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    updater = Updater("TOKEN", use_context=True)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()
</code>```

答:
You can just remove the updater.start_polling() call and use this instead.

Webhook for Heroku python-telegram-bot

Make sure you've already created your application on heroku.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to deploy a simple echo2 bot using webhook. It's working fine with polling. But, I want to use the bot using webhook. I didn't find any easy to understand answer for this question on internet.
What changes do I need to make in the below code to make the bot work using webhook..?

import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
    """Send a message when the command /start is issued."""
    update.message.reply_text('Hi!')

def help(update, context):
    """Send a message when the command /help is issued."""
    update.message.reply_text('Help!')

def echo(update, context):
    """Echo the user message."""
    update.message.reply_text(update.message.text)

def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)

def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    updater = Updater("TOKEN", use_context=True)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()


问:
UIPickerView freezes UI when reloaded
The ui of my app freezes when the index of the UIPickerView gets to 1 or the number of elements is 2. Im really confused because this was working then all the sudden its broken. Ive done some research and found it may be something to do with a thread. Can someone help me solve the issue with the UIPickerView?

```<code>// class implements UIPickerViewDelegate, UIPickerViewDataSource, UIGestureRecognizerDelegate

     @IBOutlet weak var planetPickerView: UIView!
     var planetPicker: UIPickerView!
</code>```

View did load:

```<code>override func viewDidLoad() {
     super.viewDidLoad()
     //Other code not important
     configurePlanetPicker()
}
</code>```

UIPickerView implementation: (skyBalls is an array of classes whit various data as getters)

```<code> func configurePlanetPicker() {
        planetPicker = UIPickerView(frame: CGRect(x: 0, y: 0, width: planetPickerView.frame.width, height: 70))
        planetPicker.delegate = self
        planetPicker.dataSource = self
        planetPicker.transform = CGAffineTransform(rotationAngle: CGFloat(-90 * (Double.pi/180)))
        planetPicker.frame = CGRect(x: -100, y: 0, width: planetPickerView.frame.width + 200, height: 70)
        planetPicker.showsSelectionIndicator = false
        planetPickerView.backgroundColor = .clear
        let tap = UITapGestureRecognizer(target: self, action: #selector(pickerTapped))
        tap.delegate = self
        planetPicker.addGestureRecognizer(tap)
        planetPickerView.addSubview(planetPicker)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {return skyBalls.count }

    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 70 }

    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { return 70 }

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let mainView = UIView(frame: CGRect(x: 0, y: 0, width: 70, height: 70))

        let image = UIImageView(frame: CGRect(x: 15, y: 10, width: 40, height: 40))
        image.image = UIImage(named: "\(skyBalls[row].getImage().split(separator: ".")[0])")
        image.contentMode = .scaleAspectFit
        mainView.addSubview(image)

        let titleLbl = UILabel(frame: CGRect(x: 0, y: 50, width: 70, height: 20))
        titleLbl.text = skyBalls[row].getName()
        titleLbl.textColor = .white
        titleLbl.textAlignment = .center
        titleLbl.adjustsFontSizeToFitWidth = true
        mainView.addSubview(titleLbl)

        mainView.transform = CGAffineTransform(rotationAngle: 90 * CGFloat((Double.pi/180)))
        return mainView
    }

    @objc func pickerTapped(tapRecognizer: UITapGestureRecognizer) {
        if tapRecognizer.state == .ended {
            let rowHeight = planetPicker.rowSize(forComponent: 0).height
            let selectedRowFrame = planetPicker.bounds.insetBy(dx: 0, dy: (planetPicker.frame.height - rowHeight) / 2)
            let userTappedOnSelectedRow = selectedRowFrame.contains(tapRecognizer.location(in: planetPicker))
            if userTappedOnSelectedRow {
                let selectedRow = planetPicker.selectedRow(inComponent: 0)
                upgradePlanetName = skyBalls[selectedRow].getName()
                let settings = UIStoryboard(name: "PlanetUpgrade", bundle: .main).instantiateViewController(withIdentifier: "Upgrade") as! UpgradeViewController
                self.present(settings, animated: false)
            }
        }
    }

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
</code>```

I do reload the UIPickerView upon a button press that increases the size of the skyBalls array:

```<code>planetPicker.reloadAllComponents()
</code>```

BUT the problem still occurs if planetPicker.reloadAllComponents() is entirely removed in all forms from the project.

I have tried restating my mac, iphone, and xcode, as well as deleting derived data. I cleaned the build folder and nothing seems to fix the issue.

Thank you in advance.

答:
Ok so I found out that it wasn't the UIpickerView's fault at all.
So after looking around I tried this:

1) Open "Breakpoint navigator"

2) tap '+' button and choose the "Exception Breakpoint" option

it then took me to the root of the problem witch was an array index out of bounds that for some reason wasn't crashing the app.

Title: UIPickerView freezes UI when reloaded

Body:
The ui of my app freezes when the index of the UIPickerView gets to 1 or the number of elements is 2. Im really confused because this was working then all the sudden its broken. Ive done some research and found it may be something to do with a thread. Can someone help me solve the issue with the UIPickerView?

// class implements UIPickerViewDelegate, UIPickerViewDataSource, UIGestureRecognizerDelegate

     @IBOutlet weak var planetPickerView: UIView!
     var planetPicker: UIPickerView!

View did load:

override func viewDidLoad() {
     super.viewDidLoad()
     //Other code not important
     configurePlanetPicker()
}

UIPickerView implementation: (skyBalls is an array of classes whit various data as getters)

 func configurePlanetPicker() {
        planetPicker = UIPickerView(frame: CGRect(x: 0, y: 0, width: planetPickerView.frame.width, height: 70))
        planetPicker.delegate = self
        planetPicker.dataSource = self
        planetPicker.transform = CGAffineTransform(rotationAngle: CGFloat(-90 * (Double.pi/180)))
        planetPicker.frame = CGRect(x: -100, y: 0, width: planetPickerView.frame.width + 200, height: 70)
        planetPicker.showsSelectionIndicator = false
        planetPickerView.backgroundColor = .clear
        let tap = UITapGestureRecognizer(target: self, action: #selector(pickerTapped))
        tap.delegate = self
        planetPicker.addGestureRecognizer(tap)
        planetPickerView.addSubview(planetPicker)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {return skyBalls.count }

    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 70 }

    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { return 70 }

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let mainView = UIView(frame: CGRect(x: 0, y: 0, width: 70, height: 70))

        let image = UIImageView(frame: CGRect(x: 15, y: 10, width: 40, height: 40))
        image.image = UIImage(named: "\(skyBalls[row].getImage().split(separator: ".")[0])")
        image.contentMode = .scaleAspectFit
        mainView.addSubview(image)

        let titleLbl = UILabel(frame: CGRect(x: 0, y: 50, width: 70, height: 20))
        titleLbl.text = skyBalls[row].getName()
        titleLbl.textColor = .white
        titleLbl.textAlignment = .center
        titleLbl.adjustsFontSizeToFitWidth = true
        mainView.addSubview(titleLbl)

        mainView.transform = CGAffineTransform(rotationAngle: 90 * CGFloat((Double.pi/180)))
        return mainView
    }

    @objc func pickerTapped(tapRecognizer: UITapGestureRecognizer) {
        if tapRecognizer.state == .ended {
            let rowHeight = planetPicker.rowSize(forComponent: 0).height
            let selectedRowFrame = planetPicker.bounds.insetBy(dx: 0, dy: (planetPicker.frame.height - rowHeight) / 2)
            let userTappedOnSelectedRow = selectedRowFrame.contains(tapRecognizer.location(in: planetPicker))
            if userTappedOnSelectedRow {
                let selectedRow = planetPicker.selectedRow(inComponent: 0)
                upgradePlanetName = skyBalls[selectedRow].getName()
                let settings = UIStoryboard(name: "PlanetUpgrade", bundle: .main).instantiateViewController(withIdentifier: "Upgrade") as! UpgradeViewController
                self.present(settings, animated: false)
            }
        }
    }

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }

I do reload the UIPickerView upon a button press that increases the size of the skyBalls array:

planetPicker.reloadAllComponents()

BUT the problem still occurs if planetPicker.reloadAllComponents() is entirely removed in all forms from the project.

I have tried restating my mac, iphone, and xcode, as well as deleting derived data. I cleaned the build folder and nothing seems to fix the issue.

Thank you in advance.


问:
Querying attributes and node values from XML stored in an XML data type
I have written an interface to interact with the CubeIQ BlackBox (www.magiclogic.com) and I have an SQL Server 2005 database table where I store some regular text fields, dates, and two pieces of XML in columns that have an XML data type.

There are a few values I want to pick out of the XML, and I cannot figure out how to query the XML, or the attributes of nodes within that XML.

Here is the type of query I want to do:

```<code> SELECT
    [regular_table_field1],
    [regular_table_field2],
    [opt_resposne_xml].rootnode.wrapper.child@attr('someattribute') AS 'someattribute',
    [opt_resposne_xml].rootnode.wrapper.child@attr('someattribute2') AS 'someattribute2'
 FROM [optimizations] WHERE [opt_concept_id] = '1234'
</code>```

答:
Not knowing what your XML looks like, here's a general purpose piece of code to give you an idea of what it would look like:

```<code> SELECT
    [regular_table_field1],
    [regular_table_field2],
    [opt_resposne_xml].value('(/rootnode/wrapper/child/@someattribute)[1]', 'int') AS 'someattribute',
    [opt_resposne_xml].value('(/rootnode/wrapper/child/@someattribute2)[1]', 'varchar(50)') AS 'someattribute2'
 FROM
     [optimizations]
 WHERE
     [opt_concept_id] = '1234'
</code>```

If you need to "reach into" the XML column and grab out a single value (from an XML element or attribute), you basically need to define the XPath to that location of where the information you're interested in is located, and you need to convert that to a given SQL Server datatype.

If you need to have a single relational row cross joined against a number of elements from a single XML field, you might need other approaches (CROSS APPLY).

Also: you might need to pay attention to XML namespaces that are involved - a common pitfall when trying to parse XML inside SQL Server.

ContentLicense: CC BY-SA 3.0

Body:
I have written an interface to interact with the CubeIQ BlackBox (www.magiclogic.com) and I have an SQL Server 2005 database table where I store some regular text fields, dates, and two pieces of XML in columns that have an XML data type.

There are a few values I want to pick out of the XML, and I cannot figure out how to query the XML, or the attributes of nodes within that XML.

Here is the type of query I want to do:

 SELECT
    [regular_table_field1],
    [regular_table_field2],
    [opt_resposne_xml].rootnode.wrapper.child@attr('someattribute') AS 'someattribute',
    [opt_resposne_xml].rootnode.wrapper.child@attr('someattribute2') AS 'someattribute2'
 FROM [optimizations] WHERE [opt_concept_id] = '1234'

Body:
Not knowing what your XML looks like, here's a general purpose piece of code to give you an idea of what it would look like:

 SELECT
    [regular_table_field1],
    [regular_table_field2],
    [opt_resposne_xml].value('(/rootnode/wrapper/child/@someattribute)[1]', 'int') AS 'someattribute',
    [opt_resposne_xml].value('(/rootnode/wrapper/child/@someattribute2)[1]', 'varchar(50)') AS 'someattribute2'
 FROM
     [optimizations]
 WHERE
     [opt_concept_id] = '1234'

If you need to "reach into" the XML column and grab out a single value (from an XML element or attribute), you basically need to define the XPath to that location of where the information you're interested in is located, and you need to convert that to a given SQL Server datatype.

If you need to have a single relational row cross joined against a number of elements from a single XML field, you might need other approaches (CROSS APPLY).

Also: you might need to pay attention to XML namespaces that are involved - a common pitfall when trying to parse XML inside SQL Server.


问:
Case_when dplyr
I am trying to create a buy/sell signal.  I am trying to assign the signal using a case_when statement.  I created several new columns using tidyquant TQ_MUTATE in a previous step.  This only assigns the "possible up" and "possible down" signals.

What am I doing wrong?

df_with_decisions <- test %>%
  group_by(symbol) %>%
  mutate(

```<code>signal = case_when(
   (EMA_9 > EMA_55) ~ "possible up",
  (EMA_9 > EMA_55 && EVWMA_9 > EMA_55) ~ "watch upward",
  (EMA_9 > EMA_55 && EMA_21 >= EMA_55 && EVWMA_9 > EMA_55) ~ "buy",
  (EMA_9 > EMA_55 && EMA_21 >= EMA_55 && EVWMA_9 > EMA_55 && EVWMA_21 > EMA_55) ~ "strong_buy",
  EMA_9 < EMA_55 ~ "possible down",
  (EMA_9 < EMA_55 && EVWMA_9 < EMA_55) ~ "watch downward",
  (EMA_9 < EMA_55 && EMA_21 <= EMA_55 && EVWMA_9 < EMA_55) ~ "sell",
  (EMA_9 < EMA_55 && EMA_21 <= EMA_55 && EVWMA_9 < EMA_55 && EVWMA_21 < EMA_55) ~ "strong_sell",
  ),

previous_signal = lag(signal, 1),

decision = case_when(
  signal == previous_signal ~ "hold",
  TRUE ~ signal    )  )
</code>```

答:
The issue would be that && which returns a single TRUE/FALSE output instead of logical vector of the same length as input

test %>%
     group_by(symbol) %>%
     mutate(

signal = case_when(
   (EMA_9 > EMA_55) ~ "possible up",
  (EMA_9 > EMA_55 & EVWMA_9 > EMA_55) ~ "watch upward",
  (EMA_9 > EMA_55 & EMA_21 >= EMA_55 & EVWMA_9 > EMA_55) ~ "buy",
  (EMA_9 > EMA_55 & EMA_21 >= EMA_55 & EVWMA_9 > EMA_55 & EVWMA_21 > EMA_55) ~ "strong_buy",
  EMA_9 < EMA_55 ~ "possible down",
  (EMA_9 < EMA_55 & EVWMA_9 < EMA_55) ~ "watch downward",
  (EMA_9 < EMA_55 & EMA_21 <= EMA_55 & EVWMA_9 < EMA_55) ~ "sell",
  (EMA_9 < EMA_55 && EMA_21 <= EMA_55 & EVWMA_9 < EMA_55 & EVWMA_21 < EMA_55) ~ "strong_sell",
  ),

previous_signal = lag(signal, 1),

decision = case_when(
  signal == previous_signal ~ "hold",
  TRUE ~ signal    )  )
```

Title: Case_when dplyr

Body:
I am trying to create a buy/sell signal.  I am trying to assign the signal using a case_when statement.  I created several new columns using tidyquant TQ_MUTATE in a previous step.  This only assigns the "possible up" and "possible down" signals.

What am I doing wrong?

df_with_decisions <- test %>%
  group_by(symbol) %>%
  mutate(

signal = case_when(
   (EMA_9 > EMA_55) ~ "possible up",
  (EMA_9 > EMA_55 && EVWMA_9 > EMA_55) ~ "watch upward",
  (EMA_9 > EMA_55 && EMA_21 >= EMA_55 && EVWMA_9 > EMA_55) ~ "buy",
  (EMA_9 > EMA_55 && EMA_21 >= EMA_55 && EVWMA_9 > EMA_55 && EVWMA_21 > EMA_55) ~ "strong_buy",
  EMA_9 < EMA_55 ~ "possible down",
  (EMA_9 < EMA_55 && EVWMA_9 < EMA_55) ~ "watch downward",
  (EMA_9 < EMA_55 && EMA_21 <= EMA_55 && EVWMA_9 < EMA_55) ~ "sell",
  (EMA_9 < EMA_55 && EMA_21 <= EMA_55 && EVWMA_9 < EMA_55 && EVWMA_21 < EMA_55) ~ "strong_sell",
  ),

previous_signal = lag(signal, 1),

decision = case_when(
  signal == previous_signal ~ "hold",
  TRUE ~ signal    )  )


问:
C# generic with constant
Is there something similar to this C++ template?

```<code>template <int A>
class B
{
    int f()
    {
        return A;
    }
}
</code>```

I want to make every instance of B<1>, B<2>, etc (eg tuple) a different type.

答:
The following approach may be useful depending on what you're trying to accomplish. The size of the underlying collection is determined by an abstract property.</p>

```<code>public abstract class TupleBase
{
    protected abstract int NumElems { get; }
    protected object[] values;

    protected TupleBase(params object[] init)
    {
        if (init.Length != NumElems)
        {
            throw new ArgumentException($"Collection must contains {NumElems} elements", nameof(init));
        }
        values = new object[NumElems];
        for (int i = 0; i < init.Length; i++)
        {
            values[i] = init[i];
        }
    }

    protected object Get(int idx) => values[idx];
    protected void Set(int idx, object value) => values[idx] = value;
}

public class Tuple1<T> : TupleBase {
    protected override int NumElems => 1;
    public Tuple1(T val0) : base(val0) { }
    public T Get0() => (T)Get(0);
    public void Set0(T value) => Set(0, value);
}

public class Tuple2<T, U> : TupleBase {
    protected override int NumElems => 2;
    public Tuple2(T val0, U val1) : base(val0, val1) { }
    public T Get0() => (T)Get(0);
    public U Get1() => (U)Get(1);
    public void Set0(T value) => Set(0, value);
    public void Set1(U value) => Set(1, value);
}

public class Tuple3<T, U, V> : TupleBase
{
    protected override int NumElems => 3;
    public Tuple3(T val0, U val1, V val2) : base(val0, val1, val2) { }
    public T Get0() => (T)Get(0);
    public U Get1() => (U)Get(1);
    public V Get2() => (V)Get(2);
    public void Set0(T value) => Set(0, value);
    public void Set1(U value) => Set(1, value);
    public void Set2(V value) => Set(2, value);
}

public class Tuple4<T, U, V, W> : TupleBase
{
    protected override int NumElems => 4;
    public Tuple4(T val0, U val1, V val2, W val3) : base(val0, val1, val2, val3) { }

    public T Get0() => (T)Get(0);
    public U Get1() => (U)Get(1);
    public V Get2() => (V)Get(2);
    public W Get3() => (W)Get(3);
    public void Set0(T value) => Set(0, value);
    public void Set1(U value) => Set(1, value);
    public void Set2(V value) => Set(2, value);
    public void Set3(W value) => Set(3, value);
}

public class Tuple5<T, U, V, W, X> : TupleBase
{
    protected override int NumElems => 5;
    public Tuple5(T val0, U val1, V val2, W val3, X val4) : base(val0, val1, val2, val3, val4) { }
    public T Get0() => (T)Get(0);
    public U Get1() => (U)Get(1);
    public V Get2() => (V)Get(2);
    public W Get3() => (W)Get(3);
    public X Get4() => (X)Get(4);
    public void Set0(T value) => Set(0, value);
    public void Set1(U value) => Set(1, value);
    public void Set2(V value) => Set(2, value);
    public void Set3(W value) => Set(3, value);
    public void Set4(X value) => Set(4, value);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: C# generic with constant

Body:
Is there something similar to this C++ template?

template <int A>
class B
{
    int f()
    {
        return A;
    }
}

I want to make every instance of B<1>, B<2>, etc (eg tuple) a different type.

Body:
The following approach may be useful depending on what you're trying to accomplish. The size of the underlying collection is determined by an abstract property.

public abstract class TupleBase
{
    protected abstract int NumElems { get; }
    protected object[] values;

    protected TupleBase(params object[] init)
    {
        if (init.Length != NumElems)
        {
            throw new ArgumentException($"Collection must contains {NumElems} elements", nameof(init));
        }
        values = new object[NumElems];
        for (int i = 0; i < init.Length; i++)
        {
            values[i] = init[i];
        }
    }

    protected object Get(int idx) => values[idx];
    protected void Set(int idx, object value) => values[idx] = value;
}

public class Tuple1<T> : TupleBase {
    protected override int NumElems => 1;
    public Tuple1(T val0) : base(val0) { }
    public T Get0() => (T)Get(0);
    public void Set0(T value) => Set(0, value);
}

public class Tuple2<T, U> : TupleBase {
    protected override int NumElems => 2;
    public Tuple2(T val0, U val1) : base(val0, val1) { }
    public T Get0() => (T)Get(0);
    public U Get1() => (U)Get(1);
    public void Set0(T value) => Set(0, value);
    public void Set1(U value) => Set(1, value);
}

public class Tuple3<T, U, V> : TupleBase
{
    protected override int NumElems => 3;
    public Tuple3(T val0, U val1, V val2) : base(val0, val1, val2) { }
    public T Get0() => (T)Get(0);
    public U Get1() => (U)Get(1);
    public V Get2() => (V)Get(2);
    public void Set0(T value) => Set(0, value);
    public void Set1(U value) => Set(1, value);
    public void Set2(V value) => Set(2, value);
}

public class Tuple4<T, U, V, W> : TupleBase
{
    protected override int NumElems => 4;
    public Tuple4(T val0, U val1, V val2, W val3) : base(val0, val1, val2, val3) { }

    public T Get0() => (T)Get(0);
    public U Get1() => (U)Get(1);
    public V Get2() => (V)Get(2);
    public W Get3() => (W)Get(3);
    public void Set0(T value) => Set(0, value);
    public void Set1(U value) => Set(1, value);
    public void Set2(V value) => Set(2, value);
    public void Set3(W value) => Set(3, value);
}

public class Tuple5<T, U, V, W, X> : TupleBase
{
    protected override int NumElems => 5;
    public Tuple5(T val0, U val1, V val2, W val3, X val4) : base(val0, val1, val2, val3, val4) { }
    public T Get0() => (T)Get(0);
    public U Get1() => (U)Get(1);
    public V Get2() => (V)Get(2);
    public W Get3() => (W)Get(3);
    public X Get4() => (X)Get(4);
    public void Set0(T value) => Set(0, value);
    public void Set1(U value) => Set(1, value);
    public void Set2(V value) => Set(2, value);
    public void Set3(W value) => Set(3, value);
    public void Set4(X value) => Set(4, value);
}


问:
SQL Server: problems with max and IN clause
I have this table in SQL Server 2008:

```<code>create table [hFUNDASSET]
(
    [hFundAssetID] numeric(19,0) identity not null,
    [fundAssetID] numeric(19,0) not null,
    [modified] datetime not null,
    primary key ([hFundAssetID])
);
</code>```

Its a history table, the goal is to get the closest hFundAssetID based on a given max modified column timestamp, for every distinct fundAssetID.

The following query gets the correct latest modified for each fundAssetID:

```<code>select max(modified), fundAssetID
    from hFundAsset
 where fundAssetID IN
    (
        select distinct (fundAssetID)
            from hFundAsset where modified < 'April 20, 2010 11:13:00'
    )
group by fundAssetID;
</code>```

I can't put the hFundAssetID in the select clause without it being in the group by , which would return extra rows. Somehow, I need the hFundAssetID matching each one of the modified, fundAssetID pairs returned in the above query, or equivalent. But SQL Server doesn't allow multiple values for the IN clause, according to their docs:

"subquery - Is a subquery that has a result set of one column.
           This column must have the same data type as test_expression."

Googling shows that 'exists' and joins are typically used with mssql in these cases, but I've tried that using 'max' and 'group by' and I'm having problems getting it to work. Any help appreciated.

答:
Try this:</p>

```<code>WITH qry AS
(
    SELECT a.*,
            RANK() OVER(PARTITION BY fundAssetID ORDER BY modified DESC) rnk
        FROM hFundAsset a
     WHERE modified < 'April 20, 2010 11:13:00'
)
SELECT *
  FROM qry
WHERE rnk = 1
</code>```

Body:
I have this table in SQL Server 2008:

create table [hFUNDASSET]
(
    [hFundAssetID] numeric(19,0) identity not null,
    [fundAssetID] numeric(19,0) not null,
    [modified] datetime not null,
    primary key ([hFundAssetID])
);

Its a history table, the goal is to get the closest hFundAssetID based on a given max modified column timestamp, for every distinct fundAssetID.

The following query gets the correct latest modified for each fundAssetID:

select max(modified), fundAssetID
    from hFundAsset
 where fundAssetID IN
    (
        select distinct (fundAssetID)
            from hFundAsset where modified < 'April 20, 2010 11:13:00'
    )
group by fundAssetID;

I can't put the hFundAssetID in the select clause without it being in the group by , which would return extra rows. Somehow, I need the hFundAssetID matching each one of the modified, fundAssetID pairs returned in the above query, or equivalent. But SQL Server doesn't allow multiple values for the IN clause, according to their docs:

"subquery - Is a subquery that has a result set of one column.
           This column must have the same data type as test_expression."

Googling shows that 'exists' and joins are typically used with mssql in these cases, but I've tried that using 'max' and 'group by' and I'm having problems getting it to work. Any help appreciated.

Body:
Try this:

WITH qry AS
(
    SELECT a.*,
            RANK() OVER(PARTITION BY fundAssetID ORDER BY modified DESC) rnk
        FROM hFundAsset a
     WHERE modified < 'April 20, 2010 11:13:00'
)
SELECT *
  FROM qry
WHERE rnk = 1


问:
Selenium - Java - how to assert/verify all links on a page are working, get title and verify against expected titles
I am new to test automation and i am currently working on a personal project

I have this method in which it finds all the links for a section on the page, clicks on each link, irritates through each tab and then gets the title of each page

However, i want a way to verify the titles of these links against a list of expected titles

What would be the best approach to modify this in order to do this? would it be better to store in an array and then assert/verify each title separately?

I have tried a few ways to assert by changes return type to String and also to List but with no luck

```<code>public void linksAreWorkingDashBoardLeftPanal() throws Exception {

    List<WebElement> li_All = links_myAccountNav.findElements(By.tagName("a"));
    for(int i = 0; i < li_All.size(); i++){

        String clickOnLinkTab = Keys.chord(Keys.CONTROL, Keys.ENTER);
        links_myAccountNav.findElements(By.tagName("a")).get(i).sendKeys(clickOnLinkTab);
        Thread.sleep(5000);

    }

    //Opens all the tabs
    Set<String> getTitleinWindow = driver.getWindowHandles();
    Iterator<String> it = getTitleinWindow.iterator();

    while(it.hasNext())
    {

          driver.switchTo().window(it.next());
          System.out.println(driver.getTitle());
    }
</code>```

答:
Modify the while loop as follows;

```<code>List<String> expectedTitleList = new ArrayList<>();
// Get the expected titles in a list.
// You have to initiate and add expected titles to this list, before running the while loop.

List<String> actualTitleList = new ArrayList<>();
    while(it.hasNext())
    {
          driver.switchTo().window(it.next());
          actualTitleList.add(driver.getTitle());
    }

// Create copies of each list;
Set<String> expectedSet = new HashSet<>(expectedTitleList);
Set<String> actualSet = new HashSet<>(actualTitleList);

Set<String> expectedOnlySet = new HashSet<>(expectedSet);
Set<String> actualOnlySet = new HashSet<>(actualSet);

expectedOnlySet.removeAll(actualSet);
actualOnlySet.removeAll(expectedSet);

// Check if expectedOnlySet and actualOnlySet are empty
// If both of them are empty then all titles are received as expected.

boolean isEmpty = (expectedOnlySet.size() == 0 && actualOnlySet.size() == 0);

if (expectedOnlySet.size() > 0 || actualOnlySet.size() > 0) {
   // If expectedOnlySet contain any title; it means those titles are not opened in the browser.

   // If actualOnlySet contain any title; it means those titles are not expected titles.
   StringBuilder message = new StringBuilder();

   for (String x: expectedOnlySet) {
       message.append("Did not receive: ");
       message.append(x).append(", ");
   }

   for (String y: actualOnlySet) {
       message.append("Not expected but received: ");
       message.append(y).append(", ");
   }

   Assert.assertTrue(false, message,toString());
}else {
   Assert.assertTrue(true);
}
</code>```

Here you can use removeAll() method in Collections. Check the documentation

We have to check both scenarios;

Whether all expected titles are received

All received titles are expected

Body:
I am new to test automation and i am currently working on a personal project

I have this method in which it finds all the links for a section on the page, clicks on each link, irritates through each tab and then gets the title of each page

However, i want a way to verify the titles of these links against a list of expected titles

What would be the best approach to modify this in order to do this? would it be better to store in an array and then assert/verify each title separately?

I have tried a few ways to assert by changes return type to String and also to List but with no luck

public void linksAreWorkingDashBoardLeftPanal() throws Exception {

    List<WebElement> li_All = links_myAccountNav.findElements(By.tagName("a"));
    for(int i = 0; i < li_All.size(); i++){

        String clickOnLinkTab = Keys.chord(Keys.CONTROL, Keys.ENTER);
        links_myAccountNav.findElements(By.tagName("a")).get(i).sendKeys(clickOnLinkTab);
        Thread.sleep(5000);

    }

    //Opens all the tabs
    Set<String> getTitleinWindow = driver.getWindowHandles();
    Iterator<String> it = getTitleinWindow.iterator();

    while(it.hasNext())
    {

          driver.switchTo().window(it.next());
          System.out.println(driver.getTitle());
    }

Body:
Modify the while loop as follows;

List<String> expectedTitleList = new ArrayList<>();
// Get the expected titles in a list.
// You have to initiate and add expected titles to this list, before running the while loop.

List<String> actualTitleList = new ArrayList<>();
    while(it.hasNext())
    {
          driver.switchTo().window(it.next());
          actualTitleList.add(driver.getTitle());
    }

// Create copies of each list;
Set<String> expectedSet = new HashSet<>(expectedTitleList);
Set<String> actualSet = new HashSet<>(actualTitleList);

Set<String> expectedOnlySet = new HashSet<>(expectedSet);
Set<String> actualOnlySet = new HashSet<>(actualSet);

expectedOnlySet.removeAll(actualSet);
actualOnlySet.removeAll(expectedSet);

// Check if expectedOnlySet and actualOnlySet are empty
// If both of them are empty then all titles are received as expected.

boolean isEmpty = (expectedOnlySet.size() == 0 && actualOnlySet.size() == 0);

if (expectedOnlySet.size() > 0 || actualOnlySet.size() > 0) {
   // If expectedOnlySet contain any title; it means those titles are not opened in the browser.

   // If actualOnlySet contain any title; it means those titles are not expected titles.
   StringBuilder message = new StringBuilder();

   for (String x: expectedOnlySet) {
       message.append("Did not receive: ");
       message.append(x).append(", ");
   }

   for (String y: actualOnlySet) {
       message.append("Not expected but received: ");
       message.append(y).append(", ");
   }

   Assert.assertTrue(false, message,toString());
}else {
   Assert.assertTrue(true);
}

Here you can use removeAll() method in Collections. Check the documentation

We have to check both scenarios;

Whether all expected titles are received

All received titles are expected


问:
Best practices when using Terraform
I'm in the process of swapping over our infrastructure into terraform.
What's the best practice for actually managing the terraform files and state?
I realize it's infrastructure as code, and i'll commit my .tf files into git, but do I commit tfstate as well? Should that reside somewhere like S3 ? I would like eventually for CI to manage all of this, but that's far stretched and requires me to figure out the moving pieces for the files.

I'm really just looking to see how people out there actually utilize this type of stuff in production

答: Use terraform cloud for manage and save states, together with advises above.</p>

Title: Best practices when using Terraform


问:
How to get the real value in JSON format string in Objective-C？
```<code>let jsonStr =    "[{\"data\":{\"Charge\":0.60,\"sumAmount\":11.86,\"tax\":0.0,\"withdraw\":12.46,\"deduct\":0}}]"

let resultdata = jsonStr.data(using: .utf8)!
do {
    if let jsonArray = try JSONSerialization.jsonObject(with: resultdata, options : .allowFragments) as? [Dictionary<String,Any>]
    {
//       print(jsonArray) // use the json here

        if let tax = jsonArray.first {
            if let newtax = tax["data"] as? Dictionary<String, Any> {
                if let resultTax = newtax["tax"] as? Double {
                    print(resultTax)
//                    print("resultTax")
                }
            }
        }

    } else {
        print("bad json")
    }
} catch let error as NSError {
    print(error)
}
</code>```

In swift, I can get the tax value. The value is 0.0.

In objective-c, I have not got the 0.0 value. I have used many API methods. The value is always 0.

How to get the value 0.0 in Objective-c?

答:
Given that you haven't provided any Objective-C code people can only guess, here is one, it may not be the cause of your issue:

It is the way you are displaying the value, the value is the same.

Assuming in both languages you have correctly parsed the real number and stored the result in a Double/double variable or NSNumber object then:

print(doubleVar) in Swift produces 0.0

NSLog(@"%g", doubleVar) in Obj-C produces 0

NSLog(@"%f", doubleVar) in Obj-C produces 0.000000

print(nsNumber) in Swift produces 0

NSLog(@"%@", nsNumber) in Obj-C produces 0

These differences are just how a floating-point value is formatted. There is no such floating-point value 0 distinct from 0.0 (or 4.5 distinct from 4.500 etc.)

HTH

Body:
let jsonStr =    "[{\"data\":{\"Charge\":0.60,\"sumAmount\":11.86,\"tax\":0.0,\"withdraw\":12.46,\"deduct\":0}}]"

let resultdata = jsonStr.data(using: .utf8)!
do {
    if let jsonArray = try JSONSerialization.jsonObject(with: resultdata, options : .allowFragments) as? [Dictionary<String,Any>]
    {
//       print(jsonArray) // use the json here

        if let tax = jsonArray.first {
            if let newtax = tax["data"] as? Dictionary<String, Any> {
                if let resultTax = newtax["tax"] as? Double {
                    print(resultTax)
//                    print("resultTax")
                }
            }
        }

    } else {
        print("bad json")
    }
} catch let error as NSError {
    print(error)
}

In swift, I can get the tax value. The value is 0.0.

In objective-c, I have not got the 0.0 value. I have used many API methods. The value is always 0.

How to get the value 0.0 in Objective-c?


问:
Why does haproxy path_beg only work if I don't visit default site?
I have configured haproxy to redirect the path "/rawman" to port 8080 on my server. It works the first time, but as soon as I visit the default site it stops working. The default site is running on apache with mod_rewrite and it is catching invalid requests (using codeigniter) so instead of seeing the redirected site when I visit http://mysite.com/rawman?foo=bar I see the default site.</p>

```<code>This is my haproxy config:

    global
        log 127.0.0.1   local0
        log 127.0.0.1   local1 notice
        maxconn 4096
        user haproxy
        group haproxy
        daemon
defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        retries 3
        option redispatch
        maxconn 2000
        contimeout      5000
        clitimeout      50000
        srvtimeout      50000

frontend http_proxy
        bind 0.0.0.0:8090
        acl is_ast path_beg /rawman
        use_backend ast if is_ast
        default_backend mysite

backend ast
        server ast 0.0.0.0:8080

backend mysite
        server local 0.0.0.0:80
</code>```

答:
Try setting option httpclose after the srvtimeout line.

If you don't do that then haproxy uses the target server's keepalive setting. Once you visit the main site the connection is opened and kept open, and on your next request haproxy goes oh isn't that nice: I have an open connection. Lets just use it even though it shouldn't. With the httpclose option set it always closes the connection, ensuring that each new request uses the right connection.

Lost 3 hours of my life figuring that out.

Body:
I have configured haproxy to redirect the path "/rawman" to port 8080 on my server. It works the first time, but as soon as I visit the default site it stops working. The default site is running on apache with mod_rewrite and it is catching invalid requests (using codeigniter) so instead of seeing the redirected site when I visit http://mysite.com/rawman?foo=bar I see the default site.

This is my haproxy config:

    global
        log 127.0.0.1   local0
        log 127.0.0.1   local1 notice
        maxconn 4096
        user haproxy
        group haproxy
        daemon
defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        retries 3
        option redispatch
        maxconn 2000
        contimeout      5000
        clitimeout      50000
        srvtimeout      50000

frontend http_proxy
        bind 0.0.0.0:8090
        acl is_ast path_beg /rawman
        use_backend ast if is_ast
        default_backend mysite

backend ast
        server ast 0.0.0.0:8080

backend mysite
        server local 0.0.0.0:80


问:
Call to PHP page served by nginx without using the file extension
I'm sure this is a really simple answer, but I just can't seem to crack it. I'm also quite new to nginx, but quite knowledgeable with apache2. I'm running nginx on Ubuntu and trying to fulfill these two requests:

get nginx to serve filename.php when the URI calls for filename

Calling http://example.org/bob would serve http://example.org/bob.php but still http://example.org/bob is shown in the browser URL

when a folder is requested, "index" isn't shown in the URL

Calling http://example.org/jack/ would serve http://example.org/jack/index.php but http://example.org/jack/ is still shown in the URL (and not http://example.org/jack/index)

My current config is:

```<code>server {
    listen 80;
    root /var/www/html;
    index index.php;

    location / {
        try_files $uri $uri/ @php;
    }

    location @php {
        try_files $uri.php =404;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi.conf;
    }

    rewrite ^/(.*)\.php$ /$1 redirect;

    location ~ /\.ht {
        deny all;
    }
}

</code>```

I feel as if I'm really close, requirement (1) works flawlessly, but I can't seem to find the correct config to address requirement (2).

If it helps, this is the config that works in Apache2, with the mod_rewrite module enabled:

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d       # if a folder isn't called ...
RewriteCond %{REQUEST_FILENAME}.php -f    # but a php file is ...
RewriteRule ^(.*)$ $1.php                 # take the basename, add .php then call that
</code>```

答:
See this can help you to enable Apache2 rewrite rule to nginx rules :

https://www.nginx.com/blog/converting-apache-to-nginx-rewrite-rules/

```<code>location / {
  if (!-e $request_filename){
    rewrite ^(.*)$ /$1.php;
  }
}
</code>```

Body:
I'm sure this is a really simple answer, but I just can't seem to crack it. I'm also quite new to nginx, but quite knowledgeable with apache2. I'm running nginx on Ubuntu and trying to fulfill these two requests:

get nginx to serve filename.php when the URI calls for filename

Calling http://example.org/bob would serve http://example.org/bob.php but still http://example.org/bob is shown in the browser URL

when a folder is requested, "index" isn't shown in the URL

Calling http://example.org/jack/ would serve http://example.org/jack/index.php but http://example.org/jack/ is still shown in the URL (and not http://example.org/jack/index)

My current config is:

server {
    listen 80;
    root /var/www/html;
    index index.php;

    location / {
        try_files $uri $uri/ @php;
    }

    location @php {
        try_files $uri.php =404;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi.conf;
    }

    rewrite ^/(.*)\.php$ /$1 redirect;

    location ~ /\.ht {
        deny all;
    }
}

I feel as if I'm really close, requirement (1) works flawlessly, but I can't seem to find the correct config to address requirement (2).

If it helps, this is the config that works in Apache2, with the mod_rewrite module enabled:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d       # if a folder isn't called ...
RewriteCond %{REQUEST_FILENAME}.php -f    # but a php file is ...
RewriteRule ^(.*)$ $1.php                 # take the basename, add .php then call that

Body:
See this can help you to enable Apache2 rewrite rule to nginx rules :

https://www.nginx.com/blog/converting-apache-to-nginx-rewrite-rules/

location / {
  if (!-e $request_filename){
    rewrite ^(.*)$ /$1.php;
  }
}


问:
Using Jade Array in Javascript transforms it to a string
I am passing an array of objects to my jade template, and want to use it as var in my js.

it seems to be transferred correctly, as

```<code>each level, i in stats
    .levelStats
</code>```

creates 4 divs (as expected)

now i have

```<code>script(type='text/javascript').
  var statData = "!{stats}"
</code>```

which, as far as i know, should load the data into a javascript var.
it does that, in a way...

```<code>console.log(statData);
// output: [object Object],[object Object],[object Object],[object Object]
// this means the correct data must be there..somewhere

console.log(typeof statData);
// output: string
</code>```

what am I doing wrong?
how can i get the whole array into the var?

solution + lesson:

var foo = "!{bar}" makes the data a string (pretty obvious in restrospective)

right way to go: var foo = !{bar}

答:
I spent full day to make it work. It is more advanced example, but we pass array to js in jade/pug file. Here we pass array of locations to google maps init script. Use it like this:
1)Prepare data on the server

```<code>JSON.stringify(locations = [
        { lat: -31.563910, lng: 147.154312 },
        { lat: -33.718234, lng: 150.363181 },
        { lat: 52.319277, lng: 21.000466 }
        ])
</code>```

2)pass it to your pug/jade page.
There, use this with variable that you pass, for example: DATA_THAT_YOUPASS

```<code>script.
                 function initMap() {
                 var map = new google.maps.Map(document.getElementById('map'), {
                 zoom: 3,
                 center: {lat: 52.5191758, lng: 23.0002262}
                 });
                 // Create an array of alphabetical characters used to label the markers.
                 var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                 // Add some markers to the map.
                 // Note: The code uses the JavaScript Array.prototype.map() method to
                 // create an array of markers based on a given "locations" array.
                 // The map() method here has nothing to do with the Google Maps API.
                 var markers = locations.map(function(location, i) {
                 return new google.maps.Marker({
                 position: location,
                 label: labels[i % labels.length]
                 });
                 });
                 // Add a marker clusterer to manage the markers.
                 var markerCluster = new MarkerClusterer(map, markers,
                 {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
                 }
                 var mydata = !{DATA_THAT_YOUPASS}
                 console.log(mydata);
                 console.log(mydata);
                 var locations = mydata;
             #map
            script(src='https://unpkg.com/@google/markerclustererplus@4.0.1/dist/markerclustererplus.min.js')
            // Replace the value of the key parameter with your own API key.
            script(async='', defer='', src='https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXXXXXX&callback=initMap')
</code>```

Body:
I am passing an array of objects to my jade template, and want to use it as var in my js.

it seems to be transferred correctly, as

each level, i in stats
    .levelStats

creates 4 divs (as expected)

now i have

script(type='text/javascript').
  var statData = "!{stats}"

which, as far as i know, should load the data into a javascript var.
it does that, in a way...

console.log(statData);
// output: [object Object],[object Object],[object Object],[object Object]
// this means the correct data must be there..somewhere

console.log(typeof statData);
// output: string

what am I doing wrong?
how can i get the whole array into the var?

solution + lesson:

var foo = "!{bar}" makes the data a string (pretty obvious in restrospective)

right way to go: var foo = !{bar}

Body:
I spent full day to make it work. It is more advanced example, but we pass array to js in jade/pug file. Here we pass array of locations to google maps init script. Use it like this:
1)Prepare data on the server

JSON.stringify(locations = [
        { lat: -31.563910, lng: 147.154312 },
        { lat: -33.718234, lng: 150.363181 },
        { lat: 52.319277, lng: 21.000466 }
        ])

2)pass it to your pug/jade page.
There, use this with variable that you pass, for example: DATA_THAT_YOUPASS

script.
                 function initMap() {
                 var map = new google.maps.Map(document.getElementById('map'), {
                 zoom: 3,
                 center: {lat: 52.5191758, lng: 23.0002262}
                 });
                 // Create an array of alphabetical characters used to label the markers.
                 var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                 // Add some markers to the map.
                 // Note: The code uses the JavaScript Array.prototype.map() method to
                 // create an array of markers based on a given "locations" array.
                 // The map() method here has nothing to do with the Google Maps API.
                 var markers = locations.map(function(location, i) {
                 return new google.maps.Marker({
                 position: location,
                 label: labels[i % labels.length]
                 });
                 });
                 // Add a marker clusterer to manage the markers.
                 var markerCluster = new MarkerClusterer(map, markers,
                 {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
                 }
                 var mydata = !{DATA_THAT_YOUPASS}
                 console.log(mydata);
                 console.log(mydata);
                 var locations = mydata;
             #map
            script(src='https://unpkg.com/@google/markerclustererplus@4.0.1/dist/markerclustererplus.min.js')
            // Replace the value of the key parameter with your own API key.
            script(async='', defer='', src='https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXXXXXX&callback=initMap')


问:
How does kafka streams attempt to get the same partition for each kafka topic?
If I have multiple application instances, and I am joining two topics, then each instance must get the same partition in order to join on the data. At the same time, it must evenly distribute the partitions among the instances.

If I were to guess, I am thinking that it would randomly request a partition for the first topic, keep that in a context, then request the same partition for all other topics involved in the join?

Can anyone confirm?

答:
When it comes to stream joins, it is best to have the underlying topics co-partitioned. That way you do not really have to thing about any strange behavior.

That means, as Kafka is by default partitioning the data by key, you would use the key that is used in your join condition as a key of the messages in the kafka topics. That way, together with the Range assignment strategy (partition.assignment.strategy) on Consumer side you will have an optimal join.

A required condition is to have the same amount of partitions in both topics.

Read more here.


问:
Include header file or cpp file
I have a class.h file and a class.cpp file that has the implementations of methods in class.h.
The class.cpp has an #include < class.h> statement. In my main.cpp, should I include < class.h> or < class.cpp>?</p>

答:
You should include the ".h" file (Header file).
A header file is a file which contains the function declarations and macro definitions to be shared between the source files ".cpp".</p>

Title: Include header file or cpp file


问:
R/exams Moodle schoice question with no points
I would like to create an schoice question in R/exams, via exams2moodle, which includes an answer option without points:

```<code>\begin{answerlist}
  \item Zurich is the capital of Switzerland.
  \item Italian is an official language in Switzerland.
  \item The currency in Switzerland is the Euro.
  \item Switzerland is part of the European Union (EU).
  \item No answer (****** this is a zero points answer****)
\end{answerlist}
</code>```

With these conditions I don't know how to configure \exsolution{0100?}. Thank very much.

PD. Why I need this schoice question? In Moodle when one awswer is ticked in schoice question,  imply that this question must be answered. Moodle doesn't allow to untick all answers.

答:
You can add such an option for "abstention" through the eponymous argument for processing the individual Moodle items. For example for an mchoice question (as you list above:

```<code>exams2moodle("switzerland.Rnw", mchoice = list(abstention = "No answer"))
</code>```

Analogously, you could add schoice = list(abstention = "Abstention") etc. In either case this adds an answer option that is associated with zero points:

Body:
I would like to create an schoice question in R/exams, via exams2moodle, which includes an answer option without points:

\begin{answerlist}
  \item Zurich is the capital of Switzerland.
  \item Italian is an official language in Switzerland.
  \item The currency in Switzerland is the Euro.
  \item Switzerland is part of the European Union (EU).
  \item No answer (****** this is a zero points answer****)
\end{answerlist}

With these conditions I don't know how to configure \exsolution{0100?}. Thank very much.

PD. Why I need this schoice question? In Moodle when one awswer is ticked in schoice question,  imply that this question must be answered. Moodle doesn't allow to untick all answers.

Body:
You can add such an option for "abstention" through the eponymous argument for processing the individual Moodle items. For example for an mchoice question (as you list above:

exams2moodle("switzerland.Rnw", mchoice = list(abstention = "No answer"))

Analogously, you could add schoice = list(abstention = "Abstention") etc. In either case this adds an answer option that is associated with zero points:


问:
Join on same column multiple times
how do I join on the same column multiple times, one of the tables is a configuration table with values and other is the data table.

T1:

```<code>ID    Seq    Code1     Code2     Code3
 1    001    101        203        305
 1    002    107
 2    001    103
 3    005               213
 4    009                          320
 5    001    101                   314
</code>```

T2 (Config table):

```<code>Value           Description
 101             Strawberry
 103             Raspberry
 107             Blueberry
 111             Banana
 203             Cashews
 213             Almonds
 305             Bellpepper
 320             Tomatoes
 314             Potatoes
</code>```

I need to display the code and its relevant description for each ID.

Expected Output:

```<code>ID       Code1    Description  Code2  Description  Code3 Description
1        101      Strawberry   203    Cashews      305    Bellpepper
1        107      Blueberry
2        103      Raspberry
3                              213     Almonds
4                                                  320     Tomatoes
5        101     Strawberry                        314     Potatoes
</code>```

This is what I have tried so far, however, it is not giving me the desired output:

```<code>    select distinct ID,code1, T2.description,
    code2, T2.description, code3, T2.description
    from T1,T2
    where (T1.Code1=T2.Value OR T1.Code2=T2.Value or T1.Code3=T2.Value)
</code>```

How can I achieve this? Sorry if my question is confusing, I can provide more details if needed.

答:
That's multiple outer join with the t2 table:

```<code>select a.id, a.seq,
  a.code1, d1.description,
  a.code2, d2.description,
  a.code3, d3.description
from t1 a left join t2 d1 on a.code1 = d1.value
          left join t2 d2 on a.code2 = d2.value
          left join t2 d3 on a.code3 = d3.value
order by a.id, a.seq;

   ID SEQ      CODE1 DESCRIPTIO      CODE2 DESCRIPTIO      CODE3 DESCRIPTIO
----- --- ---------- ---------- ---------- ---------- ---------- ----------
    1 001        101 Strawberry        203 Cashews           305 Bellpepper
    1 002        107 Blueberry
    2 001        103 Raspberry
    3 005                              213 Almonds
    4 009                                                    320 Tomatoes
    5 001        101 Strawberry                              314 Potatoes
</code>```

Title: Join on same column multiple times

Body:
how do I join on the same column multiple times, one of the tables is a configuration table with values and other is the data table.

T1:

ID    Seq    Code1     Code2     Code3
 1    001    101        203        305
 1    002    107
 2    001    103
 3    005               213
 4    009                          320
 5    001    101                   314

T2 (Config table):

Value           Description
 101             Strawberry
 103             Raspberry
 107             Blueberry
 111             Banana
 203             Cashews
 213             Almonds
 305             Bellpepper
 320             Tomatoes
 314             Potatoes

I need to display the code and its relevant description for each ID.

Expected Output:

ID       Code1    Description  Code2  Description  Code3 Description
1        101      Strawberry   203    Cashews      305    Bellpepper
1        107      Blueberry
2        103      Raspberry
3                              213     Almonds
4                                                  320     Tomatoes
5        101     Strawberry                        314     Potatoes

This is what I have tried so far, however, it is not giving me the desired output:

    select distinct ID,code1, T2.description,
    code2, T2.description, code3, T2.description
    from T1,T2
    where (T1.Code1=T2.Value OR T1.Code2=T2.Value or T1.Code3=T2.Value)

How can I achieve this? Sorry if my question is confusing, I can provide more details if needed.

Body:
That's multiple outer join with the t2 table:

select a.id, a.seq,
  a.code1, d1.description,
  a.code2, d2.description,
  a.code3, d3.description
from t1 a left join t2 d1 on a.code1 = d1.value
          left join t2 d2 on a.code2 = d2.value
          left join t2 d3 on a.code3 = d3.value
order by a.id, a.seq;

   ID SEQ      CODE1 DESCRIPTIO      CODE2 DESCRIPTIO      CODE3 DESCRIPTIO
----- --- ---------- ---------- ---------- ---------- ---------- ----------
    1 001        101 Strawberry        203 Cashews           305 Bellpepper
    1 002        107 Blueberry
    2 001        103 Raspberry
    3 005                              213 Almonds
    4 009                                                    320 Tomatoes
    5 001        101 Strawberry                              314 Potatoes


问:
Android, check if back button was pressed before in other Activity
I have started to play around with Firebase and made a simple activity to create an account and log in.
I all works as expected however, I noticed something once a user had logged in and got to the menu screen. If the user pressed on the back button on the android device you would expect that the app would close or go back to where you were before, but because the of the onStart() in LoginActivity it throws back the user to the menu page again. I don't want to change the onStart() method as I like that it logs you if you already have an account. So what I tried was to close the app when back button is pressed in the menu activity like so:

```<code>@Override
    public void onBackPressed() {
        finish();
        System.exit(0);
    }

</code>```

However, this did not work and I still can't close the app then pressing back button in the menu activty as the LoginActivity still brings me back.

This is the LoginActivity:

```<code>public class LoginActivity extends AppCompatActivity {

    // [START declare_auth]
    private FirebaseAuth mAuth;
    // [END declare_auth]

    private static final String TAG = "EmailPassword";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // [START initialize_auth]
        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();
        // [END initialize_auth]

    }

    //here we immediately check if user is already logged in then log in
    @Override
    protected void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        if (currentUser != null)
            updateUI(currentUser);
    }

    private void updateUI(FirebaseUser currentUser) {
        Intent mainIntent = new Intent(LoginActivity.this, MenuActivity.class);
        Toast.makeText(this, "This is current user: " + currentUser, Toast.LENGTH_LONG).show();
        startActivity(mainIntent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    public void createAccount(View view) {
        final EditText emailEdit = (EditText) findViewById(R.id.email_field);
        final String email = emailEdit.getText().toString();
        final EditText passwordEdit = (EditText) findViewById(R.id.password_field);
        final String password = passwordEdit.getText().toString();
        Log.d(TAG, "createAccount:" + email);

        // [START create_user_with_email]
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "createUserWithEmail:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            updateUI(user);
                        } else {

                            try
                            {
                                throw Objects.requireNonNull(task.getException());
                            }
                            // if user enters wrong email.
                            catch (FirebaseAuthWeakPasswordException weakPassword)
                            {
                                Log.d(TAG, "onComplete: weak_password");

                                Toast.makeText(LoginActivity.this, "Password to weak", Toast.LENGTH_LONG).show();
                            }
                            // if user enters wrong password.
                            catch (FirebaseAuthInvalidCredentialsException malformedEmail)
                            {
                                Log.d(TAG, "onComplete: malformed_email");

                                Toast.makeText(LoginActivity.this, "Wrong email", Toast.LENGTH_LONG).show();
                            }
                            catch (FirebaseAuthUserCollisionException existEmail)
                            {
                                Log.d(TAG, "onComplete: exist_email");

                                Toast.makeText(LoginActivity.this, "Email already exists", Toast.LENGTH_LONG).show();
                            }
                            catch (Exception e)
                            {
                                Log.d(TAG, "onComplete: " + e.getMessage());
                                Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
                                Toast.makeText(LoginActivity.this, "Please try again", Toast.LENGTH_SHORT).show();
                            }
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "createUserWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                });
        // [END create_user_with_email]
    }

}

</code>```

Is there a way I can close the app in the menu activity or a way to check in the onStart() method in LoginActivity if we got there through pressing the back button on the phone?

答:
You can modify your intent adding flags Intent.FLAG_ACTIVITY_CLEAR_TASK
and Intent.FLAG_ACTIVITY_NEW_TASK

```<code> private void updateUI(FirebaseUser currentUser) {
            Intent mainIntent = new Intent(LoginActivity.this, MenuActivity.class);
            mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Toast.makeText(this, "This is current user: " + currentUser, Toast.LENGTH_LONG).show();
            startActivity(mainIntent);
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        }
</code>```

This will close the previous LogicActivity and there is no need to override onBackPressed()

Body:
I have started to play around with Firebase and made a simple activity to create an account and log in.
I all works as expected however, I noticed something once a user had logged in and got to the menu screen. If the user pressed on the back button on the android device you would expect that the app would close or go back to where you were before, but because the of the onStart() in LoginActivity it throws back the user to the menu page again. I don't want to change the onStart() method as I like that it logs you if you already have an account. So what I tried was to close the app when back button is pressed in the menu activity like so:

@Override
    public void onBackPressed() {
        finish();
        System.exit(0);
    }

However, this did not work and I still can't close the app then pressing back button in the menu activty as the LoginActivity still brings me back.

This is the LoginActivity:

public class LoginActivity extends AppCompatActivity {

    // [START declare_auth]
    private FirebaseAuth mAuth;
    // [END declare_auth]

    private static final String TAG = "EmailPassword";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // [START initialize_auth]
        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();
        // [END initialize_auth]

    }

    //here we immediately check if user is already logged in then log in
    @Override
    protected void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        if (currentUser != null)
            updateUI(currentUser);
    }

    private void updateUI(FirebaseUser currentUser) {
        Intent mainIntent = new Intent(LoginActivity.this, MenuActivity.class);
        Toast.makeText(this, "This is current user: " + currentUser, Toast.LENGTH_LONG).show();
        startActivity(mainIntent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    public void createAccount(View view) {
        final EditText emailEdit = (EditText) findViewById(R.id.email_field);
        final String email = emailEdit.getText().toString();
        final EditText passwordEdit = (EditText) findViewById(R.id.password_field);
        final String password = passwordEdit.getText().toString();
        Log.d(TAG, "createAccount:" + email);

        // [START create_user_with_email]
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "createUserWithEmail:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            updateUI(user);
                        } else {

                            try
                            {
                                throw Objects.requireNonNull(task.getException());
                            }
                            // if user enters wrong email.
                            catch (FirebaseAuthWeakPasswordException weakPassword)
                            {
                                Log.d(TAG, "onComplete: weak_password");

                                Toast.makeText(LoginActivity.this, "Password to weak", Toast.LENGTH_LONG).show();
                            }
                            // if user enters wrong password.
                            catch (FirebaseAuthInvalidCredentialsException malformedEmail)
                            {
                                Log.d(TAG, "onComplete: malformed_email");

                                Toast.makeText(LoginActivity.this, "Wrong email", Toast.LENGTH_LONG).show();
                            }
                            catch (FirebaseAuthUserCollisionException existEmail)
                            {
                                Log.d(TAG, "onComplete: exist_email");

                                Toast.makeText(LoginActivity.this, "Email already exists", Toast.LENGTH_LONG).show();
                            }
                            catch (Exception e)
                            {
                                Log.d(TAG, "onComplete: " + e.getMessage());
                                Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
                                Toast.makeText(LoginActivity.this, "Please try again", Toast.LENGTH_SHORT).show();
                            }
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "createUserWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                });
        // [END create_user_with_email]
    }

}

Is there a way I can close the app in the menu activity or a way to check in the onStart() method in LoginActivity if we got there through pressing the back button on the phone?

Body:
You can modify your intent adding flags Intent.FLAG_ACTIVITY_CLEAR_TASK
and Intent.FLAG_ACTIVITY_NEW_TASK

 private void updateUI(FirebaseUser currentUser) {
            Intent mainIntent = new Intent(LoginActivity.this, MenuActivity.class);
            mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Toast.makeText(this, "This is current user: " + currentUser, Toast.LENGTH_LONG).show();
            startActivity(mainIntent);
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        }

This will close the previous LogicActivity and there is no need to override onBackPressed()


问:
Is there in JSS an equivalent of background color + image?
I am using JSS in React to style Material UI components. I have tried to surf on the web the equivalent of the code bellow from CSS in JSS, but I was unsuccessful.

```<code> background:
    linear-gradient(
      rgba(64, 153, 255, 0.5),
      rgba(64, 153, 255, 0.5)
    )
    ,
   url('myUrl');
</code>```

Can somebody help me figure out if there is a way to achieve the same result in JSS.

答:
Below is a working example of the correct syntax. The entire value for the background-image (linear-gradient is an image not a color) goes into a single string.

```<code>import React from "react";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  gradientAndUrl: {
    width: "400px",
    height: "400px",
    backgroundImage:
      "linear-gradient(rgba(64, 153, 255, 0.5), rgba(64, 153, 255, 0.5)), url(https://www.publicdomainpictures.net/pictures/10000/velka/black-monkey-11280155875i3QV.jpg)"
  }
});

export default function App() {
  const classes = useStyles();
  return <div className={classes.gradientAndUrl} />;
}
</code>```

Related answer: How to add linear-gradient color to Slider?

Body:
I am using JSS in React to style Material UI components. I have tried to surf on the web the equivalent of the code bellow from CSS in JSS, but I was unsuccessful.

 background:
    linear-gradient(
      rgba(64, 153, 255, 0.5),
      rgba(64, 153, 255, 0.5)
    )
    ,
   url('myUrl');

Can somebody help me figure out if there is a way to achieve the same result in JSS.

Body:
Below is a working example of the correct syntax. The entire value for the background-image (linear-gradient is an image not a color) goes into a single string.

import React from "react";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  gradientAndUrl: {
    width: "400px",
    height: "400px",
    backgroundImage:
      "linear-gradient(rgba(64, 153, 255, 0.5), rgba(64, 153, 255, 0.5)), url(https://www.publicdomainpictures.net/pictures/10000/velka/black-monkey-11280155875i3QV.jpg)"
  }
});

export default function App() {
  const classes = useStyles();
  return <div className={classes.gradientAndUrl} />;
}

Related answer: How to add linear-gradient color to Slider?


问:
Trying to add sample size to each row label in a dataframe
I am creating a final dataframe that has a list of different coral species. I have the dataframe set up the way I want it. All I want to do is add the sample size of each coral species to the row labels (i.e. final label will look like this example: Acropora sp. (plating) n=10).
I have a list of all coral species with their sample size but I am not sure how to incorporate that data into the row labels.</p>

```<code>count_focal_taxa = tapply(FR3_final$Type,FR3_final$Type,length)
count_focal_taxa
``

     Acropora_sp_plating            Corallimorph        Favia_stelligera
                     10                      12                      84
 My dataframe is currently:

`

    ``{r}
    result <- data.frame(ifelse(FR3_final_means > quantile_high, '+', ifelse(FR3_final_means < quantile_low, '-', 0)))
    result$Type<-(FR3_final_means$Type)
    result
    ```

        Type                A   B   C   D   E   F   G
        Acropora_sp_plating 0   0   0   0   +   0   0
        Corallimorph        +   0   0   0   0   0   0
        Favia_stelligera    0   0   0   0   0   -   +

And I want:

    Type                        A   B   C   D   E   F   G
    Acropora_sp_plating n=10    0   0   0   0   +   0   0
    Corallimorph n=12           +   0   0   0   0   0   0
    Favia_stelligera n=84       0   0   0   0   0   -   +

</code>```

答:
We can use paste

```<code>result$Type = paste(result$Type, 'n=', count_focal_taxa)
</code>```

Or with sprintf

```<code>result$Type <- sprintf('%s n=%d', result$Type, count_focal_taxa)
</code>```

Instead of tapply, we can get the frequency with table

```<code>count_focal_taxa <- table(FR3_final$Type)
</code>```

Body:
I am creating a final dataframe that has a list of different coral species. I have the dataframe set up the way I want it. All I want to do is add the sample size of each coral species to the row labels (i.e. final label will look like this example: Acropora sp. (plating) n=10).
I have a list of all coral species with their sample size but I am not sure how to incorporate that data into the row labels.

count_focal_taxa = tapply(FR3_final$Type,FR3_final$Type,length)
count_focal_taxa
``

     Acropora_sp_plating            Corallimorph        Favia_stelligera
                     10                      12                      84
 My dataframe is currently:

`

    ``{r}
    result <- data.frame(ifelse(FR3_final_means > quantile_high, '+', ifelse(FR3_final_means < quantile_low, '-', 0)))
    result$Type<-(FR3_final_means$Type)
    result
    ```

        Type                A   B   C   D   E   F   G
        Acropora_sp_plating 0   0   0   0   +   0   0
        Corallimorph        +   0   0   0   0   0   0
        Favia_stelligera    0   0   0   0   0   -   +

And I want:

    Type                        A   B   C   D   E   F   G
    Acropora_sp_plating n=10    0   0   0   0   +   0   0
    Corallimorph n=12           +   0   0   0   0   0   0
    Favia_stelligera n=84       0   0   0   0   0   -   +

Body:
We can use paste

result$Type = paste(result$Type, 'n=', count_focal_taxa)

Or with sprintf

result$Type <- sprintf('%s n=%d', result$Type, count_focal_taxa)

Instead of tapply, we can get the frequency with table

count_focal_taxa <- table(FR3_final$Type)


问:
How can I check if the next checkbox is checked?
I am attempting to find out if the next checkbox on the onclick event is checked or not. If the next checkbox is checked, I want the background color to be White. Picture 1 shows the Yellow background for an unchecked row and a White background for a checked row. Picture 2 shows when I check the Yellow row, the next row changes to Yellow, I want it to remain White if it is already checked.

Is there a next function that I can use? Here is the code I have so far:

```<code>$('input[id="chkRow"]').on('change', (function () {
            if (this.checked) {
                $(this).closest('tr').css("background-color", "white");
                $(this).closest('tr').next('tr').css("background-color", "yellow");
            }
            else {
                $(this).closest('tr').css("background-color", "yellow");
                $(this).closest('tr').next('tr').css("background-color", "white");
            }
        }));
</code>```

答:
Get the index of the current TD, and use that to find the corresponding cell in the next row, and then check whether the box is checked.

$('input[id="chkRow"]').on('change', function() {
  var curRow = $(this).closest("tr");
  var nextRow = curRow.next("tr");
  if (this.checked) {
    curRow.css("background-color", "white");
    var thisColumn = $(this).closest("td").index();
    if (nextRow.children("td").eq(thisColumn).find(":checkbox").is(":checked")) {
      nextRow.css("background-color", "white");
    } else {
      nextRow.css("background-color", "yellow");
    }
  } else {
    curRow.css("background-color", "yellow");
    nextRow.css("background-color", "white");
  }
});```

Body:
I am attempting to find out if the next checkbox on the onclick event is checked or not. If the next checkbox is checked, I want the background color to be White. Picture 1 shows the Yellow background for an unchecked row and a White background for a checked row. Picture 2 shows when I check the Yellow row, the next row changes to Yellow, I want it to remain White if it is already checked.

Is there a next function that I can use? Here is the code I have so far:

$('input[id="chkRow"]').on('change', (function () {
            if (this.checked) {
                $(this).closest('tr').css("background-color", "white");
                $(this).closest('tr').next('tr').css("background-color", "yellow");
            }
            else {
                $(this).closest('tr').css("background-color", "yellow");
                $(this).closest('tr').next('tr').css("background-color", "white");
            }
        }));


问:
How to change page of splash screen in ionic cordova?
I added the splashscreen plugin to my project with this command:

```<code>cordova plugin add org.apache.cordova.splashscreen
</code>```

After that I add this line in config.xml:

```<code><preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="3000" />
</code>```

It worked, but I do not know how to change this page at startup.

答:
If you wanna change the design of the splash screen or the icon, there is 2 way to do this:

You can go to this website:
https://apetools.webprofusion.com/
and upload a standard icon and splash screen picture (as they instruct there) and then choose your platforms. the site will generate them for you and you must replace them with the orginals in your project:

root/resources

Yo can replace icon.png (1024*1024) and splash.png (2732*2732) located in:

root/resources

then run command:

```<code>ionic cordova build [platform]
</code>```

and cordova will build them for you.
Good Luck!

Body:
I added the splashscreen plugin to my project with this command:

cordova plugin add org.apache.cordova.splashscreen

After that I add this line in config.xml:

<preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="3000" />

It worked, but I do not know how to change this page at startup.

Body:
If you wanna change the design of the splash screen or the icon, there is 2 way to do this:

You can go to this website:
https://apetools.webprofusion.com/
and upload a standard icon and splash screen picture (as they instruct there) and then choose your platforms. the site will generate them for you and you must replace them with the orginals in your project:

root/resources

Yo can replace icon.png (1024*1024) and splash.png (2732*2732) located in:

root/resources

then run command:

ionic cordova build [platform]

and cordova will build them for you.
Good Luck!


问:
Is there some way that I can that i can add up the random values and print it?
Random is obviously needed, but it makes it harder to gather the values. =) This is an unnecessary comment.

```<code>import random
class Die:
    def __init__ (self, face, face_value):
        self.face = face
        self.face_value = face_value
    def roll(self):
</code>```

I have tried making the class do this twice, but for some reason it does not work.

```<code>        self.face = random.randint(1, 6)
        if self.face == 1:
            face = ( ' ------\n|       |\n|   o   |\n|       |\n ------')
            num = 1
        elif self.face == 2:
            face =  (' ------\n|       |\n| o   o |\n|       |\n ------')
            num = 2
        elif self.face == 3:
             face =  (' ------\n|   o   |\n|   o   |\n|   o   |\n ------')
            num = 3
        elif self.face == 4:
            face =  (' ------\n| o   o |\n| o   o |\n|       |\n ------')
            num = 4
        elif self.face == 5:
            face =  (' ------\n| o   o |\n| o   o |\n|   o   |\n ------')
            num = 5
        elif self.face == 6:
            face = (' ------\n| o   o |\n| o   o |\n| o   o |\n ------' )
            num = 6
        return print(face)
 **My goal is to add up the two random values that I get from the Die class, I have tried to put two rolls in that class, but then it has the same output still. **
from DieClass import Die
user = input('Do you want to play this Dicegame?')
num = random.randint(1,6)
</code>```

I only need this num so that I have some value to put into the class.

```<code>if num == 1:
    face = ( ' ------\n|       |\n|   o   |\n|       |\n ------')
elif num == 2:
    face =  (' ------\n|       |\n| o   o |\n|       |\n ------')
elif num == 3:
    face =  (' ------\n|   o   |\n|   o   |\n|   o   |\n ------')
elif num == 4:
    face =  (' ------\n| o   o |\n| o   o |\n|       |\n ------')
elif num == 5:
    face =  (' ------\n| o   o |\n| o   o |\n|   o   |\n ------')
elif num == 6:
    face = (' ------\n| o   o |\n| o   o |\n| o   o |\n ------' )

class Dicegame(Die):
    def __init__ (self, name):
        self.name = name

    def play(self):
        Die1 = Die(face, num)
        return Die1.roll()
</code>```

I am trying to make this code more efficient, if you have any suggestions tell me

```<code>if user == 'yes' or 'yep' or 'y' or 'Yes' or 'YES!' or 'YES' or 'Yurp' or 'Yeppers' or
'si'or'1':
    while user != 5:
        user = input('Press 1 to roll, 2 to quit.')
        if user == '1':
            Dice1 = Dicegame('name')
            Dice1.play()
            Dice2 = Dicegame('bob')
            Dice2.play()
            print('')
            print('Thanks for playing!')
            print('')
        elif user == '2':
            print('Thanks for playing!')
            print('')
            exit()
</code>```

答:
Your user == 'yes' or 'yep' or 'y' ... line will always return True because or is a low-priority option, and a non-empty string's boolean value is True.

I tried to clean your code up a bit, here's what I have

import random

class Die:
    def __init__ (self, face, face_value):
        self.face = face
        self.face_value = face_value
    def roll(self):
        self.face = random.randint(1, 6)
        if self.face == 1:
            face = ( ' ------\n|       |\n|   o   |\n|       |\n ------')
            num = 1
        elif self.face == 2:
            face =  (' ------\n|       |\n| o   o |\n|       |\n ------')
            num = 2
        elif self.face == 3:
            face =  (' ------\n|   o   |\n|   o   |\n|   o   |\n ------')
            num = 3
        elif self.face == 4:
            face =  (' ------\n| o   o |\n| o   o |\n|       |\n ------')
            num = 4
        elif self.face == 5:
            face =  (' ------\n| o   o |\n| o   o |\n|   o   |\n ------')
            num = 5
        elif self.face == 6:
            face = (' ------\n| o   o |\n| o   o |\n| o   o |\n ------' )
            num = 6
        print(face)
        return num

user = input('Do you want to play this Dicegame? ')

num = random.randint(1, 6)
if num == 1:
    face = ( ' ------\n|       |\n|   o   |\n|       |\n ------')
elif num == 2:
    face =  (' ------\n|       |\n| o   o |\n|       |\n ------')
elif num == 3:
    face =  (' ------\n|   o   |\n|   o   |\n|   o   |\n ------')
elif num == 4:
    face =  (' ------\n| o   o |\n| o   o |\n|       |\n ------')
elif num == 5:
    face =  (' ------\n| o   o |\n| o   o |\n|   o   |\n ------')
elif num == 6:
    face = (' ------\n| o   o |\n| o   o |\n| o   o |\n ------' )

class Dicegame(Die):
    def __init__ (self, name):
        self.name = name

    def play(self):
        Die1 = Die(face, num)
        return Die1.roll()

if user in ('yes', 'yep', 'y', 'Yes', 'YES!', 'YES', 'Yurp', 'Yeppers', 'si', '1'):
    while user != '5': # what is the purpose of this line?
        user = input('Press 1 to roll, 2 to quit. ')
        if user == '1':
            Dice1 = Dicegame('name')
            a = Dice1.play()
            Dice2 = Dicegame('bob')
            b = Dice2.play()
            print(f'Your total is {a+b}')
            print('Thanks for playing!')
            print('')
        elif user == '2':
            print('Thanks for playing!')
            print('')
            exit()
```

Body:
Random is obviously needed, but it makes it harder to gather the values. =) This is an unnecessary comment.

import random
class Die:
    def __init__ (self, face, face_value):
        self.face = face
        self.face_value = face_value
    def roll(self):

I have tried making the class do this twice, but for some reason it does not work.

        self.face = random.randint(1, 6)
        if self.face == 1:
            face = ( ' ------\n|       |\n|   o   |\n|       |\n ------')
            num = 1
        elif self.face == 2:
            face =  (' ------\n|       |\n| o   o |\n|       |\n ------')
            num = 2
        elif self.face == 3:
             face =  (' ------\n|   o   |\n|   o   |\n|   o   |\n ------')
            num = 3
        elif self.face == 4:
            face =  (' ------\n| o   o |\n| o   o |\n|       |\n ------')
            num = 4
        elif self.face == 5:
            face =  (' ------\n| o   o |\n| o   o |\n|   o   |\n ------')
            num = 5
        elif self.face == 6:
            face = (' ------\n| o   o |\n| o   o |\n| o   o |\n ------' )
            num = 6
        return print(face)
 **My goal is to add up the two random values that I get from the Die class, I have tried to put two rolls in that class, but then it has the same output still. **
from DieClass import Die
user = input('Do you want to play this Dicegame?')
num = random.randint(1,6)

I only need this num so that I have some value to put into the class.

if num == 1:
    face = ( ' ------\n|       |\n|   o   |\n|       |\n ------')
elif num == 2:
    face =  (' ------\n|       |\n| o   o |\n|       |\n ------')
elif num == 3:
    face =  (' ------\n|   o   |\n|   o   |\n|   o   |\n ------')
elif num == 4:
    face =  (' ------\n| o   o |\n| o   o |\n|       |\n ------')
elif num == 5:
    face =  (' ------\n| o   o |\n| o   o |\n|   o   |\n ------')
elif num == 6:
    face = (' ------\n| o   o |\n| o   o |\n| o   o |\n ------' )

class Dicegame(Die):
    def __init__ (self, name):
        self.name = name

    def play(self):
        Die1 = Die(face, num)
        return Die1.roll()

I am trying to make this code more efficient, if you have any suggestions tell me

if user == 'yes' or 'yep' or 'y' or 'Yes' or 'YES!' or 'YES' or 'Yurp' or 'Yeppers' or
'si'or'1':
    while user != 5:
        user = input('Press 1 to roll, 2 to quit.')
        if user == '1':
            Dice1 = Dicegame('name')
            Dice1.play()
            Dice2 = Dicegame('bob')
            Dice2.play()
            print('')
            print('Thanks for playing!')
            print('')
        elif user == '2':
            print('Thanks for playing!')
            print('')
            exit()


问:
How to made CustomPaint like this in flutter
I know it's not the best way but I really can't do this. How to made something like this. I'm suck in geometry. I try to do this with cubicTo but I cen't get this effect :/.

Can someone help me. Below is part of my code.

```<code>var sw = size.width;
var sh = size.height;

var path = Path();

path.cubicTo(sw/2, 0, sw/4, 0, 2*sw/4, 2*sh/4);
path.cubicTo(2*sw/3, 2*sh/3, sw/3, 0, sw, 0);
path.cubicTo(0, 0, 0, 0, sw, 0);
path.lineTo(sw, sh);
path.lineTo(0, sh);
path.close();
</code>```

答:
Check this out...

```<code>class Paintter extends CustomPainter{
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()..color = Colors.orange;
    var path = Path();
    double factor = 100;
    path.lineTo(0, size.height);
    path.lineTo(size.width, size.height);
    path.lineTo(size.width, 0);
    path.lineTo(size.width - factor, 0);
    path.quadraticBezierTo(size.width/2, size.height, factor, 0);
    path.lineTo(0, 0);
    canvas.drawPath(path, paint);
  }
</code>```

The output:

Body:
I know it's not the best way but I really can't do this. How to made something like this. I'm suck in geometry. I try to do this with cubicTo but I cen't get this effect :/.

Can someone help me. Below is part of my code.

var sw = size.width;
var sh = size.height;

var path = Path();

path.cubicTo(sw/2, 0, sw/4, 0, 2*sw/4, 2*sh/4);
path.cubicTo(2*sw/3, 2*sh/3, sw/3, 0, sw, 0);
path.cubicTo(0, 0, 0, 0, sw, 0);
path.lineTo(sw, sh);
path.lineTo(0, sh);
path.close();

Body:
Check this out...

class Paintter extends CustomPainter{
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()..color = Colors.orange;
    var path = Path();
    double factor = 100;
    path.lineTo(0, size.height);
    path.lineTo(size.width, size.height);
    path.lineTo(size.width, 0);
    path.lineTo(size.width - factor, 0);
    path.quadraticBezierTo(size.width/2, size.height, factor, 0);
    path.lineTo(0, 0);
    canvas.drawPath(path, paint);
  }

The output: