问:
Ruby on rails how to connect a script with a button
So i have a completely new ruby on rails app just made and i added a button with bootstrap.
picture.
I also have a simple script that prints out "hello".

simple.rb, which is in app/scripts/simple.rb

```<code>puts "hello"

</code>```

Now can someone please explain and give me an example of how can i connect the script to the button i have. So when i click the button on the website, it does what the script is told to do.
I have been searching for a full day and found that maybe i need to create a new controller/view/route for it? or "require 'file' ". Correct me if im wrong, thank you!

答:
You will need to follow four steps in order to reach your 'script'. First of all I recomend you to read about Rails services pattern for a better practice. In my vision it fit your necessities.

Step by step:

Create a controller to handle the request

With a simple shell command you can create a controller. Access the project folder and type something like (see shell commands for better understanding):

```<code>rails g controller hello
</code>```

So now you will have a new controller called 'HelloController' inside controller's folder (app/controllers/hello_controller.rb). You can check it out and notice it have no methods. First create a method (bellow I've done one called index) for later run your service (that will contain your script). So you have a controller like:

```<code>class HelloController < ApplicationController
  def index
    # Your service goes here
  end
end
</code>```

Create a router rule to foward the request to created controller

Access your config/routes.rb file and add to it the following line:

```<code>resources :hello, only: %i[index]
</code>```

If you want to understand more about Rails routing DSL you can check it out here.

Create the service

To create the specified service in order to run your so-desired script, I recommend you to follow the instructions given by Amin Shah. No reason to repeat what he said.

Update view

Now you just have to create a link to perform a GET request to your created route. You can use Rails link_to helper. Something like:

```<code><%= link_to "Button", hello_index_path, class: "btn btn-primary" %>
</code>```

Body:
So i have a completely new ruby on rails app just made and i added a button with bootstrap.
picture.
I also have a simple script that prints out "hello".

simple.rb, which is in app/scripts/simple.rb

puts "hello"

Now can someone please explain and give me an example of how can i connect the script to the button i have. So when i click the button on the website, it does what the script is told to do.
I have been searching for a full day and found that maybe i need to create a new controller/view/route for it? or "require 'file' ". Correct me if im wrong, thank you!

Body:
You will need to follow four steps in order to reach your 'script'. First of all I recomend you to read about Rails services pattern for a better practice. In my vision it fit your necessities.

Step by step:

Create a controller to handle the request

With a simple shell command you can create a controller. Access the project folder and type something like (see shell commands for better understanding):

rails g controller hello

So now you will have a new controller called 'HelloController' inside controller's folder (app/controllers/hello_controller.rb). You can check it out and notice it have no methods. First create a method (bellow I've done one called index) for later run your service (that will contain your script). So you have a controller like:

class HelloController < ApplicationController
  def index
    # Your service goes here
  end
end

Create a router rule to foward the request to created controller

Access your config/routes.rb file and add to it the following line:

resources :hello, only: %i[index]

If you want to understand more about Rails routing DSL you can check it out here.

Create the service

To create the specified service in order to run your so-desired script, I recommend you to follow the instructions given by Amin Shah. No reason to repeat what he said.

Update view

Now you just have to create a link to perform a GET request to your created route. You can use Rails link_to helper. Something like:

<%= link_to "Button", hello_index_path, class: "btn btn-primary" %>


来源: stackexchange

问:
Making the configuration available to all classes
I'm writing a small web server, and it takes a configuration file with all sorts of different options: how many threads to run, which class deals which each file extension, which file to display by default and so on and so forth. To represent this, I'm parsing the config file into a Configuration object which contains all these settings, and the main class holds this object.

However, the config data is required on almost every level of the server - classes within classes within classes...

My question is, what is the best practice to use here? Should I give the config as a parameter for many many classes and pass it back and forth? Should I make it a singleton? Is there another solution I don't see?

答:
Passing an instance of Configuration around adds a lot of unnecessary clutter to your code. A Singleton is a good idea or add some sort of Manager class that provides all those shared resources, like configuration data.

If you go for singleton, consider implementing the enum pattern:

```<code>public enum Config{ DATA;

   private int value1;
   private int value2;
   private int value3;
   public load(File configFile) {
     // some magic to store the values
   }
   public int getValue1() {return value1;}
   public int getValue2() {return value2;}
   public int getValue3() {return value3;}
}
</code>```

You can use it everywhere in your code:

```<code>int property = Config.DATA.getValue1();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Passing an instance of Configuration around adds a lot of unnecessary clutter to your code. A Singleton is a good idea or add some sort of Manager class that provides all those shared resources, like configuration data.

If you go for singleton, consider implementing the enum pattern:

public enum Config{ DATA;

   private int value1;
   private int value2;
   private int value3;
   public load(File configFile) {
     // some magic to store the values
   }
   public int getValue1() {return value1;}
   public int getValue2() {return value2;}
   public int getValue3() {return value3;}
}

You can use it everywhere in your code:

int property = Config.DATA.getValue1();


问:
number sequence event rule issue on Axapta V4
We reached max systemId number sequence.

So I increase the max value, then, I set an event rule on system Id  numberSequence to check how it increases.

I deleted it and I still have a lot of generated records in eventCUD table.

AX seem to continue logging system ids creation even if the relative rule doesn't exist anymore. I check all event rules table and I don't have any "ghost" records.

答:
It sounds like the rule is cached somewhere/somehow.

From the AOT open the EventRule table and verify the rule is not there.

Make sure your batch jobs are withhold/ended, then restart the AOS. It's reported (in URL below) that if the batch job is not in that state, even after an AOS restart, the alerts can keep coming.

Then restart your AOS(s) just in case the kernel caches the rule somehow. If you have multiple AOS's, just stop them all, then start them 1 by 1.

Read here for more info: https://daxteam.wordpress.com/2013/10/16/ax-2012-eventcud-constant-growth/

EventCUD should hold a queue of alerts that need to be sent. If you are OK missing some alerts, just truncate the table.

Alternatively, running the job under [System Administration>Periodic>Alerts>Change based alerts] should read in all of those EventCUD records and generate a ton of alerts that have yet to be sent out. If you choose this method, make sure to inform users they may receive a bunch of alerts that were pending.

ContentLicense: CC BY-SA 4.0


问:
Use last value with operations in SQL Server
Let's assume I have a table in SQL Server called Budget_Spend like this

I know, with proper group by, sum and order by reach the next table (it's pretty obvious)

However, I don't how to replicate "Aviable" column, constructed following the logic:

For the first month, it's Budget - Spend - Taxes

For the following months is computed like PREVIOUS(Aviable)-CURRENT(Spend)-CURRENT(Taxes)

I've tried to use LAG function without succes (most of my tries didn't run due to syntax problems).

Any idea of doing? I imagine I need LAG and maybe a CASE in order to get the first value.

This is the DDL for creating the table

```<code>/* CREATE TABLE */
CREATE TABLE Budget_Spend(
Month DOUBLE,
Budget DOUBLE,
Spend DOUBLE,
Taxes DOUBLE);

/* INSERT */
INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
(1, 1000, 75, 11.25);

INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
(1, 1000, 25, 3.75);

INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
(2, 1000, 200, 30);

INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
(3, 1000, 150, 22.5);

INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
(4, 1000, 10, 1.5);

INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
(4, 1000, 10, 1.5);
</code>```

答:
You need window function : </p>

```<code>select bs.*,
      Budget - sum(Spend + Taxes) over (order by month) as Available
from (select month, Budget, sum(Spend) as Spend, sum(Taxes) as Taxes
      from Budget_Spend bs
      group by month, Budget
     ) bs;
</code>```

Body:
Let's assume I have a table in SQL Server called Budget_Spend like this

I know, with proper group by, sum and order by reach the next table (it's pretty obvious)

However, I don't how to replicate "Aviable" column, constructed following the logic:

For the first month, it's Budget - Spend - Taxes

For the following months is computed like PREVIOUS(Aviable)-CURRENT(Spend)-CURRENT(Taxes)

I've tried to use LAG function without succes (most of my tries didn't run due to syntax problems).

Any idea of doing? I imagine I need LAG and maybe a CASE in order to get the first value.

This is the DDL for creating the table

/* CREATE TABLE */
CREATE TABLE Budget_Spend(
Month DOUBLE,
Budget DOUBLE,
Spend DOUBLE,
Taxes DOUBLE);

/* INSERT */
INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
(1, 1000, 75, 11.25);

INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
(1, 1000, 25, 3.75);

INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
(2, 1000, 200, 30);

INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
(3, 1000, 150, 22.5);

INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
(4, 1000, 10, 1.5);

INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
(4, 1000, 10, 1.5);

Body:
You need window function :

select bs.*,
      Budget - sum(Spend + Taxes) over (order by month) as Available
from (select month, Budget, sum(Spend) as Spend, sum(Taxes) as Taxes
      from Budget_Spend bs
      group by month, Budget
     ) bs;


问:
Does VS Code have an extension to replace the title bar?
The Atom editor has the feature to edit and replace the title bar with some options. Does VS Code have a similar extension or can it be replaced somehow?

答:
If you mean the Window title bar (the one that generally says {WorkspaceName}-Visual Studio Code), then you have two options:

Install the title extension https://marketplace.visualstudio.com/items?itemName=nilpatel.title and use it accordingly

OR

Create a .vscode folder on your workspace root and inside it create a settings.json file (if you haven't already all of these). There add the window.title setting and set to whatever you want

```<code>{
   "window.title": "My Custom Title"
}
</code>```

Body:
If you mean the Window title bar (the one that generally says {WorkspaceName}-Visual Studio Code), then you have two options:

Install the title extension https://marketplace.visualstudio.com/items?itemName=nilpatel.title and use it accordingly

OR

Create a .vscode folder on your workspace root and inside it create a settings.json file (if you haven't already all of these). There add the window.title setting and set to whatever you want

{
   "window.title": "My Custom Title"
}


问:
To get subtring from a string
I am having issue to extract substring from string.
The input values are like

```<code>{Resultset: 234, edf, ejj, Resultvalue: hsh, 23,hhs}
{ hashvalue: 233, ehdh, Resultset: 2dd34, edf, ejj}
3rd value:
{hashvalue: 233, ehdh, Resultset: 2dd34, Resultvalue: hsh, 23,hhs}
4th value
{hashvalue: 233, ehdh, Resultset:, Resultvalue: hsh, 23,hhs}
5th value
Null
6th value
{hashvalue: 233, ehdh, Resultvalue: hsh, 23,hhs}
</code>```

Output should be like

Resultset: 234, edf, ejj
Resultset: 2dd34, edf, ejj
Resultset: 2dd34
Resultset:
Null
Null
Like this.
```

I tried but the expected string sometimes comes at first and sometimes at last. Sometime i get more than expected string.

I think, need regular expression to search for two characters and when first : appears don't go for second }

答:
Return the first remembered group of "Resultset: followed by anything (non-greedy)" when that group is followed by another group consisting of [a comma, then zero or more spaces, then 1 or more word characters ending in a colon] OR [a right curly brace].

CAVEAT: REGEXP_SUBSTR() returns NULL if the match cannot be found.  You may want to wrap the call in NVL() and return something if the value is NULL then.

Edit: Updated to reflect your new test data.

```<code>WITH tbl(ID, str) AS (
  SELECT 1, '{Resultset: 234, edf, ejj, Resultvalue: hsh, 23,hhs}' FROM dual UNION ALL
  SELECT 2, '{ hashvalue: 233, ehdh, Resultset: 2dd34, edf, ejj}'    FROM dual  UNION ALL
  SELECT 3, '{hashvalue: 233, ehdh, Resultset: 2dd34, Resultvalue: hsh, 23,hhs}' FROM dual UNION ALL
  SELECT 4, '{hashvalue: 233, ehdh, Resultset:, Resultvalue: hsh, 23,hhs}' FROM dual UNION ALL
  SELECT 5, NULL FROM dual UNION ALL
  SELECT 6, '{hashvalue: 233, ehdh, Resultvalue: hsh, 23,hhs}' FROM dual
)
SELECT ID,
  REGEXP_SUBSTR(str, '(Resultset:.*?)(, *\w+:|})', 1, 1, 'i', 1) resultset
FROM tbl
ORDER BY ID;

         ID RESULTSET
---------- ------------------------------------------------------------------
         1 Resultset: 234, edf, ejj
         2 Resultset: 2dd34, edf, ejj
         3 Resultset: 2dd34
         4 Resultset:
         5
         6

6 rows selected.
</code>```

Title: To get subtring from a string

Body:
I am having issue to extract substring from string.
The input values are like

{Resultset: 234, edf, ejj, Resultvalue: hsh, 23,hhs}
{ hashvalue: 233, ehdh, Resultset: 2dd34, edf, ejj}
3rd value:
{hashvalue: 233, ehdh, Resultset: 2dd34, Resultvalue: hsh, 23,hhs}
4th value
{hashvalue: 233, ehdh, Resultset:, Resultvalue: hsh, 23,hhs}
5th value
Null
6th value
{hashvalue: 233, ehdh, Resultvalue: hsh, 23,hhs}

Output should be like

Resultset: 234, edf, ejj
Resultset: 2dd34, edf, ejj
Resultset: 2dd34
Resultset:
Null
Null
Like this.

I tried but the expected string sometimes comes at first and sometimes at last. Sometime i get more than expected string.

I think, need regular expression to search for two characters and when first : appears don't go for second }

Body:
Return the first remembered group of "Resultset: followed by anything (non-greedy)" when that group is followed by another group consisting of [a comma, then zero or more spaces, then 1 or more word characters ending in a colon] OR [a right curly brace].

CAVEAT: REGEXP_SUBSTR() returns NULL if the match cannot be found.  You may want to wrap the call in NVL() and return something if the value is NULL then.

Edit: Updated to reflect your new test data.

WITH tbl(ID, str) AS (
  SELECT 1, '{Resultset: 234, edf, ejj, Resultvalue: hsh, 23,hhs}' FROM dual UNION ALL
  SELECT 2, '{ hashvalue: 233, ehdh, Resultset: 2dd34, edf, ejj}'    FROM dual  UNION ALL
  SELECT 3, '{hashvalue: 233, ehdh, Resultset: 2dd34, Resultvalue: hsh, 23,hhs}' FROM dual UNION ALL
  SELECT 4, '{hashvalue: 233, ehdh, Resultset:, Resultvalue: hsh, 23,hhs}' FROM dual UNION ALL
  SELECT 5, NULL FROM dual UNION ALL
  SELECT 6, '{hashvalue: 233, ehdh, Resultvalue: hsh, 23,hhs}' FROM dual
)
SELECT ID,
  REGEXP_SUBSTR(str, '(Resultset:.*?)(, *\w+:|})', 1, 1, 'i', 1) resultset
FROM tbl
ORDER BY ID;

         ID RESULTSET
---------- ------------------------------------------------------------------
         1 Resultset: 234, edf, ejj
         2 Resultset: 2dd34, edf, ejj
         3 Resultset: 2dd34
         4 Resultset:
         5
         6

6 rows selected.


问:
Error while creating Entities with Doctrine in Symfony
I am trying to create entities but I have an error, the entity is created in the project but nothing created in the database.

Here is the error message:

and this is the generated Class

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
    * @ORM\Entity(repositoryClass="App\Repository\CategoryRepository")
*/
class Category
{
    /**
        * @ORM\Id()
        * @ORM\GeneratedValue()
        * @ORM\Column(type="integer")
    */
    private $id;

    public function getId(): ?int
    {
        return $this->id;
    }
}
```

<p>and this is my doctrine.yaml</p>

```doctrine:
   dbal:
    # configure these for your database server

    driver: 'pdo_mysql'
    server_version: '8.0.18'
    charset: utf8mb4
    host: 127.0.0.1
    port: 3306
    user: 'root'
    password: 'root'
    dbname: 'omega'
    #   dbname: '%env(DATABASE_NAME)%'
```

答:
Try to add this at the end of your doctrine.yaml :

```<code>    orm:
        auto_generate_proxy_classes: true
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true
        mappings:
            App:
                is_bundle: false
                type: annotation
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'App\Entity'
                alias: App
</code>```

Then retry. Let us know.

Body:
I am trying to create entities but I have an error, the entity is created in the project but nothing created in the database.

Here is the error message:

and this is the generated Class

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
    * @ORM\Entity(repositoryClass="App\Repository\CategoryRepository")
*/
class Category
{
    /**
        * @ORM\Id()
        * @ORM\GeneratedValue()
        * @ORM\Column(type="integer")
    */
    private $id;

    public function getId(): ?int
    {
        return $this->id;
    }
}

and this is my doctrine.yaml

doctrine:
   dbal:
    # configure these for your database server

    driver: 'pdo_mysql'
    server_version: '8.0.18'
    charset: utf8mb4
    host: 127.0.0.1
    port: 3306
    user: 'root'
    password: 'root'
    dbname: 'omega'
    #   dbname: '%env(DATABASE_NAME)%'

Body:
Try to add this at the end of your doctrine.yaml :

    orm:
        auto_generate_proxy_classes: true
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true
        mappings:
            App:
                is_bundle: false
                type: annotation
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'App\Entity'
                alias: App

Then retry. Let us know.


问:
Splitting strings in Ruby
I want to split a string:

```<code>"00 85 00 04 79 E5 0B B5 82 AE C7 C9 96 37 93 AE"
</code>```

into two small strings like:

```<code>string1 => "00 85 00 04"
string2 => "79 E5 0B B5 82 AE C7 C9 96 37 93 AE"
</code>```

I tried using arrays but would like to try something new.

答:
The answer to this depends upon other information you might provide: is the first string of a known length? What conceptually defines where you want the split to occur.

In your example you might do:

```<code>s = "00 85 00 04 79 E5 0B B5 82 AE C7 C9 96 37 93 AE"

l = s.split("04")

str0 = l[0] + "04"
str1 = l[1]
</code>```

Or you could slice just like you might an array/list

Title: Splitting strings in Ruby

Body:
I want to split a string:

"00 85 00 04 79 E5 0B B5 82 AE C7 C9 96 37 93 AE"

into two small strings like:

string1 => "00 85 00 04"
string2 => "79 E5 0B B5 82 AE C7 C9 96 37 93 AE"

I tried using arrays but would like to try something new.

Body:
The answer to this depends upon other information you might provide: is the first string of a known length? What conceptually defines where you want the split to occur.

In your example you might do:

s = "00 85 00 04 79 E5 0B B5 82 AE C7 C9 96 37 93 AE"

l = s.split("04")

str0 = l[0] + "04"
str1 = l[1]

Or you could slice just like you might an array/list


问:
Applying templates to an element whose sibling element has a certain attribute value
I am trying to apply a template using XSLT1 and I can't get it to work:

```<code><xsl:apply-templates select="MeetingWorkBook/Meeting[1]/SpecialEvent/Event[/Date[@AllDayEvent='1']]" mode="FirstRow_Pray">
    <xsl:with-param name="strClass">cellBold borderRight</xsl:with-param>
</xsl:apply-templates>
</code>```

I am trying to apply this template:

```<code>  <!--This is used to insert the Chairman, or Special Event-->
  <xsl:template match="Chairman | Event" mode="FirstRow_Pray">
    <xsl:param name="strClass"/>
    <td class="{$strClass}">
      <xsl:if test="self::Event">
        <xsl:attribute name="rowspan">2</xsl:attribute>
      </xsl:if>
      <xsl:value-of select="."/>
    </td>
  </xsl:template>
</code>```

But I only want to apply the template if the Event element exists and the sibling Date[@AllDayEvent] is true.

I know I can wrap my apply-templates call with if clause first and that would work(see below).

I know I can improve the logic of the Event template to test the value of the sibling elements attribute.

I have a lot of templates for using specific Event properties and would prefer the ability the select the item Event where its sibling element Date has a certain attribute value.

But my attempt does not work. I saw this answer and tried:

MeetingWorkBook/Meeting[1]/SpecialEvent/Event[Date[@AllDayEvent='1']]

But it still doesn't work.

This will work:

```<code>  <xsl:if test="MeetingWorkBook/Meeting[1]/SpecialEvent/Date[@AllDayEvent='1']">
    <xsl:apply-templates select="MeetingWorkBook/Meeting[1]/SpecialEvent/Event" mode="FirstRow_Pray">
      <xsl:with-param name="strClass">cellBold borderRight</xsl:with-param>
    </xsl:apply-templates>
  </xsl:if>
</code>```

But I want to avoid needing the if if possible.

I can now see what was wrong with my original attempt. Date is not a child of Event but a sibling.

MeetingWorkBook/Meeting[1]/SpecialEvent/Date

MeetingWorkBook/Meeting[1]/SpecialEvent/Event

So is it possible to apply a template on Event where the sibling Date has an attribute AllDayEvent with a value of 1. Or do I have no choice but to use the if approach?

Sample XML data:

```<code><Meeting BookmarkId="2" PageBreak="0" NumberClasses="1" SpecialEvent="1" CircuitVisit="0">
    <Date ThisWeek="W20200217" NextWeek="W20200224">February 17-23</Date>
    <WeeklyBibleReading>GENESIS 18-19</WeeklyBibleReading>
    <ReviewQuestion></ReviewQuestion>
    <SpecialEvent>
        <Event>Circuit Assembly - Love Jehovah With All Your Heart</Event>
        <Location>Bristol Assembly Hall, Hortham Lane, Bristol, BS32 4JH</Location>
        <Date Day="23" DayShort="Sun" DayFull="Sunday" Month="2" MonthShort="Feb" MonthFull="February" Year="2020" Memorial="0" AllDayEvent="1" MidweekEvent="1">23/02/2020</Date>
    </SpecialEvent>
</Meeting>
</code>```

答:
You should be able to add the predicate to SpecialEvent instead of Event...

```<code><xsl:apply-templates select="MeetingWorkBook/Meeting[1]/SpecialEvent[Date/@AllDayEvent='1']/Event" mode="FirstRow_Pray">
    <xsl:with-param name="strClass">cellBold borderRight</xsl:with-param>
</xsl:apply-templates>
</code>```

Body:
I am trying to apply a template using XSLT1 and I can't get it to work:

<xsl:apply-templates select="MeetingWorkBook/Meeting[1]/SpecialEvent/Event[/Date[@AllDayEvent='1']]" mode="FirstRow_Pray">
    <xsl:with-param name="strClass">cellBold borderRight</xsl:with-param>
</xsl:apply-templates>

I am trying to apply this template:

  <xsl:template match="Chairman | Event" mode="FirstRow_Pray">
    <xsl:param name="strClass"/>

      <xsl:if test="self::Event">
        <xsl:attribute name="rowspan">2</xsl:attribute>
      </xsl:if>
      <xsl:value-of select="."/>

  </xsl:template>

But I only want to apply the template if the Event element exists and the sibling Date[@AllDayEvent] is true.

I know I can wrap my apply-templates call with if clause first and that would work(see below).

I know I can improve the logic of the Event template to test the value of the sibling elements attribute.

I have a lot of templates for using specific Event properties and would prefer the ability the select the item Event where its sibling element Date has a certain attribute value.

But my attempt does not work. I saw this answer and tried:

MeetingWorkBook/Meeting[1]/SpecialEvent/Event[Date[@AllDayEvent='1']]

But it still doesn't work.

This will work:

  <xsl:if test="MeetingWorkBook/Meeting[1]/SpecialEvent/Date[@AllDayEvent='1']">
    <xsl:apply-templates select="MeetingWorkBook/Meeting[1]/SpecialEvent/Event" mode="FirstRow_Pray">
      <xsl:with-param name="strClass">cellBold borderRight</xsl:with-param>
    </xsl:apply-templates>
  </xsl:if>

But I want to avoid needing the if if possible.

I can now see what was wrong with my original attempt. Date is not a child of Event but a sibling.

MeetingWorkBook/Meeting[1]/SpecialEvent/Date

MeetingWorkBook/Meeting[1]/SpecialEvent/Event

So is it possible to apply a template on Event where the sibling Date has an attribute AllDayEvent with a value of 1. Or do I have no choice but to use the if approach?

Sample XML data:

<Meeting BookmarkId="2" PageBreak="0" NumberClasses="1" SpecialEvent="1" CircuitVisit="0">
    <Date ThisWeek="W20200217" NextWeek="W20200224">February 17-23</Date>
    <WeeklyBibleReading>GENESIS 18-19</WeeklyBibleReading>
    <ReviewQuestion></ReviewQuestion>
    <SpecialEvent>
        <Event>Circuit Assembly - Love Jehovah With All Your Heart</Event>
        <Location>Bristol Assembly Hall, Hortham Lane, Bristol, BS32 4JH</Location>
        <Date Day="23" DayShort="Sun" DayFull="Sunday" Month="2" MonthShort="Feb" MonthFull="February" Year="2020" Memorial="0" AllDayEvent="1" MidweekEvent="1">23/02/2020</Date>
    </SpecialEvent>
</Meeting>

Body:
You should be able to add the predicate to SpecialEvent instead of Event...

<xsl:apply-templates select="MeetingWorkBook/Meeting[1]/SpecialEvent[Date/@AllDayEvent='1']/Event" mode="FirstRow_Pray">
    <xsl:with-param name="strClass">cellBold borderRight</xsl:with-param>
</xsl:apply-templates>


问:
How to completely set focus on a WebBrowser object in WPF
I have a basic class with a WebBrowser in it:

```<code><Window x:Class="X.Y"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="X- Music Video"
    WindowState="Maximized"
    WindowStyle="None">

    <WebBrowser x:Name="webBrowser1" KeyDown="Window_KeyDown" Focusable="True"/>

</Window>
</code>```

Then when I try to navigate to it, it works by opening a youtube video in fullscreen:

```<code>this.webBrowser1.NavigateToString(<html with youtube embedded>);
this.webBrowser1.Focus();
</code>```

Example html:

```<code><html>    <head>        <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>        <style type="text/css">body, html{margin: 0; padding: 0; height: 100%; overflow: hidden;}#content{position: absolute; left: 0; right: 0; bottom: 0; top: 0px;}</style>     </head>    <body>        <div id="content">            <iframe width="100%" height="100%" src="https://www.youtube.com/embed/QDfKzB2T0i4?autoplay=1&start=3"                </iframe>        </div>    </body></html>
</code>```

The issue comes into play wherein the fullscreen view now isn't "focused". The .Focus() does enable keyboard focus, but not a complete activation. What ends up happening is there is a grey border on the top and left of the screen. Clicking in removes it and gives me complete focus though.

You can see it in the picture above, the 2-ish pixels wide grey border.

Is there anything I can do to improve on this? The whole project is on github, and you can download the .exe to run it from releases. It requires a Spotify account to work though, so hopefully this is reproducible enough.

答:
It was actually an HTML/CSS fix, instead of anything to do with c# or wpf.

The two things that need to be done is:

Add frameborder = "0" to the iFrame

Implement the following CSS iframe:focus{ outline: none; }

Once they're in place, you can create a seamless youtube embed.

Body:
I have a basic class with a WebBrowser in it:

<Window x:Class="X.Y"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="X- Music Video"
    WindowState="Maximized"
    WindowStyle="None">

    <WebBrowser x:Name="webBrowser1" KeyDown="Window_KeyDown" Focusable="True"/>

</Window>

Then when I try to navigate to it, it works by opening a youtube video in fullscreen:

this.webBrowser1.NavigateToString();
this.webBrowser1.Focus();

Example html:

            <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
            <iframe width="100%" height="100%" src="https://www.youtube.com/embed/QDfKzB2T0i4?autoplay=1&start=3"

The issue comes into play wherein the fullscreen view now isn't "focused". The .Focus() does enable keyboard focus, but not a complete activation. What ends up happening is there is a grey border on the top and left of the screen. Clicking in removes it and gives me complete focus though.

You can see it in the picture above, the 2-ish pixels wide grey border.

Is there anything I can do to improve on this? The whole project is on github, and you can download the .exe to run it from releases. It requires a Spotify account to work though, so hopefully this is reproducible enough.


问:
How to prove equality from equality of Some
I want to prove equality of two nat numbers in Coq:</p>

```<code>a, b : nat
Heq : Some a = Some b
============================
a = b
</code>```

答:
When you have an equality such as this, usually, the quickest way to go is by using the inversion tactic which will more or less exploit injectivity of constructors.

```<code>Lemma foo :
  forall (a b : nat),
    Some a = Some b ->
    a = b.
Proof.
  intros a b e. inversion e. reflexivity.
Qed.
</code>```

The case of Some however is special enough that you might want to write it differently (especially if you ant to be able to read the proof that's generated).
You can write some get function for option using a default value:

```<code>Definition get_opt_default {A : Type} (x : A) (o : option A) :=
  match o with
  | Some a => a
  | None => x
  end.
</code>```

So that get_opt_default x (Some a) = a.
Now using f_equal (get_opt_default a) on equality Some a = Some b
you get

```<code>get_opt_default a (Some a) = get_opt_default a (Some b)
</code>```

which simplifies to

```<code>a = b
</code>```

```<code>Lemma Some_inj :
  forall A (a b : A),
    Some a = Some b ->
    a = b.
Proof.
  intros a b e.
  apply (f_equal (get_opt_default a)) in e.
  cbn in e.
  exact e.
Qed.
</code>```

This is something that can be done in general. Basically you write an extractor for your value as a function and you apply it to both sides of the equality.
By computation it will yield the expected result.

Body:
I want to prove equality of two nat numbers in Coq:

a, b : nat
Heq : Some a = Some b
============================
a = b

Body:
When you have an equality such as this, usually, the quickest way to go is by using the inversion tactic which will more or less exploit injectivity of constructors.

Lemma foo :
  forall (a b : nat),
    Some a = Some b ->
    a = b.
Proof.
  intros a b e. inversion e. reflexivity.
Qed.

The case of Some however is special enough that you might want to write it differently (especially if you ant to be able to read the proof that's generated).
You can write some get function for option using a default value:

Definition get_opt_default {A : Type} (x : A) (o : option A) :=
  match o with
  | Some a => a
  | None => x
  end.

So that get_opt_default x (Some a) = a.
Now using f_equal (get_opt_default a) on equality Some a = Some b
you get

get_opt_default a (Some a) = get_opt_default a (Some b)

which simplifies to

a = b

Lemma Some_inj :
  forall A (a b : A),
    Some a = Some b ->
    a = b.
Proof.
  intros a b e.
  apply (f_equal (get_opt_default a)) in e.
  cbn in e.
  exact e.
Qed.

This is something that can be done in general. Basically you write an extractor for your value as a function and you apply it to both sides of the equality.
By computation it will yield the expected result.


问:
Saving an IDataset that can be imported later to the database
Is there a way that one could save a dbunit dataset(IDataset) as some other file than xml or csv?

I would like to import the created dataset later back to the database.

I'm creating a partial dataset containing of tables:

```<code>QueryDataSet partialDataSet = new QueryDataSet(dataBaseConnection)
partialDataSet.addTable("tableName");
// save as a file
// import the file later
</code>```

I tried saving the dataset as .xml, but the order of rows is not correct if there is a dependency to another table.

答:
You may use the DatabaseSequenceFilter and FilteredDataSet as described in DBUnit FAQ.

For you this might be:

```<code>QueryDataSet partialDataSet = new QueryDataSet(dataBaseConnection)
partialDataSet.addTable("tableName");
IDatabaseConnection connection = getConnection();
//Following filter will sort tables in correct order
ITableFilter filter = new DatabaseSequenceFilter(conn);
IDataSet dataset = new FilteredDataSet(filter, partialDataSet);
FlatXmlDataSet.write(dataset, new File("data-in-correct-order.xml"));
</code>```

This xml later can be imported correctly into the DB.

http://dbunit.sourceforge.net/faq.html#tableseq

Body:
Is there a way that one could save a dbunit dataset(IDataset) as some other file than xml or csv?

I would like to import the created dataset later back to the database.

I'm creating a partial dataset containing of tables:

QueryDataSet partialDataSet = new QueryDataSet(dataBaseConnection)
partialDataSet.addTable("tableName");
// save as a file
// import the file later

I tried saving the dataset as .xml, but the order of rows is not correct if there is a dependency to another table.

Body:
You may use the DatabaseSequenceFilter and FilteredDataSet as described in DBUnit FAQ.

For you this might be:

QueryDataSet partialDataSet = new QueryDataSet(dataBaseConnection)
partialDataSet.addTable("tableName");
IDatabaseConnection connection = getConnection();
//Following filter will sort tables in correct order
ITableFilter filter = new DatabaseSequenceFilter(conn);
IDataSet dataset = new FilteredDataSet(filter, partialDataSet);
FlatXmlDataSet.write(dataset, new File("data-in-correct-order.xml"));

This xml later can be imported correctly into the DB.

http://dbunit.sourceforge.net/faq.html#tableseq


问:
How to execute the command written in python script in mac terminal immediately after logged in to the server
```<code>import os.path
import subprocess
import sys
os.system('sshpass -p password ssh root@esst-warp-d')
subprocess.call('lscpu')
</code>```

I tried the above code, but the command will execute after logging out of the server.

```<code>import os.path
import subprocess
import sys
os.system('sshpass -p password ssh root@esst-warp-d')
ssh root@esst-warp-d "lscpu"
</code>```

If I try the above code I will get syntax invalid in the fifth line

Can you please help me to sort out the problem.

答:
When you run os.system("sshpass ...") it creates a new process, unrelated to anything else, and runs your sshpass command in it. The process then exits.

When you run subprocess.call() it creates a new process, unrelated to the one that just exited above, on your local machine, and runs your command in it. The process then exits.

You actually want to create a new process that connects to the remote Linux machine and then runs a command on there, so you need this:

```<code>sshpass -p password ssh root@esst-warp-d '/path/to/lscpu'
</code>```

Try it in your Terminal.

Body:
import os.path
import subprocess
import sys
os.system('sshpass -p password ssh root@esst-warp-d')
subprocess.call('lscpu')

I tried the above code, but the command will execute after logging out of the server.

import os.path
import subprocess
import sys
os.system('sshpass -p password ssh root@esst-warp-d')
ssh root@esst-warp-d "lscpu"

If I try the above code I will get syntax invalid in the fifth line

Can you please help me to sort out the problem.

Body:
When you run os.system("sshpass ...") it creates a new process, unrelated to anything else, and runs your sshpass command in it. The process then exits.

When you run subprocess.call() it creates a new process, unrelated to the one that just exited above, on your local machine, and runs your command in it. The process then exits.

You actually want to create a new process that connects to the remote Linux machine and then runs a command on there, so you need this:

sshpass -p password ssh root@esst-warp-d '/path/to/lscpu'

Try it in your Terminal.


答:
The congruence tactic is powerful enough to solve this goal by itself.  More generally, there are situations where you would like to derive a = b as an additional hypothesis starting from an equality H : x = y of terms that begin with the same constructor.  In this case, you can call

```<code>injection H.
</code>```

to extract the equalities implied by this hypothesis.

Title: How to prove equality from equality of Some

Body:
The congruence tactic is powerful enough to solve this goal by itself.  More generally, there are situations where you would like to derive a = b as an additional hypothesis starting from an equality H : x = y of terms that begin with the same constructor.  In this case, you can call

injection H.

to extract the equalities implied by this hypothesis.


问:
I want moving test-output folder from project to other directory where should I put that moving folder code in set up or tear down?
I want to move test-output folder from project to other directory that I don't need  every time in selenium where should I put that moving folder code in set up or tear down?</p>

答:
You can have this attached to Suite base file </p>

```<code>public void reportLog(String srcFileName, String reportName, String extension){

    File srcFile = new File(System.getProperty("user.dir")+"\\src\\main\\resources\\excelfiles\\"+srcFileName+"."+extension);

    String destDir = "reportlog";
    DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa");
    String destFile = reportName+" - "+dateFormat.format(new Date()) + "."+extension;
    try {
            FileUtils.copyFile(srcFile, new File(destDir + "/" + destFile));
    } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }
}
</code>```

Body:
You can have this attached to Suite base file

public void reportLog(String srcFileName, String reportName, String extension){

    File srcFile = new File(System.getProperty("user.dir")+"\\src\\main\\resources\\excelfiles\\"+srcFileName+"."+extension);

    String destDir = "reportlog";
    DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa");
    String destFile = reportName+" - "+dateFormat.format(new Date()) + "."+extension;
    try {
            FileUtils.copyFile(srcFile, new File(destDir + "/" + destFile));
    } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }
}


问:
Refactor try and Except codeblocks in Python
Currently my app is working with several external APIs, and those functions can raise some kind of error, and I would like to be aware of all kind of situations and don't crash my app. In the following piece of code you can see my function, using slack api (it's just an example, not real example), and you can see how I'm creating a space giving the name and the emails. That function can returns several errors, like APIerror, TypeError... etc etc

Also you can see, all the functions in that file, can raise some errors so it is using try and except and try to don't break our app. In the except part, I don't want to do anything special, just return the error or I don't know, raise an custom error. In the future would be cool if I can enqueue that task if something goes wrong.

slack_client.py

def create_space():
  try:
    slack_api.create.space(spaceName='space name', email=emails)
  except (...):
    ...
```

<pre class="lang-py prettyprint-override"><code>def delete_space():
  try:
    slack_api.delete.space(spaceId=space_id)
  except (...):
    ...

</code>```

I would like to refactor the try and except part, because I don't want to copy and paste try and except during all my slack_client class, but in case the connection is down, or some parameter is wron, the "Slack" API will raise me an error.

I thought about create a class, to run each function inside try and catch, but it's a bit weird and I will loose the arguments part like "spaceName='space name'", which I think it's really cool and clear.

def execute_func(func, *args):
  try:
     func(args)
  except (..):
     ...

```

So would like some help for this kind of situation, because handle external API is not always really easy... (at the moment working with 2 external APIs)

答:
You can catch any exception that is thrown and capture it in a variable to log or raise. You could even raise your own custom exception. Something like this should work:

First create your exception:

class CustomSlackException(Exception):
    pass
```

<p>Then raise it when the API you called throws some exception:</p>

<pre class="lang-py prettyprint-override"><code>try:
    slack_api.create.space(spaceName='space name', email=emails)
except Exception as e:
    print(e)
    raise CustomSlackException("Custom error message!")
</code>```

Now you can catch your exception and handle it as needed.

Body:
Currently my app is working with several external APIs, and those functions can raise some kind of error, and I would like to be aware of all kind of situations and don't crash my app. In the following piece of code you can see my function, using slack api (it's just an example, not real example), and you can see how I'm creating a space giving the name and the emails. That function can returns several errors, like APIerror, TypeError... etc etc

Also you can see, all the functions in that file, can raise some errors so it is using try and except and try to don't break our app. In the except part, I don't want to do anything special, just return the error or I don't know, raise an custom error. In the future would be cool if I can enqueue that task if something goes wrong.

slack_client.py

def create_space():
  try:
    slack_api.create.space(spaceName='space name', email=emails)
  except (...):
    ...

def delete_space():
  try:
    slack_api.delete.space(spaceId=space_id)
  except (...):
    ...

I would like to refactor the try and except part, because I don't want to copy and paste try and except during all my slack_client class, but in case the connection is down, or some parameter is wron, the "Slack" API will raise me an error.

I thought about create a class, to run each function inside try and catch, but it's a bit weird and I will loose the arguments part like "spaceName='space name'", which I think it's really cool and clear.

def execute_func(func, *args):
  try:
     func(args)
  except (..):
     ...

So would like some help for this kind of situation, because handle external API is not always really easy... (at the moment working with 2 external APIs)

Body:
You can catch any exception that is thrown and capture it in a variable to log or raise. You could even raise your own custom exception. Something like this should work:

First create your exception:

class CustomSlackException(Exception):
    pass

Then raise it when the API you called throws some exception:

try:
    slack_api.create.space(spaceName='space name', email=emails)
except Exception as e:
    print(e)
    raise CustomSlackException("Custom error message!")

Now you can catch your exception and handle it as needed.


问:
setState doesn't execute the callback
I have a select filter, I want to filter my products by category. The state gets updated but the callback of setState is not executed. Basically I want to update my list immediately when the state is changed. Code line 31 doesn't get executed in the try blok, it's also not catching any error.

HTML

```<code><div className="col-md-4 w-25 mt-3 ml-5">
                <Select
                  onChange={this.handleChange}
                  value={selectedCategory}
                  placeholder="Select Category"
                  options={categories}
                />
   </div>
</code>```

JavaScript

```<code>    handleChange = event => {
    console.log(event.value);
    this.setState({ selectedCategory: event.value }, () => {
      try {
        products.pipe(
          map(products =>
            products
              .filter(
                product => product.category === this.state.selectedCategory
              )
              .subscribe(products => {
                console.log(products);
                this.setState({
                  items: products,
                  isLoaded: true
                });
              })
          )
        );
      } catch (error) {
        console.error(error);
      }
    });
  };
</code>```

答:
This code did the trick, still don't know why it was not working. Can anybody explain this?

handleChange = event => {

```<code>      this.setState(
        { selectedCategory: event.value },
        this.showFilteredProducts
      );
  };

  showFilteredProducts() {
    const filterItems = products.pipe(
      map(products =>
        products.filter(
          product => product.category === this.state.selectedCategory
        )
      )
    );
    filterItems.subscribe(products => {
      this.setState({
        items: products,
        isLoaded: true
      });
    });
  }
</code>```

Title: setState doesn't execute the callback

Body:
I have a select filter, I want to filter my products by category. The state gets updated but the callback of setState is not executed. Basically I want to update my list immediately when the state is changed. Code line 31 doesn't get executed in the try blok, it's also not catching any error.

HTML

                <Select
                  onChange={this.handleChange}
                  value={selectedCategory}
                  placeholder="Select Category"
                  options={categories}
                />

JavaScript

    handleChange = event => {
    console.log(event.value);
    this.setState({ selectedCategory: event.value }, () => {
      try {
        products.pipe(
          map(products =>
            products
              .filter(
                product => product.category === this.state.selectedCategory
              )
              .subscribe(products => {
                console.log(products);
                this.setState({
                  items: products,
                  isLoaded: true
                });
              })
          )
        );
      } catch (error) {
        console.error(error);
      }
    });
  };

Body:
This code did the trick, still don't know why it was not working. Can anybody explain this?

handleChange = event => {

      this.setState(
        { selectedCategory: event.value },
        this.showFilteredProducts
      );
  };

  showFilteredProducts() {
    const filterItems = products.pipe(
      map(products =>
        products.filter(
          product => product.category === this.state.selectedCategory
        )
      )
    );
    filterItems.subscribe(products => {
      this.setState({
        items: products,
        isLoaded: true
      });
    });
  }


问:
how to pass data from blank page to tabs page in ionic 4
I am new to ionic.

I want to pass the parameter from one page to the tabs page.

Basically it's a place list. On click of the item, I want to pass place_id to place tab pages.

There are 3 tabs: Place Detail, Member List, Events.

I want to pass place_id to all pages.

On click of an item if I pass a parameter to the tabs page it won't work. But without parameter, it works perfectly. It goes to the tabs page.

app-routing.module.ts

```<code>import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'tab',
    loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
  },
  {
    path: 'member-detail',
    loadChildren: () => import('./member-detail/member-detail.module').then( m => m.MemberDetailPageModule)
  },
  {
    path: 'member-detail/:userId',
    loadChildren: () => import('./member-detail/member-detail.module').then( m => m.MemberDetailPageModule)
  },
  {
    path: '',
    loadChildren: () => import('./login/login.module').then( m => m.LoginPageModule)
  },
  {
    path: 'register',
    loadChildren: () => import('./register/register.module').then( m => m.RegisterPageModule)
  },
  {
    path: 'forgot-password',
    loadChildren: () => import('./forgot-password/forgot-password.module').then( m => m.ForgotPasswordPageModule)
  },
  {
    path: 'otp',
    loadChildren: () => import('./otp/otp.module').then( m => m.OtpPageModule)
  },
  {
    path: 'edit-profile',
    loadChildren: () => import('./edit-profile/edit-profile.module').then( m => m.EditProfilePageModule)
  },
  {
    path: 'forgot-change-password',
    loadChildren: () => import('./forgot-change-password/forgot-change-password.module').then( m => m.ForgotChangePasswordPageModule)
  },
  {
    path: 'forgot-change-password/:contact',
    loadChildren: () => import('./forgot-change-password/forgot-change-password.module').then( m => m.ForgotChangePasswordPageModule)
  },
  {
    path: 'member-list',
    loadChildren: () => import('./member-list/member-list.module').then( m => m.MemberListPageModule)
  },
  {
    path: 'places',
    loadChildren: () => import('./places/places.module').then( m => m.PlacesPageModule)
  },
  // {
  //   path: 'place-tab',
  //   loadChildren: () => import('./place-tab/place-tab.module').then( m => m.PlaceTabPageModule)
  // },
  {
    path: 'place-tab/:placeId',
    loadChildren: () => import('./place-tab/place-tab.module').then( m => m.PlaceTabPageModule)
  },
  {
    path: '',
    loadChildren: () => import('./place-tab/place-tab.module').then( m => m.PlaceTabPageModule)
  },
  {
    path: '',
    loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
  }
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}
</code>```

places.page.ts

```<code>placeDetail(placeId: string) {
    console.log(placeId);
    this.router.navigate(['/place-tab/', placeId]);
    // this.router.navigateByUrl('/place-tab');
  }
</code>```

place-tab.page.ts

```<code>export class PlaceTabPage {
  placeId: any;
  constructor(private activatedRoute: ActivatedRoute) {
    this.activatedRoute.params.subscribe(params => {
      this.placeId = params['placeId'];
    });
    console.log(this.placeId);
  }
}
</code>```

place-tab-routing.module.ts

```<code>const routes: Routes = [
  {
    path: 'place-tab',
    component: PlaceTabPage,
    children: [
      {
        path: 'place-detail',
        children: [
          {
            path: '',
            loadChildren: () =>
              import('../place-detail/place-detail.module').then(m => m.PlaceDetailPageModule)
          }
        ]
      },
      {
        path: 'place-member',
        children: [
          {
            path: '',
            loadChildren: () =>
              import('../place-member/place-member.module').then(m => m.PlaceMemberPageModule)
          }
        ]
      },
      {
        path: 'place-event',
        children: [
          {
            path: '',
            loadChildren: () =>
              import('../place-event/place-event.module').then(m => m.PlaceEventPageModule)
          }
        ]
      },
      {
        path: '',
        redirectTo: '/place-tab/place-detail',
        pathMatch: 'full'
      }
    ]
  },
  {
    path: '',
    redirectTo: '/place-tab/place-detail',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class PlaceTabPageRoutingModule { }
</code>```

答:
Here's an example of how you can pass data to the tabs component and maintain that state throughout navigation of the child tabs. This solution does feel a little clunky so it would not surprise me if a better answer surfaces at some point.

Let's assume we will be navigating from home.page.html to tabs.page.html by a button click. You can register a click event to a function in home.page.ts and within that function use Angular's router to navigate to the tabs page. The trick here is to add NavigationExtras which is where you can add state. Angular docs define the state property as:

Developer-defined state that can be passed to any navigation. Access this value through the Navigation.extras object returned from router.getCurrentNavigation() while a navigation is executing.

After a navigation completes, the router writes an object containing this value together with a navigationId to history.state. The value is written when location.go() or location.replaceState() is called before activating this route.

The state property can contain whatever you want to pass along to the route. The html and ts file would look something like this

home.page.html

```<code><ion-content>
  <ion-button (click)="routeToTabs(1)">Pass the ID of 1 to tabs pages</ion-button>
  <ion-button (click)="routeToTabs(2)">Pass the ID of 2 to tabs pages</ion-button>
  <ion-button (click)="routeToTabs(3)">Pass the ID of 3 to tabs pages</ion-button>
</ion-content>
</code>```

home.page.ts

```<code>import { Router, NavigationExtras } from '@angular/router';

...
export class HomePage implements OnInit {

  constructor(private router: Router) { }

  routeToTabs(myId: any) {
    const navigationExtras: NavigationExtras = { state: { id: myId } };
    this.router.navigate(['tabs'], navigationExtras);
  }
}
</code>```

Once the navigation completes the state property goes away (sort of - it get stored in a history.state property) so within the tabs.page.ts constructor grab the data passed in and assign it to local variables like this

```<code>export class TabsPage implements OnInit {
  id: any;

  constructor(private router: Router) {
    const navigation = this.router.getCurrentNavigation();
    const state = navigation.extras.state;
    this.id = state.id;
  }
}
</code>```

Here's where it does not feel quite right... In the tabs.page.html add a click event   to all of your tabs calling a function and passing it the tab name like this

```<code><ion-tabs>

  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="tab1" (click)="routeToTab('tab1')">
      <ion-icon name="triangle"></ion-icon>
      <ion-label>Tab 1</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab2" (click)="routeToTab('tab2')">
      <ion-icon name="ellipse"></ion-icon>
      <ion-label>Tab 2</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab3" (click)="routeToTab('tab3')">
      <ion-icon name="square"></ion-icon>
      <ion-label>Tab 3</ion-label>
    </ion-tab-button>
  </ion-tab-bar>

</ion-tabs>
</code>```

In tabs.page.ts add in the function which will add the state to NavigationExtras and route to the tab

```<code>routeToTab(tabRoute: string) {
    const navigationExtras: NavigationExtras = {
      state: { id: this.id }
    };
    this.router.navigate(['tabs/' + tabRoute], navigationExtras);
}
</code>```

Finally, in each of the tab component files add to the constructor and extract out the data passed in by the state object

```<code>id: any;

constructor(private router: Router) {
  const navigation = this.router.getCurrentNavigation();
  const state = navigation.extras.state
  this.id = state.id;
}
</code>```

I think that's it. Hope this helps.

Body:
I am new to ionic.

I want to pass the parameter from one page to the tabs page.

Basically it's a place list. On click of the item, I want to pass place_id to place tab pages.

There are 3 tabs: Place Detail, Member List, Events.

I want to pass place_id to all pages.

On click of an item if I pass a parameter to the tabs page it won't work. But without parameter, it works perfectly. It goes to the tabs page.

app-routing.module.ts

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'tab',
    loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
  },
  {
    path: 'member-detail',
    loadChildren: () => import('./member-detail/member-detail.module').then( m => m.MemberDetailPageModule)
  },
  {
    path: 'member-detail/:userId',
    loadChildren: () => import('./member-detail/member-detail.module').then( m => m.MemberDetailPageModule)
  },
  {
    path: '',
    loadChildren: () => import('./login/login.module').then( m => m.LoginPageModule)
  },
  {
    path: 'register',
    loadChildren: () => import('./register/register.module').then( m => m.RegisterPageModule)
  },
  {
    path: 'forgot-password',
    loadChildren: () => import('./forgot-password/forgot-password.module').then( m => m.ForgotPasswordPageModule)
  },
  {
    path: 'otp',
    loadChildren: () => import('./otp/otp.module').then( m => m.OtpPageModule)
  },
  {
    path: 'edit-profile',
    loadChildren: () => import('./edit-profile/edit-profile.module').then( m => m.EditProfilePageModule)
  },
  {
    path: 'forgot-change-password',
    loadChildren: () => import('./forgot-change-password/forgot-change-password.module').then( m => m.ForgotChangePasswordPageModule)
  },
  {
    path: 'forgot-change-password/:contact',
    loadChildren: () => import('./forgot-change-password/forgot-change-password.module').then( m => m.ForgotChangePasswordPageModule)
  },
  {
    path: 'member-list',
    loadChildren: () => import('./member-list/member-list.module').then( m => m.MemberListPageModule)
  },
  {
    path: 'places',
    loadChildren: () => import('./places/places.module').then( m => m.PlacesPageModule)
  },
  // {
  //   path: 'place-tab',
  //   loadChildren: () => import('./place-tab/place-tab.module').then( m => m.PlaceTabPageModule)
  // },
  {
    path: 'place-tab/:placeId',
    loadChildren: () => import('./place-tab/place-tab.module').then( m => m.PlaceTabPageModule)
  },
  {
    path: '',
    loadChildren: () => import('./place-tab/place-tab.module').then( m => m.PlaceTabPageModule)
  },
  {
    path: '',
    loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
  }
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}

places.page.ts

placeDetail(placeId: string) {
    console.log(placeId);
    this.router.navigate(['/place-tab/', placeId]);
    // this.router.navigateByUrl('/place-tab');
  }

place-tab.page.ts

export class PlaceTabPage {
  placeId: any;
  constructor(private activatedRoute: ActivatedRoute) {
    this.activatedRoute.params.subscribe(params => {
      this.placeId = params['placeId'];
    });
    console.log(this.placeId);
  }
}

place-tab-routing.module.ts

const routes: Routes = [
  {
    path: 'place-tab',
    component: PlaceTabPage,
    children: [
      {
        path: 'place-detail',
        children: [
          {
            path: '',
            loadChildren: () =>
              import('../place-detail/place-detail.module').then(m => m.PlaceDetailPageModule)
          }
        ]
      },
      {
        path: 'place-member',
        children: [
          {
            path: '',
            loadChildren: () =>
              import('../place-member/place-member.module').then(m => m.PlaceMemberPageModule)
          }
        ]
      },
      {
        path: 'place-event',
        children: [
          {
            path: '',
            loadChildren: () =>
              import('../place-event/place-event.module').then(m => m.PlaceEventPageModule)
          }
        ]
      },
      {
        path: '',
        redirectTo: '/place-tab/place-detail',
        pathMatch: 'full'
      }
    ]
  },
  {
    path: '',
    redirectTo: '/place-tab/place-detail',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class PlaceTabPageRoutingModule { }

Body:
Here's an example of how you can pass data to the tabs component and maintain that state throughout navigation of the child tabs. This solution does feel a little clunky so it would not surprise me if a better answer surfaces at some point.

Let's assume we will be navigating from home.page.html to tabs.page.html by a button click. You can register a click event to a function in home.page.ts and within that function use Angular's router to navigate to the tabs page. The trick here is to add NavigationExtras which is where you can add state. Angular docs define the state property as:

Developer-defined state that can be passed to any navigation. Access this value through the Navigation.extras object returned from router.getCurrentNavigation() while a navigation is executing.

After a navigation completes, the router writes an object containing this value together with a navigationId to history.state. The value is written when location.go() or location.replaceState() is called before activating this route.

The state property can contain whatever you want to pass along to the route. The html and ts file would look something like this

home.page.html

<ion-content>
  <ion-button (click)="routeToTabs(1)">Pass the ID of 1 to tabs pages</ion-button>
  <ion-button (click)="routeToTabs(2)">Pass the ID of 2 to tabs pages</ion-button>
  <ion-button (click)="routeToTabs(3)">Pass the ID of 3 to tabs pages</ion-button>
</ion-content>

home.page.ts

import { Router, NavigationExtras } from '@angular/router';

...
export class HomePage implements OnInit {

  constructor(private router: Router) { }

  routeToTabs(myId: any) {
    const navigationExtras: NavigationExtras = { state: { id: myId } };
    this.router.navigate(['tabs'], navigationExtras);
  }
}

Once the navigation completes the state property goes away (sort of - it get stored in a history.state property) so within the tabs.page.ts constructor grab the data passed in and assign it to local variables like this

export class TabsPage implements OnInit {
  id: any;

  constructor(private router: Router) {
    const navigation = this.router.getCurrentNavigation();
    const state = navigation.extras.state;
    this.id = state.id;
  }
}

Here's where it does not feel quite right... In the tabs.page.html add a click event   to all of your tabs calling a function and passing it the tab name like this

<ion-tabs>

  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="tab1" (click)="routeToTab('tab1')">
      <ion-icon name="triangle"></ion-icon>
      <ion-label>Tab 1</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab2" (click)="routeToTab('tab2')">
      <ion-icon name="ellipse"></ion-icon>
      <ion-label>Tab 2</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab3" (click)="routeToTab('tab3')">
      <ion-icon name="square"></ion-icon>
      <ion-label>Tab 3</ion-label>
    </ion-tab-button>
  </ion-tab-bar>

</ion-tabs>

In tabs.page.ts add in the function which will add the state to NavigationExtras and route to the tab

routeToTab(tabRoute: string) {
    const navigationExtras: NavigationExtras = {
      state: { id: this.id }
    };
    this.router.navigate(['tabs/' + tabRoute], navigationExtras);
}

Finally, in each of the tab component files add to the constructor and extract out the data passed in by the state object

id: any;

constructor(private router: Router) {
  const navigation = this.router.getCurrentNavigation();
  const state = navigation.extras.state
  this.id = state.id;
}

I think that's it. Hope this helps.


问:
How to get the previous value of a node in firebase realtime database
I am sending a request to the firebase client SDK (JavaScript) which sends to the location of a vehicle in realtime..I get the following object

```<code>{
  "bearing": 264.8562316894531,
  "latitude": "19.9742249",
  "longitude": "73.7910482",
  "timestamp": "1582103153697",
  "trip": "40be478c-b0b0-41fb-bc70-66b2507719ef",
  "user": "1985"
}
</code>```

I want to be able to get the value before it changes so I can calculate the angle to rotate my marker(HEADING).

any help is appreciated

答:
Isn't bearing enough for you to rotate your marker? Something like

```<code>marker.rotate(newData.bearing - marker.bearing);
</code>```

Body:
I am sending a request to the firebase client SDK (JavaScript) which sends to the location of a vehicle in realtime..I get the following object

{
  "bearing": 264.8562316894531,
  "latitude": "19.9742249",
  "longitude": "73.7910482",
  "timestamp": "1582103153697",
  "trip": "40be478c-b0b0-41fb-bc70-66b2507719ef",
  "user": "1985"
}

I want to be able to get the value before it changes so I can calculate the angle to rotate my marker(HEADING).

any help is appreciated

Body:
Isn't bearing enough for you to rotate your marker? Something like

marker.rotate(newData.bearing - marker.bearing);


问:
Azure Web App in a Private VPN?
I'm simply wondering if it is possible to create a private network on Azure and place a web app there? I know I can put VM's, SQL instances etc, but my question concern Web Apps specifically. Seems like such basic thing, but can't seem to make any progress on this...

My goal is to setup a Dev, Test and Prod environment in Azure.  I setup a VPN for each environment. Each VPN has three subnets (Public Web Front End, Private App Service, and a private Data sub net)

I want Dev, and Test environments to be completely private, but Prod should have the "Web Front End" subnet open to the Internet.

I cannot find a way to put the Web App in the subnet? If this is not possible, then does that mean I can't use Web Apps, and must instead use a VM with IIS? Is my approach using VPN's and subnets incorrect?

Thanks,

Per

答: Earlier this was possible only for azure VM connected via private peering via expressroute.This is now possible with azure private link</p>

Title: Azure Web App in a Private VPN?


问:
What is the proper SWI statement to print integers in assembly?
Im trying to make a while loop in assembly but my SWI statement to get the numbers to "print" is giving me an error.

```<code>.text
    mov r1, #10
    mov r2, #1
    b L2

L3:
    SWI 0x6b

    sub r1,r1,#-1

L2:
    cmp r1, r2
    bgt L3
</code>```

The error occurs once i get to the SWI 0x6b and the exact error message is "Unimplemented SWI code.

答:
You may have encountered multiple problems here:

ARMSim v2.1 is supposed to be honoring a subset of the Angel/Semihosting interface.

That means that r0 should contain a function number, r1 a pointer to a parameter block, and that the SWI number to be used shall be 0x123456, as in  swi 0x123456, and your program is obviously not compliant.

If you want to display a digit, you have to convert this digit into a representation of this digit that can be displayed. For example, if register r1 does contain #10, the value shall be processed so that value #'A' will be displayed. If r1 does contain a value in the range 0..9, the shall be processed so that a value in the #'0'..#'9' will be displayed.

The ARMSim v2.1 I experimented with on my Lubuntu 19.10 system failed executing swi 0x123456, and I got the same infamous error message, "Unimplemented SWI code." you got. Even more, the program Angel_print_int.s, contained in the ARMSim examples archive file, failed to execute as well.

At this stage, I would assume ARMSim v2.1 is not working as expected, and I switched to an online simulator supporting the Terasic DE1-SoC Board. The emulation does support a JTAG-UART device suitable for displaying characters.

You program was modified so that it would be able to display hexadecimal representations of values in range 1..10 using the emulated JTAG-UART device;

```<code>.global _start
.text
_start:
    mov r1, #10
    mov r2, #1
    // http://www-ug.eecg.toronto.edu/msl/nios_devices/dev_jtaguart.html
    ldr r3, =0xFF201000
    b L2

L3:
    mov r0, r1
    // convert value contained in r1 into a displayable hexadecimal digit
    cmp r0,#9
    bgt hex
dec:
    add r0,#'0'
    b continue
hex:
    add r0,#'A' - 10
continue:
    strb r0, [r3]

    sub r1,r1,#1

L2:
    cmp r1, r2
    bge L3
    mov r0, #'0'
done:
    b done
</code>```

Compiling/loading/executing the program resulted in the following chraracters being displayed in the JTAG UART Windows ah the right:

```<code>A987654321
</code>```

An alternative to using this emulator would be to use QEMU for Windows and arm-none-eabi-gdb.exe. I could provide a working procedure/example in the case you would be interested.

I hope this helped.

Body:
Im trying to make a while loop in assembly but my SWI statement to get the numbers to "print" is giving me an error.

.text
    mov r1, #10
    mov r2, #1
    b L2

L3:
    SWI 0x6b

    sub r1,r1,#-1

L2:
    cmp r1, r2
    bgt L3

The error occurs once i get to the SWI 0x6b and the exact error message is "Unimplemented SWI code.

Body:
You may have encountered multiple problems here:

ARMSim v2.1 is supposed to be honoring a subset of the Angel/Semihosting interface.

That means that r0 should contain a function number, r1 a pointer to a parameter block, and that the SWI number to be used shall be 0x123456, as in  swi 0x123456, and your program is obviously not compliant.

If you want to display a digit, you have to convert this digit into a representation of this digit that can be displayed. For example, if register r1 does contain #10, the value shall be processed so that value #'A' will be displayed. If r1 does contain a value in the range 0..9, the shall be processed so that a value in the #'0'..#'9' will be displayed.

The ARMSim v2.1 I experimented with on my Lubuntu 19.10 system failed executing swi 0x123456, and I got the same infamous error message, "Unimplemented SWI code." you got. Even more, the program Angel_print_int.s, contained in the ARMSim examples archive file, failed to execute as well.

At this stage, I would assume ARMSim v2.1 is not working as expected, and I switched to an online simulator supporting the Terasic DE1-SoC Board. The emulation does support a JTAG-UART device suitable for displaying characters.

You program was modified so that it would be able to display hexadecimal representations of values in range 1..10 using the emulated JTAG-UART device;

.global _start
.text
_start:
    mov r1, #10
    mov r2, #1
    // http://www-ug.eecg.toronto.edu/msl/nios_devices/dev_jtaguart.html
    ldr r3, =0xFF201000
    b L2

L3:
    mov r0, r1
    // convert value contained in r1 into a displayable hexadecimal digit
    cmp r0,#9
    bgt hex
dec:
    add r0,#'0'
    b continue
hex:
    add r0,#'A' - 10
continue:
    strb r0, [r3]

    sub r1,r1,#1

L2:
    cmp r1, r2
    bge L3
    mov r0, #'0'
done:
    b done

Compiling/loading/executing the program resulted in the following chraracters being displayed in the JTAG UART Windows ah the right:

A987654321

An alternative to using this emulator would be to use QEMU for Windows and arm-none-eabi-gdb.exe. I could provide a working procedure/example in the case you would be interested.

I hope this helped.


问:
Regex for matching decimals only, not integers
I'm looking for a regex to match decimal numbers only, but to fail on integers.

For example, the following numbers should pass

```<code>0.00
1.00
-1.00
3.3
2.22123
</code>```

But the following should fail

```<code>-1
-3
4
559
</code>```

I don't know why this is so hard to find/create, but I'm not having any luck. All available regexes that I found online don't exclude integers.

答:
\d+\.\d+?$
this pattern should work

Body:
I'm looking for a regex to match decimal numbers only, but to fail on integers.

For example, the following numbers should pass

0.00
1.00
-1.00
3.3
2.22123

But the following should fail

-1
-3
4
559

I don't know why this is so hard to find/create, but I'm not having any luck. All available regexes that I found online don't exclude integers.

Body:
\d+\.\d+?$
this pattern should work


问:
How would I send the same data to several android phones using TCP?
This is a bit of a "further down the track now" extension to a question I asked a while ago... I have a better understanding of sockets now, and have some working code but need to improve it...

Ok, so I have currently got UDP multicasting working to send short strings of text from a Java 'server' application to several Android phones (which will potentially become several hundred Android phones).  This works fine most of the time, but it does tend to lose the odd string on the odd phone, and randomly it will just go total loss for a short period and nothing will get through to any of them, which can be a little frustrating.

Since, as I understand, there is no way to broadcast on TCP - my idea is to have the phones initially 'connect' to the server app using a ServerSocket.  This will do nothing more than harvest client IP addresses which are to be stored in a Set<InetAddress> called clients.  Then I will want to iterate over these addresses and send the string to each phone individually - but I don't want to block the code, nor do I want to spend forever waiting for sends to occur if, say, the phone has gone to sleep and can't / won't accept connections.  The information will need to get to all phones within a few seconds of starting to send (even with 2-300 clients).

My initial code is below, and the questions I have regarding it are:

Is this code in one thread enough?

Would a modern CPU make good use of several threads with the address set split evenly amongst them (say 4 threads?)

Is it (as I believe) a bad idea to spin every connection/send off in its own thread?

Does setting the socket timeout allow the thread to work through its list faster? Or will this cause problems?

If socket timeout setting is a good idea, then what is a sensible time?  Or do I need to just test to get this right?

Thanks in advance for any help you guys can provide...

```<code>for (InetAddress client : clients) {
try {
    Socket sendQuestionSocket = new Socket(client, portSend);
    // Theory: 50 milliseconds is enough to connect, and could allow 200 clients
    // to get their questions in around 10 seconds.  Maybe?
    sendQuestionSocket.setSoTimeout(50);
    PrintWriter outStream = new PrintWriter(sendQuestionSocket.getOutputStream());
    outStream.println(question.toString());
    outStream.flush(); // Do I need this line?
    sendQuestionSocket.close();
    outStream.close();
} catch (InterruptedIOException e) {
    logger.log(Level.WARNING, "Couldn't connect in time... passing this one over");
    e.printStackTrace();
} catch (UnknownHostException e) {
    logger.log(Level.SEVERE, "Unable to find that client");
    e.printStackTrace();
} catch (IOException e) {
    logger.log(Level.SEVERE, "Unable to create question sending port");
    e.printStackTrace();
}
</code>```

}

答:
I'm not sure what you're trying to do will work.  ServerSocket is not there to allow you to gather remote IP addresses and just connect back when you want.  In order to connect back to those devices they would have to have a server listening on a particular port and accept your incoming connection.

Since it seems like you already have the clients connecting to your server socket i would just tell them whatever they need to know once they have connected - unless you really can have a server on each phone.

Another option would be to use (connectionless) UDP but the client code would still have to be actively waiting for datagram packets.

When doing anything Socket related in Java i highly recommend Netty.  Netty will handle all the asynchronous network IO for you and let you focus on what to do once the client has connected.

Body:
This is a bit of a "further down the track now" extension to a question I asked a while ago... I have a better understanding of sockets now, and have some working code but need to improve it...

Ok, so I have currently got UDP multicasting working to send short strings of text from a Java 'server' application to several Android phones (which will potentially become several hundred Android phones).  This works fine most of the time, but it does tend to lose the odd string on the odd phone, and randomly it will just go total loss for a short period and nothing will get through to any of them, which can be a little frustrating.

Since, as I understand, there is no way to broadcast on TCP - my idea is to have the phones initially 'connect' to the server app using a ServerSocket.  This will do nothing more than harvest client IP addresses which are to be stored in a Set<InetAddress> called clients.  Then I will want to iterate over these addresses and send the string to each phone individually - but I don't want to block the code, nor do I want to spend forever waiting for sends to occur if, say, the phone has gone to sleep and can't / won't accept connections.  The information will need to get to all phones within a few seconds of starting to send (even with 2-300 clients).

My initial code is below, and the questions I have regarding it are:

Is this code in one thread enough?

Would a modern CPU make good use of several threads with the address set split evenly amongst them (say 4 threads?)

Is it (as I believe) a bad idea to spin every connection/send off in its own thread?

Does setting the socket timeout allow the thread to work through its list faster? Or will this cause problems?

If socket timeout setting is a good idea, then what is a sensible time?  Or do I need to just test to get this right?

Thanks in advance for any help you guys can provide...

for (InetAddress client : clients) {
try {
    Socket sendQuestionSocket = new Socket(client, portSend);
    // Theory: 50 milliseconds is enough to connect, and could allow 200 clients
    // to get their questions in around 10 seconds.  Maybe?
    sendQuestionSocket.setSoTimeout(50);
    PrintWriter outStream = new PrintWriter(sendQuestionSocket.getOutputStream());
    outStream.println(question.toString());
    outStream.flush(); // Do I need this line?
    sendQuestionSocket.close();
    outStream.close();
} catch (InterruptedIOException e) {
    logger.log(Level.WARNING, "Couldn't connect in time... passing this one over");
    e.printStackTrace();
} catch (UnknownHostException e) {
    logger.log(Level.SEVERE, "Unable to find that client");
    e.printStackTrace();
} catch (IOException e) {
    logger.log(Level.SEVERE, "Unable to create question sending port");
    e.printStackTrace();
}

}


问:
Why can I not unpack two lists into a format string within a for loop?
I was trying to do a basic spinning animation using "\|/-" which went fine, but I wanted two on the same updating line. With one spinning clockwise and one spinning anti-clockwise.

Here is what I came up with:

```<code>animation_1 = ['\\', '|', '/', '-']
animation_2 = ['/', '|', '\\', '-']

while True:
    for iteration_1, iteration_2 in animation_1, animation_2:
        print(f'\r    {iteration_2}  {iteration_1}', end='')
        sleep(.5)
        sys.stdout.flush()
</code>```

Which get the output:

"Traceback (most recent call last):
  File "/Users/pungkrock/PycharmProjects/ans/fib.py", line 18, in <module>
    for iteration_1, iteration_2 in animation_1, animation_2:
ValueError: too many values to unpack (expected 2)"
```

<p>This example:</p>

```animation_1 = ['\\', '|', '/', '-']
animation_2 = ['/', '|', '\\', '-']

while True:
    for iteration_1, iteration_2 in animation_1:
        print(f'\r    {iteration_2}  {iteration_1}', end='')
        sleep(.5)
        sys.stdout.flush()
```

<p>Gets the output:</p>

<pre class="lang-none prettyprint-override"><code>"Traceback (most recent call last):
  File "/Users/pungkrock/PycharmProjects/ans/fib.py", line 18, in <module>
    for iteration_1, iteration_2 in animation_1:
ValueError: not enough values to unpack (expected 2, got 1)"
</code>```

And this error massage I do understand. But I don't understand why I get an error message from the first example.

This example works fine:

```<code>animation_1 = ['\\', '|', '/', '-']
# animation_2 = ['/', '|', '\\', '-']

while True:
    for iteration_1 in animation_1:
        print(f'\r      {iteration_1}', end='')
        sleep(.5)
        sys.stdout.flush()
</code>```

Can some kind soul explain to me way the first code example doesn't work? Or if I'm missing some basic understanding of some concept of the language?
"too many values to unpack (expected 2)", it did get 2? What am I missing?

答:
in animation_1, animation_2 is not valid syntax

I assume you want to zip them

```<code>for a1, a2 in zip(animation_1, animation_2)
</code>```

Body:
I was trying to do a basic spinning animation using "\|/-" which went fine, but I wanted two on the same updating line. With one spinning clockwise and one spinning anti-clockwise.

Here is what I came up with:

animation_1 = ['\\', '|', '/', '-']
animation_2 = ['/', '|', '\\', '-']

while True:
    for iteration_1, iteration_2 in animation_1, animation_2:
        print(f'\r    {iteration_2}  {iteration_1}', end='')
        sleep(.5)
        sys.stdout.flush()

Which get the output:

"Traceback (most recent call last):
  File "/Users/pungkrock/PycharmProjects/ans/fib.py", line 18, in <module>
    for iteration_1, iteration_2 in animation_1, animation_2:
ValueError: too many values to unpack (expected 2)"

This example:

animation_1 = ['\\', '|', '/', '-']
animation_2 = ['/', '|', '\\', '-']

while True:
    for iteration_1, iteration_2 in animation_1:
        print(f'\r    {iteration_2}  {iteration_1}', end='')
        sleep(.5)
        sys.stdout.flush()

Gets the output:

"Traceback (most recent call last):
  File "/Users/pungkrock/PycharmProjects/ans/fib.py", line 18, in <module>
    for iteration_1, iteration_2 in animation_1:
ValueError: not enough values to unpack (expected 2, got 1)"

And this error massage I do understand. But I don't understand why I get an error message from the first example.

This example works fine:

animation_1 = ['\\', '|', '/', '-']
# animation_2 = ['/', '|', '\\', '-']

while True:
    for iteration_1 in animation_1:
        print(f'\r      {iteration_1}', end='')
        sleep(.5)
        sys.stdout.flush()

Can some kind soul explain to me way the first code example doesn't work? Or if I'm missing some basic understanding of some concept of the language?
"too many values to unpack (expected 2)", it did get 2? What am I missing?

Body:
in animation_1, animation_2 is not valid syntax

I assume you want to zip them

for a1, a2 in zip(animation_1, animation_2)


问:
Pattern matching with Alternative empty or Applicative pure
I know it is possible, to pattern match against (named) constructors like so:

f1 :: Maybe a -> Bool
f1 Nothing = False
f1 (Just x) = True -- in reality have something that uses x here

f2 :: [a] -> Int
f2 [] = False
f2 x = True
```

<p>How can I write such a function for general <code>Alternative</code>s similar to</p>

<pre class="lang-hs prettyprint-override"><code>f :: (Alternative m) => m a -> Bool
f empty = False
f x = True
</code>```

If I try this, I get the error Parse error in pattern: empty. Which makes sense, I guess, as empty as a function here and not a constructor. But how can I accomplish this for general Alternatives idiomatically?

Edit 1:
My actual goal is to define a Monad instance (and probably also a MonadPlus instance) for a custom result type. Instead of the basic Either Error Result type, it should support a Maybe Error (and if possible also other Alternatives like [Error]) as error type and also some Applicative as result type in order to support lazy evaluation, for example with the result type (Maybe Error, [Tokens]) of a tokenizer.

I'd like something similar to

instance (Alterantive mErr, Applicative mRes) => Monad (mErr e, mRes a) where
  return x = (empty, pure x)
  (empty, pure x) >>= f = f x
  (err, x) >>= f = (err, x)
```

答:
It is in fact possible using -XPatternSynonyms and -XViewPatterns:

```<code>{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
import Control.Applicative (empty)

pattern Empty :: (Eq (m a), Alternative m) => m a
pattern Empty <- ((==) empty -> True)

f :: (Eq (m a), Alternative m) => m a -> Bool
f Empty = False
f _ = True
</code>```

Body:
I know it is possible, to pattern match against (named) constructors like so:

f1 :: Maybe a -> Bool
f1 Nothing = False
f1 (Just x) = True -- in reality have something that uses x here

f2 :: [a] -> Int
f2 [] = False
f2 x = True

How can I write such a function for general Alternatives similar to

f :: (Alternative m) => m a -> Bool
f empty = False
f x = True

If I try this, I get the error Parse error in pattern: empty. Which makes sense, I guess, as empty as a function here and not a constructor. But how can I accomplish this for general Alternatives idiomatically?

Edit 1:
My actual goal is to define a Monad instance (and probably also a MonadPlus instance) for a custom result type. Instead of the basic Either Error Result type, it should support a Maybe Error (and if possible also other Alternatives like [Error]) as error type and also some Applicative as result type in order to support lazy evaluation, for example with the result type (Maybe Error, [Tokens]) of a tokenizer.

I'd like something similar to

instance (Alterantive mErr, Applicative mRes) => Monad (mErr e, mRes a) where
  return x = (empty, pure x)
  (empty, pure x) >>= f = f x
  (err, x) >>= f = (err, x)

Body:
It is in fact possible using -XPatternSynonyms and -XViewPatterns:

{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
import Control.Applicative (empty)

pattern Empty :: (Eq (m a), Alternative m) => m a
pattern Empty <- ((==) empty -> True)

f :: (Eq (m a), Alternative m) => m a -> Bool
f Empty = False
f _ = True


问:
Move in doubly linked list Ramda.js
When I started using a doubly linked list, it became more difficult to manage prev_id & next_id.

```<code>const dll = [
  {id: '14', prev_id: null, next_id: '41'}, // <- source
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null}, // <- destination
]
</code>```

For example, I want to move object 14 to the end, so the array should become:

```<code>const dll_result = [
  {id: '41', prev_id: null, next_id: '22'},
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: '14'},
  {id: '14', prev_id: '45', next_id: null},
]
</code>```

The hardest thing what I need to do to change the prev_id & next_id of the objects?

My attempt:

.as-console-wrapper { max-height: 100% !important; top: 0; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" charset="utf8" src="//cdn.jsdelivr.net/npm/ramda@0.27.0/dist/ramda.min.js"></script>
<script>
  const {move} = R

  const dll = [
    {id: '14', prev_id: null, next_id: '41'}, //<- source
    {id: '41', prev_id: '14', next_id: '22'}, //<- destination
    {id: '22', prev_id: '41', next_id: '45'},
    {id: '45', prev_id: '22', next_id: null},
  ]

  const fromId = '14'
  const toId = '41'

  const fromItem = dll.find(item => item.id === fromId)
  const toItem = dll.find(item => item.id === toId)

  const updated = dll.map(item => {
    if (item.id === fromId) {
      return {...item, prev_id: toId, next_id: toItem.next_id}
    } else if (item.prev_id === fromId) {
      return {...item, prev_id: fromItem.prev_id}
    } else if (item.id === toItem.next_id) {
      return {...item, prev_id: fromId}
    } else if (item.id === toId) {
      return {...item, next_id: fromId}
    } else {
      return item
    }
  })

  console.log(JSON.stringify(move(0, 1, updated), null, 2))
</script></code>```

答:
As I mentioned in my comments, I find that this is an unlikely data structure, gaining none of the benefits of a true doubly linked list.  Also in the comments I asked about before versus after when inserting or moving an item.  This version assumes that what was meant was to move after the given node, noting where we might also want before versions of the functions.

Fair warning, it is ugly imperative code, mutating data structures willy-nilly inside its functions.  (Although not, of course at the function boundaries; I'm not a barbarian!)

You said in a comment that you already had insert and delete functions.  If so, you might be able to write a simple version of move the way I do here, simply inserting an altered copy of the removed node after the target one.

I do not try to place the inserted node in any particular place in the array; I assume from the data structure that just placing it at the end is not an issue.  If it is, we'd have to start mucking about with indices too.  That's not hard, but it's ugly.

This code has no error checking, leaving that as an exercise for the reader.  If you use an id that's not in the list, we're not responsible for what happens.  It might divide by zero, launch the missiles, or steal your boyfriend.  You've been warned.

// or Ramda's `clone`, or whatever
const clone = (o) => JSON .parse (JSON .stringify (o))

const removeNode = (dll, id) => {
  const list = clone (dll)
  const byId  = (i) => list .find (({id}) => id === i)
  const node = byId (id)
  const prevNode = node .prev_id ? byId (node .prev_id) : null
  const nextNode = node .next_id ? byId (node .next_id) : null
  if (prevNode) prevNode .next_id = node .next_id
  if (nextNode) nextNode .prev_id = node .prev_id
  return list.filter(node => node .id !== id)
}

const insertAfter = (dll, id, item) => {
  const list = clone (dll)
  const byId  = (i) => list .find (({id}) => id === i)
  const node = byId (id)
  const nextNode = node .next_id ? byId (node .next_id) : null
  node .next_id = item .id
  if (nextNode) nextNode .prev_id = item .id
  return [...list, {
    ...item,
    prev_id: node .id,
    next_id: nextNode ? nextNode .id : null
  }]
}

const moveAfter = (dll, fromId, afterId) => {
  const node = dll .find (({id}) => id == fromId)
  return insertAfter (removeNode (dll, fromId), afterId, node)
}

// and insertBefore, moveBefore

const dll = [
  {id: '14', prev_id: null, next_id: '41'},
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null},
]

console.log (
  moveAfter (dll, '14', '41')
)```

Title: Move in doubly linked list Ramda.js

Body:
When I started using a doubly linked list, it became more difficult to manage prev_id & next_id.

const dll = [
  {id: '14', prev_id: null, next_id: '41'}, // <- source
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null}, // <- destination
]

For example, I want to move object 14 to the end, so the array should become:

const dll_result = [
  {id: '41', prev_id: null, next_id: '22'},
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: '14'},
  {id: '14', prev_id: '45', next_id: null},
]

The hardest thing what I need to do to change the prev_id & next_id of the objects?

My attempt:

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Unable to configure WCF service to be consumed by silverlight client
I am trying hard to develop a duplex wcf service to be consumed by silverlight clients. Now for adventure sake, I decided to use nettcpbinding. I understand that the concept of PolicyServer to be running on port 943 is obselete now and it should be served from root of the service.

given Below is config section for the service

```<code>  <behaviors>
    <serviceBehaviors>
      <behavior name="WcfServer.WcfServiceBehavior">
        <serviceMetadata httpGetEnabled="true" />
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="CrossDomainServiceBehavior">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <services>
    <service behaviorConfiguration="WcfServer.WcfServiceBehavior"
      name="WcfServer.MainService">
      <endpoint address="" binding="netTcpBinding" bindingConfiguration="TCPBinding" contract="WCFWebFrontCommunication.IMainService">

      </endpoint>
      <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" />
      <endpoint address="" binding="webHttpBinding" behaviorConfiguration="CrossDomainServiceBehavior" contract="WCFWebFrontCommunication.IClientAccessPolicy" />

      <host>
        <baseAddresses>
          <!--<add baseAddress= "http://192.168.0.101:943/WcfServer/MainService" />-->
          <!--<add baseAddress= "http://localhost:943/WcfServer/MainService" />-->
          <add baseAddress= "net.tcp://localhost:4502/WcfServer/MainService" />
          <add baseAddress="http://localhost:4502"/>
        </baseAddresses>
      </host>
    </service>

  </services>
</system.serviceModel>
</code>```

now at runtime I get an exception HTTP could not register URL http://+:4502/ because TCP port 4502 is being used by another application. when Open Method is called.

Am I doing something silly here .., although http exception was there with basicHttpBinding as well

As Troubleshooting:
 checked for open port using Netstat -aon
There were some post regarding HTTP configuration followed them nothing happened

Thanks for reading.

答:
You're trying to host a clientaccesspolicy.xml file over HTTP, and use net.tcp on the same port number, that's not going to work. While both of these protocols build on TCP/IP, they are incompatible.

As far as I understand (see also this article), port 943 is still used for this type of thing.

Body:
I am trying hard to develop a duplex wcf service to be consumed by silverlight clients. Now for adventure sake, I decided to use nettcpbinding. I understand that the concept of PolicyServer to be running on port 943 is obselete now and it should be served from root of the service.

given Below is config section for the service

  <behaviors>
    <serviceBehaviors>
      <behavior name="WcfServer.WcfServiceBehavior">
        <serviceMetadata httpGetEnabled="true" />
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="CrossDomainServiceBehavior">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <services>
    <service behaviorConfiguration="WcfServer.WcfServiceBehavior"
      name="WcfServer.MainService">
      <endpoint address="" binding="netTcpBinding" bindingConfiguration="TCPBinding" contract="WCFWebFrontCommunication.IMainService">

      </endpoint>
      <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" />
      <endpoint address="" binding="webHttpBinding" behaviorConfiguration="CrossDomainServiceBehavior" contract="WCFWebFrontCommunication.IClientAccessPolicy" />

      <host>
        <baseAddresses>

          <add baseAddress= "net.tcp://localhost:4502/WcfServer/MainService" />
          <add baseAddress="http://localhost:4502"/>
        </baseAddresses>
      </host>
    </service>

  </services>
</system.serviceModel>

now at runtime I get an exception HTTP could not register URL http://+:4502/ because TCP port 4502 is being used by another application. when Open Method is called.

Am I doing something silly here .., although http exception was there with basicHttpBinding as well

As Troubleshooting:
 checked for open port using Netstat -aon
There were some post regarding HTTP configuration followed them nothing happened

Thanks for reading.