问:
Warning: React has detected a change in the order of Hooks called by Table
I'm creating a simple table that collects data from json and displays the info in the table.

In the table I also have a highlighted background for people with over 100 score. And a button to change their colours.

I have wrapped the colour changing as a context provider.

When my table renders I get this error message in console.

```<code>react-dom.development.js:51 Warning: React has detected a change in the order of Hooks called by Table. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks

   Previous render            Next render
   ------------------------------------------------------
1. useContext                 useContext
2. useState                   useState
3. useState                   useState
4. useState                   useState
5. useEffect                  useEffect
6. undefined                  useContext
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    at Table (http://localhost:3001/static/js/bundle.js:447:71)
    at ColorContextProvider (http://localhost:3001/static/js/bundle.js:207:5)
    at App
</code>```

Below is the code:

import CheckScore from "./checkScore";
import { useEffect, useState } from "react";
import { useColorContext } from "./contexts/Color";

export const Table = () => {
  const { setHighlightingColor } = useColorContext();

  const [users, setUsers] = useState([]);
  const [total2, setTotal2] = useState(0);
  const [average2, setAverage2] = useState(0);

  useEffect(() => {
    fetch("../players.json")
      .then((r) => r.json())
      .then((parsedData) => {
        const totalPoints = parsedData
          .map((player) => {
            return player.points;
          })
          .reduce((prevValue, curValue) => {
            return prevValue + curValue;
          });
        setUsers(parsedData);
        setTotal2(totalPoints);
        const averagePoints = total2 / parsedData.length;
        setAverage2(averagePoints);
      })
      .catch((err) => {
        console.log(err);
      });
  });

  return (
    <>

          <button onClick={() => setHighlightingColor("red")}>Red</button>
          <button onClick={() => setHighlightingColor("blue")}>Blue</button>

              Username

              Points

            {users.map((e) => CheckScore(e.points, e.username))}

              Total
              {total2}

              Average
              {average2}

    </>
  );
};```
</div>
</div>
</p>
<p>And the checkScore code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { ColorContext } from "./contexts/Color";
import { useContext } from "react";

export default function CheckScore(score, player) {
  const { highlightingColor } = useContext(ColorContext);

  return (
    <tr key={player} className={`${score > 100 ? highlightingColor : ""} `}>
      <td>{player}</td>
      <td>{score}</td>
    </tr>
  );
}</code>```

And ColorContext

import { useState, createContext, useContext } from "react";

export const ColorContext = createContext("red");

export const ColorContextProvider = ({ children }) => {
  const [highlightingColor, setHighlightingColor] = useState("red");

  return (
    <ColorContext.Provider value={{ highlightingColor, setHighlightingColor }}>
      {children}
    </ColorContext.Provider>
  );
};

export const useColorContext = () => useContext(ColorContext);```

Any ideas what I'm doing wrong?

答:
TL;DR: The problem is that you call useContext in CheckScore function.

Either way will fix:

Pass highlightingColor as param into CheckScore functiona, and don’t call useContext in it.

{users.map((e) => <CheckScore score={e.points} player={e.username} />)} and change params of function CheckScore(score, player) to function CheckScore({ score, player })

Explanation

You need to make clear distinction between a) “react functional component” and b) “a function that returns react elements”.

CheckScore is qualified as a functional component only when called as <CheckScore />. The way you called it, as a normal function, disqualify it from being a component, and so that useContext call is considered called within the lifespan of
 component.

When users count varies, count of useContext calls varies. As suggested in https://reactjs.org/link/rules-of-hooks, this code will cause trouble.

===

Below is a bug I spot in your code. Not related to your current question but worth noting. Here’s how to fix it. I post as answer because I can’t get proper format in comment.

```<code>    setTotal2(totalPoints);
    - const averagePoints = total2 / parsedData.length;
    + const averagePoints = totalPoints / parsedData.length;
    setAverage2(averagePoints);
</code>```

At the point you calculate averagePoints, total2 != totalPoints. You should use totalPoints instead. Reason being that setState update is async, so total2 is not updated until next render.

Body:
I'm creating a simple table that collects data from json and displays the info in the table.

In the table I also have a highlighted background for people with over 100 score. And a button to change their colours.

I have wrapped the colour changing as a context provider.

When my table renders I get this error message in console.

react-dom.development.js:51 Warning: React has detected a change in the order of Hooks called by Table. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks

   Previous render            Next render
   ------------------------------------------------------
1. useContext                 useContext
2. useState                   useState
3. useState                   useState
4. useState                   useState
5. useEffect                  useEffect
6. undefined                  useContext
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    at Table (http://localhost:3001/static/js/bundle.js:447:71)
    at ColorContextProvider (http://localhost:3001/static/js/bundle.js:207:5)
    at App

Below is the code:

import CheckScore from "./checkScore";
import { useEffect, useState } from "react";
import { useColorContext } from "./contexts/Color";

export const Table = () => {
  const { setHighlightingColor } = useColorContext();

  const [users, setUsers] = useState([]);
  const [total2, setTotal2] = useState(0);
  const [average2, setAverage2] = useState(0);

  useEffect(() => {
    fetch("../players.json")
      .then((r) => r.json())
      .then((parsedData) => {
        const totalPoints = parsedData
          .map((player) => {
            return player.points;
          })
          .reduce((prevValue, curValue) => {
            return prevValue + curValue;
          });
        setUsers(parsedData);
        setTotal2(totalPoints);
        const averagePoints = total2 / parsedData.length;
        setAverage2(averagePoints);
      })
      .catch((err) => {
        console.log(err);
      });
  });

  return (
    <>

          <button onClick={() => setHighlightingColor("red")}>Red</button>
          <button onClick={() => setHighlightingColor("blue")}>Blue</button>

              Username

              Points

            {users.map((e) => CheckScore(e.points, e.username))}

              Total
              {total2}

              Average
              {average2}

    </>
  );
};

And the checkScore code

import { ColorContext } from "./contexts/Color";
import { useContext } from "react";

export default function CheckScore(score, player) {
  const { highlightingColor } = useContext(ColorContext);

  return (
    <tr key={player} className={`${score > 100 ? highlightingColor : ""} `}>
      {player}
      {score}

  );
}

And ColorContext

import { useState, createContext, useContext } from "react";

export const ColorContext = createContext("red");

export const ColorContextProvider = ({ children }) => {
  const [highlightingColor, setHighlightingColor] = useState("red");

  return (
    <ColorContext.Provider value={{ highlightingColor, setHighlightingColor }}>
      {children}
    </ColorContext.Provider>
  );
};

export const useColorContext = () => useContext(ColorContext);

Any ideas what I'm doing wrong?

Body:
TL;DR: The problem is that you call useContext in CheckScore function.

Either way will fix:

Pass highlightingColor as param into CheckScore functiona, and don’t call useContext in it.

{users.map((e) => <CheckScore score={e.points} player={e.username} />)} and change params of function CheckScore(score, player) to function CheckScore({ score, player })

Explanation

You need to make clear distinction between a) “react functional component” and b) “a function that returns react elements”.

CheckScore is qualified as a functional component only when called as <CheckScore />. The way you called it, as a normal function, disqualify it from being a component, and so that useContext call is considered called within the lifespan of <Table /> component.

When users count varies, count of useContext calls varies. As suggested in https://reactjs.org/link/rules-of-hooks, this code will cause trouble.

===

Below is a bug I spot in your code. Not related to your current question but worth noting. Here’s how to fix it. I post as answer because I can’t get proper format in comment.

    setTotal2(totalPoints);
    - const averagePoints = total2 / parsedData.length;
    + const averagePoints = totalPoints / parsedData.length;
    setAverage2(averagePoints);

At the point you calculate averagePoints, total2 != totalPoints. You should use totalPoints instead. Reason being that setState update is async, so total2 is not updated until next render.


来源: stackexchange

问:
Pass model data to javascript function
I have this model @model WebApplication1.Models.Person which has an Id data. I want to pass Id to a javascript function via href="#" onclick=myFunction(idGoesHere)>.

I tried putting @Model.id or passing the value of @Model.id to another variable, but still it doesn't work. Any help would be appreciated.

答:
Your call to your JS function will look like this:

```<code><a href="#" onclick="myFunction('@Model.id')"> </a>
</code>```

This will send the current id in concern to your JS function.

ContentLicense: CC BY-SA 4.0

Title: Pass model data to javascript function

Body:
I have this model @model WebApplication1.Models.Person which has an Id data. I want to pass Id to a javascript function via .

I tried putting @Model.id or passing the value of @Model.id to another variable, but still it doesn't work. Any help would be appreciated.

Body:
Your call to your JS function will look like this:

<a href="#" onclick="myFunction('@Model.id')"> </a>

This will send the current id in concern to your JS function.


问:
Is that possible to make radiobuttons on scrollview
I want to make radio buttons on UIScrollView. When I try to make it on UIView then it works perfectly but when i tried on UIScrollView then the same code will work as checkboxes. So is there any way to make radio buttons on UIScrollView?

I am using this code for scrollview

```<code>for (int i = 0; i < 5; i++) {
        UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
        [but setImage:[UIImage imageNamed:@"emptycheckbox.png"] forState:UIControlStateNormal];
        [but setImage:[UIImage imageNamed:@"checkbox.png"] forState:UIControlStateSelected];
        [but setFrame:CGRectMake(0, 0, 40, 33)];
        [but setCenter:CGPointMake( 50,  i*40+20 )];
        [but addTarget:self action:@selector(checkboxButton:) forControlEvents:UIControlEventTouchUpInside];
        [scrollView addSubview:but];

        scrollView.showsVerticalScrollIndicator = NO;
        [scrollView setContentSize:CGSizeMake(200,1000)];
    }

- (IBAction)checkboxButton:(UIButton *)button{

    for (UIButton *but in [self.view subviews]) {
        if ([but isKindOfClass:[UIButton class]] && ![but isEqual:button]) {
            [but setSelected:NO];
        }
    }
    if (!button.selected) {
        button.selected = !button.selected;
    }
}
</code>```

I an using this code for UIView

```<code>for (int i = 0; i < 5; i++) {
        UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
        [but setImage:[UIImage imageNamed:@"emptycheckbox.png"] forState:UIControlStateNormal];
        [but setImage:[UIImage imageNamed:@"checkbox.png"] forState:UIControlStateSelected];
        [but setFrame:CGRectMake(0, 0, 40, 33)];
        [but setCenter:CGPointMake( 50,  i*40+20 )];
        [but addTarget:self action:@selector(checkboxButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:but];

    }

- (IBAction)checkboxButton:(UIButton *)button{

    for (UIButton *but in [self.view subviews]) {
        if ([but isKindOfClass:[UIButton class]] && ![but isEqual:button]) {
            [but setSelected:NO];
        }
    }
    if (!button.selected) {
        button.selected = !button.selected;
    }
}
</code>```

答:
for scrollview should be:</p>

```<code>for (UIButton *but in [scrollview subviews]) {...

NOT: for (UIButton *but in [self.view subviews]) {...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to make radio buttons on UIScrollView. When I try to make it on UIView then it works perfectly but when i tried on UIScrollView then the same code will work as checkboxes. So is there any way to make radio buttons on UIScrollView?

I am using this code for scrollview

for (int i = 0; i < 5; i++) {
        UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
        [but setImage:[UIImage imageNamed:@"emptycheckbox.png"] forState:UIControlStateNormal];
        [but setImage:[UIImage imageNamed:@"checkbox.png"] forState:UIControlStateSelected];
        [but setFrame:CGRectMake(0, 0, 40, 33)];
        [but setCenter:CGPointMake( 50,  i*40+20 )];
        [but addTarget:self action:@selector(checkboxButton:) forControlEvents:UIControlEventTouchUpInside];
        [scrollView addSubview:but];

        scrollView.showsVerticalScrollIndicator = NO;
        [scrollView setContentSize:CGSizeMake(200,1000)];
    }

- (IBAction)checkboxButton:(UIButton *)button{

    for (UIButton *but in [self.view subviews]) {
        if ([but isKindOfClass:[UIButton class]] && ![but isEqual:button]) {
            [but setSelected:NO];
        }
    }
    if (!button.selected) {
        button.selected = !button.selected;
    }
}

I an using this code for UIView

for (int i = 0; i < 5; i++) {
        UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
        [but setImage:[UIImage imageNamed:@"emptycheckbox.png"] forState:UIControlStateNormal];
        [but setImage:[UIImage imageNamed:@"checkbox.png"] forState:UIControlStateSelected];
        [but setFrame:CGRectMake(0, 0, 40, 33)];
        [but setCenter:CGPointMake( 50,  i*40+20 )];
        [but addTarget:self action:@selector(checkboxButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:but];

    }

- (IBAction)checkboxButton:(UIButton *)button{

    for (UIButton *but in [self.view subviews]) {
        if ([but isKindOfClass:[UIButton class]] && ![but isEqual:button]) {
            [but setSelected:NO];
        }
    }
    if (!button.selected) {
        button.selected = !button.selected;
    }
}

Body:
for scrollview should be:

for (UIButton *but in [scrollview subviews]) {...

NOT: for (UIButton *but in [self.view subviews]) {...


问:
Powershell - Scan for multiple strings in multiple files
I am having issues resolving a revision to the script below.
This script will take in a number of key words, either manually added or read from a file.
It will output the data when it finds a match by listing the File Name, Line number and the search word.  Unfortunately if I'm searching for multiple words it has to scan the files for each separate word. That means if I have 20 search words, it will open, scan, close each file 20 times.  Once for each word.
Not good as it takes time and I still have to troll through the output to total how many matches per file.
Every change I make is disastrous as it prints every single search word without knowing what word was the match or worse it fails to run.
Would anyone be able to help me alter the script to scan the files once for ALL the search words and list out only the matches in a readable way like the output below?</p>
```<code>$searchWords="Address", "City","State"
Foreach ($sw in $searchWords)
{
    Get-Childitem -Path "C:\Workspace\src" -Recurse -include "*.cbl" |
    Select-String -Pattern "$sw" |
    Select Path,LineNumber,@{n='SearchWord';e={$sw}}

}
</code>```

答:
-Pattern accepts an array of patterns, and which of those pattern caused a given match can be accessed via the .Pattern property of Select-String's output objects:[1]

Get-Childitem -Path "C:\Workspace\src" -Recurse -include "*.cbl" |
  Select-String -Pattern "Address", "City", "State" |
    Select Path, LineNumber, @{n='SearchWord';e={$_.Pattern}}
```
<p>Note: I'm passing the search words as a literal array here, for brevity; in your code, simply replace <code>"Address", "City", "State"</code> with <code>$searchWords</code> (<em>without</em> enclosure in <code>"..."</code>).</p>
<hr />
<p>As an aside: Using <code>-Filter</code> instead of <code>-Include</code> can speed up your command, and, given that your command arguments don't contains spaces or other metacharacters, <em>quoting</em> them is optional:</p>
<pre class="lang-sh prettyprint-override"><code>Get-Childitem -Path C:\Workspace\src -Recurse -Filter *.cbl |
  Select-String -Pattern Address, City, State |
    Select Path, LineNumber, @{n='SearchWord';e={$_.Pattern}}
</code>```

[1] Note: Only the first among the specified pattern that matches, in the order specified, that matches on a given line is reported as the matching pattern for that line - even if others would match too. Even -AllMatches doesn't change that - it would only report multiple matches per line for that first pattern.

Body:
I am having issues resolving a revision to the script below.
This script will take in a number of key words, either manually added or read from a file.
It will output the data when it finds a match by listing the File Name, Line number and the search word.  Unfortunately if I'm searching for multiple words it has to scan the files for each separate word. That means if I have 20 search words, it will open, scan, close each file 20 times.  Once for each word.
Not good as it takes time and I still have to troll through the output to total how many matches per file.
Every change I make is disastrous as it prints every single search word without knowing what word was the match or worse it fails to run.
Would anyone be able to help me alter the script to scan the files once for ALL the search words and list out only the matches in a readable way like the output below?

$searchWords="Address", "City","State"
Foreach ($sw in $searchWords)
{
    Get-Childitem -Path "C:\Workspace\src" -Recurse -include "*.cbl" |
    Select-String -Pattern "$sw" |
    Select Path,LineNumber,@{n='SearchWord';e={$sw}}

}

Body:
-Pattern accepts an array of patterns, and which of those pattern caused a given match can be accessed via the .Pattern property of Select-String's output objects:[1]

Get-Childitem -Path "C:\Workspace\src" -Recurse -include "*.cbl" |
  Select-String -Pattern "Address", "City", "State" |
    Select Path, LineNumber, @{n='SearchWord';e={$_.Pattern}}

Note: I'm passing the search words as a literal array here, for brevity; in your code, simply replace "Address", "City", "State" with $searchWords (without enclosure in "...").

As an aside: Using -Filter instead of -Include can speed up your command, and, given that your command arguments don't contains spaces or other metacharacters, quoting them is optional:

Get-Childitem -Path C:\Workspace\src -Recurse -Filter *.cbl |
  Select-String -Pattern Address, City, State |
    Select Path, LineNumber, @{n='SearchWord';e={$_.Pattern}}

[1] Note: Only the first among the specified pattern that matches, in the order specified, that matches on a given line is reported as the matching pattern for that line - even if others would match too. Even -AllMatches doesn't change that - it would only report multiple matches per line for that first pattern.


问:
Safely check if public GitHub repo exists in bash without login?

Context

While trying out the answer provided in this question on how to check if a GitHub repository exists using bash, I notice that the command asks for credentials and throws an error if the repository is not found:

```<code>git ls-remote https://github.com/some_git_user/some_non_existing_repo_name -q
Username for 'https://github.com': some_git_user
Password for 'https://some_git_user@github.com':
remote: Repository not found.
fatal: repository 'https://github.com/some_git_user/some_non_existing_repo_name/' not found
(base) somename@somepcname:~$ echo $?
128
</code>```

This answer seems to prevent git from asking credentials.

Issues

Being asked for credentials is fine in other scenarios, so I would prefer to not disable git from asking credentials system-wide. Yet still, I would like the function to run automatically without asking for credentials, as they are not needed for a check to a public repository.

The command yields an error status 128 if it does not find the repository. Instead, I would like to safely check if the repository is found or not, without raising an error. E.g. by producing outputs echo "FOUND" or echo "NOTFOUND".

Question

How can one test if a public GitHub repository exists in bash, without being prompted for credentials, without raising an error?

Details

The user has not provided any ssh-key nor credentials to/in the script.

答:
In order to easily check if a public repository exists on GitHub, you actually need not git nor any credentials: you can make a simple HTTP request to the GitHub REST API.

Proof-of-concept:

#!/usr/bin/env bash
exists_public_github_repo() {
  local user_slash_repo=$1

  if curl -fsS "https://api.github.com/repos/${user_slash_repo}" >/dev/null; then
    printf '%s\n' "The GitHub repo ${user_slash_repo} exists." >&2
    return 0
  else
    printf '%s\n' "Error: no GitHub repo ${user_slash_repo} found." >&2
    return 1
  fi
}

if exists_public_github_repo "ocaml/ocaml"; then
  echo "OK"
fi
```

For more details on the curl command itself and the flags -f, -s, -S I used, you can browse its man page online.

Body:
Context

While trying out the answer provided in this question on how to check if a GitHub repository exists using bash, I notice that the command asks for credentials and throws an error if the repository is not found:

git ls-remote https://github.com/some_git_user/some_non_existing_repo_name -q
Username for 'https://github.com': some_git_user
Password for 'https://some_git_user@github.com':
remote: Repository not found.
fatal: repository 'https://github.com/some_git_user/some_non_existing_repo_name/' not found
(base) somename@somepcname:~$ echo $?
128

This answer seems to prevent git from asking credentials.

Issues

Being asked for credentials is fine in other scenarios, so I would prefer to not disable git from asking credentials system-wide. Yet still, I would like the function to run automatically without asking for credentials, as they are not needed for a check to a public repository.

The command yields an error status 128 if it does not find the repository. Instead, I would like to safely check if the repository is found or not, without raising an error. E.g. by producing outputs echo "FOUND" or echo "NOTFOUND".

Question

How can one test if a public GitHub repository exists in bash, without being prompted for credentials, without raising an error?

Details

The user has not provided any ssh-key nor credentials to/in the script.

Body:
In order to easily check if a public repository exists on GitHub, you actually need not git nor any credentials: you can make a simple HTTP request to the GitHub REST API.

Proof-of-concept:

#!/usr/bin/env bash
exists_public_github_repo() {
  local user_slash_repo=$1

  if curl -fsS "https://api.github.com/repos/${user_slash_repo}" >/dev/null; then
    printf '%s\n' "The GitHub repo ${user_slash_repo} exists." >&2
    return 0
  else
    printf '%s\n' "Error: no GitHub repo ${user_slash_repo} found." >&2
    return 1
  fi
}

if exists_public_github_repo "ocaml/ocaml"; then
  echo "OK"
fi

For more details on the curl command itself and the flags -f, -s, -S I used, you can browse its man page online.


问:
Why is my Rails 7 Join Table not being created until I enter console commands?
I created a table for items and a table for jobs. I then created a join table, Items Jobs.

This is my migration for the join table and the models:

```<code>class CreateItemsJobs < ActiveRecord::Migration[7.0]
  def change
    create_table :items_jobs, id: false do |t|
      t.belongs_to :item
      t.belongs_to :job

      t.timestamps
    end
  end
end

class Item < ApplicationRecord
  belongs_to :part
  belongs_to :employee, optional: true

  has_and_belongs_to_many :jobs
end

class Job < ApplicationRecord
  belongs_to :client
  belongs_to :employee

  has_and_belongs_to_many :items
end

class ItemsJobs < ApplicationRecord
    belongs_to :item
    belongs_to :job
end
</code>```

I then migrate successfully...

```<code>rails db:migrate ==>

== 20220210032352 CreateItemsJobs: migrating ==================================
-- create_table(:items_jobs, {:id=>false})
   -> 0.0085s
== 20220210032352 CreateItemsJobs: migrated (0.0086s) =========================
</code>```

But if I try to seed, I get an error. If I run my rails console, I can't add to the table until I attempt to view a table that doesn't exist.

```<code>rails c ==>
Loading development environment (Rails 7.0.1)

2.7.4 :001 > ItemsJobs.all
Traceback (most recent call last):
(irb):1:in `<main>': uninitialized constant ItemsJobs (NameError)
Did you mean?  ItemJob

2.7.4 :002 > ItemJob.all
Traceback (most recent call last):
(irb):2:in `<main>': uninitialized constant ItemJob (NameError)
Did you mean?  ItemsJobs

2.7.4 :003 > ItemsJobs.all
  ItemsJobs Load (0.4ms)  SELECT "items_jobs".* FROM "items_jobs"
 => []

2.7.4 :004 > ItemsJobs.create(item_id: 1, job_id: 1)
  TRANSACTION (0.2ms)  BEGIN1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Job Load (0.3ms)  SELECT "jobs".* FROM "jobs" WHERE "jobs"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ItemsJobs Create (0.6ms)  INSERT INTO "items_jobs" ("item_id", "job_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4)  [["item_id", 1], ["job_id", 1], ["created_at", "2022-02-10 15:23:44.127164"], ["updated_at", "2022-02-10 15:23:44.127164"]]
  TRANSACTION (1.1ms)  COMMIT
 =>
#<ItemsJobs:0x00007f33c0aa7a80
 item_id: 1,
 job_id: 1,
 created_at: Thu, 10 Feb 2022 15:23:44.127164000 UTC +00:00,
 updated_at: Thu, 10 Feb 2022 15:23:44.127164000 UTC +00:00>
</code>```

What is going wrong here? Why can't I view/add to the ItemsJobs table until I've attempted to view the suggested, non-existent ItemJob table?

答:
You're mixing up has_and_belongs_to_many and has_many through: and the weird autoloading behavior is most likely because the naming scheme is throwing off how ActiveRecord maps classes to database tables through convention over configuration. The rule of thumb is that ActiveRecord expects models (class names) to be singular and tables to be plural.

HABTM assocations don't use a model for the join table. Rather its just a "headless" assocation where you just implicitly add/remove rows through the assocations on each end. HABTM is really only good for the case where you know that you won't need to query the table directly or access any additional columns - in other words it's quite useless outside of that niche. HABTM is the only place in ActiveRecord where you use the plural_plural naming scheme for tables - using that scheme with a model will cause constant lookup errors unless you explicitly configure everything.

If you want to setup an assocation with a join model (I would recommend this) you need to name the class and tables correctly and use an indirect assocation:

```<code>class CreateItemJobs < ActiveRecord::Migration[7.0]
  def change
    # table name should be singular_plural
    create_table :item_jobs do |t|
      t.belongs_to :item
      t.belongs_to :job
      t.timestamps
    end
  end
end

# model class names should always be singular
class ItemJob < ApplicationRecord
  belongs_to :item
  belongs_to :job
end

class Item < ApplicationRecord
  belongs_to :part
  belongs_to :employee, optional: true
  has_many :item_jobs
  has_many :jobs, through: :item_jobs
end

class Job < ApplicationRecord
  belongs_to :client
  belongs_to :employee
  has_many :item_jobs
  has_many :items, through: :item_jobs
end
</code>```

Since you probally haven't run the migration in production and don't have any meaningful data in the table you can roll the bad CreateItemsJobs migration back and delete it. rails g model ItemJob item:belongs_to job:belongs_to will create both the model and migration.

See:

https://guides.rubyonrails.org/active_record_basics.html#convention-over-configuration-in-active-record

https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Body:
I created a table for items and a table for jobs. I then created a join table, Items Jobs.

This is my migration for the join table and the models:

class CreateItemsJobs < ActiveRecord::Migration[7.0]
  def change
    create_table :items_jobs, id: false do |t|
      t.belongs_to :item
      t.belongs_to :job

      t.timestamps
    end
  end
end

class Item < ApplicationRecord
  belongs_to :part
  belongs_to :employee, optional: true

  has_and_belongs_to_many :jobs
end

class Job < ApplicationRecord
  belongs_to :client
  belongs_to :employee

  has_and_belongs_to_many :items
end

class ItemsJobs < ApplicationRecord
    belongs_to :item
    belongs_to :job
end

I then migrate successfully...

rails db:migrate ==>

== 20220210032352 CreateItemsJobs: migrating ==================================
-- create_table(:items_jobs, {:id=>false})
   -> 0.0085s
== 20220210032352 CreateItemsJobs: migrated (0.0086s) =========================

But if I try to seed, I get an error. If I run my rails console, I can't add to the table until I attempt to view a table that doesn't exist.

rails c ==>
Loading development environment (Rails 7.0.1)

2.7.4 :001 > ItemsJobs.all
Traceback (most recent call last):
(irb):1:in `': uninitialized constant ItemsJobs (NameError)
Did you mean?  ItemJob

2.7.4 :002 > ItemJob.all
Traceback (most recent call last):
(irb):2:in `': uninitialized constant ItemJob (NameError)
Did you mean?  ItemsJobs

2.7.4 :003 > ItemsJobs.all
  ItemsJobs Load (0.4ms)  SELECT "items_jobs".* FROM "items_jobs"
 => []

2.7.4 :004 > ItemsJobs.create(item_id: 1, job_id: 1)
  TRANSACTION (0.2ms)  BEGIN1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Job Load (0.3ms)  SELECT "jobs".* FROM "jobs" WHERE "jobs"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ItemsJobs Create (0.6ms)  INSERT INTO "items_jobs" ("item_id", "job_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4)  [["item_id", 1], ["job_id", 1], ["created_at", "2022-02-10 15:23:44.127164"], ["updated_at", "2022-02-10 15:23:44.127164"]]
  TRANSACTION (1.1ms)  COMMIT
 =>
#<ItemsJobs:0x00007f33c0aa7a80
 item_id: 1,
 job_id: 1,
 created_at: Thu, 10 Feb 2022 15:23:44.127164000 UTC +00:00,
 updated_at: Thu, 10 Feb 2022 15:23:44.127164000 UTC +00:00>

What is going wrong here? Why can't I view/add to the ItemsJobs table until I've attempted to view the suggested, non-existent ItemJob table?

Body:
You're mixing up has_and_belongs_to_many and has_many through: and the weird autoloading behavior is most likely because the naming scheme is throwing off how ActiveRecord maps classes to database tables through convention over configuration. The rule of thumb is that ActiveRecord expects models (class names) to be singular and tables to be plural.

HABTM assocations don't use a model for the join table. Rather its just a "headless" assocation where you just implicitly add/remove rows through the assocations on each end. HABTM is really only good for the case where you know that you won't need to query the table directly or access any additional columns - in other words it's quite useless outside of that niche. HABTM is the only place in ActiveRecord where you use the plural_plural naming scheme for tables - using that scheme with a model will cause constant lookup errors unless you explicitly configure everything.

If you want to setup an assocation with a join model (I would recommend this) you need to name the class and tables correctly and use an indirect assocation:

class CreateItemJobs < ActiveRecord::Migration[7.0]
  def change
    # table name should be singular_plural
    create_table :item_jobs do |t|
      t.belongs_to :item
      t.belongs_to :job
      t.timestamps
    end
  end
end

# model class names should always be singular
class ItemJob < ApplicationRecord
  belongs_to :item
  belongs_to :job
end

class Item < ApplicationRecord
  belongs_to :part
  belongs_to :employee, optional: true
  has_many :item_jobs
  has_many :jobs, through: :item_jobs
end

class Job < ApplicationRecord
  belongs_to :client
  belongs_to :employee
  has_many :item_jobs
  has_many :items, through: :item_jobs
end

Since you probally haven't run the migration in production and don't have any meaningful data in the table you can roll the bad CreateItemsJobs migration back and delete it. rails g model ItemJob item:belongs_to job:belongs_to will create both the model and migration.

See:

https://guides.rubyonrails.org/active_record_basics.html#convention-over-configuration-in-active-record

https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association


问:
How to make sure background fills the whole flex row which overflows?
How to make sure that background-color fills the whole flex row which overflows to the right? Currently, it only fills a portion of it that fits on the screen.

Here's an example:

main {
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: white;
  overflow-x: scroll;
}

.wrapper {
  display: flex;
  flex-direction: row;
}
.wrapper:hover {
  background-color: rgba(0, 0, 0, 0.5);
}
.content {
  min-width: 150px;
  min-height: 20px;
  padding: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
</main></code>```

答:
You can set a width to any .content(e.g: width:30%) then set width: 180% to .wrapper. since you have 6 div tag in the any wrapper:

main {
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: white;
  overflow-x: scroll;
  }

.wrapper {
  display: flex;
  flex-direction: row;
  width: 180%;
  border: 1px solid red;

}
.wrapper:hover {
  background-color: rgba(0, 0, 0, 0.5);
}
.content {
  width: 30%;
  min-height: 20px;
  padding: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
</main></code>```

Body:
How to make sure that background-color fills the whole flex row which overflows to the right? Currently, it only fills a portion of it that fits on the screen.

Here's an example:

main {
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: white;
  overflow-x: scroll;
}

.wrapper {
  display: flex;
  flex-direction: row;
}
.wrapper:hover {
  background-color: rgba(0, 0, 0, 0.5);
}
.content {
  min-width: 150px;
  min-height: 20px;
  padding: 20px;
}

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Body:
You can set a width to any .content(e.g: width:30%) then set width: 180% to .wrapper. since you have 6 div tag in the any wrapper:

main {
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: white;
  overflow-x: scroll;
  }

.wrapper {
  display: flex;
  flex-direction: row;
  width: 180%;
  border: 1px solid red;

}
.wrapper:hover {
  background-color: rgba(0, 0, 0, 0.5);
}
.content {
  width: 30%;
  min-height: 20px;
  padding: 20px;
}

<main>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
</main>


问:
Wix Installer - Customize MsiRMFilesInUse dialog box
I was trying to change the default MsiRMFilesInUse dialog box provided by restart manager used in wix toolset. Basically I want to localize the default message in the dialog box since it is not getting localized by windows.

I found this answer (https://stackoverflow.com/a/46462452/14162315) which explains the steps of making the custom dialog box instead of normal one. A custom dialog box could help me in localizing the message.

I tried the above steps but I am getting the error - Duplicate symbol 'Property:WixUIRMOption' found. This typically means that an Id is duplicated. Check to make sure all your identifiers of a given type (File, Component, Feature) are unique.

I thought that I have to change the property id of WixUIRMOption also to some custom value to mitigate the error, so I changed it to Custom_WixUIRMOption. It compiled successfully after this change but the dialog box is not coming at all after this change.

link to source code of default MsiRMFilesInUse.wxs - https://github.com/AnalogJ/Wix3.6Toolset/blob/master/RC0-source/wix36-sources/src/ext/UIExtension/wixlib/MsiRMFilesInUse.wxs

答:
you should be fine if you provide a localization for MsiRMFilesInUseText.

```<code><String Id="MsiRMFilesInUseText" Overridable="yes">Translated text</String>
</code>```

See how the dialog is implemented:
https://github.com/wixtoolset/wix3/blob/develop/src/ext/UIExtension/wixlib/MsiRMFilesInUse.wxs

See how wix ui is translated:
https://github.com/wixtoolset/wix3/blob/develop/src/ext/UIExtension/wixlib/WixUI_en-us.wxl

Body:
you should be fine if you provide a localization for MsiRMFilesInUseText.

<String Id="MsiRMFilesInUseText" Overridable="yes">Translated text</String>

See how the dialog is implemented:
https://github.com/wixtoolset/wix3/blob/develop/src/ext/UIExtension/wixlib/MsiRMFilesInUse.wxs

See how wix ui is translated:
https://github.com/wixtoolset/wix3/blob/develop/src/ext/UIExtension/wixlib/WixUI_en-us.wxl


问:
How to reverse a negative Number in JavaScript?
I am trying to get the output in this way, unfortunately, it isn't return expected value...

function reverseInt(int){
    let intRev ="";
    for(let i= 0; i<int.length; i++){
        intRev = int[i]+intRev ;
    }
    return intRev ;
}
console.log(reverseInt("-12345"));```

答:
function reverseInt(n) {
    const isNegativeNumber = Boolean(n < 0)
    const reversedStringifiedNumber = n.toString().split('').reverse().join('')

    return parseInt(`${isNegativeNumber ? '-' : ''}${reversedStringifiedNumber}`)
}

console.log(reverseInt(1234))
console.log(reverseInt(-1234))
console.log(reverseInt(0))
console.log(reverseInt(-0))```


问:
How do API work with CORS policies to serve multiple apps
I am creating an API that would serve data to my frontend app. The API is on api.myapp.com and the app on www.myapp.com (same domain, just another subdomain). They communicate with AJAX requests and CORS is all set up, working fine.

But I have another app on another domain (www.myotherapp.com) which partialy uses the same data as myapp, so I was thinking of reusing the API so myotherapp could requests data from it too.

I think it is one use case of API, to be reusable, right?

But then, there is something that I may have missed, because as my API has CORS enabled with "Access-Control-Allow-Origin: www.myapp.com", it won't allow other apps to use its endpoints, right? Their AJAX requests would fail with CORS policies.

So how are public API built and configured? How should I set my API so it can serve several apps (ideally, only the ones I allow)?

Thanks for the explanations :)

答:
There is an Origin header in the request and your API should check if this header is one of the allowed. If it is, then return it as an Access-Control-Allow-Origin header.

If the API is public, it can returns * as Access-Control-Allow-Origin header.


问:
Pass list as argument in neo4j using Python
I am trying to run this query in which the parameter is a list:

```<code>codes = ["123","234"]
query = graph.run("""
     MATCH (n:NAME)
     where n.codes = "{}"
     RETURN return n.commonName as commonName""".format(codes))
</code>```

I am trying to pass the "codes" as parameter to Neo4j query. This throws an error that "list is not readable in the query"

Any suggestions would be appreciated.

答:
You can use below code that I am using on my testing:</p>
```<code>from py2neo import Graph
session = Graph("http://localhost:7474", auth=("neo4j", "*****"))
//create a dictionary of key:value
param = {"codes":["Angy","Rodney"]}
//use $<dict_key> in your query. For ex: $codes
query = """
     MATCH (n:Customer)
     where n.Name in $codes
     RETURN n"""
//Run the result
result = session.run(query, parameters=param).data()
//Below are my debugging/print to check what is inside the node

print ("What is data type of result? ", type(result))
print ("What is the data type of each item? ", type(result[0]))
print ("What are the keys of the dictionary? ", result[0].keys())
print ("What is the class of the node? ", type(result[0].get('n')))
print ("How to access the first node? ", result[0].get('n'))
print ("How to access values inside the node? ", result[0].get('n',{}).get('Name'))

Result:
What is data type of result?  <class 'list'>
What is the data type of each item?  <class 'dict'>
What are the keys of the dictionary?  dict_keys(['n'])
What is the class of the node?  <class 'py2neo.data.Node'>
How to access the first node?  (_327:Customer {Latitude: 48.509075, Longitude: -2.7383235, Name: 'Angy'})
How to access values inside the node?  Angy
</code>```

Body:
I am trying to run this query in which the parameter is a list:

codes = ["123","234"]
query = graph.run("""
     MATCH (n:NAME)
     where n.codes = "{}"
     RETURN return n.commonName as commonName""".format(codes))

I am trying to pass the "codes" as parameter to Neo4j query. This throws an error that "list is not readable in the query"

Any suggestions would be appreciated.

Body:
You can use below code that I am using on my testing:

from py2neo import Graph
session = Graph("http://localhost:7474", auth=("neo4j", "*****"))
//create a dictionary of key:value
param = {"codes":["Angy","Rodney"]}
//use $<dict_key> in your query. For ex: $codes
query = """
     MATCH (n:Customer)
     where n.Name in $codes
     RETURN n"""
//Run the result
result = session.run(query, parameters=param).data()
//Below are my debugging/print to check what is inside the node

print ("What is data type of result? ", type(result))
print ("What is the data type of each item? ", type(result[0]))
print ("What are the keys of the dictionary? ", result[0].keys())
print ("What is the class of the node? ", type(result[0].get('n')))
print ("How to access the first node? ", result[0].get('n'))
print ("How to access values inside the node? ", result[0].get('n',{}).get('Name'))

Result:
What is data type of result?  <class 'list'>
What is the data type of each item?  <class 'dict'>
What are the keys of the dictionary?  dict_keys(['n'])
What is the class of the node?  <class 'py2neo.data.Node'>
How to access the first node?  (_327:Customer {Latitude: 48.509075, Longitude: -2.7383235, Name: 'Angy'})
How to access values inside the node?  Angy


问:
Getting "EHOSTUNREACH" when trying to connect to API using Axios + Express.js
I started playing around with the Philips Hue Bridge API by sending it requests using Postman.  I was able to authenticate myself, create a user and even successfully turn lights on or off.
Conclusion: I am able to reach the API.

Next I made a mini test javascript file to do the exact same using Node.js and axios@0.21.4. When I try the following code everything works and I receive the expected JSON responses:

```<code>const axios = require('axios')

axios({
    method: 'GET',
    url: 'http://philips-hue.local/api/BYLCIlxABzz2eDHAxx70T'
})
    .then(({data}) => {
        console.log('------> AXIOS RES: ', data)
    })
    .catch((err) => {
        console.log('------> AXIOS ERR: ', err)
    })
</code>```

Conclusion: Axios is able to communicate with the API.

Next I wanted to build this into an Express.js endpoint.  However when I try to use the same code inside of express@4.17.1 I get an error:

```<code>router.route('/getlights').get((req, res) => {
    axios({
        method: 'GET',
        url: 'http://philips-hue.local/api/BYLCIlxABzz2eDHAxx70T/lights'
        })
        .then(({data}) => {
            console.log('------> AXIOS RES: ', data)
            res.json({
                state: 'SUCCESS',
                data
            })
        })
        .catch((err) => {
            console.log('------> AXIOS ERR: ', err)
            res.json({
                state: 'ERROR',
                err
            })
        })
})
</code>```

Response:

```<code>{
    "state": "ERROR",
    "err": {
        "message": "connect EHOSTUNREACH 192.168.0.107:80",
        "name": "Error",
        "stack": "Error: connect EHOSTUNREACH 192.168.0.107:80\n    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16)",
        "config": {
            "url": "http://philips-hue.local/api/BYLCIlxABzz2eDHAxx70T/lights",
            "method": "get",
            "headers": {
                "Accept": "application/json, text/plain, */*",
                "User-Agent": "axios/0.21.1"
            },
            "transformRequest": [
                null
            ],
            "transformResponse": [
                null
            ],
            "timeout": 0,
            "xsrfCookieName": "XSRF-TOKEN",
            "xsrfHeaderName": "X-XSRF-TOKEN",
            "maxContentLength": -1,
            "maxBodyLength": -1
        },
        "code": "EHOSTUNREACH"
    }
}
</code>```

I started troubleshooting the problem by first trying to changing the URL to a random online place holder like http://jsonplaceholder.typicode.com/posts/1 just to see if I could establish any connection at all.  This actually worked right away.

This is where I got really confused.  Why am I able to successfully communicate with the bridge using Postman or Axios in a javascript file, but NOT able to connect with it when the same Axios code is used by express.  The problems seems to occur only when using both axios and express to connect to the bridge API.

I have already tried retesting this with node-fetch and 3 other versions of Axios.  All tests failed the exact same way.  The code by itself can always connect to the API but once the code is being called by express it causes the EHOSTUNREACH error.

I ran out of ideas on how to further google this issue since I am not sure what exactly is causing the problem (express and/or axios and/or bridge).  Any trouble shooting ideas or google keywords are also very welcome. :)

答: I had the same error, for some reason the ip address of my hue bridge had changed so I went into the hue app on my smartphone and copied the new ip address. IDK if this is helpfull, im pretty new here.</p>

Body:
I started playing around with the Philips Hue Bridge API by sending it requests using Postman.  I was able to authenticate myself, create a user and even successfully turn lights on or off.
Conclusion: I am able to reach the API.

Next I made a mini test javascript file to do the exact same using Node.js and axios@0.21.4. When I try the following code everything works and I receive the expected JSON responses:

const axios = require('axios')

axios({
    method: 'GET',
    url: 'http://philips-hue.local/api/BYLCIlxABzz2eDHAxx70T'
})
    .then(({data}) => {
        console.log('------> AXIOS RES: ', data)
    })
    .catch((err) => {
        console.log('------> AXIOS ERR: ', err)
    })

Conclusion: Axios is able to communicate with the API.

Next I wanted to build this into an Express.js endpoint.  However when I try to use the same code inside of express@4.17.1 I get an error:

router.route('/getlights').get((req, res) => {
    axios({
        method: 'GET',
        url: 'http://philips-hue.local/api/BYLCIlxABzz2eDHAxx70T/lights'
        })
        .then(({data}) => {
            console.log('------> AXIOS RES: ', data)
            res.json({
                state: 'SUCCESS',
                data
            })
        })
        .catch((err) => {
            console.log('------> AXIOS ERR: ', err)
            res.json({
                state: 'ERROR',
                err
            })
        })
})

Response:

{
    "state": "ERROR",
    "err": {
        "message": "connect EHOSTUNREACH 192.168.0.107:80",
        "name": "Error",
        "stack": "Error: connect EHOSTUNREACH 192.168.0.107:80\n    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16)",
        "config": {
            "url": "http://philips-hue.local/api/BYLCIlxABzz2eDHAxx70T/lights",
            "method": "get",
            "headers": {
                "Accept": "application/json, text/plain, */*",
                "User-Agent": "axios/0.21.1"
            },
            "transformRequest": [
                null
            ],
            "transformResponse": [
                null
            ],
            "timeout": 0,
            "xsrfCookieName": "XSRF-TOKEN",
            "xsrfHeaderName": "X-XSRF-TOKEN",
            "maxContentLength": -1,
            "maxBodyLength": -1
        },
        "code": "EHOSTUNREACH"
    }
}

I started troubleshooting the problem by first trying to changing the URL to a random online place holder like http://jsonplaceholder.typicode.com/posts/1 just to see if I could establish any connection at all.  This actually worked right away.

This is where I got really confused.  Why am I able to successfully communicate with the bridge using Postman or Axios in a javascript file, but NOT able to connect with it when the same Axios code is used by express.  The problems seems to occur only when using both axios and express to connect to the bridge API.

I have already tried retesting this with node-fetch and 3 other versions of Axios.  All tests failed the exact same way.  The code by itself can always connect to the API but once the code is being called by express it causes the EHOSTUNREACH error.

I ran out of ideas on how to further google this issue since I am not sure what exactly is causing the problem (express and/or axios and/or bridge).  Any trouble shooting ideas or google keywords are also very welcome. :)


问:
How we can insert multiple paragraphs after the insertion of table in google docs using google docs api with PHP?
I am working on google docs api.I want to create a google docs with google docs api using PHP.AS per my requirement I want some paragraphs then insert a table and then again a paragraph as shown in below picture-

I am able to  insert texts like this -

```<code>$requests[] = new Google_Service_Docs_Request(array(
            'insertText' => [
                'text' => 'Paragraph 1',
                'location' => [
                    'index' => 1,
                ]
            ]
        ));
</code>```

I am also able to add table like this-

```<code>$requests [] = new Google_Service_Docs_Request([
    'insertTable' => [
        'rows' =>  4,
        'columns' =>  4,
        'endOfSegmentLocation' => [
          'segmentId' => ''
        ],
    ],
]);
</code>```

but after adding this table I want to add another paragraph as shown in pic.I have added another insertion text request after this table request like this -

```<code>$requests[] = new Google_Service_Docs_Request(array(
            'insertText' => array(
                'text' => "Paragraph 2",
                'endOfSegmentLocation' => array(
                    'segmentId' => '',
                    ),
            ),
        ));
</code>```

But like this i want to add more paragraphs after the insertion of table and for that I need index location but I am not able to do that. Can anybody help me on this how to add contents like this as shown in above pic.It would be a great huge help if anyone can help me through this.I want this in PHP.

答:
I don't have PHP in me so I can only provide you the request and process on how to insert paragraphs after the table.

Sample Doc:

After inserting your table, you need to get the document's last endIndex by using get request and pass body/content/endIndex as your field parameter values. This will return this response from using the above sample doc:

```<code>{
  "body": {
    "content": [
      {
        "endIndex": 1
      },
      {
        "endIndex": 576
      },
      {
        "endIndex": 614
      },
      {
        "endIndex": 615
      }
    ]
  }
}
</code>```

You have to iterate all the endIndex from the response and get the last one (e.g. 615). Subtract 1 from the last endIndex value and then pass it as index location in the next insert paragraph response.

Sample request:

```<code>{
  "requests": [
    {
      "insertText": {
        "location": {
          "index": 614
        },
        "text": "\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n"
      }
    }
  ]
}
</code>```

Output:

Note:

I have enclosed the text with \n at both ends to have some space.

You can also append all your paragraphs into one request so you wouldn't have to get the last endIndex everytime.

You can also use offsets by counting every character you add so that you can follow what index you should use next.

As for the paragraph formatting like having indention and aligning the paragraph to right, see changing paragraph formatting and see the sample request. If you have a question regarding this, I recommend you post a separate post for it.

Body:
I am working on google docs api.I want to create a google docs with google docs api using PHP.AS per my requirement I want some paragraphs then insert a table and then again a paragraph as shown in below picture-

I am able to  insert texts like this -

$requests[] = new Google_Service_Docs_Request(array(
            'insertText' => [
                'text' => 'Paragraph 1',
                'location' => [
                    'index' => 1,
                ]
            ]
        ));

I am also able to add table like this-

$requests [] = new Google_Service_Docs_Request([
    'insertTable' => [
        'rows' =>  4,
        'columns' =>  4,
        'endOfSegmentLocation' => [
          'segmentId' => ''
        ],
    ],
]);

but after adding this table I want to add another paragraph as shown in pic.I have added another insertion text request after this table request like this -

$requests[] = new Google_Service_Docs_Request(array(
            'insertText' => array(
                'text' => "Paragraph 2",
                'endOfSegmentLocation' => array(
                    'segmentId' => '',
                    ),
            ),
        ));

But like this i want to add more paragraphs after the insertion of table and for that I need index location but I am not able to do that. Can anybody help me on this how to add contents like this as shown in above pic.It would be a great huge help if anyone can help me through this.I want this in PHP.

Body:
I don't have PHP in me so I can only provide you the request and process on how to insert paragraphs after the table.

Sample Doc:

After inserting your table, you need to get the document's last endIndex by using get request and pass body/content/endIndex as your field parameter values. This will return this response from using the above sample doc:

{
  "body": {
    "content": [
      {
        "endIndex": 1
      },
      {
        "endIndex": 576
      },
      {
        "endIndex": 614
      },
      {
        "endIndex": 615
      }
    ]
  }
}

You have to iterate all the endIndex from the response and get the last one (e.g. 615). Subtract 1 from the last endIndex value and then pass it as index location in the next insert paragraph response.

Sample request:

{
  "requests": [
    {
      "insertText": {
        "location": {
          "index": 614
        },
        "text": "\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n"
      }
    }
  ]
}

Output:

Note:

I have enclosed the text with \n at both ends to have some space.

You can also append all your paragraphs into one request so you wouldn't have to get the last endIndex everytime.

You can also use offsets by counting every character you add so that you can follow what index you should use next.

As for the paragraph formatting like having indention and aligning the paragraph to right, see changing paragraph formatting and see the sample request. If you have a question regarding this, I recommend you post a separate post for it.


问:
Removing rows out of a table given a certain condition
I have the following table "HAVE":

ID
Date

Test_5000_ABC_2022-01
01MAY2020

Test_12345_XYZ_2022-05
15OCT2021

Test_00000_UMX_2022-12
01SEP2021

Test_00000_UMX_2022-12
01DEC2022

The last part of a string in the "ID column" there is always a year and a month delimited by "-", while the column "date" has a date in the "DDMMYYY" format.

Now, I would want to delete all entries from this table where the date from the "ID" column is after the date (after the month and year) in the "date" column and save it as a new table. So, basically, my WANT table would look like this:

ID
Date

Test_00000_UMX_2022-12
01DEC2022

I appreciate any kind of help, as I am very new to SAS. Thank you!

答:
You can use the following condition both in proc sql and in a DATA step:

where input(scan(ID, -1, '_')||'-01', yyyymmdd10.) > Date

The scan takes the fraction from your ID after the last _, without the trainling blanks. The input applies the informat yyyymmdd10. to it.


问:
Fast Algorithm for partial sums on a list
I have been learning Python for 2 months now. In order to hone my programming skills, I solve problems on Codewars from time to time.

Task

Codewars kata:

Write a program that takes a list of numbers as an argument and return a list of partial sums.

My Attempt

I wrote a solution that I tested and it works:

```<code>def parts_sums(ls):
    length=len(ls)+1
    def gen():
        for elt in range(0,length):
            yield sum(ls[elt:])

    result= list(gen())
    return result
</code>```

Codewars is rejecting this solution because it's too slow for lists with thousands of numbers.

I have spent an embarrassingly huge amount of time trying to come up with a faster solution with no avail.

How can the algorithm be designed more performant?

答:
As commented by Yves Daoust, seems like a suffix sum array with additional zero-element (as sum over empty array).

Suffix Sum

Some notes on Suffix Sum:

Given an array ‘A’ of size N, its suffix sum array is an array of the same size N such that the ith element of the suffix sum array ‘Suffix’ is the sum of all elements of the given array till ith index from the end, i.e Suffix[i] = A[i] + A[i+1] + A[i+2] + … + A[N-1] - (0-Based indexing).

For Example:
Given A[] = [3, 4, -1, 2, 5], the suffix sum array S[] is given as - S[0] = 13, S1 = 10, S1 = 6, S3 = 7, S[5] = 5.

i.e. S[] = [13, 10, 6, 7, 5]

See also:

Dev.to (2020): Prefix Sum & Suffix Sum - Programming Tools

Wikipedia: suffix array (might be related, not sure)

Implementation

Following approach uses these concepts for performance:

predefined, fix-sized result array (instead of extending or list-comprehension)

fix-sized loop for i (instead of recursion) to reverse increment

explicit fast-returning if-branch for inputs with 0 or 1 elements

```<code>def suffix_sum(arr):
    result = arr + [0]   # add the zero as last element for this task (copied input)

    n = len(arr)
    if (n <= 1):  # input with 0 or 1 elements returned as is
        return result

    last = n-1  # the last of the input array stays unmodified

    # iterate by element (last to first):
    for i in range(last, -1, -1):  # step backwards from last to first
        result[i] = result[i+1] + arr[i]   # result-sum = previous-sum + element (increases with each element)

    return result
</code>```

Results for 3 test-cases:

```<code>in: [0, 1, 3, 6, 10]
out:[20, 20, 19, 16, 10, 0]
in: []
out:[0]
in: [1234]
out:[1234, 0]
</code>```

Notes:

The reverse-for-loop using a range as in Print a list in reverse order with range()?

the first element is denoted by -1 as second range-argument

Debug-print each iteration with print(f"{i:2}: {result[i]} = {result[i+1]} + {arr[i]}") shows 4 iterations for example-input [0, 1, 3, 6, 10] with length n=5:

```<code> 3: 16 = 10 + 6
 2: 19 = 16 + 3
 1: 20 = 19 + 1
 0: 20 = 20 + 0
</code>```

Body:
I have been learning Python for 2 months now. In order to hone my programming skills, I solve problems on Codewars from time to time.

Task

Codewars kata:

Write a program that takes a list of numbers as an argument and return a list of partial sums.

My Attempt

I wrote a solution that I tested and it works:

def parts_sums(ls):
    length=len(ls)+1
    def gen():
        for elt in range(0,length):
            yield sum(ls[elt:])

    result= list(gen())
    return result

Codewars is rejecting this solution because it's too slow for lists with thousands of numbers.

I have spent an embarrassingly huge amount of time trying to come up with a faster solution with no avail.

How can the algorithm be designed more performant?

Body:
As commented by Yves Daoust, seems like a suffix sum array with additional zero-element (as sum over empty array).

Suffix Sum

Some notes on Suffix Sum:

Given an array ‘A’ of size N, its suffix sum array is an array of the same size N such that the ith element of the suffix sum array ‘Suffix’ is the sum of all elements of the given array till ith index from the end, i.e Suffix[i] = A[i] + A[i+1] + A[i+2] + … + A[N-1] - (0-Based indexing).

For Example:
Given A[] = [3, 4, -1, 2, 5], the suffix sum array S[] is given as - S[0] = 13, S1 = 10, S1 = 6, S3 = 7, S[5] = 5.

i.e. S[] = [13, 10, 6, 7, 5]

See also:

Dev.to (2020): Prefix Sum & Suffix Sum - Programming Tools

Wikipedia: suffix array (might be related, not sure)

Implementation

Following approach uses these concepts for performance:

predefined, fix-sized result array (instead of extending or list-comprehension)

fix-sized loop for i (instead of recursion) to reverse increment

explicit fast-returning if-branch for inputs with 0 or 1 elements

def suffix_sum(arr):
    result = arr + [0]   # add the zero as last element for this task (copied input)

    n = len(arr)
    if (n <= 1):  # input with 0 or 1 elements returned as is
        return result

    last = n-1  # the last of the input array stays unmodified

    # iterate by element (last to first):
    for i in range(last, -1, -1):  # step backwards from last to first
        result[i] = result[i+1] + arr[i]   # result-sum = previous-sum + element (increases with each element)

    return result

Results for 3 test-cases:

in: [0, 1, 3, 6, 10]
out:[20, 20, 19, 16, 10, 0]
in: []
out:[0]
in: [1234]
out:[1234, 0]

Notes:

The reverse-for-loop using a range as in Print a list in reverse order with range()?

the first element is denoted by -1 as second range-argument

Debug-print each iteration with print(f"{i:2}: {result[i]} = {result[i+1]} + {arr[i]}") shows 4 iterations for example-input [0, 1, 3, 6, 10] with length n=5:

 3: 16 = 10 + 6
 2: 19 = 16 + 3
 1: 20 = 19 + 1
 0: 20 = 20 + 0


问:
RSA modulus and exponent from public key
I basically have the same problem as in this question, but I'm having trouble filling in the apparently trivial parts left out from the accepted answer. I'm doing this in C# with Mono.

I have a CA root certificate, and from that I can get a byte[] holding a public key. I then get an untrusted certificate I need to verify. From what I understand, RSACryptoServiceProvider.VerifyData should do the trick, but first I need to set RSAParameters with the modulus and exponent from the public key.

(Edit: The following repeats some things already apparent from the question I linked to above.)

The piece of code that should do what I need and validate a server's certificate with a root certificate I trust is as follows:

```<code>RSACryptoServiceProvider publicKey = new RSACryptoServiceProvider();
RSAParameters publicKeyParams = new RSAParameters();
publicKeyParams.Modulus = GetPublicKeyModulus();
publicKeyParams.Exponent = GetPublicKeyExponent();
publicKey.ImportParameters(publicKeyParams);
return publicKey.VerifyData(SignedValue(), CryptoConfig.MapNameToOID("SHA1"), Signature());
</code>```

My problem is the contents of the GetPublicKeyModulus() and GetPublicKeyExponent(). In the accepted answer they are left out as apparently trivial, with just a comment saying the modulus is the value of the first TLV in my public key, and the exponent is the second TLV in the public key. I don't fully understand  what that means.

```<code>byte[] GetPublicKeyExponent()
{
  // The value of the second TLV in your Public Key
}

byte[] GetPublicKeyModulus()
{
  // The value of the first TLV in your Public Key
}
byte[] SignedValue()
{
  // The first TLV in your Ceritificate
}

byte[] Signature()
{
  // The value of the third TLV in your Certificate
}
</code>```

My question is what do these "first TLV"/"second TLV" exactly mean and how do I get those values from the byte array I have?

From what I understand, TLV stands for type-length-value. So if I have it correct, first bits of the byte array containing the public key have information about how many bits the modulus data is. Using that information I'm supposed to copy that amount of bits from the public key into another array, and set RSAParameters.Modulus to that value. After the modulus in the  public key comes the exponent, and I should do the same operation with that. But I can't find information about in how many bits and in what format is the "TL" part of a TLV in the public key data contained.

I found information elsewhere saying the modulus is the first 1024 bits in the public key, and the exponent is the remainder, but that gave me an error about size when copying data between the byte arrays.

At the moment my code that I've been forming based on the accepted answer in the question I linked looks basically like this:

```<code>using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;

X509Certificate2 trustedRootCertificate = new X509Certificate2(X509Certificate2.CreateFromCertFile(filename));
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
.
.
public bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
  .
  .
  byte[] publicKeyBytes = trustedRootCertificate.GetPublicKey();
  byte[] modulusData = // The value of the first TLV in the Public Key??
  byte[] exponentData = // The value of the second TLV in the Public Key??

  RSAParameters publicKeyParams = new RSAParameters();
  publicKeyParams.Modulus = modulusData;
  publicKeyParams.Exponent = exponentData;
  RSACryptoServiceProvider publicKey = new RSACryptoServiceProvider();
  publicKey.ImportParameters(publicKeyParams);

  byte[] certificateData = certificate.GetRawCertData();
  byte[] signedValue = // The first TLV in the certificate??
  byte[] encryptedSignature = // The third TLV in the certificate??

  return publicKey.VerifyData(certificateData, HashAlgorithm.Create("SHA1"), encryptedSignature);
}
</code>```

Or should I be using certificateData (the return value of certificate.GetRawCertData()) in the VerifyData call?

Elsewhere I've found that the encrypted signature part is the last 256 bits in the certificateData, I'm not sure if that's the same as "the third TLV in the certificate". If not, I'd be doing

```<code>byte[] certificateData = certificate.GetRawCertData();
byte[] encryptedSignature = new byte[256];
System.Array.Copy(certificateData, certificateData.Length - 256, encryptedSignature, 0, 256);
</code>```

and then using encryptedSignature as the last parameter in the VerifyData call.

Instead of all this TLV business I've also tried simply

```<code>RSACryptoServiceProvider publicKey = trustedRootCertificate.PublicKey.Key as RSACryptoServiceProvider;
</code>```

as the person in the question I linked to above, but using this the VerifyData call then returned false when I thought it shouldn't. The certificate the application gets from the server has trustedRootCertificate as its root cert, I should be able to do this with that, correct? The root's public key should be able to verify the server's cert?

It's very much possible I just have the very basics of certificate verification wrong from the start. If that's not the case, then my question is how do I get these values

```<code>// The value of the second TLV in your Public Key
..
// The value of the first TLV in your Public Key
</code>```

from the public key of the trusted root cert I have.

Edit: I've also verified that the root certificate loaded from the file and the certificate the app gets from the server are what they're supposed to be by printing out their information, so the problem is not at least in the certificates being wrong. I just don't know how to use them correctly.

答:
With RSACryptoServiceProvider:

```<code>X509Certificate2 certificate = Certificate.CreateFromBase64String(stringCert);
RSACryptoServiceProvider key = certificate.PublicKey.Key as RSACryptoServiceProvider;
if(key != null)
{
    RSAParameters parameters = key.ExportParameters(false);
    byte[] expoenet = parameters.Exponent;
    byte[] modulus = parameters.Modulus;
}
</code>```

https://social.msdn.microsoft.com/Forums/vstudio/en-US/4282dda1-4803-435a-b63a-65e2d5ac9941/get-modulus-exponent-from-certificate-public-key?forum=netfxbcl

Body:
I basically have the same problem as in this question, but I'm having trouble filling in the apparently trivial parts left out from the accepted answer. I'm doing this in C# with Mono.

I have a CA root certificate, and from that I can get a byte[] holding a public key. I then get an untrusted certificate I need to verify. From what I understand, RSACryptoServiceProvider.VerifyData should do the trick, but first I need to set RSAParameters with the modulus and exponent from the public key.

(Edit: The following repeats some things already apparent from the question I linked to above.)

The piece of code that should do what I need and validate a server's certificate with a root certificate I trust is as follows:

RSACryptoServiceProvider publicKey = new RSACryptoServiceProvider();
RSAParameters publicKeyParams = new RSAParameters();
publicKeyParams.Modulus = GetPublicKeyModulus();
publicKeyParams.Exponent = GetPublicKeyExponent();
publicKey.ImportParameters(publicKeyParams);
return publicKey.VerifyData(SignedValue(), CryptoConfig.MapNameToOID("SHA1"), Signature());

My problem is the contents of the GetPublicKeyModulus() and GetPublicKeyExponent(). In the accepted answer they are left out as apparently trivial, with just a comment saying the modulus is the value of the first TLV in my public key, and the exponent is the second TLV in the public key. I don't fully understand  what that means.

byte[] GetPublicKeyExponent()
{
  // The value of the second TLV in your Public Key
}

byte[] GetPublicKeyModulus()
{
  // The value of the first TLV in your Public Key
}
byte[] SignedValue()
{
  // The first TLV in your Ceritificate
}

byte[] Signature()
{
  // The value of the third TLV in your Certificate
}

My question is what do these "first TLV"/"second TLV" exactly mean and how do I get those values from the byte array I have?

From what I understand, TLV stands for type-length-value. So if I have it correct, first bits of the byte array containing the public key have information about how many bits the modulus data is. Using that information I'm supposed to copy that amount of bits from the public key into another array, and set RSAParameters.Modulus to that value. After the modulus in the  public key comes the exponent, and I should do the same operation with that. But I can't find information about in how many bits and in what format is the "TL" part of a TLV in the public key data contained.

I found information elsewhere saying the modulus is the first 1024 bits in the public key, and the exponent is the remainder, but that gave me an error about size when copying data between the byte arrays.

At the moment my code that I've been forming based on the accepted answer in the question I linked looks basically like this:

using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;

X509Certificate2 trustedRootCertificate = new X509Certificate2(X509Certificate2.CreateFromCertFile(filename));
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
.
.
public bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
  .
  .
  byte[] publicKeyBytes = trustedRootCertificate.GetPublicKey();
  byte[] modulusData = // The value of the first TLV in the Public Key??
  byte[] exponentData = // The value of the second TLV in the Public Key??

  RSAParameters publicKeyParams = new RSAParameters();
  publicKeyParams.Modulus = modulusData;
  publicKeyParams.Exponent = exponentData;
  RSACryptoServiceProvider publicKey = new RSACryptoServiceProvider();
  publicKey.ImportParameters(publicKeyParams);

  byte[] certificateData = certificate.GetRawCertData();
  byte[] signedValue = // The first TLV in the certificate??
  byte[] encryptedSignature = // The third TLV in the certificate??

  return publicKey.VerifyData(certificateData, HashAlgorithm.Create("SHA1"), encryptedSignature);
}

Or should I be using certificateData (the return value of certificate.GetRawCertData()) in the VerifyData call?

Elsewhere I've found that the encrypted signature part is the last 256 bits in the certificateData, I'm not sure if that's the same as "the third TLV in the certificate". If not, I'd be doing

byte[] certificateData = certificate.GetRawCertData();
byte[] encryptedSignature = new byte[256];
System.Array.Copy(certificateData, certificateData.Length - 256, encryptedSignature, 0, 256);

and then using encryptedSignature as the last parameter in the VerifyData call.

Instead of all this TLV business I've also tried simply

RSACryptoServiceProvider publicKey = trustedRootCertificate.PublicKey.Key as RSACryptoServiceProvider;

as the person in the question I linked to above, but using this the VerifyData call then returned false when I thought it shouldn't. The certificate the application gets from the server has trustedRootCertificate as its root cert, I should be able to do this with that, correct? The root's public key should be able to verify the server's cert?

It's very much possible I just have the very basics of certificate verification wrong from the start. If that's not the case, then my question is how do I get these values

// The value of the second TLV in your Public Key
..
// The value of the first TLV in your Public Key

from the public key of the trusted root cert I have.

Edit: I've also verified that the root certificate loaded from the file and the certificate the app gets from the server are what they're supposed to be by printing out their information, so the problem is not at least in the certificates being wrong. I just don't know how to use them correctly.

Body:
With RSACryptoServiceProvider:

X509Certificate2 certificate = Certificate.CreateFromBase64String(stringCert);
RSACryptoServiceProvider key = certificate.PublicKey.Key as RSACryptoServiceProvider;
if(key != null)
{
    RSAParameters parameters = key.ExportParameters(false);
    byte[] expoenet = parameters.Exponent;
    byte[] modulus = parameters.Modulus;
}

https://social.msdn.microsoft.com/Forums/vstudio/en-US/4282dda1-4803-435a-b63a-65e2d5ac9941/get-modulus-exponent-from-certificate-public-key?forum=netfxbcl


问:
Installed turtle package not recognized by vscode
I have an issue with working with the turtle package in python. I have Anaconda installed on my computer. Within Anaconda I have installed the turtle package with pip command (there is no conda install option for turtle as to my knowledge).

When I start a jupyter notebook and import turtle everything works just fine.

When I start vscode from conda and use the same python environment, I get an import error from vscode saying: importerror: cannot import name Turtle.

Why is this happening and how could I start turtle in vscode?

Thank you!

答: Use pip install PythonTurtle in the vs code terminal


问:
Why immutability of super class is not forced in child class?
You can break immutabiliy of super class, even if you declare the immutable fields with val in interface or abstract class.

interface Foo {
    val bar: String // immutable
}

class FooImpl : Foo {
    override var bar: String = "bar" // mutable

    init {
        bar = "changed"
    }
}

println(FooImpl().bar) // changed
```

I expected above code will occurs compile error, but it works.
Why is this possible in kotlin?

答:
val doesn’t mean immutable. It means read-only. Even if you don’t override it as a var you could make it a val that returns a different value each time.

So expanding it to also be writable isn’t breaking any contract.

There is no way to enforce an open property to be immutable. Best you can do is use documentation that declares that it will not behave correctly if it doesn’t return the same value every time.

Body:
You can break immutabiliy of super class, even if you declare the immutable fields with val in interface or abstract class.

interface Foo {
    val bar: String // immutable
}

class FooImpl : Foo {
    override var bar: String = "bar" // mutable

    init {
        bar = "changed"
    }
}

println(FooImpl().bar) // changed

I expected above code will occurs compile error, but it works.
Why is this possible in kotlin?


问:
Sanity.io webhook with body params
I added a webhook to Sanity and it works as expected, but I would like to pass a parameter in the body for {branch:"develop"} and I do not see an input field.

I have tried appending ?branch=develop to the url, but that does not work.

Any ideas on how to include this parameter?

答:
Would it work to add this into your projection? Something like the following would return everything, plus 'branch': 'develop':

```<code>{
  ...,
  'branch': 'develop',
}
</code>```

Title: Sanity.io webhook with body params

Body:
Would it work to add this into your projection? Something like the following would return everything, plus 'branch': 'develop':

{
  ...,
  'branch': 'develop',
}


问:
EF5 Core Update database Error Unable to create an object of type 'ApplicationDbContext'
I want a migration of my database , I was able to create the migration but the update database command does not pass

DI

```<code>services.AddDbContext<ApplicationDbContext>(options =>
         options.UseSqlServer(Configuration.GetConnectionString("TravelCS")
         ));

  services.AddScoped<IApplicationDbContext>(provider => provider.GetService<ApplicationDbContext>());
</code>```

Interface IApplicationDbContext:

```<code>    DbSet<TourList> TourLists { get; set; }
DbSet<TourPackage> TourPackages { get; set; }

Task<int> SaveChangesAsync(CancellationToken cancellationToken);
</code>```

AppDbContext

```<code>  public class ApplicationDbContext : DbContext, IApplicationDbContext
  {
    private readonly IDateTime _dateTime;
    private IDbContextTransaction _currentTransaction;

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
          : base(options)
    {
    }

    public DbSet<TourList> TourLists { get; set; }
    public DbSet<TourPackage> TourPackages { get; set; }

    public ApplicationDbContext(
      DbContextOptions<ApplicationDbContext> options,
      IDateTime dateTime) : base(options)
    {
      _dateTime = dateTime;
    }
</code>```

答:
Resolved

Resolved by using update-database instead of dtonet ef update-database  O.o

Body:
I want a migration of my database , I was able to create the migration but the update database command does not pass

DI

services.AddDbContext<ApplicationDbContext>(options =>
         options.UseSqlServer(Configuration.GetConnectionString("TravelCS")
         ));

  services.AddScoped<IApplicationDbContext>(provider => provider.GetService<ApplicationDbContext>());

Interface IApplicationDbContext:

    DbSet<TourList> TourLists { get; set; }
DbSet<TourPackage> TourPackages { get; set; }

Task<int> SaveChangesAsync(CancellationToken cancellationToken);

AppDbContext

  public class ApplicationDbContext : DbContext, IApplicationDbContext
  {
    private readonly IDateTime _dateTime;
    private IDbContextTransaction _currentTransaction;

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
          : base(options)
    {
    }

    public DbSet<TourList> TourLists { get; set; }
    public DbSet<TourPackage> TourPackages { get; set; }

    public ApplicationDbContext(
      DbContextOptions<ApplicationDbContext> options,
      IDateTime dateTime) : base(options)
    {
      _dateTime = dateTime;
    }


问:
Merge two lists into dynamic list in Python
I have a scenario where have lists List1 and List2 which has below values

List1 = [1,2,3]

List2 = [(11,22,33),(44,55,66),(77,88,99)]

Expected List3 = [(1,11,22,33),(2,44,55,66),(3,77,88,99)]

I need to populate this List3 in Python.Any help is appriciated.

i tried using multiple for loops but didnt work somehing like this

```<code>list = []
        for id in tIDs:
            tIDy = id["ID"]
            for row in PlanDf[["Owner","SP","rep"]].itertuples(index=False):
                list.append((tIDy ,tuple(row)[0],tuple(row)[1],tuple(row)[2]))
                break
</code>```

答:
This should solve your problem:

Firstly, do not name your list "list". When it comes to concocting the final list you simply put your id, and *unpacked vars in a tuple.

```<code>L1 = [id["ID"] for id in tIDs]
L2 = [row for row in PlanDf[["Owner","SP","rep"]].itertuples(index=False)]
L3 = [(a,*b) for a, b in zip(L1, L2)]

print(L3)
</code>```

Since all this code is specific to you, and without the rest of it I cannot test or prove it, here is a generic example of the same thing.

```<code>L1 = [1,2,3]
L2 = [(11,12,13), (21,22,23), (31,32,33)]
L3 = [(a,*b) for a, b in zip(L1, L2)]

print(L3)
</code>```

Body:
I have a scenario where have lists List1 and List2 which has below values

List1 = [1,2,3]

List2 = [(11,22,33),(44,55,66),(77,88,99)]

Expected List3 = [(1,11,22,33),(2,44,55,66),(3,77,88,99)]

I need to populate this List3 in Python.Any help is appriciated.

i tried using multiple for loops but didnt work somehing like this

list = []
        for id in tIDs:
            tIDy = id["ID"]
            for row in PlanDf[["Owner","SP","rep"]].itertuples(index=False):
                list.append((tIDy ,tuple(row)[0],tuple(row)[1],tuple(row)[2]))
                break

Body:
This should solve your problem:

Firstly, do not name your list "list". When it comes to concocting the final list you simply put your id, and *unpacked vars in a tuple.

L1 = [id["ID"] for id in tIDs]
L2 = [row for row in PlanDf[["Owner","SP","rep"]].itertuples(index=False)]
L3 = [(a,*b) for a, b in zip(L1, L2)]

print(L3)

Since all this code is specific to you, and without the rest of it I cannot test or prove it, here is a generic example of the same thing.

L1 = [1,2,3]
L2 = [(11,12,13), (21,22,23), (31,32,33)]
L3 = [(a,*b) for a, b in zip(L1, L2)]

print(L3)


问:
Randomize control visibility (asp.net)
I have been searching for a solution to this but haven't come across one yet and i'm not too good at randomizing with c#.

I have three asp.net controls and I would like to make visible one of those controls at any one time.

The controls may be like this

panel 1

panel 2

panel 3

So I guess all of these controls would be set to visible='false' by default. Then the randomize method would choose one of those controls and make it visible='true'.

I think the hardest part here would be to put the controls into an array to randomize? Again, i'm not sure how to do that so any help would be great.

Thank you in advance.

答:
```<code>Random rnd = new Random();
var visiblePanel = rnd.Next(1, 4);
switch (visiblePanel) {
    case 1:
        Panel1.Visible = true;
        Panel2.Visible = false;
        Panel3.Visible = false;
        break;
    case 2:
        Panel1.Visible = false;
        Panel2.Visible = true;
        Panel3.Visible = false;
        break;
    case 3:
        Panel1.Visible = false;
        Panel2.Visible = false;
        Panel3.Visible = true;
        break;
}
</code>```

Title: Randomize control visibility (asp.net)


问:
Getting flake8 returned a non none zero code : 1 in docker
I was following this article.
https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#production-dockerfile

In the Production Dockerfile section, the Dockerfile.prod file has these lines.

```<code># lint
RUN pip install --upgrade pip
RUN pip install flake8
COPY . /usr/src/app/
RUN flake8 --ignore=E501,F401 .
</code>```

When I run the below command,

```<code>docker-compose -f docker-compose.prod.yml up -d --build
</code>```

I'm getting the below error.

```<code>ERROR: Service 'web' failed to build: The command '/bin/sh -c flake8 --ignore=E501,F401' returned a non-zero code: 1
</code>```

I'm not much aware of flake8, When I commented the 'RUN flake8 --ignore=E501,F401 .' line from the Dockerfile.prod file everything worked.

Can anyone please tell me why I'm facing this issue and tell me a fix instead of removing that line from the Dockerfile. I'm not much aware of flak8 and I'm quite new to Docker too and your help will be much appreciated :)

Thanks.

答:
I also got the same problem, as shown below and how  solved is that, by fixing the error as mentioned their in error " settings.py:23:1: E265 block comment should start with '# '. "

Edit the comment line give the proper space like '# This is comment'

you may got different type but fix it by as per error suggestions.

Body:
I was following this article.
https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#production-dockerfile

In the Production Dockerfile section, the Dockerfile.prod file has these lines.

# lint
RUN pip install --upgrade pip
RUN pip install flake8
COPY . /usr/src/app/
RUN flake8 --ignore=E501,F401 .

When I run the below command,

docker-compose -f docker-compose.prod.yml up -d --build

I'm getting the below error.

ERROR: Service 'web' failed to build: The command '/bin/sh -c flake8 --ignore=E501,F401' returned a non-zero code: 1

I'm not much aware of flake8, When I commented the 'RUN flake8 --ignore=E501,F401 .' line from the Dockerfile.prod file everything worked.

Can anyone please tell me why I'm facing this issue and tell me a fix instead of removing that line from the Dockerfile. I'm not much aware of flak8 and I'm quite new to Docker too and your help will be much appreciated :)

Thanks.


问:
Send UIButton touch event to didSelectRowAtIndexPath
I have a UIButton added to a UITableViewCell

In order to reduce code redundancy, I'd like to touch event of UIButton to fall through the cell - so it ends up in:

```<code>- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

Can you tell me how?

答:
In your button's action method, you can determine the index path of the row from the table view and pass that to the delegate method:</p>

```<code>- (IBAction)buttonClicked:(UIButton *)button
{
    CGPoint point = [button center];
    UITableView *table = [self tableView];
    NSIndexPath *indexPath = [table indexPathForRowAtPoint:point];
    [[table delegate] tableView:table didSelectRowAtIndexPath:indexPath];
}
</code>```

Body:
I have a UIButton added to a UITableViewCell

In order to reduce code redundancy, I'd like to touch event of UIButton to fall through the cell - so it ends up in:

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

Can you tell me how?

Body:
In your button's action method, you can determine the index path of the row from the table view and pass that to the delegate method:

- (IBAction)buttonClicked:(UIButton *)button
{
    CGPoint point = [button center];
    UITableView *table = [self tableView];
    NSIndexPath *indexPath = [table indexPathForRowAtPoint:point];
    [[table delegate] tableView:table didSelectRowAtIndexPath:indexPath];
}


问:
I there a way of changing the text of "add child page" button wagtail
Is there a way to change the text of the button add child page of default Page model of Wagtail?

答:
Minor suggestion to avoid having to re-construct the button, since we are just replacing the text. Should also build this out so that it dynamically changes if the child pages are limited to a single content type.

wagtail_hooks.py

```<code>
@hooks.register('construct_page_listing_buttons')
def replace_page_listing_button_item(buttons, page, page_perms, is_parent=False, context=None):
    for index, button in enumerate(buttons):
       # basic code only - recommend you find a more robust way to confirm this is the add child page button
        if button.label == 'Add child page':
            button.label = 'Add New...'
            buttons[index] = button # update the matched button with a new one (note. PageListingButton is used in page listing)

</code>```

Body:
Minor suggestion to avoid having to re-construct the button, since we are just replacing the text. Should also build this out so that it dynamically changes if the child pages are limited to a single content type.

wagtail_hooks.py

@hooks.register('construct_page_listing_buttons')
def replace_page_listing_button_item(buttons, page, page_perms, is_parent=False, context=None):
    for index, button in enumerate(buttons):
       # basic code only - recommend you find a more robust way to confirm this is the add child page button
        if button.label == 'Add child page':
            button.label = 'Add New...'
            buttons[index] = button # update the matched button with a new one (note. PageListingButton is used in page listing)


问:
Can Java BufferedWriter autosize columns before writing and write colored rows?
Currently, I have a method that writes out CSV files from a list of models:

File file = null;
Writer rw = null;
BufferedWriter bw = null;

try {
    file = new File(outPath + filename);
    rw = new FileWriter(reportFile);
    bw = new BufferedWriter(reportWriter);

    bw.write("HeaderCell1,HeaderCell2");

    for (Model model : models) {
        String line = quote(String.valueOf(modelclass.getField1())) + ",";
        line += quote(String.valueOf(modelclass.getField2())) + ",";
        line += "/n";

        bw.write(line);
    }

} catch (Exception e) {
    e.printStackTrace();
}
finally {
    if (bw != null) {
        try {
            bw.close();
        } catch (IOException e) {
            LOGGER.error("Error closing buffered writer", e);
            e.printStackTrace();
        }
    }
}

public String quotes(String toQuote) {
    return "\"" + outStr + "\"";
}
```
<p>When this writes out, it looks like this in a CSV:</p>
<pre class="lang-none prettyprint-override"><code>|Header1    |Header2    |
|-----------|-----------|
|field1Value|field2Value|
</code>```

There is no formatting or anything or autosizing, and I was wondering if there are methods in BufferedWriter that allow you to color the cells "Header1" and "Header2" and to autosize them and center it? Or is that something outside of BufferedWriter

答:
A CSV is just a simple plain textfile, so there is no formatting for CSV-Files.

But there are APIs for writing Excel-Files.

Apache POI is one of them.

Baeldung has also written about Working with Microsoft Excel in Java

Besides Apache POI he mentions a JExcel API there.

Body:
Currently, I have a method that writes out CSV files from a list of models:

File file = null;
Writer rw = null;
BufferedWriter bw = null;

try {
    file = new File(outPath + filename);
    rw = new FileWriter(reportFile);
    bw = new BufferedWriter(reportWriter);

    bw.write("HeaderCell1,HeaderCell2");

    for (Model model : models) {
        String line = quote(String.valueOf(modelclass.getField1())) + ",";
        line += quote(String.valueOf(modelclass.getField2())) + ",";
        line += "/n";

        bw.write(line);
    }

} catch (Exception e) {
    e.printStackTrace();
}
finally {
    if (bw != null) {
        try {
            bw.close();
        } catch (IOException e) {
            LOGGER.error("Error closing buffered writer", e);
            e.printStackTrace();
        }
    }
}

public String quotes(String toQuote) {
    return "\"" + outStr + "\"";
}

When this writes out, it looks like this in a CSV:

|Header1    |Header2    |
|-----------|-----------|
|field1Value|field2Value|

There is no formatting or anything or autosizing, and I was wondering if there are methods in BufferedWriter that allow you to color the cells "Header1" and "Header2" and to autosize them and center it? Or is that something outside of BufferedWriter