问:
How to auto increment counter by repeteaded values in a column
I Have a data frame with the column name and I need to create the column seq, which allows me identify the different times that a name appears in the data frame, it's important to preserve the order.

```<code>import pandas as pd

data = {'name': ['Tom', 'Joseph','Joseph','Joseph', 'Tom', 'Tom', 'John','Tom','Tom','John','Joseph']
        , 'seq': ['Tom 0', 'Joseph 0','Joseph 0','Joseph 0', 'Tom 1', 'Tom 1', 'John 0','Tom 2','Tom 2','John 1','Joseph 1']}

df = pd.DataFrame(data)

print(df)

</code>```
```<code>      name       seq
0      Tom     Tom 0
1   Joseph  Joseph 0
2   Joseph  Joseph 0
3   Joseph  Joseph 0
4      Tom     Tom 1
5      Tom     Tom 1
6     John    John 0
7      Tom     Tom 2
8      Tom     Tom 2
9     John    John 1
10  Joseph  Joseph 1
</code>```

答:
You need check for the existence of a new name and then create a new index for each name using groupby and cumsum, the resulting string Series can be concatenated with str.cat</p>
```<code>df['seq'] = df['name'].str.cat(
    df['name'].ne(df['name'].shift()).groupby(df['name']).cumsum().sub(1).astype(str),
    sep=' '
)
</code>```

Body:
I Have a data frame with the column name and I need to create the column seq, which allows me identify the different times that a name appears in the data frame, it's important to preserve the order.

import pandas as pd

data = {'name': ['Tom', 'Joseph','Joseph','Joseph', 'Tom', 'Tom', 'John','Tom','Tom','John','Joseph']
        , 'seq': ['Tom 0', 'Joseph 0','Joseph 0','Joseph 0', 'Tom 1', 'Tom 1', 'John 0','Tom 2','Tom 2','John 1','Joseph 1']}

df = pd.DataFrame(data)

print(df)

      name       seq
0      Tom     Tom 0
1   Joseph  Joseph 0
2   Joseph  Joseph 0
3   Joseph  Joseph 0
4      Tom     Tom 1
5      Tom     Tom 1
6     John    John 0
7      Tom     Tom 2
8      Tom     Tom 2
9     John    John 1
10  Joseph  Joseph 1

Body:
You need check for the existence of a new name and then create a new index for each name using groupby and cumsum, the resulting string Series can be concatenated with str.cat

df['seq'] = df['name'].str.cat(
    df['name'].ne(df['name'].shift()).groupby(df['name']).cumsum().sub(1).astype(str),
    sep=' '
)


来源: stackexchange

问:
Problem getting output of sp_executesql into a table column (SQL SERVER)
I have a table called QUERY_TABLE.
QUERY_TABLE contains queries of the following format (nothing dynamic, except the parameters in the WHERE clause):

```<code>  SELECT
     CASE
         WHEN COUNT(*) > 10 THEN 'Y'
         ELSE 'N'
     END check_ind
FROM
     DATA_TABLE
WHERE date_y = @DATE_Y AND date_m = @DATE_M
</code>```

I wrote the following script, to fetch each one of the above queries, run it, and put the result into another table - CONTROL_LOG_TABLE.

My problem is that the result column, STATUS_IND, should get either 'Y' or 'N' as values, but for some reason I have not figured out yet, it contains '0'.

Appreciate your help!

```<code>DECLARE
       @DATE_C DATE,
       @DATE_Y           INTEGER,
       @DATE_M           INTEGER,
       @CHECK_NUM        INTEGER,
       @CHECK_ID         INTEGER,
       @CTRLM_TREE       VARCHAR(50),
       @CTRLM_TREE_PARAM VARCHAR(50),
       @SQL_QUERY        NVARCHAR(MAX),
       @CHECK_DESC       NVARCHAR(MAX),
       @ACTION_DESC      NVARCHAR(MAX),
       @EXEC_SQL_QUERY   NVARCHAR(MAX),
       @RESULT_SQL       CHAR(1),
       @RowNo            INTEGER,
          @params NVARCHAR(100) = '@DATE_Y NVARCHAR(4), @DATE_M NVARCHAR(2)';

BEGIN

SET @RowNo = 0;
SET @DATE_C = GETDATE();
SET @DATE_Y = (SELECT YEAR (@DATE_C));
SET @DATE_M = (SELECT MONTH (@DATE_C));

DECLARE CURSOR_CHECK_ID CURSOR
FOR SELECT
       CHECK_ID,
       CTRLM_TREE,
       SQL_QUERY,
       CHECK_DESC,
       ACTION_DESC
    FROM
       QUERY_TABLE

OPEN CURSOR_CHECK_ID;
FETCH NEXT FROM CURSOR_CHECK_ID INTO
            @CHECK_ID,
            @CTRLM_TREE,
            @SQL_QUERY,
            @CHECK_DESC,
            @ACTION_DESC;
       WHILE @@FETCH_STATUS = 0
    BEGIN
           SET @RowNo = @RowNo+1
           SET @CHECK_NUM = @RowNo
           SET @EXEC_SQL_QUERY = @SQL_QUERY

                       EXECUTE @result_sql = sp_executesql @EXEC_SQL_QUERY, @params, @DATE_Y, @DATE_M

        INSERT INTO CONTROL_LOG_TABLE (UPDATE_DATE, DATE_C, CHECK_NUM, CHECK_ID, CTRLM_TREE, SQL_QUERY,
              CHECK_DESC, ACTION_DESC, STATUS_IND)
              values (GETDATE(), @DATE_C, @RowNo, @CHECK_ID, @CTRLM_TREE, @SQL_QUERY, @CHECK_DESC, @ACTION_DESC, @RESULT_SQL)

        FETCH NEXT FROM CURSOR_CHECK_ID INTO
            @CHECK_ID,
            @CTRLM_TREE,
            @SQL_QUERY,
            @CHECK_DESC,
            @ACTION_DESC;
    END;
CLOSE CURSOR_CHECK_ID;
DEALLOCATE CURSOR_CHECK_ID;
END;
</code>```

答:
To capture a resultset from a dynamic batch use INSERT...EXECUTE to load a temp table or table variable.  EG</p>
```<code>    declare @r table (check_ind char(1))

    insert into @r(check_ind)
    EXECUTE sp_executesql @EXEC_SQL_QUERY, @params, @DATE_Y, @DATE_M

    INSERT INTO CONTROL_LOG_TABLE (UPDATE_DATE, DATE_C, CHECK_NUM, CHECK_ID, CTRLM_TREE, SQL_QUERY,
          CHECK_DESC, ACTION_DESC, STATUS_IND)
          values (GETDATE(), @DATE_C, @RowNo, @CHECK_ID, @CTRLM_TREE, @SQL_QUERY, @CHECK_DESC, @ACTION_DESC, (select check_ind from @r) )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a table called QUERY_TABLE.
QUERY_TABLE contains queries of the following format (nothing dynamic, except the parameters in the WHERE clause):

  SELECT
     CASE
         WHEN COUNT(*) > 10 THEN 'Y'
         ELSE 'N'
     END check_ind
FROM
     DATA_TABLE
WHERE date_y = @DATE_Y AND date_m = @DATE_M

I wrote the following script, to fetch each one of the above queries, run it, and put the result into another table - CONTROL_LOG_TABLE.

My problem is that the result column, STATUS_IND, should get either 'Y' or 'N' as values, but for some reason I have not figured out yet, it contains '0'.

Appreciate your help!

DECLARE
       @DATE_C DATE,
       @DATE_Y           INTEGER,
       @DATE_M           INTEGER,
       @CHECK_NUM        INTEGER,
       @CHECK_ID         INTEGER,
       @CTRLM_TREE       VARCHAR(50),
       @CTRLM_TREE_PARAM VARCHAR(50),
       @SQL_QUERY        NVARCHAR(MAX),
       @CHECK_DESC       NVARCHAR(MAX),
       @ACTION_DESC      NVARCHAR(MAX),
       @EXEC_SQL_QUERY   NVARCHAR(MAX),
       @RESULT_SQL       CHAR(1),
       @RowNo            INTEGER,
          @params NVARCHAR(100) = '@DATE_Y NVARCHAR(4), @DATE_M NVARCHAR(2)';

BEGIN

SET @RowNo = 0;
SET @DATE_C = GETDATE();
SET @DATE_Y = (SELECT YEAR (@DATE_C));
SET @DATE_M = (SELECT MONTH (@DATE_C));

DECLARE CURSOR_CHECK_ID CURSOR
FOR SELECT
       CHECK_ID,
       CTRLM_TREE,
       SQL_QUERY,
       CHECK_DESC,
       ACTION_DESC
    FROM
       QUERY_TABLE

OPEN CURSOR_CHECK_ID;
FETCH NEXT FROM CURSOR_CHECK_ID INTO
            @CHECK_ID,
            @CTRLM_TREE,
            @SQL_QUERY,
            @CHECK_DESC,
            @ACTION_DESC;
       WHILE @@FETCH_STATUS = 0
    BEGIN
           SET @RowNo = @RowNo+1
           SET @CHECK_NUM = @RowNo
           SET @EXEC_SQL_QUERY = @SQL_QUERY

                       EXECUTE @result_sql = sp_executesql @EXEC_SQL_QUERY, @params, @DATE_Y, @DATE_M

        INSERT INTO CONTROL_LOG_TABLE (UPDATE_DATE, DATE_C, CHECK_NUM, CHECK_ID, CTRLM_TREE, SQL_QUERY,
              CHECK_DESC, ACTION_DESC, STATUS_IND)
              values (GETDATE(), @DATE_C, @RowNo, @CHECK_ID, @CTRLM_TREE, @SQL_QUERY, @CHECK_DESC, @ACTION_DESC, @RESULT_SQL)

        FETCH NEXT FROM CURSOR_CHECK_ID INTO
            @CHECK_ID,
            @CTRLM_TREE,
            @SQL_QUERY,
            @CHECK_DESC,
            @ACTION_DESC;
    END;
CLOSE CURSOR_CHECK_ID;
DEALLOCATE CURSOR_CHECK_ID;
END;

Body:
To capture a resultset from a dynamic batch use INSERT...EXECUTE to load a temp table or table variable.  EG

    declare @r table (check_ind char(1))

    insert into @r(check_ind)
    EXECUTE sp_executesql @EXEC_SQL_QUERY, @params, @DATE_Y, @DATE_M

    INSERT INTO CONTROL_LOG_TABLE (UPDATE_DATE, DATE_C, CHECK_NUM, CHECK_ID, CTRLM_TREE, SQL_QUERY,
          CHECK_DESC, ACTION_DESC, STATUS_IND)
          values (GETDATE(), @DATE_C, @RowNo, @CHECK_ID, @CTRLM_TREE, @SQL_QUERY, @CHECK_DESC, @ACTION_DESC, (select check_ind from @r) )


问:
Flutter- How to have differing Text Styles in List
I have a list that is populated with the return data of various var's

This list also has a text element preceding the data

I want to have separate weight, size etc for the initial text and then the String being passed in

I have tried RichText  and TextStyle but needed a text function, not a list for it to work correctly

Here is the List which is then passed into a function which pushes it to ShowDialog

For example, Line: to be FontWeight.w600 & $pln String to be FontWeight.w400

```<code>List data = [
    "Line: $pln",
    "Departed from: $originname",
    "Destination: $destname",
    "Last seen: $recordedattime",
    ];
</code>```

ShowDialog, where message is the list from previous function

```<code>title: Text(title),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text(message,
                style: TextStyle(
              fontSize: 18,
              color: Color(0xff2F2F2F),
              fontWeight: FontWeight.w500,
              ...
</code>```

答:
Try creating a new widget for it, this way you can modify the build however you desire easily.

class NewTextWidget extends StatelessWidget {
  final String prefix;
  final String value;

  NewTextWidget({required String message, Key? key})
      : prefix = message.split(": ")[0],
        value = message.split(": ")[1],
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return RichText(
      text: TextSpan(
          text: prefix,
          style: const TextStyle(fontWeight: FontWeight.w600),
          children: [
            TextSpan(
                text: value,
                style: const TextStyle(fontWeight: FontWeight.w400))
          ]),
    );
  }
}
```
<p>The <strong>NewTextWidget</strong> expects the message with the <em><strong>prefix: value</strong></em> format.</p>
<p>So when you call it you need to update your ListBody as:</p>
<pre class="lang-dart prettyprint-override"><code>ListBody(
  children: data.map((String message) => NewTextWidget(message: message)).toList()
)
</code>```

Body:
I have a list that is populated with the return data of various var's

This list also has a text element preceding the data

I want to have separate weight, size etc for the initial text and then the String being passed in

I have tried RichText  and TextStyle but needed a text function, not a list for it to work correctly

Here is the List which is then passed into a function which pushes it to ShowDialog

For example, Line: to be FontWeight.w600 & $pln String to be FontWeight.w400

List data = [
    "Line: $pln",
    "Departed from: $originname",
    "Destination: $destname",
    "Last seen: $recordedattime",
    ];

ShowDialog, where message is the list from previous function

title: Text(title),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text(message,
                style: TextStyle(
              fontSize: 18,
              color: Color(0xff2F2F2F),
              fontWeight: FontWeight.w500,
              ...

Body:
Try creating a new widget for it, this way you can modify the build however you desire easily.

class NewTextWidget extends StatelessWidget {
  final String prefix;
  final String value;

  NewTextWidget({required String message, Key? key})
      : prefix = message.split(": ")[0],
        value = message.split(": ")[1],
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return RichText(
      text: TextSpan(
          text: prefix,
          style: const TextStyle(fontWeight: FontWeight.w600),
          children: [
            TextSpan(
                text: value,
                style: const TextStyle(fontWeight: FontWeight.w400))
          ]),
    );
  }
}

The NewTextWidget expects the message with the prefix: value format.

So when you call it you need to update your ListBody as:

ListBody(
  children: data.map((String message) => NewTextWidget(message: message)).toList()
)


问:
change the time interval in spring app using the code
I have a spring boot applicate that is using many types of date objects it
like:

java.util.Date

java.time.LocalDate

java.time.Instant

I have a sandbox environment, I want to do some tests on it,
but in tests, I need time to be changed by shifting the current_time by one year, in other words, I want to interval the time by 1 year.

example:
let's suppose the date now is 7/feb/2022
if I called any date function, I need it to return 7/feb/2023,

I want to change the date just in the spring app, I don't want to change the whole server time.

Is this doable in spring app for any of the previous date objects?

update:
I am using code like this in all my app

```<code>LocalDate localDate = LocalDate.now();
Date date = new Date()
</code>```

I don't want to change the code in all my app (line by line)

I am looking at changing the date by adding some configurations, not by changing the existing code.

答:
For java.time classes, you can pass an optional Clock argument. The Clock class offers several static method returning alerted clock behavior. One of those supports a fixed moment, that does not increment.

Set up your altered clock.

```<code>ZoneId zoneId = ZoneId.of( "Africa/Tunis" ) ;
LocalDate aYearFromToday = LocalDate.now( zoneId ).plusYears( 1 ) ;
ZonedDateTime zdt = aYearFromToday.atStartOfDay( zoneId ) ;
Instant instant = zdt.toInstant() ;
Clock fixedClock = Clock.fixed( instant , zoneId ) ;
</code>```

Usage.

```<code>Instant nowFake = Instant.now( fixedClock ) ;
LocalDate todayFake = LocalDate.now( fixedClock ) ;
</code>```

Body:
I have a spring boot applicate that is using many types of date objects it
like:

java.util.Date

java.time.LocalDate

java.time.Instant

I have a sandbox environment, I want to do some tests on it,
but in tests, I need time to be changed by shifting the current_time by one year, in other words, I want to interval the time by 1 year.

example:
let's suppose the date now is 7/feb/2022
if I called any date function, I need it to return 7/feb/2023,

I want to change the date just in the spring app, I don't want to change the whole server time.

Is this doable in spring app for any of the previous date objects?

update:
I am using code like this in all my app

LocalDate localDate = LocalDate.now();
Date date = new Date()

I don't want to change the code in all my app (line by line)

I am looking at changing the date by adding some configurations, not by changing the existing code.

Body:
For java.time classes, you can pass an optional Clock argument. The Clock class offers several static method returning alerted clock behavior. One of those supports a fixed moment, that does not increment.

Set up your altered clock.

ZoneId zoneId = ZoneId.of( "Africa/Tunis" ) ;
LocalDate aYearFromToday = LocalDate.now( zoneId ).plusYears( 1 ) ;
ZonedDateTime zdt = aYearFromToday.atStartOfDay( zoneId ) ;
Instant instant = zdt.toInstant() ;
Clock fixedClock = Clock.fixed( instant , zoneId ) ;

Usage.

Instant nowFake = Instant.now( fixedClock ) ;
LocalDate todayFake = LocalDate.now( fixedClock ) ;


问:
Why does a button not fire when clicked through cypress in a nuxt web app?
I have a button component in a Nuxt.js web app. The button component emits a click event when it is clicked. I use that button component on a Nuxt page and provide a page method as an event handler. When I click that button manually, the event is triggered and the application flow continues as expected. This is my code:

<MyButton id="button" @click="openModal()">
  {{ $t('open') }}
</MyButton>
```
<p>However, when I click the same button using Cypress, nothing happens at all and the event handler is not called:</p>
<pre class="lang-js prettyprint-override"><code>cy.get('#button').click()
</code>```

After the test fails, I can press the button (in Cypress) manually and it will work. This led my to this blog post suggesting a race condition: https://www.cypress.io/blog/2019/01/22/when-can-the-test-click/

答:
The blog post is indeed correct, this is a race condition. The button gets rendered server-side and sent to the browser. Cypress waits for the page to load but it doesn't know to also wait for the hydration. So the event handler is attached by some client-side code. Cypress is too fast here and clicks the button before the event handler is attached. That's also why it always works manually. Additionally, the click() method of cypress will not be retried automatically so the test will just fail.

So basically, we'd want to wait on some signal from Nuxt that it is done hydrating. Unfortunately, I didn't find an API to do that. The best solution I came up with is adding a class to your layout to signal readiness and wait for that in Cypress:

<template>

    <nuxt />

</template>

```
<p>Then in <code>cypress/support/commands.ts</code> you can add a custom command to wait for the <code>hydrated</code> class:</p>
<pre class="lang-js prettyprint-override"><code>
Cypress.Commands.add('waitForHydration', (timeout: number = 20_000) => {
  cy.log('Waiting for hydration ...')
  cy.get('.default-layout.hydrated', { log: false, timeout })
})
</code>```

If you're using typescript, add the typings in cypress/support/index.d.ts:

/// <reference types="cypress" />

declare namespace Cypress {
  interface Chainable {
    waitForHydration(timeout?: number): Chainable<void>
  }
}
```
<p>And finally, in your test suite, use it like this:</p>
<pre class="lang-js prettyprint-override"><code>it('can click the button', () => {
  cy.visit('/')
  cy.waitForHydration()
  cy.get('#button').click()
})
</code>```

Body:
I have a button component in a Nuxt.js web app. The button component emits a click event when it is clicked. I use that button component on a Nuxt page and provide a page method as an event handler. When I click that button manually, the event is triggered and the application flow continues as expected. This is my code:

<MyButton id="button" @click="openModal()">
  {{ $t('open') }}
</MyButton>

However, when I click the same button using Cypress, nothing happens at all and the event handler is not called:

cy.get('#button').click()

After the test fails, I can press the button (in Cypress) manually and it will work. This led my to this blog post suggesting a race condition: https://www.cypress.io/blog/2019/01/22/when-can-the-test-click/

Body:
The blog post is indeed correct, this is a race condition. The button gets rendered server-side and sent to the browser. Cypress waits for the page to load but it doesn't know to also wait for the hydration. So the event handler is attached by some client-side code. Cypress is too fast here and clicks the button before the event handler is attached. That's also why it always works manually. Additionally, the click() method of cypress will not be retried automatically so the test will just fail.

So basically, we'd want to wait on some signal from Nuxt that it is done hydrating. Unfortunately, I didn't find an API to do that. The best solution I came up with is adding a class to your layout to signal readiness and wait for that in Cypress:

<template>
  <div :class="['default-layout', hydrated ? 'hydrated' : 'hydrating']">
    <nuxt />
  </div>
</template>

<script>
export default {
  name: 'DefaultLayout',
  data () {
    return {
      hydrated: false,
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.hydrated = true
    })
  }
}
</script>

Then in cypress/support/commands.ts you can add a custom command to wait for the hydrated class:

Cypress.Commands.add('waitForHydration', (timeout: number = 20_000) => {
  cy.log('Waiting for hydration ...')
  cy.get('.default-layout.hydrated', { log: false, timeout })
})

If you're using typescript, add the typings in cypress/support/index.d.ts:

/// <reference types="cypress" />

declare namespace Cypress {
  interface Chainable {
    waitForHydration(timeout?: number): Chainable<void>
  }
}

And finally, in your test suite, use it like this:

it('can click the button', () => {
  cy.visit('/')
  cy.waitForHydration()
  cy.get('#button').click()
})


问:
How to atomically delete keys matching a pattern using Redis
In my Redis DB I have a number of prefix:<numeric_id> hashes.

Sometimes I want to purge them all atomically. How do I do this without using some distributed locking mechanism?

答:
this is the easiest way that comes to mind without using any xargs magic

pure bash!

redis-cli DEL $(redis-cli KEYS *pattern*)
```

ContentLicense: CC BY-SA 3.0


问:
Open specific URL from Outlook with Chrome
Our company use IE as the default browser, but certain application we are working with require chrome. since we can't abandon IE, we need to open specific \ certain links with chrome, only with outlook.
I tried the following vba, which works great, but open automaticlly.

```<code>Sub LaunchURL(itm As MailItem)

Dim bodyString As String
Dim bodyStringSplitLine
Dim bodyStringSplitWord
Dim splitLine
Dim splitWord

bodyString = itm.Body
bodyStringSplitLine = Split(bodyString, vbCrLf)

For Each splitLine In bodyStringSplitLine
    bodyStringSplitWord = Split(splitLine, " ")

    For Each splitWord In bodyStringSplitWord
        If Left(splitWord, 7) = "http://" Then
            Shell ("C:\Program Files\Google\Chrome\Application\chrome.exe" & " " & splitWord)
        End If
    Next

Next

Set itm = Nothing

End Sub

Private Sub test()
    Dim currItem As MailItem
    Set currItem = ActiveInspector.CurrentItem
    LaunchURL currItem
End Sub
</code>```

Is there any way to make this script work when the users clicks the url and not automaticlly ? or therefore any way to make this work when the users read the message (so he can unread and when read it will open when he needs to) ?

Sorry in advance for my bad english.

答:
If the code runs automatically you probably have it in a rule.

To run code manually from a button when the item is open:

Change LaunchURL to standalone code.

-Drop (itm As MailItem)

-Add ActiveInspector.CurrentItem lines from Private Sub test()

or

Remove Private from Private Sub test()

Body:
Our company use IE as the default browser, but certain application we are working with require chrome. since we can't abandon IE, we need to open specific \ certain links with chrome, only with outlook.
I tried the following vba, which works great, but open automaticlly.

Sub LaunchURL(itm As MailItem)

Dim bodyString As String
Dim bodyStringSplitLine
Dim bodyStringSplitWord
Dim splitLine
Dim splitWord

bodyString = itm.Body
bodyStringSplitLine = Split(bodyString, vbCrLf)

For Each splitLine In bodyStringSplitLine
    bodyStringSplitWord = Split(splitLine, " ")

    For Each splitWord In bodyStringSplitWord
        If Left(splitWord, 7) = "http://" Then
            Shell ("C:\Program Files\Google\Chrome\Application\chrome.exe" & " " & splitWord)
        End If
    Next

Next

Set itm = Nothing

End Sub

Private Sub test()
    Dim currItem As MailItem
    Set currItem = ActiveInspector.CurrentItem
    LaunchURL currItem
End Sub

Is there any way to make this script work when the users clicks the url and not automaticlly ? or therefore any way to make this work when the users read the message (so he can unread and when read it will open when he needs to) ?

Sorry in advance for my bad english.


问:
How to keep the Lived documents in MongoDB as per the TTL index?
I know that the TTL index in MongoDB set a time to live for its documents. When they live for the specified time then those documents gets deleted. So what if I want to archive those documents without losing them. is there any way to do it?
I am sorry If I asked it in the wrong place.</p>

答: At the start you have a document with "column" (timestamp) that is in the TTL index. To prevent its deletion, you can move that timestamp to the future, or remove that "column" from the document.</p>


问:
R : y[x] & x[y] when x,y vectors
Silly question but for real i cant undestand what is happening here (Screenshot) ,especially in x[y]. In y[x] i undestand that he is getting the similar objects for x & y. But in x[y] he is getting objects that y is not having

答:
x[y] is looking for the y'th index in x. Essentially it is looking for elements 1,2,3,4,5,6,7 in x, which correspond to the first 7 elements in x. Hence x[y] just returns the contents of x.

y[x] is looking for the x'th index in y - that is the 2nd, 4th, 6th, 8th etc up to 14th indexes. But since y is only 7 elements long, everything after that just returns NA, because there is no 8th index in y, and so on.

Title: R : y[x] & x[y] when x,y vectors


问:
Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "<local2>" is null
i have this Main code

```<code>    public static void main(String[] args)
    {
        //display Gui
        DisplayGUI();
        //input Person
        InputPerson();
        //display input data
        Display();
        //sort person
        //SortbySalary();
        //display sorted person
        //Display();

    }

    private static void DisplayGUI() {
        System.out.println("=====Management person Programmer=====");
    }

    private static void InputPerson() {
        //array of person
        Person persons[] = new Person[3];
        //constructor
        Person person = new Person();

        for(int i = 0; i<3; i++){
            persons[i] = person.InputPersonInfo(person.getName(),person.getAddress(),person.getSalary());
        }

        for (Person p: persons){
            person.DisplayPersonInfo(p);
            System.out.println();
        }
    }

    public static void Display() {
        Person person = new Person();
        Person persons[] = null;
                for (Person p: persons){
            person.DisplayPersonInfo(p);
            System.out.println();
        }
    }
}
</code>```

this is my person class

```<code>class Person {
    private String name;
    private String address;
    private double salary;

    public Person() {
    }

    public Person(String name, String address, double salary) {
        this.name = name;
        this.address = address;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public Person InputPersonInfo(String name, String address, double salary){
        Scanner sc = new Scanner(System.in);
        System.out.println("Input Information of person:");
        System.out.println("Please input name:");
        name = sc.nextLine();
        System.out.println("Please input Address)");
        address = sc.nextLine();
        System.out.println("Please input salary:");
        salary = sc.nextDouble();

        return new Person(name,address,salary);

    }
    public void DisplayPersonInfo(Person persons){
        System.out.println("Information of Person you entered");
        System.out.println("Name:" + persons.getName());
        System.out.println("address:" + persons.getAddress());
        System.out.println("slary:" + persons.getSalary());
    }
</code>```

i dont understand when i push this code in the InputPerson() class, it will display the information of person i entered

```<code>        for (Person p: persons){
            person.DisplayPersonInfo(p);
            System.out.println();
        }
</code>```

but when i try to do this in Display() class it keep telling error "Cannot read the array length because "" is null"

i dont know how to pass data i entered in InPutPerson() class to the Display() class, please help me

答:
InputPerson method should return persons and then use this output as a parameter in display(persons) method.

Something like this:

```<code>    public static void main(String[] args) {
        //input Person
        Person persons[] = InputPerson();
        //display input data
        display(persons);

    }

    private static Person[] InputPerson() {
        Person persons[] = new Person[3];
        Person person = new Person();

        for (int i = 0; i < 3; i++) {
            persons[i] = person.InputPersonInfo(person.getName(), person.getAddress(), person.getSalary());
        }

        for (Person p : persons) {
            person.displayPersonInfo(p);
            System.out.println();
        }
        return persons;
    }

    public static void display(Person[] persons) {
        Person person = new Person();
        for (Person p : persons) {
            person.displayPersonInfo(p);
            System.out.println();
        }
    }
}

</code>```

Body:
i have this Main code

    public static void main(String[] args)
    {
        //display Gui
        DisplayGUI();
        //input Person
        InputPerson();
        //display input data
        Display();
        //sort person
        //SortbySalary();
        //display sorted person
        //Display();

    }

    private static void DisplayGUI() {
        System.out.println("=====Management person Programmer=====");
    }

    private static void InputPerson() {
        //array of person
        Person persons[] = new Person[3];
        //constructor
        Person person = new Person();

        for(int i = 0; i<3; i++){
            persons[i] = person.InputPersonInfo(person.getName(),person.getAddress(),person.getSalary());
        }

        for (Person p: persons){
            person.DisplayPersonInfo(p);
            System.out.println();
        }
    }

    public static void Display() {
        Person person = new Person();
        Person persons[] = null;
                for (Person p: persons){
            person.DisplayPersonInfo(p);
            System.out.println();
        }
    }
}

this is my person class

class Person {
    private String name;
    private String address;
    private double salary;

    public Person() {
    }

    public Person(String name, String address, double salary) {
        this.name = name;
        this.address = address;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public Person InputPersonInfo(String name, String address, double salary){
        Scanner sc = new Scanner(System.in);
        System.out.println("Input Information of person:");
        System.out.println("Please input name:");
        name = sc.nextLine();
        System.out.println("Please input Address)");
        address = sc.nextLine();
        System.out.println("Please input salary:");
        salary = sc.nextDouble();

        return new Person(name,address,salary);

    }
    public void DisplayPersonInfo(Person persons){
        System.out.println("Information of Person you entered");
        System.out.println("Name:" + persons.getName());
        System.out.println("address:" + persons.getAddress());
        System.out.println("slary:" + persons.getSalary());
    }

i dont understand when i push this code in the InputPerson() class, it will display the information of person i entered

        for (Person p: persons){
            person.DisplayPersonInfo(p);
            System.out.println();
        }

but when i try to do this in Display() class it keep telling error "Cannot read the array length because "" is null"

i dont know how to pass data i entered in InPutPerson() class to the Display() class, please help me

Body:
InputPerson method should return persons and then use this output as a parameter in display(persons) method.

Something like this:

    public static void main(String[] args) {
        //input Person
        Person persons[] = InputPerson();
        //display input data
        display(persons);

    }

    private static Person[] InputPerson() {
        Person persons[] = new Person[3];
        Person person = new Person();

        for (int i = 0; i < 3; i++) {
            persons[i] = person.InputPersonInfo(person.getName(), person.getAddress(), person.getSalary());
        }

        for (Person p : persons) {
            person.displayPersonInfo(p);
            System.out.println();
        }
        return persons;
    }

    public static void display(Person[] persons) {
        Person person = new Person();
        for (Person p : persons) {
            person.displayPersonInfo(p);
            System.out.println();
        }
    }
}


问:
Django Rest 'PageNumberPagination' object has no attribute 'page' error
I have a function based Django API as shown in this sample:

```<code>@api_view(['GET'])
def findData(request):
    dataId = request.GET['dataId']
    page_query_param = 'page'
    page_size = request.GET['page_size']
    paginator = PageNumberPagination()
    paginator.page_size = page_size
    paginator.page_query_param = page_query_param
    qry_set = Data.objects.all()
    serializer = dataIdSerializer(qry_set, many=True)
    theData= serializer.data
    return Response(paginator.get_paginated_response(theData))
</code>```

But I keep getting this error:

```<code>AttributeError: 'PageNumberPagination' object has no attribute 'page'
</code>```

I tried setting

```<code>paginator.page_query_param = page_query_param
</code>```

But still same problem.  Please advise of how to fix.

答:
For me adding this to the settings.py fixed the issue.

```<code>REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10    # the size of one page
}
</code>```

Body:
I have a function based Django API as shown in this sample:

@api_view(['GET'])
def findData(request):
    dataId = request.GET['dataId']
    page_query_param = 'page'
    page_size = request.GET['page_size']
    paginator = PageNumberPagination()
    paginator.page_size = page_size
    paginator.page_query_param = page_query_param
    qry_set = Data.objects.all()
    serializer = dataIdSerializer(qry_set, many=True)
    theData= serializer.data
    return Response(paginator.get_paginated_response(theData))

But I keep getting this error:

AttributeError: 'PageNumberPagination' object has no attribute 'page'

I tried setting

paginator.page_query_param = page_query_param

But still same problem.  Please advise of how to fix.

Body:
For me adding this to the settings.py fixed the issue.

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10    # the size of one page
}


问:
Firestore Rules and custom claim with variable keys
I m looking for a way to secure my app using custom claim, but i had difficulty to access them in firestore rules.

My user can be employees of multiple (say 1 to 5) organizations.
I would like to had oganizationId(s) as key in the user custom claims and roles as value.

Like that:

```<code>claims: {
  "organisationId1":"admin",
  "organisationId2":"regularEmployee",
  "organisationId3":"regularEmployee"
}
</code>```

Setting the claims via cloud function work well, but i can't find the way to access customs Claims with variable keys

exemple of Security Rules:

```<code>rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /organisations/{oid} {
      allow read: if request.auth.token[oid] == "regularEmployee";
      allow write: if request.auth.token[oid] == "admin";
   }
}
</code>```

Hope it is possible it would be an easy way to restrict many-to-many relationship

答:
The Net Ninja actually made a video about this back in 2019 that I just stumbled on.

Basically you want to check for request.auth.token.yourCustomClaim. In my case it looks something like this:

```<code>match /orders/{record} {
  allow read, update, delete: request.auth.token.isAdmin == true;
}
</code>```

Haven't tested it against string values, but I can't think why it wouldn't work. Let us know how it goes, I suppose :)

Body:
I m looking for a way to secure my app using custom claim, but i had difficulty to access them in firestore rules.

My user can be employees of multiple (say 1 to 5) organizations.
I would like to had oganizationId(s) as key in the user custom claims and roles as value.

Like that:

claims: {
  "organisationId1":"admin",
  "organisationId2":"regularEmployee",
  "organisationId3":"regularEmployee"
}

Setting the claims via cloud function work well, but i can't find the way to access customs Claims with variable keys

exemple of Security Rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /organisations/{oid} {
      allow read: if request.auth.token[oid] == "regularEmployee";
      allow write: if request.auth.token[oid] == "admin";
   }
}

Hope it is possible it would be an easy way to restrict many-to-many relationship

Body:
The Net Ninja actually made a video about this back in 2019 that I just stumbled on.

Basically you want to check for request.auth.token.yourCustomClaim. In my case it looks something like this:

match /orders/{record} {
  allow read, update, delete: request.auth.token.isAdmin == true;
}

Haven't tested it against string values, but I can't think why it wouldn't work. Let us know how it goes, I suppose :)


问:
OpenCV: An Array of images: How can I identify which image has been found?
I'm learning OpenCV & Python by writing a bot for a 2d spaceship game.

The basic principle is there are certain targets my spaceship can defeat and certain spaceships it cannot defeat. One target is displayed on the screen at a time and you click either next or attack depending on what you want to do. In doing this you're able to cycle through targets until you find one you want to attack.

At the moment my code:

Loads images of ships it cannot defeat into an numpy array

Some pyautigui interactions to skip through menus

Checks the numpy array to determine if it wants to attack or skip the target it's been given

Clicks attack or skip with pyautogui

This all works correctly and the bot happily searches away and either clicks skip or attack.

My issue:

The names of the images being loaded are human-readable e.g. Ship 1.jpg, Ship 2.jpg, Ship 3.jpg When I load them into the numpy array they lose their human-readable component.

My Question:

I want to be able to log what was attacked to refine the detection, at the moment I'm able to output the actual array array([[106, 106, 106, ..., 42, 41, 42], but I can't seem to figure out how to keep the human-readable element. How can I keep the human-readable element?

I'm loading the images like this:

```<code># Load Images
def loadImages(directory):
    # Intialise empty array
    image_list = []
    # Add images to array
    for i in directory:
        img = cv.imread(i, cv.IMREAD_REDUCED_GRAYSCALE_2)
        image_list.append(img)
    return image_list
</code>```

And the object detection is done with cv.matchTemplate

```<code>def objectDetection(image_list):
    # Object Detection
    for i in image_list:
        needle_img = i
        result = cv.matchTemplate(haystack, needle_img, cv.TM_CCORR_NORMED)
</code>```

Update with Error from Answer:

I updated my loadImages function with image_list.append((img, i)) and that's worked and I can now see the appended file name attached to the array in the debugger. I also updated the object detection with for i in image_list[i][2]: to select the array object but then I get the following error:

```<code>Exception has occurred: UnboundLocalError
local variable 'i' referenced before assignment
  File "C:\Users\test6.py", line 65, in objectDetection
    for i in image_list[i][2]:
  File "C:\Users\test6.py", line 202, in <module>
    objectDetection(ships_to_avoid, 0.9)
</code>```

答:
You can append tuples to your list.
Where the first element is the name and the second is the image.

```<code>image_list.append((img, i))
</code>```

Now 'i' represents the filename and 'img' the image file.
You can now access the name of the image or the image with j being the index (e.g. 0)  as follows:

```<code>img_name = image_list[j][1]
img = image_list[j][0]
</code>```

Edit 1:
if you want to access your images in your list for object detection rewrite it the following way:

```<code>def objectDetection(image_list):
# Object Detection
    for i in image_list:
        needle_img = i[0]
        needle_name = i[1]
        result = cv.matchTemplate(haystack, needle_img, cv.TM_CCORR_NORMED)
</code>```

Edit 2: fixed the indices

Body:
I'm learning OpenCV & Python by writing a bot for a 2d spaceship game.

The basic principle is there are certain targets my spaceship can defeat and certain spaceships it cannot defeat. One target is displayed on the screen at a time and you click either next or attack depending on what you want to do. In doing this you're able to cycle through targets until you find one you want to attack.

At the moment my code:

Loads images of ships it cannot defeat into an numpy array

Some pyautigui interactions to skip through menus

Checks the numpy array to determine if it wants to attack or skip the target it's been given

Clicks attack or skip with pyautogui

This all works correctly and the bot happily searches away and either clicks skip or attack.

My issue:

The names of the images being loaded are human-readable e.g. Ship 1.jpg, Ship 2.jpg, Ship 3.jpg When I load them into the numpy array they lose their human-readable component.

My Question:

I want to be able to log what was attacked to refine the detection, at the moment I'm able to output the actual array array([[106, 106, 106, ..., 42, 41, 42], but I can't seem to figure out how to keep the human-readable element. How can I keep the human-readable element?

I'm loading the images like this:

# Load Images
def loadImages(directory):
    # Intialise empty array
    image_list = []
    # Add images to array
    for i in directory:
        img = cv.imread(i, cv.IMREAD_REDUCED_GRAYSCALE_2)
        image_list.append(img)
    return image_list

And the object detection is done with cv.matchTemplate

def objectDetection(image_list):
    # Object Detection
    for i in image_list:
        needle_img = i
        result = cv.matchTemplate(haystack, needle_img, cv.TM_CCORR_NORMED)

Update with Error from Answer:

I updated my loadImages function with image_list.append((img, i)) and that's worked and I can now see the appended file name attached to the array in the debugger. I also updated the object detection with for i in image_list[i][2]: to select the array object but then I get the following error:

Exception has occurred: UnboundLocalError
local variable 'i' referenced before assignment
  File "C:\Users\test6.py", line 65, in objectDetection
    for i in image_list[i][2]:
  File "C:\Users\test6.py", line 202, in <module>
    objectDetection(ships_to_avoid, 0.9)

Body:
You can append tuples to your list.
Where the first element is the name and the second is the image.

image_list.append((img, i))

Now 'i' represents the filename and 'img' the image file.
You can now access the name of the image or the image with j being the index (e.g. 0)  as follows:

img_name = image_list[j][1]
img = image_list[j][0]

Edit 1:
if you want to access your images in your list for object detection rewrite it the following way:

def objectDetection(image_list):
# Object Detection
    for i in image_list:
        needle_img = i[0]
        needle_name = i[1]
        result = cv.matchTemplate(haystack, needle_img, cv.TM_CCORR_NORMED)

Edit 2: fixed the indices


问:
PowerShell: Restart Service By Executable Name
all

I implemented my first PowerShell script, that does some setup, sets registry keys and at then end needs to restart services. The problem is that I have only have name of the executable, but not service name. Restart-Service can work only with name of the service. Googling (well Binging also) around didn't give me much result.

I was wondering whether there is a way to restart service by executable name?

I know that I can get process by executable name, but just killing the process and starting it again is NOT good choice, since service Start/Stop functions are not called and it may not work properly.

Thanks.

答:
You can try using wmi and do something like this:</p>

```<code>(gwmi win32_service | ?{$_.pathname -match "\\executable.exe "}) | Restart-Service
</code>```

Body:
You can try using wmi and do something like this:

(gwmi win32_service | ?{$_.pathname -match "\\executable.exe "}) | Restart-Service


问:
Regex replacement only if it's in braces and not in quotes
I'm looking to do replacements in unknown third-party inputs in strings that sometimes have quotes among them. I want to replace a wholeword whereever it occurs if it's in braces {} or marked with {replaceinside}{/replaceinside} unless it's in double or single-quotes, and unless the quote is escaped.

Regex so far largely comes from this question: Regex replace word in string that are not in quotes Thanks Wiktor Stribiżew and anubhava who helped me out there.

I thought after asking that question it would be easy to integrate the final braces requirement but guess not.

Here's my test string and the output:

```<code>`name: FOO
{favoriteQuote: "I am my own FOO."}
children: 'FOO\'s children'
{cars: ownersList[FOO]}
statement = {FOO} + " is the owner of the house."
{replaceinside}FOO "FOO" {'FOO' "    1 + FOO + 2 " ABCFOOXYZ} "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"FOO\"{/replaceinside}`
</code>```

I would like to replace FOO with BAR.
Expected Output:

```<code>`name: FOO
{favoriteQuote: "I am my own FOO."}
children: 'FOO\'s children'
{cars: ownersList[BAR]}
statement = {BAR} + " is the owner of the house."
{replaceinside}BAR "FOO" {'FOO' "    1 + FOO + 2 " ABCFOOXYZ} "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"BAR\"{/replaceinside}`
</code>```

Ultimately I would like to use the text as a template and create an array of strings with mapped replacements. Like so:

```<code>var v = "BAR", arr = ["BAR", "BAZ"], finalArr = [], swappedFromValue = "FOO"

const text = String.raw`
name: FOO
{favoriteQuote: "I am my own FOO."}
children: 'FOO\'s children'
{cars: ownersList[FOO]}
statement = {FOO} + " is the owner of the house."
{replaceinside}FOO "FOO" {'FOO' "    1 + FOO + 2 " ABCFOOXYZ} "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"FOO\"{/replaceinside}
`

var replacementRegex = new RegExp('{(.*?)((?:[^\\\\]|^)(?:\\\\{2})*(?:"[^"\\\\]*(?:\\\\[^][^"\\\\]*)*"|\'[^\'\\\\]*(?:\\\\[^][^\'\\\\]*)*\'))|\\b' + swappedFromValue + '\\b(.*?)}', 'g') // single line
var replacementInsideRegex = new RegExp('{replaceinside}(.*?)((?:[^\\\\]|^)(?:\\\\{2})*(?:"[^"\\\\]*(?:\\\\[^][^"\\\\]*)*"|\'[^\'\\\\]*(?:\\\\[^][^\'\\\\]*)*\'))|\\b' + swappedFromValue + '\\b(.*?){/replaceinside}', 'gs') // multi line

function replaceFunc (v, k) {
  var replacedText = text.replace(replacementRegex, function (match, group) {
    return group || v;
  })
  replacedText = replacedText.replace(replacementInsideRegex, function (match, group) {
    return group || v;
  })
  finalArr.push(replacedText)
}

arr.forEach(replaceFunc)
document.body.innerHTML = finalArr.join("<br><br>")
</code>```

Expected output:

```<code>`name: FOO
{favoriteQuote: "I am my own FOO."}
children: 'FOO\'s children'
{cars: ownersList[BAR]}
statement = {BAR} + " is the owner of the house."
{replaceinside}BAR "FOO" {'FOO' "    1 + FOO + 2 " ABCFOOXYZ} "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"BAR\"{/replaceinside}

name: FOO
{favoriteQuote: "I am my own FOO."}
children: 'FOO\'s children'
{cars: ownersList[BAZ]}
statement = {BAZ} + " is the owner of the house."
{replaceinside}BAZ "FOO" {'FOO' "    1 + FOO + 2 " ABCFOOXYZ} "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"BAZ\"{/replaceinside}`
</code>```

fiddle: https://jsfiddle.net/x7016sv4/1/

答:
As the solution should also deal well with nested braces, and JavaScript regular expression have no recursion capability, I would suggest to move some of the logic out of the regular expression into JavaScript code. A regular expression can still be used to identify the individual parts, but some code will be needed to:

Maintain a stack of nested braces and nested tags

Pair balanced braces/tags

Make the replacement conditional on a non-empty stack

Decide how nesting of braces and tags should be dealt with when they overlap, like { aa {replaceinside} bb } cc {/replaceinside} dd. For instance, braces could be thought of as ineffective inside tags.

function solution(text, source, target) {
    const regex = RegExp(String.raw`(?:\\["'])+|\{\/?replaceinside\}|[{}]|(['"])(?:\\.|.)*?\1|\b${source}\b|.`, "gs");
    let stack = [];
    return input.replace(regex, function (token) {
        if (token === "{replaceinside}") {
            stack.push("{/replaceinside}");
        } else if (token === "{" && stack.at(-1) !== "{/replaceinside}") { // Braces inside tags have no meaning
            stack.push("}");
        } else if (token === stack.at(-1)) { // Pair balanced braces/tags
            stack.pop();
        } else if (token === "\n") { // Auto-close all braces
            stack = stack.filter(item => item !== "}");
        } else if (token === source && stack.length) { // Only replace within braces/tags
            return target;
        }
        return token;
    });
}

let input = String.raw`name: FOO
{favoriteQuote: "I am my own FOO."}
children: 'FOO\'s children'
{cars: ownersList[FOO]}
statement = {FOO} + " is the owner of the house."
{replaceinside}FOO "FOO" {'FOO' "    1 + FOO + 2 " ABCFOOXYZ} "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"FOO\"{/replaceinside}`;

console.log(solution(input, "FOO", "BAR"));```

Body:
I'm looking to do replacements in unknown third-party inputs in strings that sometimes have quotes among them. I want to replace a wholeword whereever it occurs if it's in braces {} or marked with {replaceinside}{/replaceinside} unless it's in double or single-quotes, and unless the quote is escaped.

Regex so far largely comes from this question: Regex replace word in string that are not in quotes Thanks Wiktor Stribiżew and anubhava who helped me out there.

I thought after asking that question it would be easy to integrate the final braces requirement but guess not.

Here's my test string and the output:

`name: FOO
{favoriteQuote: "I am my own FOO."}
children: 'FOO\'s children'
{cars: ownersList[FOO]}
statement = {FOO} + " is the owner of the house."
{replaceinside}FOO "FOO" {'FOO' "    1 + FOO + 2 " ABCFOOXYZ} "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"FOO\"{/replaceinside}`

I would like to replace FOO with BAR.
Expected Output:

`name: FOO
{favoriteQuote: "I am my own FOO."}
children: 'FOO\'s children'
{cars: ownersList[BAR]}
statement = {BAR} + " is the owner of the house."
{replaceinside}BAR "FOO" {'FOO' "    1 + FOO + 2 " ABCFOOXYZ} "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"BAR\"{/replaceinside}`

Ultimately I would like to use the text as a template and create an array of strings with mapped replacements. Like so:

var v = "BAR", arr = ["BAR", "BAZ"], finalArr = [], swappedFromValue = "FOO"

const text = String.raw`
name: FOO
{favoriteQuote: "I am my own FOO."}
children: 'FOO\'s children'
{cars: ownersList[FOO]}
statement = {FOO} + " is the owner of the house."
{replaceinside}FOO "FOO" {'FOO' "    1 + FOO + 2 " ABCFOOXYZ} "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"FOO\"{/replaceinside}
`

var replacementRegex = new RegExp('{(.*?)((?:[^\\\\]|^)(?:\\\\{2})*(?:"[^"\\\\]*(?:\\\\[^][^"\\\\]*)*"|\'[^\'\\\\]*(?:\\\\[^][^\'\\\\]*)*\'))|\\b' + swappedFromValue + '\\b(.*?)}', 'g') // single line
var replacementInsideRegex = new RegExp('{replaceinside}(.*?)((?:[^\\\\]|^)(?:\\\\{2})*(?:"[^"\\\\]*(?:\\\\[^][^"\\\\]*)*"|\'[^\'\\\\]*(?:\\\\[^][^\'\\\\]*)*\'))|\\b' + swappedFromValue + '\\b(.*?){/replaceinside}', 'gs') // multi line

function replaceFunc (v, k) {
  var replacedText = text.replace(replacementRegex, function (match, group) {
    return group || v;
  })
  replacedText = replacedText.replace(replacementInsideRegex, function (match, group) {
    return group || v;
  })
  finalArr.push(replacedText)
}

arr.forEach(replaceFunc)
document.body.innerHTML = finalArr.join("

")

Expected output:

`name: FOO
{favoriteQuote: "I am my own FOO."}
children: 'FOO\'s children'
{cars: ownersList[BAR]}
statement = {BAR} + " is the owner of the house."
{replaceinside}BAR "FOO" {'FOO' "    1 + FOO + 2 " ABCFOOXYZ} "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"BAR\"{/replaceinside}

name: FOO
{favoriteQuote: "I am my own FOO."}
children: 'FOO\'s children'
{cars: ownersList[BAZ]}
statement = {BAZ} + " is the owner of the house."
{replaceinside}BAZ "FOO" {'FOO' "    1 + FOO + 2 " ABCFOOXYZ} "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"BAZ\"{/replaceinside}`

fiddle: https://jsfiddle.net/x7016sv4/1/


问:
Git diff for n'th modified file?
Suppose we change several files, and want to view the diff for one at a time, I know we can use something like this

git status

Changes not staged for commit:
 directory)
    modified:   app/assets/stylesheets/application.scss
    modified:   app/javascript/packs/application.js
    modified:   app/views/layouts/application.html.erb
    modified:   config/webpack/environment.js
```
<p>and run</p>
<pre class="lang-sh prettyprint-override"><code>git diff app/assets/stylesheets/application.scss
</code>```

then

git diff app/javascript/packs/application.js
```
<p>and so on..</p>
<pre class="lang-sh prettyprint-override"><code>git diff app/views/layouts/application.html.erb
</code>```

To view each of the files' diffs one by one (one by one is desired here, but all the typing of file paths isn't, even with tab to auto complete).

Question

Is there a way to achieve the same (i.e. view git diff for a single file at a time) but without having to type (manually, nor with tab autocomplete) the full path to the changed file? (e.g. can we reference somehow, pseudo-code: git diff --mod_file 1, git diff --mod_file 2 etc) ?

答:
I think git difftool will do what you want.

Perhaps you want to install some own difftool, whatever suits your needs.

Title: Git diff for n'th modified file?

Body:
Suppose we change several files, and want to view the diff for one at a time, I know we can use something like this

git status

Changes not staged for commit:
 directory)
    modified:   app/assets/stylesheets/application.scss
    modified:   app/javascript/packs/application.js
    modified:   app/views/layouts/application.html.erb
    modified:   config/webpack/environment.js

and run

git diff app/assets/stylesheets/application.scss

then

git diff app/javascript/packs/application.js

and so on..

git diff app/views/layouts/application.html.erb

To view each of the files' diffs one by one (one by one is desired here, but all the typing of file paths isn't, even with tab to auto complete).

Question

Is there a way to achieve the same (i.e. view git diff for a single file at a time) but without having to type (manually, nor with tab autocomplete) the full path to the changed file? (e.g. can we reference somehow, pseudo-code: git diff --mod_file 1, git diff --mod_file 2 etc) ?


问:
Google Appscript: Copy Data from a Form Sheet to Another Sheet in Last Row and Clear Form
Trying to get an Appscript to run but I can't seem to figure out the last few steps.

Background: I have a Google Sheet with two tabs, #1 is called "Data Form" which hosts a fillable form to capture Transaction information to then be input onto tab #2 called "Posted Transactions". This is a personal budget spreadsheet..

Anyways, The script below is intended to take the information input on the "Data Form", verify what the last row with data is on the "Posted Transactions" tab based on whether or not Column A has any data. (To further clarify, the "Posted Transactions" tab has formulas in columns G-I which prohibits me from using a simple "Find last Row" script.)

As it is written now, I receive an error "Exception: The number of columns in the data does not match the number of columns in the range. The data has 6 but the range has 1.
RecordNewTransaction    @ Code.gs:24"

Any suggestions to make this work properly?

UPDATE:

```<code>var dataRange = datasheet.getRange(lastRow+1,1,1,datasheet.getLastColumn()-3);
</code>```

After many attempts at trial and error, I needed to edit the line shown above. Current & full script is performing as expected now and is shown below. Image snips of what I was trying to accomplish are also shown for reference.

```<code>function RecordNewTransaction() {
var ss        = SpreadsheetApp.getActiveSpreadsheet();
var formSS    = ss.getSheetByName("Data Form"); //Form Sheet
var datasheet = ss.getSheetByName("Posted Transactions"); //Data
//Input Values
var values = [[formSS.getRange("B4").getValue(),
               formSS.getRange("B6").getValue(),
               formSS.getRange("B8").getValue(),
               formSS.getRange("B10").getValue(),
               formSS.getRange("B12").getValue(),
               formSS.getRange("B14").getValue()]];

var columnToCheck = datasheet.getRange("A:A").getValues();
var lastRow = getLastRowSpecial(columnToCheck);
Logger.log(lastRow);

var dataRange = datasheet.getRange(lastRow+1,1,1,datasheet.getLastColumn()-3);
Logger.log(dataRange);
var dataValues = dataRange.getValues();

Logger.log(dataValues);

dataRange.setValues(values);
Logger.log(dataRange.setValues(values))

formSS.getRange('B4:B14').clearContent();

};

function getLastRowSpecial(range){
var rowNum = 0;
var blank = false;
for(var row = 0; row < range.length; row++){

  if(range[row][0] === "" && !blank){
    rowNum = row;
    blank = true;
  }else if(range[row][0] !== ""){
    blank = false;
  };
};
return rowNum;
  };
</code>```

答:
See edited question above which contains the revised script needed.

The problem here was that columns G-I of my results sheet contain formulas (shown in grey) which required this line below to be modified to grab the last column -3, otherwise the script was looking at too many columns that it didn't need to. Also had to modify "lastRow" to "lastRow+1" because this kept overriding the very last line of data I already had input and the +1 will make new data go to the next available row.

```<code>var dataRange = datasheet.getRange(lastRow+1,1,1,datasheet.getLastColumn()-3);
</code>```

Body:
Trying to get an Appscript to run but I can't seem to figure out the last few steps.

Background: I have a Google Sheet with two tabs, #1 is called "Data Form" which hosts a fillable form to capture Transaction information to then be input onto tab #2 called "Posted Transactions". This is a personal budget spreadsheet..

Anyways, The script below is intended to take the information input on the "Data Form", verify what the last row with data is on the "Posted Transactions" tab based on whether or not Column A has any data. (To further clarify, the "Posted Transactions" tab has formulas in columns G-I which prohibits me from using a simple "Find last Row" script.)

As it is written now, I receive an error "Exception: The number of columns in the data does not match the number of columns in the range. The data has 6 but the range has 1.
RecordNewTransaction    @ Code.gs:24"

Any suggestions to make this work properly?

UPDATE:

var dataRange = datasheet.getRange(lastRow+1,1,1,datasheet.getLastColumn()-3);

After many attempts at trial and error, I needed to edit the line shown above. Current & full script is performing as expected now and is shown below. Image snips of what I was trying to accomplish are also shown for reference.

function RecordNewTransaction() {
var ss        = SpreadsheetApp.getActiveSpreadsheet();
var formSS    = ss.getSheetByName("Data Form"); //Form Sheet
var datasheet = ss.getSheetByName("Posted Transactions"); //Data
//Input Values
var values = [[formSS.getRange("B4").getValue(),
               formSS.getRange("B6").getValue(),
               formSS.getRange("B8").getValue(),
               formSS.getRange("B10").getValue(),
               formSS.getRange("B12").getValue(),
               formSS.getRange("B14").getValue()]];

var columnToCheck = datasheet.getRange("A:A").getValues();
var lastRow = getLastRowSpecial(columnToCheck);
Logger.log(lastRow);

var dataRange = datasheet.getRange(lastRow+1,1,1,datasheet.getLastColumn()-3);
Logger.log(dataRange);
var dataValues = dataRange.getValues();

Logger.log(dataValues);

dataRange.setValues(values);
Logger.log(dataRange.setValues(values))

formSS.getRange('B4:B14').clearContent();

};

function getLastRowSpecial(range){
var rowNum = 0;
var blank = false;
for(var row = 0; row < range.length; row++){

  if(range[row][0] === "" && !blank){
    rowNum = row;
    blank = true;
  }else if(range[row][0] !== ""){
    blank = false;
  };
};
return rowNum;
  };

Body:
See edited question above which contains the revised script needed.

The problem here was that columns G-I of my results sheet contain formulas (shown in grey) which required this line below to be modified to grab the last column -3, otherwise the script was looking at too many columns that it didn't need to. Also had to modify "lastRow" to "lastRow+1" because this kept overriding the very last line of data I already had input and the +1 will make new data go to the next available row.

var dataRange = datasheet.getRange(lastRow+1,1,1,datasheet.getLastColumn()-3);


问:
Chart.js 3.x custom positioners: cannot use them in TypeScript
I'm using ChartJS v3 and I'm trying to implement a custom tooltip positioner, as described in the docs:

https://www.chartjs.org/docs/master/configuration/tooltip.html#position-modes

However, the problem is that I'm coding in TypeScript and the type checking is fighting me over this.
The first problem is that I cannot define the custom positioner like in the example:

```<code>const tooltipPlugin = Chart.registry.getPlugin('tooltip');
tooltipPlugin.positioners.myCustomPositioner = ...
</code>```

because the type returned by getPlugin() does not contain the positioners property.

The second problem is when you then have to configure the plugin. I cannot do this:

```<code>plugins: {
    tooltip: {
      position: 'myCustomPositioner',
      ...
    }
}
</code>```

because the position property only accepts the defaults built in values ('average' and 'nearest') but does not take a custom string.

How do I work around this? I wasa happy that the latest ChartJS provides strong types, but they are no use if the make core features of the library unusable... what am I missing?

答:
The proper way to do this is to extend the positioners map typings to include your custom function.
Refer to https://www.chartjs.org/docs/3.4.1/developers/charts.html, which includes how to extend the typings for custom charts, it is similar to this.

By just casting the position, as the solution from @bangash, you are tricking the compiler. That solution also does not solve the problem when you create the positioner.

Note: This expects you are using ChartJS 3.x

Create a file called chartjs.d.ts somewhere in your project that tsconfig.json reads from, for example @types/chartjs.d.ts

import type { TooltipPositionerFunction } from 'chart.js';

declare module 'chart.js' {
  // Extend tooltip positioner map
  interface TooltipPositionerMap {
    cursor: TooltipPositionerFunction<ChartType>;
  }
}
```
<p>Then, create your function where you are registering your components:</p>
<pre class="lang-js prettyprint-override"><code>import { Tooltip } from 'chart.js'

// Create positioner to put tooltip at cursor position
Tooltip.positioners.cursor = function (chartElements, coordinates) {
  return coordinates;
};
</code>```

Now you can use your cursor as position property of the tooltip.

Body:
I'm using ChartJS v3 and I'm trying to implement a custom tooltip positioner, as described in the docs:

https://www.chartjs.org/docs/master/configuration/tooltip.html#position-modes

However, the problem is that I'm coding in TypeScript and the type checking is fighting me over this.
The first problem is that I cannot define the custom positioner like in the example:

const tooltipPlugin = Chart.registry.getPlugin('tooltip');
tooltipPlugin.positioners.myCustomPositioner = ...

because the type returned by getPlugin() does not contain the positioners property.

The second problem is when you then have to configure the plugin. I cannot do this:

plugins: {
    tooltip: {
      position: 'myCustomPositioner',
      ...
    }
}

because the position property only accepts the defaults built in values ('average' and 'nearest') but does not take a custom string.

How do I work around this? I wasa happy that the latest ChartJS provides strong types, but they are no use if the make core features of the library unusable... what am I missing?

Body:
The proper way to do this is to extend the positioners map typings to include your custom function.
Refer to https://www.chartjs.org/docs/3.4.1/developers/charts.html, which includes how to extend the typings for custom charts, it is similar to this.

By just casting the position, as the solution from @bangash, you are tricking the compiler. That solution also does not solve the problem when you create the positioner.

Note: This expects you are using ChartJS 3.x

Create a file called chartjs.d.ts somewhere in your project that tsconfig.json reads from, for example @types/chartjs.d.ts

import type { TooltipPositionerFunction } from 'chart.js';

declare module 'chart.js' {
  // Extend tooltip positioner map
  interface TooltipPositionerMap {
    cursor: TooltipPositionerFunction<ChartType>;
  }
}

Then, create your function where you are registering your components:

import { Tooltip } from 'chart.js'

// Create positioner to put tooltip at cursor position
Tooltip.positioners.cursor = function (chartElements, coordinates) {
  return coordinates;
};

Now you can use your cursor as position property of the tooltip.


问:
Need help animating two things with a background in turtle python
I have both the drawings under guy0 and guy1, and the background is back0. I can have one of the drawings animate with the method I am trying to use, but not both.

I also cannot seem to get the background to be drawn when I animate it either. The other human is the exact same as the human0 just a different color shirt. I needed to make this post shorter. Any help is appreciated.

Here is the code:

```<code>from turtle import *
def back0():
  delay(0)
  tracer(0)
  bgcolor("#87ceeb")
  up()
  goto(0,0)
  pd()
  up()
  goto(160,350)
  pd()
  fillcolor("#FDB813")
  begin_fill()
  circle(60)
  end_fill()
  rt(90)
  up()
  fd(5)
  rt(90)
  pd()
  begin_fill()
  fd(5)
  lt(130)
  fd(20)
  lt(130)
  fd(20)
  lt(30)
  lt(90)
  fd(15)
  end_fill()
  up()

def guy0(x,y):
  delay(0)
  tracer(0)
  up()
  goto(x,y)
  pd()
  fillcolor("#E8BEAC")
  begin_fill()
  circle(25)
  end_fill()
  up()
  goto(x,y-80)
  pd()
  fd(20)
  lt(90)
  fd(60)
  fillcolor("#FF5F1F")
  begin_fill()
  circle(20,180)
  end_fill()
  begin_fill()
  fd(60)
  lt(90)
  fd(40)
  lt(90)
  fd(60)
  lt(90)
  up()
  fd(40)
  end_fill()
  setheading(0)

xCoor = -400
yCoor = -50
screen = Screen()
def move():
  global xCoor, yCoor
  xCoor += 3

  if xCoor  > 420:
    xCoor=-420

  clear()
  guy0(xCoor,yCoor)

  screen.ontimer(move,1)

move()
</code>```

答:
I don't see guy1 or human0 anywhere, so I'll work with your code as-is and let you take it from there.

In general, when debugging and coding, it's important to work slowly and methodically. If you leap ahead and add a bunch of code without validating that it makes sense and works at each step along the way, you can easily wind up with 4-5 problems that are hard to fix.

back0 is never called.

tracer(0) and bgcolor("#87ceeb") should be one-off calls at the beginning of the program rather than running in the loop, doing the same thing over and over.

I'm not sure what your screen size is, but for me, goto(160,350) moves what appears to be the sun offscreen and there are some pd()/up() calls that don't seem to achieve anything. I'd add a comment or move the sun-drawing code into its own function so it's easier to understand.

After drawing the sun, call setheading(0) to restore the heading and avoid guy0's body from being drawn askew.

I suggest screen.ontimer(10), the default value, rather than screen.ontimer(1), which is faster than my screen can refresh and might result in jitter.

Here are the modifications with comments:

from turtle import *

def back0():
    up()
    goto(0, 0)
    goto(160, 150) # 350 is off-screen for me
    pd()
    fillcolor("#FDB813")
    begin_fill()
    circle(60)
    end_fill()
    rt(90)
    up()
    fd(5)
    rt(90)
    pd()
    begin_fill()
    fd(5)
    lt(130)
    fd(20)
    lt(130)
    fd(20)
    lt(30)
    lt(90)
    fd(15)
    end_fill()
    up()
    setheading(0) # restore heading

def guy0(x, y):
    up()
    goto(x, y)
    pd()
    fillcolor("#E8BEAC")
    begin_fill()
    circle(25)
    end_fill()
    up()
    goto(x, y - 80)
    pd()
    fd(20)
    lt(90)
    fd(60)
    fillcolor("#FF5F1F")
    begin_fill()
    circle(20, 180)
    end_fill()
    begin_fill()
    fd(60)
    lt(90)
    fd(40)
    lt(90)
    fd(60)
    lt(90)
    up()
    fd(40)
    end_fill()
    setheading(0)

x_coor = -400
y_coor = -50
screen = Screen()
ht()               #
tracer(0)          # call once up front rather than in the loop
bgcolor("#87ceeb") #

def move():
    global x_coor, y_coor
    x_coor += 3

    if x_coor > 420:
        x_coor =- 420

    clear()
    back0()
    guy0(x_coor, y_coor)
    screen.ontimer(move, 10)

move()
exitonclick()
```

Now, if you want to animate another person, add coordinates and a draw function and call it in the loop just like guy0. Or research and create a class (and probably also lists and loops) which can be used to store coordinates dynamically to let you make as many people as you want easily, without repeating the code with guy0, guy1... guy100 which gets tedious quickly.

Body:
I have both the drawings under guy0 and guy1, and the background is back0. I can have one of the drawings animate with the method I am trying to use, but not both.

I also cannot seem to get the background to be drawn when I animate it either. The other human is the exact same as the human0 just a different color shirt. I needed to make this post shorter. Any help is appreciated.

Here is the code:

from turtle import *
def back0():
  delay(0)
  tracer(0)
  bgcolor("#87ceeb")
  up()
  goto(0,0)
  pd()
  up()
  goto(160,350)
  pd()
  fillcolor("#FDB813")
  begin_fill()
  circle(60)
  end_fill()
  rt(90)
  up()
  fd(5)
  rt(90)
  pd()
  begin_fill()
  fd(5)
  lt(130)
  fd(20)
  lt(130)
  fd(20)
  lt(30)
  lt(90)
  fd(15)
  end_fill()
  up()

def guy0(x,y):
  delay(0)
  tracer(0)
  up()
  goto(x,y)
  pd()
  fillcolor("#E8BEAC")
  begin_fill()
  circle(25)
  end_fill()
  up()
  goto(x,y-80)
  pd()
  fd(20)
  lt(90)
  fd(60)
  fillcolor("#FF5F1F")
  begin_fill()
  circle(20,180)
  end_fill()
  begin_fill()
  fd(60)
  lt(90)
  fd(40)
  lt(90)
  fd(60)
  lt(90)
  up()
  fd(40)
  end_fill()
  setheading(0)

xCoor = -400
yCoor = -50
screen = Screen()
def move():
  global xCoor, yCoor
  xCoor += 3

  if xCoor  > 420:
    xCoor=-420

  clear()
  guy0(xCoor,yCoor)

  screen.ontimer(move,1)

move()

Body:
I don't see guy1 or human0 anywhere, so I'll work with your code as-is and let you take it from there.

In general, when debugging and coding, it's important to work slowly and methodically. If you leap ahead and add a bunch of code without validating that it makes sense and works at each step along the way, you can easily wind up with 4-5 problems that are hard to fix.

back0 is never called.

tracer(0) and bgcolor("#87ceeb") should be one-off calls at the beginning of the program rather than running in the loop, doing the same thing over and over.

I'm not sure what your screen size is, but for me, goto(160,350) moves what appears to be the sun offscreen and there are some pd()/up() calls that don't seem to achieve anything. I'd add a comment or move the sun-drawing code into its own function so it's easier to understand.

After drawing the sun, call setheading(0) to restore the heading and avoid guy0's body from being drawn askew.

I suggest screen.ontimer(10), the default value, rather than screen.ontimer(1), which is faster than my screen can refresh and might result in jitter.

Here are the modifications with comments:

from turtle import *

def back0():
    up()
    goto(0, 0)
    goto(160, 150) # 350 is off-screen for me
    pd()
    fillcolor("#FDB813")
    begin_fill()
    circle(60)
    end_fill()
    rt(90)
    up()
    fd(5)
    rt(90)
    pd()
    begin_fill()
    fd(5)
    lt(130)
    fd(20)
    lt(130)
    fd(20)
    lt(30)
    lt(90)
    fd(15)
    end_fill()
    up()
    setheading(0) # restore heading

def guy0(x, y):
    up()
    goto(x, y)
    pd()
    fillcolor("#E8BEAC")
    begin_fill()
    circle(25)
    end_fill()
    up()
    goto(x, y - 80)
    pd()
    fd(20)
    lt(90)
    fd(60)
    fillcolor("#FF5F1F")
    begin_fill()
    circle(20, 180)
    end_fill()
    begin_fill()
    fd(60)
    lt(90)
    fd(40)
    lt(90)
    fd(60)
    lt(90)
    up()
    fd(40)
    end_fill()
    setheading(0)

x_coor = -400
y_coor = -50
screen = Screen()
ht()               #
tracer(0)          # call once up front rather than in the loop
bgcolor("#87ceeb") #

def move():
    global x_coor, y_coor
    x_coor += 3

    if x_coor > 420:
        x_coor =- 420

    clear()
    back0()
    guy0(x_coor, y_coor)
    screen.ontimer(move, 10)

move()
exitonclick()

Now, if you want to animate another person, add coordinates and a draw function and call it in the loop just like guy0. Or research and create a class (and probably also lists and loops) which can be used to store coordinates dynamically to let you make as many people as you want easily, without repeating the code with guy0, guy1... guy100 which gets tedious quickly.


问:
What are the most hardcore optimisations you've seen?
I'm not talking about algorithmic stuff (eg use quicksort instead of bubblesort), and I'm not talking about simple things like loop unrolling.

I'm talking about the hardcore stuff. Like Tiny Teensy ELF, The Story of Mel; practically everything in the demoscene, and so on.

答:
I wrote a tile-based game engine for the Apple IIgs in 65816 assembly language a few years ago.  This was a fairly slow machine and programming "on the metal" is a virtual requirement for coaxing out acceptable performance.

In order to quickly update the graphics screen one has to map the stack to the screen in order to use some special instructions that allow one to update 4 screen pixels in only 5 machine cycles.  This is nothing particularly fantastic and is described in detail in IIgs Tech Note #70. The hard-core bit was how I had to organize the code to make it flexible enough to be a general-purpose library while still maintaining maximum speed.

I decomposed the graphics screen into scan lines and created a 246 byte code buffer to insert the specialized 65816 opcodes. The 246 bytes are needed because each scan line of the graphics screen is 80 words wide and 1 additional word is required on each end for smooth scrolling.  The Push Effective Address (PEA) instruction takes up 3 bytes, so 3 * (80 + 1 + 1) = 246 bytes.

The graphics screen is rendered by jumping to an address within the 246 byte code buffer that corresponds to the right edge of the screen and patching in a BRanch Always (BRA) instruction into the code at the word immediately following the left-most word.  The BRA instruction takes a signed 8-bit offset as its argument, so it just barely has the range to jump out of the code buffer.

Even this isn't too terribly difficult, but the real hard-core optimization comes in here.  My graphics engine actually supported two independent background layers and animated tiles by using different 3-byte code sequences depending on the mode:

Background 1 uses a Push Effective Address (PEA) instruction

Background 2 uses a Load Indirect Indexed (LDA ($00),y) instruction followed by a push (PHA)

Animated tiles use a Load Direct Page Indexed (LDA $00,x) instruction followed by a push (PHA)

The critical restriction is that both of the 65816 registers (X and Y) are used to reference data and cannot be modified.  Further the direct page register (D) is set based on the origin of the second background and cannot be changed;  the data bank register is set to the data bank that holds pixel data for the second background and cannot be changed; the stack pointer (S) is mapped to graphics screen, so there is no possibility of jumping to a subroutine and returning.

Given these restrictions, I had the need to quickly handle cases where a word that is about to be pushed onto the stack is mixed, i.e. half comes from Background 1 and half from Background 2.  My solution was to trade memory for speed.  Because all of the normal registers were in use, I only had the Program Counter (PC) register to work with.  My solution was the following:

Define a code fragment to do the blend in the same 64K program bank as the code buffer

Create a copy of this code for each of the 82 words

There is a 1-1 correspondence, so the return from the code fragment can be a hard-coded address

Done! We have a hard-coded subroutine that does not affect the CPU registers.

Here is the actual code fragments

```<code>code_buff:   PEA $0000            ; rightmost word (16-bits = 4 pixels)
             PEA $0000            ; background 1
             PEA $0000            ; background 1
             PEA $0000            ; background 1
             LDA (72),y           ; background 2
             PHA
             LDA (70),y           ; background 2
             PHA
             JMP word_68          ; mix the data
word_68_rtn: PEA $0000            ; more background 1
             ...
             PEA $0000
             BRA *+40             ; patched exit code

             ...
word_68:     LDA (68),y           ; load data for background 2
             AND #$00FF           ; mask
             ORA #$AB00           ; blend with data from background 1
             PHA
             JMP word_68_rtn      ; jump back
word_66:     LDA (66),y
             ...
</code>```

The end result was a near-optimal blitter that has minimal overhead and cranks out more than 15 frames per second at 320x200 on a 2.5 MHz CPU with a 1 MB/s memory bus.

OwnerDisplayName: TraumaPony

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: anon

Body:
I wrote a tile-based game engine for the Apple IIgs in 65816 assembly language a few years ago.  This was a fairly slow machine and programming "on the metal" is a virtual requirement for coaxing out acceptable performance.

In order to quickly update the graphics screen one has to map the stack to the screen in order to use some special instructions that allow one to update 4 screen pixels in only 5 machine cycles.  This is nothing particularly fantastic and is described in detail in IIgs Tech Note #70. The hard-core bit was how I had to organize the code to make it flexible enough to be a general-purpose library while still maintaining maximum speed.

I decomposed the graphics screen into scan lines and created a 246 byte code buffer to insert the specialized 65816 opcodes. The 246 bytes are needed because each scan line of the graphics screen is 80 words wide and 1 additional word is required on each end for smooth scrolling.  The Push Effective Address (PEA) instruction takes up 3 bytes, so 3 * (80 + 1 + 1) = 246 bytes.

The graphics screen is rendered by jumping to an address within the 246 byte code buffer that corresponds to the right edge of the screen and patching in a BRanch Always (BRA) instruction into the code at the word immediately following the left-most word.  The BRA instruction takes a signed 8-bit offset as its argument, so it just barely has the range to jump out of the code buffer.

Even this isn't too terribly difficult, but the real hard-core optimization comes in here.  My graphics engine actually supported two independent background layers and animated tiles by using different 3-byte code sequences depending on the mode:

Background 1 uses a Push Effective Address (PEA) instruction

Background 2 uses a Load Indirect Indexed (LDA ($00),y) instruction followed by a push (PHA)

Animated tiles use a Load Direct Page Indexed (LDA $00,x) instruction followed by a push (PHA)

The critical restriction is that both of the 65816 registers (X and Y) are used to reference data and cannot be modified.  Further the direct page register (D) is set based on the origin of the second background and cannot be changed;  the data bank register is set to the data bank that holds pixel data for the second background and cannot be changed; the stack pointer (S) is mapped to graphics screen, so there is no possibility of jumping to a subroutine and returning.

Given these restrictions, I had the need to quickly handle cases where a word that is about to be pushed onto the stack is mixed, i.e. half comes from Background 1 and half from Background 2.  My solution was to trade memory for speed.  Because all of the normal registers were in use, I only had the Program Counter (PC) register to work with.  My solution was the following:

Define a code fragment to do the blend in the same 64K program bank as the code buffer

Create a copy of this code for each of the 82 words

There is a 1-1 correspondence, so the return from the code fragment can be a hard-coded address

Done! We have a hard-coded subroutine that does not affect the CPU registers.

Here is the actual code fragments

code_buff:   PEA $0000            ; rightmost word (16-bits = 4 pixels)
             PEA $0000            ; background 1
             PEA $0000            ; background 1
             PEA $0000            ; background 1
             LDA (72),y           ; background 2
             PHA
             LDA (70),y           ; background 2
             PHA
             JMP word_68          ; mix the data
word_68_rtn: PEA $0000            ; more background 1
             ...
             PEA $0000
             BRA *+40             ; patched exit code

             ...
word_68:     LDA (68),y           ; load data for background 2
             AND #$00FF           ; mask
             ORA #$AB00           ; blend with data from background 1
             PHA
             JMP word_68_rtn      ; jump back
word_66:     LDA (66),y
             ...

The end result was a near-optimal blitter that has minimal overhead and cranks out more than 15 frames per second at 320x200 on a 2.5 MHz CPU with a 1 MB/s memory bus.


问:
Apache: Multiple virtual host subdomain for the same server
I would like to redirect all my apps to their urls:

for example:

https://gitlab.example.com -> to gitlab

https://sonarqube.example.com -> to sonarqube

Here is my actual config:

```<code><IfModule mod_ssl.c>
<VirtualHost monitoring.example.com:443>
    ServerName monitoring.example.com

    # Monitoring
    ProxyPass / http://localhost:9089/
    ProxyPassReverse / http://localhost:9089/

SSLEngine on
SSLCertificateFile      /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile   /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>

<VirtualHost sonarqube.example.com:443>
    ServerName sonarqube.example.com

    # Sonarqube
    ProxyPass / http://localhost:90000/
    ProxyPassReverse / http://localhost:90000/

SSLEngine on
SSLCertificateFile      /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile   /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>

<VirtualHost *:443>
        ServerName example.com

        DocumentRoot /var/www/html

        ErrorLog /var/log/apache2/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog /var/log/apache2/access.log combined

        SSLEngine on
        SSLCertificateFile      /etc/letsencrypt/live/example.com/fullchain.pem
        SSLCertificateKeyFile   /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>
</IfModule>
</code>```

But there problem is that if I go to another subdomain (ex: test.example.com) it will redirect to my monitoring.example.com whereas it should only redirect to DocumentRoot...

How can I segment my virtualHost based on subdomain?

答:
Finally it seems that I don't have to put

```<code><VirtualHost monitoring.example.com:443>
</code>```

but I need to put

```<code><VirtualHost *:443>
</code>```

The ServerName will make it works!

Body:
I would like to redirect all my apps to their urls:

for example:

https://gitlab.example.com -> to gitlab

https://sonarqube.example.com -> to sonarqube

Here is my actual config:

<IfModule mod_ssl.c>
<VirtualHost monitoring.example.com:443>
    ServerName monitoring.example.com

    # Monitoring
    ProxyPass / http://localhost:9089/
    ProxyPassReverse / http://localhost:9089/

SSLEngine on
SSLCertificateFile      /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile   /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>

<VirtualHost sonarqube.example.com:443>
    ServerName sonarqube.example.com

    # Sonarqube
    ProxyPass / http://localhost:90000/
    ProxyPassReverse / http://localhost:90000/

SSLEngine on
SSLCertificateFile      /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile   /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>

<VirtualHost *:443>
        ServerName example.com

        DocumentRoot /var/www/html

        ErrorLog /var/log/apache2/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog /var/log/apache2/access.log combined

        SSLEngine on
        SSLCertificateFile      /etc/letsencrypt/live/example.com/fullchain.pem
        SSLCertificateKeyFile   /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>
</IfModule>

But there problem is that if I go to another subdomain (ex: test.example.com) it will redirect to my monitoring.example.com whereas it should only redirect to DocumentRoot...

How can I segment my virtualHost based on subdomain?

Body:
Finally it seems that I don't have to put

<VirtualHost monitoring.example.com:443>

but I need to put

<VirtualHost *:443>

The ServerName will make it works!


问:
Tabling in Prolog, when are values stored?
So let's say I have this code that uses a table to take 'note' of previous solutions or answers.

```<code>first_rule:-
   doSomething,
   recursive_call(A,B,C). %where A and B are lists of character codes

:- table recursive_call(_,_,min).

recursive_call([],B,C):- doSomething.
recursive_call(A,[],C):- doSomething.
</code>```

My question is, are the values being 'stored' or 'cached' into the table each time recursive_call is called?

Note (just to add more context to this code in case it might help): This is actually a snippet code of edit distance algorithm implementation in Prolog. So the purpose of :- table recursive_call(_,_,min) is to add the solutions or answers into the table while keeping the minimum value.

答:
I think the following program helps to understand when a table is updated.

```<code>% This predicate shows updates that are triggered by the query.

show_updates :-
    abolish_all_tables,
    nl,
    cost(a, e, _),
    show_table(cost/3).

% This predicate shows the current state of a table.

show_table(Name/Arity) :-
    writeln('-- table --'),
    functor(Term, Name, Arity),
    forall( ( get_calls(Term, Trie, Return),
              get_returns(Trie, Return) ),
            writeln(Term)),
    writeln('-----------\n').

% This predicate is called each time a new solution cost must be
% compared with a previous one. It selects the minimum cost and informs
% whether the table should be updated or not.

mincost(Old, New, Min) :-
    Min is min(Old, New),
    show_table(cost/3),
    compare(R, New, Old),
    format('new_cost(~w) ~w previous_cost(~w) => ', [New, R, Old]),
    ( New < Old -> format('update with ~w\n\n', [New])
    ;          format('don\'t update\n\n', []) ).

%          B
%       ^  |  \
%      /   |   \
%     3    4    6
%    /     |     \
%   /      v      v
% A --8--> C --1--> E
%   \      ^      ^
%    \     |     /
%     7    5    9
%      \   |   /
%       v  |  /
%          D

:- table cost(_, _, lattice(mincost/3)).

link(a, b, 3).
link(a, c, 8).
link(a, d, 7).
link(b, c, 4).
link(b, e, 6).
link(c, e, 1).
link(d, c, 5).
link(d, e, 9).

cost(U, W, C) :- link(U, W, C).
cost(U, W, C) :- link(U, V, Cuv), cost(V, W, Cvw), C is Cuv + Cvw.
</code>```

Execution result:

```<code>?- show_updates.

-- table --
cost(c,e,1)
cost(b,e,6)
-----------

new_cost(5) < previous_cost(6) => update with 5

-- table --
cost(c,e,1)
cost(a,e,8)
cost(b,e,5)
-----------

new_cost(9) > previous_cost(8) => don't update

-- table --
cost(d,e,9)
cost(c,e,1)
cost(a,e,8)
cost(b,e,5)
-----------

new_cost(6) < previous_cost(9) => update with 6

-- table --
cost(d,e,6)
cost(c,e,1)
cost(a,e,8)
cost(b,e,5)
-----------

new_cost(13) > previous_cost(8) => don't update

-- table --
cost(d,e,6)
cost(c,e,1)
cost(a,e,8)
cost(b,e,5)
-----------

true.
</code>```

Body:
So let's say I have this code that uses a table to take 'note' of previous solutions or answers.

first_rule:-
   doSomething,
   recursive_call(A,B,C). %where A and B are lists of character codes

:- table recursive_call(_,_,min).

recursive_call([],B,C):- doSomething.
recursive_call(A,[],C):- doSomething.

My question is, are the values being 'stored' or 'cached' into the table each time recursive_call is called?

Note (just to add more context to this code in case it might help): This is actually a snippet code of edit distance algorithm implementation in Prolog. So the purpose of :- table recursive_call(_,_,min) is to add the solutions or answers into the table while keeping the minimum value.

Body:
I think the following program helps to understand when a table is updated.

% This predicate shows updates that are triggered by the query.

show_updates :-
    abolish_all_tables,
    nl,
    cost(a, e, _),
    show_table(cost/3).

% This predicate shows the current state of a table.

show_table(Name/Arity) :-
    writeln('-- table --'),
    functor(Term, Name, Arity),
    forall( ( get_calls(Term, Trie, Return),
              get_returns(Trie, Return) ),
            writeln(Term)),
    writeln('-----------\n').

% This predicate is called each time a new solution cost must be
% compared with a previous one. It selects the minimum cost and informs
% whether the table should be updated or not.

mincost(Old, New, Min) :-
    Min is min(Old, New),
    show_table(cost/3),
    compare(R, New, Old),
    format('new_cost(~w) ~w previous_cost(~w) => ', [New, R, Old]),
    ( New < Old -> format('update with ~w\n\n', [New])
    ;          format('don\'t update\n\n', []) ).

%          B
%       ^  |  \
%      /   |   \
%     3    4    6
%    /     |     \
%   /      v      v
% A --8--> C --1--> E
%   \      ^      ^
%    \     |     /
%     7    5    9
%      \   |   /
%       v  |  /
%          D

:- table cost(_, _, lattice(mincost/3)).

link(a, b, 3).
link(a, c, 8).
link(a, d, 7).
link(b, c, 4).
link(b, e, 6).
link(c, e, 1).
link(d, c, 5).
link(d, e, 9).

cost(U, W, C) :- link(U, W, C).
cost(U, W, C) :- link(U, V, Cuv), cost(V, W, Cvw), C is Cuv + Cvw.

Execution result:

?- show_updates.

-- table --
cost(c,e,1)
cost(b,e,6)
-----------

new_cost(5) < previous_cost(6) => update with 5

-- table --
cost(c,e,1)
cost(a,e,8)
cost(b,e,5)
-----------

new_cost(9) > previous_cost(8) => don't update

-- table --
cost(d,e,9)
cost(c,e,1)
cost(a,e,8)
cost(b,e,5)
-----------

new_cost(6) < previous_cost(9) => update with 6

-- table --
cost(d,e,6)
cost(c,e,1)
cost(a,e,8)
cost(b,e,5)
-----------

new_cost(13) > previous_cost(8) => don't update

-- table --
cost(d,e,6)
cost(c,e,1)
cost(a,e,8)
cost(b,e,5)
-----------

true.


问:
Unable to return variable from one function and use it in another function
I am attempting to return a list of coins from one function to another, then split it and sum the results. I'm trying to return one list from a function, then use it in the next. I put the list in as a positional argument in the main function, but it says it isn't defined. I have a return statement in the function, so I'm not sure what's wrong.</p>
```<code>import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']

#Controls all other functions
def main():

    choose_coins()
    coin_tokens = choose_coins()

#Choose the number and type of coins
def choose_coins():

    coin_tokens = []

    #List of coins to pick from
    coin_list = ['Penny', 'Nickel', 'Dime', 'Quarter']

    #Choose the number of coins
    num_coins = random.randint(2,4)

    #Add chosen coins to a list
    for i in range(num_coins):

        coins_to_be_counted = random.choice(coin_list)

        coin_tokens.append(coins_to_be_counted)

    print(coin_tokens)

    return coin_tokens

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):

    #Iterate through coin_tokens list
    for i in coin_tokens:

        if token == 'Penny':
            coin_total += 1

        elif token == 'Nickel':
            coin_total += 5

        elif token == 'Dime':
            coin_total += 10

        elif token == 'Quarter':
            coin_total += 25

        coin_total = 0

    print(coin_total)

#Starts the Program
if __name__ == "__main__":
    main()
</code>```

答:
You have made a lot of minor errors. For instance, using 'i' in the for loop but checking condition on a undefined variable 'token', calling a function with return value and not assigning a variable for it.

Please check the following code. I have made a changes, it should work now.

```<code>import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']

#Controls all other functions
def main():

    coins = choose_coins()
    add_coins(coins)

#Choose the number and type of coins
def choose_coins():
    coin_tokens = []
    #List of coins to pick from
    coin_list = ['Penny', 'Nickel', 'Dime', 'Quarter']
    #Choose the number of coins
    num_coins = random.randint(2,4)
    #Add chosen coins to a list
    for i in range(num_coins):
        coins_to_be_counted = random.choice(coin_list)
        coin_tokens.append(coins_to_be_counted)
    print(coin_tokens)

    return coin_tokens

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):
    coin_total = 0
    for token in coin_tokens:
        if token == 'Penny':
            coin_total += 1
        elif token == 'Nickel':
            coin_total += 5
        elif token == 'Dime':
            coin_total += 10
        elif token == 'Quarter':
            coin_total += 25

    print(coin_total)

#Starts the Program
if __name__ == "__main__":
    main()
</code>```

Body:
I am attempting to return a list of coins from one function to another, then split it and sum the results. I'm trying to return one list from a function, then use it in the next. I put the list in as a positional argument in the main function, but it says it isn't defined. I have a return statement in the function, so I'm not sure what's wrong.

import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']

#Controls all other functions
def main():

    choose_coins()
    coin_tokens = choose_coins()

#Choose the number and type of coins
def choose_coins():

    coin_tokens = []

    #List of coins to pick from
    coin_list = ['Penny', 'Nickel', 'Dime', 'Quarter']

    #Choose the number of coins
    num_coins = random.randint(2,4)

    #Add chosen coins to a list
    for i in range(num_coins):

        coins_to_be_counted = random.choice(coin_list)

        coin_tokens.append(coins_to_be_counted)

    print(coin_tokens)

    return coin_tokens

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):

    #Iterate through coin_tokens list
    for i in coin_tokens:

        if token == 'Penny':
            coin_total += 1

        elif token == 'Nickel':
            coin_total += 5

        elif token == 'Dime':
            coin_total += 10

        elif token == 'Quarter':
            coin_total += 25

        coin_total = 0

    print(coin_total)

#Starts the Program
if __name__ == "__main__":
    main()

Body:
You have made a lot of minor errors. For instance, using 'i' in the for loop but checking condition on a undefined variable 'token', calling a function with return value and not assigning a variable for it.

Please check the following code. I have made a changes, it should work now.

import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']

#Controls all other functions
def main():

    coins = choose_coins()
    add_coins(coins)

#Choose the number and type of coins
def choose_coins():
    coin_tokens = []
    #List of coins to pick from
    coin_list = ['Penny', 'Nickel', 'Dime', 'Quarter']
    #Choose the number of coins
    num_coins = random.randint(2,4)
    #Add chosen coins to a list
    for i in range(num_coins):
        coins_to_be_counted = random.choice(coin_list)
        coin_tokens.append(coins_to_be_counted)
    print(coin_tokens)

    return coin_tokens

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):
    coin_total = 0
    for token in coin_tokens:
        if token == 'Penny':
            coin_total += 1
        elif token == 'Nickel':
            coin_total += 5
        elif token == 'Dime':
            coin_total += 10
        elif token == 'Quarter':
            coin_total += 25

    print(coin_total)

#Starts the Program
if __name__ == "__main__":
    main()