问:
Add existing NodeJs (node, Express, monodb,...) project to existing a NX monorepo (Angular)
Has anyone experienced how to add an existing NodeJS API to an existing (Angular) Nx Monrepo?

Unfortunately the manual doesn´t help me so much
https://nx.dev/migration/manual

答:
The process of migrating a repo into your mono repo requires a few manual steps. I think there would not be a simpler way to do it.

Assuming your node project does not share files with your current monorepo, this should be the steps:

on your node repo, create a branch 'to-monorepo' and in it, move all the files to folders that match the nx folder structure and push the commits to it.

remove your package.json file (we will later merge it with the monorepo's one)

once the folders match the nx folder structure, time to merge into the monorepo. From the monorepo add the remote of the other repo

```<code>git remote add node-repo <your git repo's node url>
</code>```

at the monorepo folder, checkout your master

run a pull to make the node repo branches be available in the monorepo

```<code>git pull
</code>```

create a new branch 'merging-node-repo' on your monorepo.

merge the branch node-repo/to-monorepo into your merging-node-repo branch, preserving the history:

```<code>git merge node-repo/to-monorepo --allow-unrelated-histories
</code>```

push your new branch (all the code and its history will now be listed in this new branch)

remove the remote node-repo from your local monorepo configs

```<code>git remote rm node-repo
</code>```

manually merge all the node repo's original package.json file dependencies into the monorepo's one, and run npm install from the monorepo. This way your package-lock.json file is updated. Once you are done, create a commit and push it.

this last step is more tricky. You have now to manually update the monorepo's config files to allow nx to start managing it. This is where the link you had in your question might help. Once you are done, create a commit and push it.

With these steps you can then merge your merging-node-repo branch into master.

I recommend you to create a separated nx workspace with a nodejs project on it. This helps you with having a baseline for all the necessary nx configurations and dependencies.
You might want to make sure your project works via nx commands from this separated workspace; this way you will have a better chance of getting configurations of your monorepo right.

Hopefully this gets you started.

Body:
The process of migrating a repo into your mono repo requires a few manual steps. I think there would not be a simpler way to do it.

Assuming your node project does not share files with your current monorepo, this should be the steps:

on your node repo, create a branch 'to-monorepo' and in it, move all the files to folders that match the nx folder structure and push the commits to it.

remove your package.json file (we will later merge it with the monorepo's one)

once the folders match the nx folder structure, time to merge into the monorepo. From the monorepo add the remote of the other repo

git remote add node-repo <your git repo's node url>

at the monorepo folder, checkout your master

run a pull to make the node repo branches be available in the monorepo

git pull

create a new branch 'merging-node-repo' on your monorepo.

merge the branch node-repo/to-monorepo into your merging-node-repo branch, preserving the history:

git merge node-repo/to-monorepo --allow-unrelated-histories

push your new branch (all the code and its history will now be listed in this new branch)

remove the remote node-repo from your local monorepo configs

git remote rm node-repo

manually merge all the node repo's original package.json file dependencies into the monorepo's one, and run npm install from the monorepo. This way your package-lock.json file is updated. Once you are done, create a commit and push it.

this last step is more tricky. You have now to manually update the monorepo's config files to allow nx to start managing it. This is where the link you had in your question might help. Once you are done, create a commit and push it.

With these steps you can then merge your merging-node-repo branch into master.

I recommend you to create a separated nx workspace with a nodejs project on it. This helps you with having a baseline for all the necessary nx configurations and dependencies.
You might want to make sure your project works via nx commands from this separated workspace; this way you will have a better chance of getting configurations of your monorepo right.

Hopefully this gets you started.


来源: stackexchange

问:
Best way to get a rotating Secrets Manager secret to Parameter Store
I'd like to setup a rotating token in Secrets Manager. Our app however uses environment variables from Parameter Store. I need to reference this updated token in our app.

What's the best way to have my app get the updated token? Maybe every 30 days or whatever the rotation period is. Is it a scheduled lambda?

答:
Parameter Store parameters can reference Secret Manager secrets. This means that you can save a value in AWS Secrets Manager and use the rotation provided by it. As long as your secret is not an RDS, DocumentDB or Redshift secret, you will have to create a Lambda function for rotation (see docs).

Although, the solution above would work, it might be simpler to have a the value saved in SSM Parameter Store encrypted and simply use a Lambda function with a CloudWatch scheduled event to rotate it.

ContentLicense: CC BY-SA 4.0


问:
Facing Permission related issues in MacBook pro with Big Sur 11.4
Whenever I'm trying to open Eclipse or SpringToolSuite 4, I'm getting the same permission related issues It was working fine a day before yesterday but now It's showing weird stuff.

You do not have permission to open the application “SpringToolSuite4”.

You do not have permission to open the application “Eclipse”.

If anyone has any solutions please share

答:
Try this :
codesign --force --deep --sign - /Applications/SpringToolSuite4.app</p>


问:
Generate a WITH clause/UNIONs from a SELECT
I want to generate a WITH clause/UNIONs — for the purpose of easily sharing small samples of data  (10-20 rows).

I want to do that without creating tables or inserting rows.

Example:

Take a table or query like this:

...and generate this:

```<code>with cte as(
select 10 as asset_id, 1 as vertex_num, 118.56 as x, 3.8 as y from dual
union all
select 10 as asset_id, 2 as vertex_num, 118.62 as x, 1.03 as y from dual
union all
select 10 as asset_id, 3 as vertex_num, 121.93 as x, 1.03 as y from dual)

 --There are lots more rows. But it's too much work to write them all out.

select * from cte
</code>```

Using SQL, how can I automatically generate a WITH clause/UNIONs from the resultset?

I believe there is OOTB export functionality in Toad that can do that. But I don't think there are any tools in SQL Developer that can do it, which is what I'm using.

When attempting this with SQL, I think the main challenge is to loop through n columns. I'm not sure how to do that.

答:
You could use dbms_sql to execute a query against your real table, interrogate the data types, and use that information to generate the CTE and its inner queries.

As a first stab:

```<code>create or replace procedure print_cte (p_statement varchar2) as
  -- dbms_sql variables
  l_c pls_integer;
  l_col_cnt pls_integer;
  l_rows pls_integer;
  l_desc_t dbms_sql.desc_tab;

  l_first_row boolean := true;
  l_varchar2 varchar2(4000);
  l_number number;
  l_date date;
  -- etc.
begin
  -- ideally add some checks for p_statement being a sinple query

  l_c := dbms_sql.open_cursor;
  dbms_sql.parse(c => l_c, statement => p_statement, language_flag => dbms_sql.native);
  l_rows := dbms_sql.execute(c => l_c);

  dbms_sql.describe_columns(c => l_c, col_cnt => l_col_cnt, desc_t => l_desc_t);

  -- define columns, and output CTE columns at the same time
  dbms_output.put('with cte (');

  for i in 1..l_col_cnt loop
    case l_desc_t(i).col_type
      when 1 then
        dbms_sql.define_column(c => l_c, position=> i, column => l_varchar2, column_size => 4000);
      when 2 then
        dbms_sql.define_column(c => l_c, position=> i, column => l_number);
      when 12 then
        dbms_sql.define_column(c => l_c, position=> i, column => l_date);
      -- etc. plus else to skip or throw error for anything not handled
    end case;

    if i > 1 then
      dbms_output.put(', ');
    end if;
    dbms_output.put('"' || l_desc_t(i).col_name || '"');
  end loop;

  dbms_output.put(') as (');

  while dbms_sql.fetch_rows(c => l_c) > 0 loop
    if (l_first_row) then
      l_first_row := false;
    else
      dbms_output.put('  union all');
    end if;
    dbms_output.new_line;

    for i in 1..l_col_cnt loop
      if i = 1 then
        dbms_output.put('  select ');
      else
        dbms_output.put(', ');
      end if;

      case l_desc_t(i).col_type
        when 1 then
          dbms_sql.column_value(c => l_c, position => i, value => l_varchar2);
          dbms_output.put(q'[']' || l_varchar2 || q'[']');
        when 2 then
          dbms_sql.column_value(c => l_c, position => i, value => l_number);
          dbms_output.put(l_number);
        when 12 then
          dbms_sql.column_value(c => l_c, position => i, value => l_date);
          dbms_output.put(q'[to_date(']'
            || to_char(l_date, 'SYYYY-MM-DD-HH24:MI:SS')
            || q'[', 'SYYYY-MM-DD HH24:MI:SS')]');
        -- etc. plus else to skip or throw error for anything not handled
     end case;
    end loop;

    dbms_output.put(' from dual');
    dbms_output.new_line;
  end loop;

  dbms_output.put_line(')');
  dbms_output.put_line('select * from cte;');

  dbms_sql.close_cursor(c => l_c);
end print_cte;
/
</code>```

and then you can do:

```<code>begin
  print_cte('select * from your_table');
end;
/
</code>```

which produces:

```<code>with cte ("ASSET_ID", "VERTEX_NUM", "X", "Y") as (
  select 10, 1, 118.56, 3.8 from dual
  union all
  select 10, 2, 118.62, 1.03 from dual
  union all
  select 10, 3, 121.93, 1.03 from dual
)
select * from cte;
</code>```

Your client has to be configured to handle dbms_output, of course.

As noted in the inline comments you should check the passed-in statement isn't going to do something nasty; and you need to add handling for other data types. This is just a starting point.

db<>fiddle

Body:
I want to generate a WITH clause/UNIONs — for the purpose of easily sharing small samples of data  (10-20 rows).

I want to do that without creating tables or inserting rows.

Example:

Take a table or query like this:

...and generate this:

with cte as(
select 10 as asset_id, 1 as vertex_num, 118.56 as x, 3.8 as y from dual
union all
select 10 as asset_id, 2 as vertex_num, 118.62 as x, 1.03 as y from dual
union all
select 10 as asset_id, 3 as vertex_num, 121.93 as x, 1.03 as y from dual)

 --There are lots more rows. But it's too much work to write them all out.

select * from cte

Using SQL, how can I automatically generate a WITH clause/UNIONs from the resultset?

I believe there is OOTB export functionality in Toad that can do that. But I don't think there are any tools in SQL Developer that can do it, which is what I'm using.

When attempting this with SQL, I think the main challenge is to loop through n columns. I'm not sure how to do that.

Body:
You could use dbms_sql to execute a query against your real table, interrogate the data types, and use that information to generate the CTE and its inner queries.

As a first stab:

create or replace procedure print_cte (p_statement varchar2) as
  -- dbms_sql variables
  l_c pls_integer;
  l_col_cnt pls_integer;
  l_rows pls_integer;
  l_desc_t dbms_sql.desc_tab;

  l_first_row boolean := true;
  l_varchar2 varchar2(4000);
  l_number number;
  l_date date;
  -- etc.
begin
  -- ideally add some checks for p_statement being a sinple query

  l_c := dbms_sql.open_cursor;
  dbms_sql.parse(c => l_c, statement => p_statement, language_flag => dbms_sql.native);
  l_rows := dbms_sql.execute(c => l_c);

  dbms_sql.describe_columns(c => l_c, col_cnt => l_col_cnt, desc_t => l_desc_t);

  -- define columns, and output CTE columns at the same time
  dbms_output.put('with cte (');

  for i in 1..l_col_cnt loop
    case l_desc_t(i).col_type
      when 1 then
        dbms_sql.define_column(c => l_c, position=> i, column => l_varchar2, column_size => 4000);
      when 2 then
        dbms_sql.define_column(c => l_c, position=> i, column => l_number);
      when 12 then
        dbms_sql.define_column(c => l_c, position=> i, column => l_date);
      -- etc. plus else to skip or throw error for anything not handled
    end case;

    if i > 1 then
      dbms_output.put(', ');
    end if;
    dbms_output.put('"' || l_desc_t(i).col_name || '"');
  end loop;

  dbms_output.put(') as (');

  while dbms_sql.fetch_rows(c => l_c) > 0 loop
    if (l_first_row) then
      l_first_row := false;
    else
      dbms_output.put('  union all');
    end if;
    dbms_output.new_line;

    for i in 1..l_col_cnt loop
      if i = 1 then
        dbms_output.put('  select ');
      else
        dbms_output.put(', ');
      end if;

      case l_desc_t(i).col_type
        when 1 then
          dbms_sql.column_value(c => l_c, position => i, value => l_varchar2);
          dbms_output.put(q'[']' || l_varchar2 || q'[']');
        when 2 then
          dbms_sql.column_value(c => l_c, position => i, value => l_number);
          dbms_output.put(l_number);
        when 12 then
          dbms_sql.column_value(c => l_c, position => i, value => l_date);
          dbms_output.put(q'[to_date(']'
            || to_char(l_date, 'SYYYY-MM-DD-HH24:MI:SS')
            || q'[', 'SYYYY-MM-DD HH24:MI:SS')]');
        -- etc. plus else to skip or throw error for anything not handled
     end case;
    end loop;

    dbms_output.put(' from dual');
    dbms_output.new_line;
  end loop;

  dbms_output.put_line(')');
  dbms_output.put_line('select * from cte;');

  dbms_sql.close_cursor(c => l_c);
end print_cte;
/

and then you can do:

begin
  print_cte('select * from your_table');
end;
/

which produces:

with cte ("ASSET_ID", "VERTEX_NUM", "X", "Y") as (
  select 10, 1, 118.56, 3.8 from dual
  union all
  select 10, 2, 118.62, 1.03 from dual
  union all
  select 10, 3, 121.93, 1.03 from dual
)
select * from cte;

Your client has to be configured to handle dbms_output, of course.

As noted in the inline comments you should check the passed-in statement isn't going to do something nasty; and you need to add handling for other data types. This is just a starting point.

db<>fiddle


问:
Recursive behavior
Why does the following executes such that the print statement is called as often as it recursed but the count variable, count, when x == 1 is never reached.

```<code>def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1 # when x == 1

  count_bits(int(n/2), count)
  print("counter")

  return count

</code>```

why is it necessary to recurse with the return statement?  Because if the recursive call is above the return statement the code
returns the wrong output but with the recursive call called with
return keyword, everything works well.  Typically, the print statement
prints 'counter' as often as it recursed showing that the recursive call
works.

On the other hand, if "return" follows after the recursive call, it returns the count from the base condition, correctly.

```<code>def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1

  return count_bits(int(n/2), count)
</code>```

答:
I advised you to use snoop package to debug your code more efficient , by this package you can track the executing step by step.
to install it run:

Pip install snoop

Import snoop

add snoop decorator to count_bits()

for about the package see this link
https://pypi.org/project/snoop/

Title: Recursive behavior

Body:
Why does the following executes such that the print statement is called as often as it recursed but the count variable, count, when x == 1 is never reached.

def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1 # when x == 1

  count_bits(int(n/2), count)
  print("counter")

  return count

why is it necessary to recurse with the return statement?  Because if the recursive call is above the return statement the code
returns the wrong output but with the recursive call called with
return keyword, everything works well.  Typically, the print statement
prints 'counter' as often as it recursed showing that the recursive call
works.

On the other hand, if "return" follows after the recursive call, it returns the count from the base condition, correctly.

def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1

  return count_bits(int(n/2), count)


问:
Changing number of columns with GridLayoutManager and RecyclerView
Inside my fragment I'm setting my GridLayout in the following way:
mRecycler.setLayoutManager(new GridLayoutManager(rootView.getContext(), 2));

So, I just want to change that 2 for a 4 when the user rotates the phone/tablet. I've read about onConfigurationChanged and I tried to make it work for my case, but it isn't going in the right way. When I rotate my phone, the app crashes...

Could you tell me how to solve this issue?

Here is my approach to find the solution, which is not working correctly:

```<code>  @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        int orientation = newConfig.orientation;

        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            mRecycler.setLayoutManager(new GridLayoutManager(mContext, 2));
        } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mRecycler.setLayoutManager(new GridLayoutManager(mContext, 4));
        }
    }
</code>```

答:
I will try to explain it step by step. And you can check integers.xml, integers.xml (land) and MainFragment files of github project that I shared. You will see that number of columns will change based on orientation or screen size(tablet vs phone)(I will explain only how to do it when orientation changed, since the question is only about it).
https://github.com/b-basoglu/NewsApp/blob/master/app/src/main/java/com/news/newsapp/ui/main/MainFragment.kt

Create a resources file called integers.xml. -> Open the res folder in the Project > Android pane, right-click on the values folder, and select New > Values resource file.

Name the file integers.xml and click OK.

Create an integer constant between the  tags called grid_column_count and set it equal to 2:

< integer name="grid_column_count">2</ integer >

Create another values resource file, again called integers.xml; however, the name will be modified as you add resource qualifiers from the Available qualifiers pane. The resource qualifiers are used to label resource configurations for various situations.

Select Orientation in the Available qualifiers pane, and press the >> symbol in the middle of the dialog to assign this qualifier.

Change the Screen orientation menu to Landscape, and notice how the directory name values-land appears. This is the essence of resource qualifiers: the directory name tells Android when to use that specific layout file. In this case, that is when the phone is rotated to landscape mode.

Click OK to generate the new layout file.

Copy the integer constant you created into this new resource file, but change the value to 4.

< integer name="grid_column_count">4</ integer >

[You have these files][1]

Now all you have to do is re-assigning your span count when configuration changed as below:

```<code>    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        gridLayoutManager?.let {
            it.spanCount = resources.getInteger(R.integer.grid_column_count)
        }
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        gridLayoutManager = GridLayoutManager(requireContext(),
                                resources.getInteger(R.integer.grid_column_count))
        ${yourRecyclerView}.layoutManager = gridLayoutManager
        ...
  [1]: https://i.stack.imgur.com/3NZdq.png
</code>```

Body:
Inside my fragment I'm setting my GridLayout in the following way:
mRecycler.setLayoutManager(new GridLayoutManager(rootView.getContext(), 2));

So, I just want to change that 2 for a 4 when the user rotates the phone/tablet. I've read about onConfigurationChanged and I tried to make it work for my case, but it isn't going in the right way. When I rotate my phone, the app crashes...

Could you tell me how to solve this issue?

Here is my approach to find the solution, which is not working correctly:

  @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        int orientation = newConfig.orientation;

        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            mRecycler.setLayoutManager(new GridLayoutManager(mContext, 2));
        } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mRecycler.setLayoutManager(new GridLayoutManager(mContext, 4));
        }
    }

Body:
I will try to explain it step by step. And you can check integers.xml, integers.xml (land) and MainFragment files of github project that I shared. You will see that number of columns will change based on orientation or screen size(tablet vs phone)(I will explain only how to do it when orientation changed, since the question is only about it).
https://github.com/b-basoglu/NewsApp/blob/master/app/src/main/java/com/news/newsapp/ui/main/MainFragment.kt

Create a resources file called integers.xml. -> Open the res folder in the Project > Android pane, right-click on the values folder, and select New > Values resource file.

Name the file integers.xml and click OK.

Create an integer constant between the  tags called grid_column_count and set it equal to 2:

< integer name="grid_column_count">2</ integer >

Create another values resource file, again called integers.xml; however, the name will be modified as you add resource qualifiers from the Available qualifiers pane. The resource qualifiers are used to label resource configurations for various situations.

Select Orientation in the Available qualifiers pane, and press the >> symbol in the middle of the dialog to assign this qualifier.

Change the Screen orientation menu to Landscape, and notice how the directory name values-land appears. This is the essence of resource qualifiers: the directory name tells Android when to use that specific layout file. In this case, that is when the phone is rotated to landscape mode.

Click OK to generate the new layout file.

Copy the integer constant you created into this new resource file, but change the value to 4.

< integer name="grid_column_count">4</ integer >

[You have these files][1]

Now all you have to do is re-assigning your span count when configuration changed as below:

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        gridLayoutManager?.let {
            it.spanCount = resources.getInteger(R.integer.grid_column_count)
        }
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        gridLayoutManager = GridLayoutManager(requireContext(),
                                resources.getInteger(R.integer.grid_column_count))
        ${yourRecyclerView}.layoutManager = gridLayoutManager
        ...
  [1]: https://i.stack.imgur.com/3NZdq.png


问:
How pivothigh() and pivotlow() function work on Tradingview Pinescript?
I'm trying to rewrite a script to Python, but I can't figure out how pivothigh() and pivotlow() function work, and I can't find source code, I know how to calculate Pivot Points, but what leftbars and rightbars means in this two function? Please help.</p>

答:
I too had a need to better understand how the pivothigh() and pivotlow() functions work internally so I made the effort to code a Pine Script version (using version 5 of Pine Script) for myself and tested it side-by-side with the ta.pivotlow() and ta.pivothigh() functions and it seems to work well. Maybe this will help you as well.

```<code>my_pivothigh(float _series = high, int _leftBars, int _rightBars) =>
    float _pivotHigh = na
    int _pivotRange = ( _leftBars + _rightBars )
    float _leftEdgeValue = nz(_series[_pivotRange], na)
    if not na(_series) and _leftBars > 0 and _rightBars > 0 and not na(_leftEdgeValue)
        float _possiblePivotHigh = _series[_rightBars]
        float[] _arrayOfSeriesValues = array.new_float(0)
        for _barIndex = _pivotRange to 0
            array.push(_arrayOfSeriesValues, _series[_barIndex])
        //end for
        int _pivotHighRightBars = array.size(_arrayOfSeriesValues) - array.lastindexof(_arrayOfSeriesValues, array.max(_arrayOfSeriesValues)) - 1
        _pivotHigh := ( _pivotHighRightBars == _rightBars ) ? _possiblePivotHigh : na
    //end if
    _pivotHigh
</code>```
```<code>my_pivotlow(float _series = low, int _leftBars, int _rightBars) =>
    float _pivotLow = na
    int _pivotRange = ( _leftBars + _rightBars )
    float _leftEdgeValue = nz(_series[_pivotRange], na)
    if not na(_series) and _leftBars > 0 and _rightBars > 0 and not na(_leftEdgeValue)
        float _possiblePivotLow = _series[_rightBars]
        float[] _arrayOfSeriesValues = array.new_float(0)
        for _barIndex = _pivotRange to 0
            array.push(_arrayOfSeriesValues, _series[_barIndex])
        //end for
        int _pivotLowRightBars = array.size(_arrayOfSeriesValues) - array.lastindexof(_arrayOfSeriesValues, array.min(_arrayOfSeriesValues)) - 1
        _pivotLow := ( _pivotLowRightBars == _rightBars ) ? _possiblePivotLow : na
    //end if
    _pivotLow
</code>```

Body:
I too had a need to better understand how the pivothigh() and pivotlow() functions work internally so I made the effort to code a Pine Script version (using version 5 of Pine Script) for myself and tested it side-by-side with the ta.pivotlow() and ta.pivothigh() functions and it seems to work well. Maybe this will help you as well.

my_pivothigh(float _series = high, int _leftBars, int _rightBars) =>
    float _pivotHigh = na
    int _pivotRange = ( _leftBars + _rightBars )
    float _leftEdgeValue = nz(_series[_pivotRange], na)
    if not na(_series) and _leftBars > 0 and _rightBars > 0 and not na(_leftEdgeValue)
        float _possiblePivotHigh = _series[_rightBars]
        float[] _arrayOfSeriesValues = array.new_float(0)
        for _barIndex = _pivotRange to 0
            array.push(_arrayOfSeriesValues, _series[_barIndex])
        //end for
        int _pivotHighRightBars = array.size(_arrayOfSeriesValues) - array.lastindexof(_arrayOfSeriesValues, array.max(_arrayOfSeriesValues)) - 1
        _pivotHigh := ( _pivotHighRightBars == _rightBars ) ? _possiblePivotHigh : na
    //end if
    _pivotHigh

my_pivotlow(float _series = low, int _leftBars, int _rightBars) =>
    float _pivotLow = na
    int _pivotRange = ( _leftBars + _rightBars )
    float _leftEdgeValue = nz(_series[_pivotRange], na)
    if not na(_series) and _leftBars > 0 and _rightBars > 0 and not na(_leftEdgeValue)
        float _possiblePivotLow = _series[_rightBars]
        float[] _arrayOfSeriesValues = array.new_float(0)
        for _barIndex = _pivotRange to 0
            array.push(_arrayOfSeriesValues, _series[_barIndex])
        //end for
        int _pivotLowRightBars = array.size(_arrayOfSeriesValues) - array.lastindexof(_arrayOfSeriesValues, array.min(_arrayOfSeriesValues)) - 1
        _pivotLow := ( _pivotLowRightBars == _rightBars ) ? _possiblePivotLow : na
    //end if
    _pivotLow


问:
I had a problem with javascript alert fuunction
I am having 3 kind of swf players and if any one of player is playing all others should pause.

1 st one - audioPlayer - autoplay = true;
2 nd one - audioPlayer - autoplay = false;
3 rd one - audioPlayer - autoplay = false;

If 2nd and 3rd paused or ended then 1st one should continue if it was not paused.

This is my java script code.

```<code>function videoPlaying(val){
    tmp = val;
}
function sendTojs(value){
        if(value == "end" || value == "pause"){
         thisMovie("movie0").sndToAS("pause");
         alert("done");
    }
    for(i=0; i<=7; i++){
         var mov="movie"+i;
        if(tmp!=mov){
                thisMovie(mov).sndToAS("resume");
            }
         }
        }
</code>```

here sndToAS is my actionscript function and tmp will have the strings "resume", "pause" and "end". I have used externalInterface.callBack in AS3.

actionscript3.0

within callback function

```<code>if(val == "pause")
{
    videoPlay();
}
</code>```

My problem:
   if I use the alert function within sendTojs then the condition is working else not. Why?

答: If adding an alert fixes the problem, then it's a timing problem.  The alert stops execution until you dismiss it, radically changing the timing of the code.  Perhaps there's an asynchronous operation that needs to complete?</p>

ContentLicense: CC BY-SA 3.0

Body:
I am having 3 kind of swf players and if any one of player is playing all others should pause.

1 st one - audioPlayer - autoplay = true;
2 nd one - audioPlayer - autoplay = false;
3 rd one - audioPlayer - autoplay = false;

If 2nd and 3rd paused or ended then 1st one should continue if it was not paused.

This is my java script code.

function videoPlaying(val){
    tmp = val;
}
function sendTojs(value){
        if(value == "end" || value == "pause"){
         thisMovie("movie0").sndToAS("pause");
         alert("done");
    }
    for(i=0; i<=7; i++){
         var mov="movie"+i;
        if(tmp!=mov){
                thisMovie(mov).sndToAS("resume");
            }
         }
        }

here sndToAS is my actionscript function and tmp will have the strings "resume", "pause" and "end". I have used externalInterface.callBack in AS3.

actionscript3.0

within callback function

if(val == "pause")
{
    videoPlay();
}

My problem:
   if I use the alert function within sendTojs then the condition is working else not. Why?


问:
Type Definition : How to type an array to don't have tow specific value at the same time
I want to create a type that can only have those specific values and nothing else :

```<code>[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[-1,1]
</code>```

So to achieve that, I have made this type definition :

type Steps = -1 | 0 | 1;
type Directions = [width:Steps, height:Steps];
```
<p>But with this definition, I can do that :</p>
<pre class="lang-js prettyprint-override"><code>const invalidDirection : Directions = [0,0];
</code>```

And I don't know how to restrict that, especially for [0,0].

答:
There is no single, specific tuple type that corresponds to your intended Directions.  The single specific tuple type [width: Steps, height: Steps] will, by necessity, allow the first element (labeled width) to be chosen independently of the second element (labeled height).  And therefore nothing stops someone from choosing 0 for both elements.

If you want the two elements to depend on each other, you should write Directions as a union of acceptable types.  You could do this manually, either as

```<code>type Directions = [width: Steps, height: Exclude<Steps, 0>] |
  [width: Exclude<Steps, 0>, height: Steps];
</code>```

or as

```<code>type Directions = [width: 0, height: Exclude<Steps, 0>] |
  [width: Exclude<Steps, 0>, height: 0] |
  [width: Exclude<Steps, 0>, height: Exclude<Steps, 0>];
</code>```

or as

```<code>type Directions = [width: 0, height: 1] | [width: 0, height: -1] |
  [width: 1, height: 0] | [width: 1, height: 1] |
  [width: 1, height: -1] | [width: -1, height: 0] |
  [width: -1, height: 1] | [width: -1, height: -1];
</code>```

(Note that while all three of those correspond to the same set of static
values, they are not considered mutually equivalent by the compiler and may exhibit different behavior in different contexts; see Specializing Union Literal type property for some discussion)

Any of those result in the desired behavior:

```<code>let dir: Directions;
dir = [0, -1]; // okay
dir = [1, -1]; // okay
dir = [1, 0]; // okay
dir = [1, 1]; // okay
dir = [0, 1]; // okay
dir = [-1, 1]; // okay
dir = [-1, 0]; // okay
dir = [-1, -1]; // okay
dir = [0, 0]; // error!
</code>```

The first two approaches use the Exclude<T, U> utility type to filter types out of a union.  Note that the first one is terse enough that you may decide to use it directly.

On the other hand, you might want to do this programmatically from the definition of Steps, instead of manually... especially if you care about scaling the unions up or changing their values.  Here's one way to do it:

```<code>type Directions = Exclude<
    { [W in Steps]: {
        [H in Steps]: [width: W, height: H] }[Steps]
    }[Steps], [0, 0]>;
</code>```

We are Exclude-ing the bad [0, 0] member from the expression {[W in Steps]....}, so let's examine that.  Here I'm making a nested "distributive object type" (as defined in microsoft/TypeScript#47109), which is making a mapped type and then immediately indexing into it to get a union.  Let's look at the inner one, {[H in Steps]: [width: W, height: H]}[Steps]:

The mapped type iterates H over each union member of Steps and makes a new three-keyed object type like {"-1": [width: W, height: -1], "0": [width: W, height: 0], "1": [width: W, height: 1]}.  We then index into that object type with the index [-1 | 0 | 1] which produces the three-member union [width: W, height: -1] | [width: W, height: 0] | [width: W, height: 1].  You can hopefully see how the outer distributed object type plugs in -1, 0, and 1 for W and produces a nine-element union.

And recall that we Exclude the [width: 0, height: 0] element from that union to get the eight-element union you desired!

Playground link to code

Body:
I want to create a type that can only have those specific values and nothing else :

[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[-1,1]

So to achieve that, I have made this type definition :

type Steps = -1 | 0 | 1;
type Directions = [width:Steps, height:Steps];

But with this definition, I can do that :

const invalidDirection : Directions = [0,0];

And I don't know how to restrict that, especially for [0,0].

Body:
There is no single, specific tuple type that corresponds to your intended Directions.  The single specific tuple type [width: Steps, height: Steps] will, by necessity, allow the first element (labeled width) to be chosen independently of the second element (labeled height).  And therefore nothing stops someone from choosing 0 for both elements.

If you want the two elements to depend on each other, you should write Directions as a union of acceptable types.  You could do this manually, either as

type Directions = [width: Steps, height: Exclude<Steps, 0>] |
  [width: Exclude<Steps, 0>, height: Steps];

or as

type Directions = [width: 0, height: Exclude<Steps, 0>] |
  [width: Exclude<Steps, 0>, height: 0] |
  [width: Exclude<Steps, 0>, height: Exclude<Steps, 0>];

or as

type Directions = [width: 0, height: 1] | [width: 0, height: -1] |
  [width: 1, height: 0] | [width: 1, height: 1] |
  [width: 1, height: -1] | [width: -1, height: 0] |
  [width: -1, height: 1] | [width: -1, height: -1];

(Note that while all three of those correspond to the same set of static
values, they are not considered mutually equivalent by the compiler and may exhibit different behavior in different contexts; see Specializing Union Literal type property for some discussion)

Any of those result in the desired behavior:

let dir: Directions;
dir = [0, -1]; // okay
dir = [1, -1]; // okay
dir = [1, 0]; // okay
dir = [1, 1]; // okay
dir = [0, 1]; // okay
dir = [-1, 1]; // okay
dir = [-1, 0]; // okay
dir = [-1, -1]; // okay
dir = [0, 0]; // error!

The first two approaches use the Exclude<T, U> utility type to filter types out of a union.  Note that the first one is terse enough that you may decide to use it directly.

On the other hand, you might want to do this programmatically from the definition of Steps, instead of manually... especially if you care about scaling the unions up or changing their values.  Here's one way to do it:

type Directions = Exclude<
    { [W in Steps]: {
        [H in Steps]: [width: W, height: H] }[Steps]
    }[Steps], [0, 0]>;

We are Exclude-ing the bad [0, 0] member from the expression {[W in Steps]....}, so let's examine that.  Here I'm making a nested "distributive object type" (as defined in microsoft/TypeScript#47109), which is making a mapped type and then immediately indexing into it to get a union.  Let's look at the inner one, {[H in Steps]: [width: W, height: H]}[Steps]:

The mapped type iterates H over each union member of Steps and makes a new three-keyed object type like {"-1": [width: W, height: -1], "0": [width: W, height: 0], "1": [width: W, height: 1]}.  We then index into that object type with the index [-1 | 0 | 1] which produces the three-member union [width: W, height: -1] | [width: W, height: 0] | [width: W, height: 1].  You can hopefully see how the outer distributed object type plugs in -1, 0, and 1 for W and produces a nine-element union.

And recall that we Exclude the [width: 0, height: 0] element from that union to get the eight-element union you desired!

<a href="https://www.typescriptlang.org/play?#code/HYQwtgpgzgDiDGEAEBZEwCuIA2BGJA3gFBFJlIAuAnjMgMoUQxRIC8SAtPgD5IAMSXrgDcJcpRrIAIgEsAThHgUZAe2At2AbQDuMgCYUAFgC4kDJlAA0SQxBkBzQxVMBRAB7xsGPRAA855ms+AD4AXUEkHX0jVw8vH39GQP5g61sHJ1MAqFDRUnJsCAokPXlTWQUlVXVRcVK5Nki+ay5cpAB6dqQVAGsQKnyyesbNXBbcNs7uvoG6+RGx-kmu3v7BkvmtRYnhDpWZ9eGtZqQdvem1uYatLmszqdXZ8iPI26Xdh4OrkbfWj-3Ls9Nk0gsskBA5HIVHIAIQkAC+JFAkFgCGQaEwOAATIQxORqLQzEkNJwePwIiI8WQCdJ5IplGoSVEDCZ+Gk7I5nEh3J5vH5skEwhFmTFuXE+YkLIL2RkuXxwtx1iLWTz4vzidKbBzMmLeQkBSlclSkIVivVynSqozakDriDSWDHodgaNxo6vraFqD-hcnkMXdt3YD-XbNCd7gC-RtQ28I77nTHFvKfU7vjdFn9zqnPcdvecIVDYQiSERkdA4IhUOgsNgAMy49Y0okWRpcCICIR5cRNir06pM3Qs0wndKc0wTYWD0Uj7Vc1qT6KsxajnXywRKqdLmVj04KyKb8fbnXz3jK0xvFdyvdn0lHrkTxXiG8X2fnibG03Ri2VBk1BMjE5M0+YNoy9B0Uw9EMwOTLNINArY7iDKMXjDRCIJAlDYyQ-90zzYDkJdX442zKDc3efNIWhOFEVLcByzRJAAAUoXsORwDAEBlHgBtu0kZtmFbMkO1OLt8T43srXURpVQldZxAISIAHUkBkYB+JyUxiHEbTyE0AAJFS1OyUJTBvRS71MPTwnhTRjLk8gbOM6xUKWYJRLIdoACoJEJCTfwHRdhws3cFyHNktVlN9rwPU5grXXg5JvZdXxC08YuSyKHVC0UX0y+L90C28Ip3B8kESmLcp3edPPaEtxE-c0kD8-sbVI+0gMjHDIgzYi4JQpNsLTbq0NgjCXXDQac1eQN0IIxM8M6obNCIya2pcmCpgLKiESAA" rel="nofollow noreferrer">Playground link to code


问:
Error: A required parameter (id) was not provided as a string in getStaticPaths for /location/[id]
im working on a next.js and mongodb website and im following this tutorial exactly but with different files/variable names. i keep running into this error when trying to access the dynamic page : Error: A required parameter (id) was not provided as a string in getStaticPaths for /location/[id]

tutorial : https://www.youtube.com/watch?v=MFuwkrseXVE&ab_channel=Academind       Just before 2 hours 40 min

PS deleted db info for security reasons

```<code>export async function getStaticPaths(){
    const client = await MongoClient.connect(''); ////////// username and password here for mongo db and db name
    const db = client.db();

    const destinationsCollection = db.collection('destination');
    const destinations = await destinationsCollection.find({},{_id: 1}).toArray();
    client.close();
    return {
        fallback: false,
        paths: destinations.map((destination) => ({ params: {destinationId: destination._id.toString()},
    })),
    };
}
</code>```

答:
NextJS is very meticulous with its data fetching functions and you have to be very careful with the way that you return parameters with getStaticPaths() in dynamic routing pages. I believe the problem here is that when you return "params", you store the id of your data (destination._id.toString()) into a JSON variable called "destinationId". However, since the page is called "[id]", Next will be expecting an "id" JSON variable inside of "params". So your final code should look something like this:

```<code>export async function getStaticPaths(){
const client = await MongoClient.connect(''); ////////// username and password here for mongo db and db name
const db = client.db();

const destinationsCollection = db.collection('destination');
const destinations = await destinationsCollection.find({},{_id: 1}).toArray();
client.close();
return {
    fallback: false,
    paths: destinations.map((destination) => ({ params: {id: destination._id.toString()},
})),
};
</code>```

}

Hopefully this solves the issue!

Body:
im working on a next.js and mongodb website and im following this tutorial exactly but with different files/variable names. i keep running into this error when trying to access the dynamic page : Error: A required parameter (id) was not provided as a string in getStaticPaths for /location/[id]

tutorial : https://www.youtube.com/watch?v=MFuwkrseXVE&ab_channel=Academind       Just before 2 hours 40 min

PS deleted db info for security reasons

export async function getStaticPaths(){
    const client = await MongoClient.connect(''); ////////// username and password here for mongo db and db name
    const db = client.db();

    const destinationsCollection = db.collection('destination');
    const destinations = await destinationsCollection.find({},{_id: 1}).toArray();
    client.close();
    return {
        fallback: false,
        paths: destinations.map((destination) => ({ params: {destinationId: destination._id.toString()},
    })),
    };
}

Body:
NextJS is very meticulous with its data fetching functions and you have to be very careful with the way that you return parameters with getStaticPaths() in dynamic routing pages. I believe the problem here is that when you return "params", you store the id of your data (destination._id.toString()) into a JSON variable called "destinationId". However, since the page is called "[id]", Next will be expecting an "id" JSON variable inside of "params". So your final code should look something like this:

export async function getStaticPaths(){
const client = await MongoClient.connect(''); ////////// username and password here for mongo db and db name
const db = client.db();

const destinationsCollection = db.collection('destination');
const destinations = await destinationsCollection.find({},{_id: 1}).toArray();
client.close();
return {
    fallback: false,
    paths: destinations.map((destination) => ({ params: {id: destination._id.toString()},
})),
};

}

Hopefully this solves the issue!


问:
Comparing and coloring 2 cells in the same row pandas
I am trying to compare 2 cells in pandas. To do this:

```<code>import pandas as pd
from pandas_datareader import data as web
df = web.DataReader('fb', 'yahoo')
</code>```

With this lambda function to get the dates where df['Open'] > df['Close']:

```<code>df.apply(lambda x: x['Close'] if x['Close'] <=
                     x['Open'] else np.nan, axis=1)
</code>```

I want to highlight df['Close'] cell with red once this condition is met:

```<code>df.style.applymap(lambda x: 'background-color : red' if x['Close'] <=
                     x['Open'] else 'background-color : green')
</code>```

But this is giving me this error:

TypeError: 'float' object is not subscriptable

Could you please advise why is it giving this error?

答:
You should achieve it through this, without applying the first lambda function:</p>
```<code>def row_style(row):
    if if x['Close'] <= x['Open']:
        return pd.Series('background-color: red', row.index)
    else:
        return pd.Series('background-color: green', row.index)

df.style.apply(row_style, axis=1, subset=['Close'])
</code>```

Body:
I am trying to compare 2 cells in pandas. To do this:

import pandas as pd
from pandas_datareader import data as web
df = web.DataReader('fb', 'yahoo')

With this lambda function to get the dates where df['Open'] > df['Close']:

df.apply(lambda x: x['Close'] if x['Close'] <=
                     x['Open'] else np.nan, axis=1)

I want to highlight df['Close'] cell with red once this condition is met:

df.style.applymap(lambda x: 'background-color : red' if x['Close'] <=
                     x['Open'] else 'background-color : green')

But this is giving me this error:

TypeError: 'float' object is not subscriptable

Could you please advise why is it giving this error?

Body:
You should achieve it through this, without applying the first lambda function:

def row_style(row):
    if if x['Close'] <= x['Open']:
        return pd.Series('background-color: red', row.index)
    else:
        return pd.Series('background-color: green', row.index)

df.style.apply(row_style, axis=1, subset=['Close'])


问:
Integer to pointer cast pessimism optimization opportunities
The from_base function returns the memory address from the base to a selected
value in a program. I want to retrieve this value and return it in a function, however, I am getting a warning that says integer to pointer cast pessimism optimization opportunities.

DWORD chat::client() {
    return *reinterpret_cast<DWORD*>(core::from_base(offsets::chat::client));
}
```
<p>I am also getting this warning when casting a function from the program:</p>
<pre class="lang-cpp prettyprint-override"><code>auto og_print = reinterpret_cast<chat::fn_print_chat>(core::from_base(offsets::chat::print));
</code>```

I don't understand why I am getting a warning from clang-tidy about integer to pointer cast pessimism optimization opportunities

performance-no-int-to-ptr

I looked it up, but I can't figure it out. The code works, and gets the correct value. I am just concerned about the warning.

答:
If a program performs a computation like:

```<code>char x[10],y[10];
int test(ptrdiff_t i)
{
  int *p = x+i;
  *p = 1;
  y[1] = 2;
  return *p;
}
</code>```

a compiler would be reasonably entitled to assume that because p was formed via pointer arithmetic using x, it could not possible equal y+1, and thus the function would always return 1.  If, however, the code had been written as:

```<code>char x[10],y[10];
int test(ptrdiff_t i)
{
  int *p = (char*)((uintptr_t)x + i);
  *p = 1;
  y[1] = 2;
  return *p;
}
</code>```

then such an assumption would be far less reasonable, since unsigned numerical semantics would define the behavior of uintptr_t z = (uintptr_t)(y+1)-(uintptr_t)x as yielding a value such that x+z would equal (uintptr_t)(y+1).

I find the apparent caution clang exhibits here a bit surprising, given that clang is prone to assume that, given some pointer char*p, it's not possible for p to equal y if (uintptr_t)p to equal (uintptr_t)(x+10) and yet for p to equal y.  The Standard doesn't forbid such an assumption, but then again it also wouldn't forbid an assumption that code will never use the result of any integer-to-pointer conversion for any purpose other than comparisons with other pointers.  Implementations that support type uintptr_t should of course offer stronger guarantees about round-tripped pointers which than merely saying they may be compared for equality with the originals, but the Standard doesn't require such treatment.

Body:
The from_base function returns the memory address from the base to a selected
value in a program. I want to retrieve this value and return it in a function, however, I am getting a warning that says integer to pointer cast pessimism optimization opportunities.

DWORD chat::client() {
    return *reinterpret_cast<DWORD*>(core::from_base(offsets::chat::client));
}

I am also getting this warning when casting a function from the program:

auto og_print = reinterpret_cast<chat::fn_print_chat>(core::from_base(offsets::chat::print));

I don't understand why I am getting a warning from clang-tidy about integer to pointer cast pessimism optimization opportunities

performance-no-int-to-ptr

I looked it up, but I can't figure it out. The code works, and gets the correct value. I am just concerned about the warning.

Body:
If a program performs a computation like:

char x[10],y[10];
int test(ptrdiff_t i)
{
  int *p = x+i;
  *p = 1;
  y[1] = 2;
  return *p;
}

a compiler would be reasonably entitled to assume that because p was formed via pointer arithmetic using x, it could not possible equal y+1, and thus the function would always return 1.  If, however, the code had been written as:

char x[10],y[10];
int test(ptrdiff_t i)
{
  int *p = (char*)((uintptr_t)x + i);
  *p = 1;
  y[1] = 2;
  return *p;
}

then such an assumption would be far less reasonable, since unsigned numerical semantics would define the behavior of uintptr_t z = (uintptr_t)(y+1)-(uintptr_t)x as yielding a value such that x+z would equal (uintptr_t)(y+1).

I find the apparent caution clang exhibits here a bit surprising, given that clang is prone to assume that, given some pointer char*p, it's not possible for p to equal y if (uintptr_t)p to equal (uintptr_t)(x+10) and yet for p to equal y.  The Standard doesn't forbid such an assumption, but then again it also wouldn't forbid an assumption that code will never use the result of any integer-to-pointer conversion for any purpose other than comparisons with other pointers.  Implementations that support type uintptr_t should of course offer stronger guarantees about round-tripped pointers which than merely saying they may be compared for equality with the originals, but the Standard doesn't require such treatment.


问:
Python/Json:Expecting property name enclosed in double quotes
I've been trying to figure out a good way to load JSON objects in Python.
I send this json data:

```<code>{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}
</code>```

to the backend where it will be received as a string then I used json.loads(data) to parse it.

But each time I got the same exception :

```<code>ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
</code>```

I googled it but nothing seems to work besides this solution json.loads(json.dumps(data)) which personally seems for me not that efficient since it accept any kind of data even the ones that are not in json format.

Any suggestions will be much appreciated.

答: My problem was that I copy and pasted a JSON snippet and the double quotes that were used were somehow a different, unrecognized double quote character. My file was valid JSON after replacing the double quotes.</p>

Body:
I've been trying to figure out a good way to load JSON objects in Python.
I send this json data:

{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}

to the backend where it will be received as a string then I used json.loads(data) to parse it.

But each time I got the same exception :

ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

I googled it but nothing seems to work besides this solution json.loads(json.dumps(data)) which personally seems for me not that efficient since it accept any kind of data even the ones that are not in json format.

Any suggestions will be much appreciated.


问:
Non-binary tree finding leaf nodes (C#)
```<code>           Child c1 = new Child();
            c1.name = "c1";
            c1.Isleaf = false;

            Child c2 = new Child();
            c2.name = "c2";
            c2.Isleaf = true;

            Child c11 = new Child();
            c11.name = "c11";
            c11.Isleaf = true;

            Child c12 = new Child();
            c12.name = "c12";
            c12.Isleaf = false;

            Child c121 = new Child();
            c121.name = "c121";
            c121.Isleaf = true;

            c12.Children = new List<Child>() { c121 };
            c1.Children = new List<Child>() { c11, c12 };

            Parent p = new Parent();

            p.name = "P1";

            p.Children = new List<Child>() { c1, c2 };
            List<Child> leaves = new List<Child>();

enter code here
</code>```

I implemented finding leaves as following using Queue

```<code>static public void FindLeavesQueue(Parent p, List<Child> leaves)
{

    if (p.Children == null) return;

    var toVisit = new Queue<Child>(p.Children);

    while (toVisit.Count > 0)
    {
        var current = toVisit.Dequeue();
        if (current.Isleaf)
            leaves.Add(current);

        if (current.Children != null)
        {
            foreach (var child in current.Children)
            {
                if (child.Isleaf)
                    leaves.Add(child);
                else
                {
                    foreach (Child c in child.Children)
                       toVisit.Enqueue(c);
                }

            }

        }

    }

}
enter code here
</code>```

But in my application this is running very slow. Because tree is really huge and database transactions are involved.
What is the best way to have it faster?
Thanks

答:
recursive descent is simply and faster, no copy of stuff to queues.</p>
```<code>static public void FindLeaves(Parent p, List<Child> leaves)
{

    if (p.Children == null) return;
    foreach(var child in p.Children)
    {
          if(child.IsLeaf)
             leaves.Add(child);
          else
             FindLeaves(child, leaves);
    }

}
</code>```

Title: Non-binary tree finding leaf nodes (C#)

Body:
           Child c1 = new Child();
            c1.name = "c1";
            c1.Isleaf = false;

            Child c2 = new Child();
            c2.name = "c2";
            c2.Isleaf = true;

            Child c11 = new Child();
            c11.name = "c11";
            c11.Isleaf = true;

            Child c12 = new Child();
            c12.name = "c12";
            c12.Isleaf = false;

            Child c121 = new Child();
            c121.name = "c121";
            c121.Isleaf = true;

            c12.Children = new List<Child>() { c121 };
            c1.Children = new List<Child>() { c11, c12 };

            Parent p = new Parent();

            p.name = "P1";

            p.Children = new List<Child>() { c1, c2 };
            List<Child> leaves = new List<Child>();

enter code here

I implemented finding leaves as following using Queue

static public void FindLeavesQueue(Parent p, List<Child> leaves)
{

    if (p.Children == null) return;

    var toVisit = new Queue<Child>(p.Children);

    while (toVisit.Count > 0)
    {
        var current = toVisit.Dequeue();
        if (current.Isleaf)
            leaves.Add(current);

        if (current.Children != null)
        {
            foreach (var child in current.Children)
            {
                if (child.Isleaf)
                    leaves.Add(child);
                else
                {
                    foreach (Child c in child.Children)
                       toVisit.Enqueue(c);
                }

            }

        }

    }

}
enter code here

But in my application this is running very slow. Because tree is really huge and database transactions are involved.
What is the best way to have it faster?
Thanks

Body:
recursive descent is simply and faster, no copy of stuff to queues.

static public void FindLeaves(Parent p, List<Child> leaves)
{

    if (p.Children == null) return;
    foreach(var child in p.Children)
    {
          if(child.IsLeaf)
             leaves.Add(child);
          else
             FindLeaves(child, leaves);
    }

}


问:
Numpy add (append) value to each row of 2-d array
I have numpy array of floats with shape (x,14) and I would like to add to the end of each "row" one more value (to each row different value), so that end result has shape (x,15).

We can suppose that I have those values in some list, so that part of the question is also defined.

How to do it with numpy functions?

答:
You can use numpy.insert function (https://numpy.org/doc/stable/reference/generated/numpy.insert.html)

```<code>a = np.array([[1, 1], [2, 2], [3, 3]])
np.insert(a, 2, 0, axis=1)
</code>```

Output:

```<code>array([[1, 1, 0],
       [2, 2, 0],
       [3, 3, 0]])
</code>```

Body:
You can use numpy.insert function (https://numpy.org/doc/stable/reference/generated/numpy.insert.html)

a = np.array([[1, 1], [2, 2], [3, 3]])
np.insert(a, 2, 0, axis=1)

Output:

array([[1, 1, 0],
       [2, 2, 0],
       [3, 3, 0]])


问:
mysql-connector won't connect

import mysql.connector
from mysql.connector import Error

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='Electronics',
                                         user='pynative',
                                         password='pynative@#29')
    if connection.is_connected():
        db_Info = connection.get_server_info()
        print("Connected to MySQL Server version ", db_Info)
        cursor = connection.cursor()
        cursor.execute("select database();")
        record = cursor.fetchone()
        print("You're connected to database: ", record)

except Error as e:
    print("Error while connecting to MySQL", e)
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")
```

I know this should work because I have the code copied from a website. But for some reason it show s the error

'if connection.is_connected():
NameError: name 'connection' is not defined'

答:
If the mysql.connector.connect raisesan error, then connection variabe is never defined and you can't use it in the finally.

A solution is to initialize it as None and check that it isn't none before using it in the finally

connection = None
try:
    connection = mysql.connector.connect(host='localhost',
                                         database='Electronics',
                                         user='pynative',
                                         password='pynative@#29')
    if connection.is_connected():
        db_Info = connection.get_server_info()
        print("Connected to MySQL Server version ", db_Info)
        cursor = connection.cursor()
        cursor.execute("select database();")
        record = cursor.fetchone()
        print("You're connected to database: ", record)

except Error as e:
    print("Error while connecting to MySQL", e)
finally:
    if connection and connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")
```

Title: mysql-connector won't connect

Body:
import mysql.connector
from mysql.connector import Error

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='Electronics',
                                         user='pynative',
                                         password='pynative@#29')
    if connection.is_connected():
        db_Info = connection.get_server_info()
        print("Connected to MySQL Server version ", db_Info)
        cursor = connection.cursor()
        cursor.execute("select database();")
        record = cursor.fetchone()
        print("You're connected to database: ", record)

except Error as e:
    print("Error while connecting to MySQL", e)
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")

I know this should work because I have the code copied from a website. But for some reason it show s the error

'if connection.is_connected():
NameError: name 'connection' is not defined'


答:
It would be easier to use xmltable or (json_table for Oracle 12+) for such purposes.

Example with xmltable:

Just aggregate all the required data into xmltype:
you can use xmltype(cursor(select...from...)):

select xmltype(cursor(select * from test)) xml from dual;
```
<p>or <code>dbms_xmlgen.getxmltype(query_string)</code>:</p>
<pre class="lang-sql prettyprint-override"><code>select dbms_xmlgen.getxmltype('select * from test') xml from dual;
</code>```

then you can use the returned XML with

```<code>xmltable('/ROWSET/ROW' passing xmltype(your_xml) columns ...)
</code>```

Example:

```<code>select *
from xmltable(
        '/ROWSET/ROW'
        passing xmltype(q'[<?xml version="1.0"?>
<ROWSET>
 <ROW>
  <ASSET_ID>10</ASSET_ID>
  <VERTEX_NUM>1</VERTEX_NUM>
  <X>118.56</X>
  <Y>3.8</Y>
 </ROW>
 <ROW>
  <ASSET_ID>10</ASSET_ID>
  <VERTEX_NUM>2</VERTEX_NUM>
  <X>118.62</X>
  <Y>1.03</Y>
 </ROW>
</ROWSET>
        ]')
    columns
        asset_id,vertex_num,x,y
) test
</code>```

Full example on DBFiddle: https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=036b718f2b18df898c3e3de722c97378

Title: Generate a WITH clause/UNIONs from a SELECT

Body:
I want to generate a WITH clause/UNIONs — for the purpose of easily sharing small samples of data  (10-20 rows).

I want to do that without creating tables or inserting rows.

Example:

Take a table or query like this:

...and generate this:

with cte as(
select 10 as asset_id, 1 as vertex_num, 118.56 as x, 3.8 as y from dual
union all
select 10 as asset_id, 2 as vertex_num, 118.62 as x, 1.03 as y from dual
union all
select 10 as asset_id, 3 as vertex_num, 121.93 as x, 1.03 as y from dual)

 --There are lots more rows. But it's too much work to write them all out.

select * from cte

Using SQL, how can I automatically generate a WITH clause/UNIONs from the resultset?

I believe there is OOTB export functionality in Toad that can do that. But I don't think there are any tools in SQL Developer that can do it, which is what I'm using.

When attempting this with SQL, I think the main challenge is to loop through n columns. I'm not sure how to do that.

Body:
It would be easier to use xmltable or (json_table for Oracle 12+) for such purposes.

Example with xmltable:

Just aggregate all the required data into xmltype:
you can use xmltype(cursor(select...from...)):

select xmltype(cursor(select * from test)) xml from dual;

or dbms_xmlgen.getxmltype(query_string):

select dbms_xmlgen.getxmltype('select * from test') xml from dual;

then you can use the returned XML with

xmltable('/ROWSET/ROW' passing xmltype(your_xml) columns ...)

Example:

select *
from xmltable(
        '/ROWSET/ROW'
        passing xmltype(q'[<?xml version="1.0"?>
<ROWSET>
 <ROW>
  <ASSET_ID>10</ASSET_ID>
  <VERTEX_NUM>1</VERTEX_NUM>
  <X>118.56</X>
  <Y>3.8</Y>
 </ROW>
 <ROW>
  <ASSET_ID>10</ASSET_ID>
  <VERTEX_NUM>2</VERTEX_NUM>
  <X>118.62</X>
  <Y>1.03</Y>
 </ROW>
</ROWSET>
        ]')
    columns
        asset_id,vertex_num,x,y
) test

Full example on DBFiddle: https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=036b718f2b18df898c3e3de722c97378


问:
jQuery - remove user input text from textarea
Okay I have a list of devices where i can select which to edit.
I have 3 states for the edit. When no devices are selected, when 1 device is selected or when x devices are selected.

The problem i have is when a user type some text in the textarea (commentField) and cancels the edit to edit another device, the text there was typed in the textarea won't disapere. It stays so when i get the new dialog for the new edit, the commentfield has the text from the old commentField (as if it wasn't cleared)

I have tried the following codes to remove the text (both when then cancel button is pressed and when i start a new dialog), but nothing works:

```<code>$("#commentField").text(" ");
$("#commentField").value = ' ';
</code>```

Is there anyone who knows how to remove user-typed text from a textarea using jQuery??

Thanks in advance.

-Thor

答: In jQuery it's actually $("#commentField").val(" ");

Body:
Okay I have a list of devices where i can select which to edit.
I have 3 states for the edit. When no devices are selected, when 1 device is selected or when x devices are selected.

The problem i have is when a user type some text in the textarea (commentField) and cancels the edit to edit another device, the text there was typed in the textarea won't disapere. It stays so when i get the new dialog for the new edit, the commentfield has the text from the old commentField (as if it wasn't cleared)

I have tried the following codes to remove the text (both when then cancel button is pressed and when i start a new dialog), but nothing works:

$("#commentField").text(" ");
$("#commentField").value = ' ';

Is there anyone who knows how to remove user-typed text from a textarea using jQuery??

Thanks in advance.

-Thor


问:
How To Parse A List Of Strings And Add Values to a Map<String,Integer> Using Lambdas
In my console project I receive input {String resource} {int quantity} on one line (can receive several pairs example: 3 Motes 5 stones 5 Shards

My goal is to refactor the body of while loop to use as many lambdas as possible.
I'd love to reduce the ungodly amount of if-else statements and use a Predicate, but I'm a newbie and am more looking for pointers what else I could try.

I've checked the javadoc for Collectors, Arrays.stream() and also read through the tutorials in Oracle's JDK 8 lambdas and functional programming, but obviously need more of a practical example.

The goal is to obtain 250 of a resource for one of the legendaries Map key and stop the program.
I parse the values with Scanner, split by one whitespace and implement my logic as follows:

```<code>private final static int REQUIRED_QUANTITY = 250;
private static boolean gameOver = false;
Map<String, String> legendary = new HashMap<>();
        legendary.put("shards", "Shadowmourne");
        legendary.put("fragments", "Valanyr");
        legendary.put("motes", "Dragonwrath");

        Map<String, Integer> resources = new HashMap<>();

        while (true) {
            String[] loot = scanner.nextLine().toLowerCase().split(" ");
            String material = null;
            int quantity = 0;

            for (int i = 0; i < loot.length; i++) {
                if (i % 2 != 0) {
                    material = loot[i];
                } else {
                    quantity = Integer.parseInt(loot[i]);
                }

                if (material != null && quantity != 0) {
                    if (resources.containsKey(material.toLowerCase())) {
                        resources.replace(material, resources.get(material) + quantity);
                    }
                    resources.putIfAbsent(material.toLowerCase(), quantity);

                    material = null;
                    quantity = 0;
                }
            }

            resources.forEach((s, integer) -> {
                if (integer > REQUIRED_QUANTITY) {
                    System.out.println("Legendary obtained: " + legendary.get(s));
                    gameOver = true;
                }
            });
</code>```

答:
I've encapsulated the code you've provided into a class.

Map resources renamed and changed to an instance variable Map<String, Integer> resourceToQuantity. Flag gameOver was made into an instance variable as well.

The main game-logic resides inside the collectResources() method and main enhancements were made here:

The flag gameOver is used as an exit condition of the while loop;

Condition of the nested for loop was changed;

The for loop was shortened, if/else statement removed;

The scope of variables quantity and material was reduced;

At each iteration of the loop quantity is being merged and the total is being checked against the REQUIRED_QUANTITY;

If this condition is meat flag gameOver is being set to true and the game-loop exits.

Collected resources are being printed.

```<code>public class LootHunter {
    private final static int REQUIRED_QUANTITY = 250;
    private static final Map<String, String> legendary = Map.of(
            "shards", "Shadowmourne",
            "fragments", "Valanyr",
            "motes", "Dragonwrath"
    );

    private final Map<String, Integer> resourceToQuantity;
    private boolean gameOver;

    public LootHunter() {
        this.resourceToQuantity = new HashMap<>();
    }

    public void collectResources() {
        while (!gameOver) {
            Scanner scanner = new Scanner(System.in);
            String[] loot = scanner.nextLine().toLowerCase().split(" ");

            for (int i = 0; i < loot.length - 1; i += 2) {
                int quantity = Integer.parseInt(loot[i]);
                String material = loot[i + 1];
                int totalQuantity = resourceToQuantity.merge(material, quantity, Integer::sum); // merges quantities and returns the sum

                if (totalQuantity > REQUIRED_QUANTITY) {
                    System.out.printf("You win! %d of %s have been collected.%n", totalQuantity, material);
                    System.out.println("Legendary item obtained: " + legendary.get(material));
                    gameOver = true;
                    break;
                }
            }
        }
        printAllResources(); // prints all the collected resources
    }

    public void printAllResources() {
        System.out.println("List of resources collected:");
        resourceToQuantity.forEach((material, quantity) ->
                System.out.printf("%s: %d%n", material, quantity));
    }

    public static void main(String[] args) {
        LootHunter lootHunter = new LootHunter();
        lootHunter.collectResources();
    }
}
</code>```

input:

```<code>"30 shards 10 fragments 50 motes 80 fragments 70 shards 180 fragments"
</code>```

output

```<code>You win! 270 of fragments have been collected.
Legendary item obtained: Valanyr
List of resources collected:
shards: 100
motes: 50
fragments: 270
</code>```

Body:
In my console project I receive input {String resource} {int quantity} on one line (can receive several pairs example: 3 Motes 5 stones 5 Shards

My goal is to refactor the body of while loop to use as many lambdas as possible.
I'd love to reduce the ungodly amount of if-else statements and use a Predicate, but I'm a newbie and am more looking for pointers what else I could try.

I've checked the javadoc for Collectors, Arrays.stream() and also read through the tutorials in Oracle's JDK 8 lambdas and functional programming, but obviously need more of a practical example.

The goal is to obtain 250 of a resource for one of the legendaries Map key and stop the program.
I parse the values with Scanner, split by one whitespace and implement my logic as follows:

private final static int REQUIRED_QUANTITY = 250;
private static boolean gameOver = false;
Map<String, String> legendary = new HashMap<>();
        legendary.put("shards", "Shadowmourne");
        legendary.put("fragments", "Valanyr");
        legendary.put("motes", "Dragonwrath");

        Map<String, Integer> resources = new HashMap<>();

        while (true) {
            String[] loot = scanner.nextLine().toLowerCase().split(" ");
            String material = null;
            int quantity = 0;

            for (int i = 0; i < loot.length; i++) {
                if (i % 2 != 0) {
                    material = loot[i];
                } else {
                    quantity = Integer.parseInt(loot[i]);
                }

                if (material != null && quantity != 0) {
                    if (resources.containsKey(material.toLowerCase())) {
                        resources.replace(material, resources.get(material) + quantity);
                    }
                    resources.putIfAbsent(material.toLowerCase(), quantity);

                    material = null;
                    quantity = 0;
                }
            }

            resources.forEach((s, integer) -> {
                if (integer > REQUIRED_QUANTITY) {
                    System.out.println("Legendary obtained: " + legendary.get(s));
                    gameOver = true;
                }
            });

Body:
I've encapsulated the code you've provided into a class.

Map resources renamed and changed to an instance variable Map<String, Integer> resourceToQuantity. Flag gameOver was made into an instance variable as well.

The main game-logic resides inside the collectResources() method and main enhancements were made here:

The flag gameOver is used as an exit condition of the while loop;

Condition of the nested for loop was changed;

The for loop was shortened, if/else statement removed;

The scope of variables quantity and material was reduced;

At each iteration of the loop quantity is being merged and the total is being checked against the REQUIRED_QUANTITY;

If this condition is meat flag gameOver is being set to true and the game-loop exits.

Collected resources are being printed.

public class LootHunter {
    private final static int REQUIRED_QUANTITY = 250;
    private static final Map<String, String> legendary = Map.of(
            "shards", "Shadowmourne",
            "fragments", "Valanyr",
            "motes", "Dragonwrath"
    );

    private final Map<String, Integer> resourceToQuantity;
    private boolean gameOver;

    public LootHunter() {
        this.resourceToQuantity = new HashMap<>();
    }

    public void collectResources() {
        while (!gameOver) {
            Scanner scanner = new Scanner(System.in);
            String[] loot = scanner.nextLine().toLowerCase().split(" ");

            for (int i = 0; i < loot.length - 1; i += 2) {
                int quantity = Integer.parseInt(loot[i]);
                String material = loot[i + 1];
                int totalQuantity = resourceToQuantity.merge(material, quantity, Integer::sum); // merges quantities and returns the sum

                if (totalQuantity > REQUIRED_QUANTITY) {
                    System.out.printf("You win! %d of %s have been collected.%n", totalQuantity, material);
                    System.out.println("Legendary item obtained: " + legendary.get(material));
                    gameOver = true;
                    break;
                }
            }
        }
        printAllResources(); // prints all the collected resources
    }

    public void printAllResources() {
        System.out.println("List of resources collected:");
        resourceToQuantity.forEach((material, quantity) ->
                System.out.printf("%s: %d%n", material, quantity));
    }

    public static void main(String[] args) {
        LootHunter lootHunter = new LootHunter();
        lootHunter.collectResources();
    }
}

input:

"30 shards 10 fragments 50 motes 80 fragments 70 shards 180 fragments"

output

You win! 270 of fragments have been collected.
Legendary item obtained: Valanyr
List of resources collected:
shards: 100
motes: 50
fragments: 270


问:
Multiple Trips to the Db
I have those group of CheckBox Lists and Repeaters (about 8 controls needed to be loaded from my db) and for each control, I have a method in my DataAccess Layer to select the information and get it back to my control.

But There's a page that I need all those 8 controls to be loaded on the same time .. so each method will be a trip to the db and I understand that's what affects the performance. So can I have like a new method to create the connection and open it, then I can call multiple methods to access the db and load the info then close the connection at the end.

Any ideas if those 8 connections are okay for performance ? and what do you think about this idea and how can it be applied in a practical way ?

答: Unless your app is going to be on a high-traffic website, I wouldn't worry about it until it becomes an issue.  It's relatively simple to go back and fix it later should problems arise, but this sounds like a case of premature optimization, to be honest.</p>

Title: Multiple Trips to the Db


问:
Android studio Gradle Tab
I've started to work on an android project that has many Gradle tasks. After cloning the project from git, there is no Gradle tab in Android Studio!</p>

答:
In a flutter project, it would not show when I opened the root folder, but if I opened the android folder underneath the root flutter folder, then the Gradle window appeared.

Most notably, Gradle did NOT appear as an option under View -> Tool Windows until I opened the correct folder.

Title: Android studio Gradle Tab


问:
Is there any code in flutter to change the border color when a TextFormField has a value?
```<code>TextFormField(
                style: TextStyle(color: Colors.black),
                textAlign: TextAlign.center,
                controller: _HeightController,
                validator: (value) {
                  if (value!.trim().isEmpty) {
                    return 'enter some text';
                  } else {
                    return null;
                  }
                },
                decoration:InputDecoration(
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                    borderSide: BorderSide(
                      color: pro.backColor_main,
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                    borderSide: BorderSide(

color: Color(0xffC2C2C2),
                  width: 2.0,
                ),
              ),
              hintText: '키를 입력해주세요',
              hintStyle: TextStyle(fontSize: 13.sp,
                color: Color(0xffA9A9A9),
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              fillColor: Colors.white,
              filled: true,
            ),
            keyboardType: TextInputType.number,
          ),
</code>```

This is my textformfield code.

Changing color when TextFormField is selected

Changing color when TextFormField is not selected

I understand that changing the color of the border of TextFormField itself.

But I want to keep the color of pro.main(blue) after a value is entered in TextFormField
This is because if you deselect the selection after entering a value, it becomes gray.

In this case, I wonder if there is a code to change the outline color if there is a value in the TextFormField.

答: you can try that, define a bool variable. check textfield controller, if != "" or null set your color</p>

Body:
TextFormField(
                style: TextStyle(color: Colors.black),
                textAlign: TextAlign.center,
                controller: _HeightController,
                validator: (value) {
                  if (value!.trim().isEmpty) {
                    return 'enter some text';
                  } else {
                    return null;
                  }
                },
                decoration:InputDecoration(
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                    borderSide: BorderSide(
                      color: pro.backColor_main,
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                    borderSide: BorderSide(

color: Color(0xffC2C2C2),
                  width: 2.0,
                ),
              ),
              hintText: '키를 입력해주세요',
              hintStyle: TextStyle(fontSize: 13.sp,
                color: Color(0xffA9A9A9),
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              fillColor: Colors.white,
              filled: true,
            ),
            keyboardType: TextInputType.number,
          ),

This is my textformfield code.

Changing color when TextFormField is selected

Changing color when TextFormField is not selected

I understand that changing the color of the border of TextFormField itself.

But I want to keep the color of pro.main(blue) after a value is entered in TextFormField
This is because if you deselect the selection after entering a value, it becomes gray.

In this case, I wonder if there is a code to change the outline color if there is a value in the TextFormField.


问:
React js add middleware to redirect to login when axios response is 401
I'm using react js :
"react": "^17.0.2",
"react-router": "^5.2.1",
"react-router-dom": "^5.3.0",
I want to add a middleware in my react js code to redirect to the login page when the response from axios on the front end side is 401.
Please any help .</p>

答:
You can use the following;</p>
```<code>    import axios from 'axios';
    axios.interceptors.response.use((response) => {
        return response;
    }, (error) => { // Anything except 2XX goes to here
        const status = error.response?.status || 500;
        if (status === 401) {
             window.location = window.location.protocol + "//" + window.location.host + "/sign-in"
        } else {
            return Promise.reject(error); // Delegate error to calling side
        }
    });
</code>```

Body:
You can use the following;

    import axios from 'axios';
    axios.interceptors.response.use((response) => {
        return response;
    }, (error) => { // Anything except 2XX goes to here
        const status = error.response?.status || 500;
        if (status === 401) {
             window.location = window.location.protocol + "//" + window.location.host + "/sign-in"
        } else {
            return Promise.reject(error); // Delegate error to calling side
        }
    });


问:
Recursive behavior
Why does the following executes such that the print statement is called as often as it recursed but the count variable, count, when x == 1 is never reached.

```<code>def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1 # when x == 1

  count_bits(int(n/2), count)
  print("counter")

  return count

</code>```

why is it necessary to recurse with the return statement?  Because if the recursive call is above the return statement the code
returns the wrong output but with the recursive call called with
return keyword, everything works well.  Typically, the print statement
prints 'counter' as often as it recursed showing that the recursive call
works.

On the other hand, if "return" follows after the recursive call, it returns the count from the base condition, correctly.

```<code>def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1

  return count_bits(int(n/2), count)
</code>```

答:
the difference in the output between the two methods is because of the way in which python handles fundamental data types. Fundamental data types such as float, ints, strings etc are passed by value, whereas complex data types such as dict, list, tuple etc are passed by reference. changes made to fundamental data types within a function will therefore only be changed within the local scope of the function, however changes made to a complex data type will change the original object. See below for an example:

x = 5

def test_sum(i : int):
  print(i)
  i += 5
  print(i)

# the integer value in the global scope is not changed, changes in test_sum() are only applied within the function scope
test_sum(x)
print(x)

y = [1,2,3,4]

def test_append(l : list):
  print(l)
  l.append(10)
  print(l)

# the list in the global scope has '10' appended after being passed to test_append by reference
test_append(y)
print(y)
```
<p>This happens because it's far cheaper computationally to pass a reference to a large object in memory than to copy it into the local scope of the function. For more information on the difference, there are thousands of resources available by searching "what is the difference between by reference and by value in programming".</p>
<p>As for your code, it seems to me the only difference is you should alter your first snippet as follows:</p>
<pre class="lang-py prettyprint-override"><code>def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1 # when x == 1

  # assign the returned count to the count variable in this function scope
  count = count_bits(int(n/2), count)
  print("counter")

  return count
</code>```

The second code snippet you wrote is almost identical, it just doesn't assign the new value to the 'count' variable. Does this answer your question?

Title: Recursive behavior

Body:
Why does the following executes such that the print statement is called as often as it recursed but the count variable, count, when x == 1 is never reached.

def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1 # when x == 1

  count_bits(int(n/2), count)
  print("counter")

  return count

why is it necessary to recurse with the return statement?  Because if the recursive call is above the return statement the code
returns the wrong output but with the recursive call called with
return keyword, everything works well.  Typically, the print statement
prints 'counter' as often as it recursed showing that the recursive call
works.

On the other hand, if "return" follows after the recursive call, it returns the count from the base condition, correctly.

def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1

  return count_bits(int(n/2), count)

Body:
the difference in the output between the two methods is because of the way in which python handles fundamental data types. Fundamental data types such as float, ints, strings etc are passed by value, whereas complex data types such as dict, list, tuple etc are passed by reference. changes made to fundamental data types within a function will therefore only be changed within the local scope of the function, however changes made to a complex data type will change the original object. See below for an example:

x = 5

def test_sum(i : int):
  print(i)
  i += 5
  print(i)

# the integer value in the global scope is not changed, changes in test_sum() are only applied within the function scope
test_sum(x)
print(x)

y = [1,2,3,4]

def test_append(l : list):
  print(l)
  l.append(10)
  print(l)

# the list in the global scope has '10' appended after being passed to test_append by reference
test_append(y)
print(y)

This happens because it's far cheaper computationally to pass a reference to a large object in memory than to copy it into the local scope of the function. For more information on the difference, there are thousands of resources available by searching "what is the difference between by reference and by value in programming".

As for your code, it seems to me the only difference is you should alter your first snippet as follows:

def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1 # when x == 1

  # assign the returned count to the count variable in this function scope
  count = count_bits(int(n/2), count)
  print("counter")

  return count

The second code snippet you wrote is almost identical, it just doesn't assign the new value to the 'count' variable. Does this answer your question?


问:
How to serve up a GET request from Azure Function and Storage Blob?
For this frontend request  I have the following Azure Function (AF) to access the image file at Storage Blob

function.json

```<code>"methods": ["get"],
"route": "img/{filename}"
</code>```

index.js

```<code>const bbc = blobServiceClient.getContainerClient("pngfiles").getBlockBlobClient(context.req.params.filename);
</code>```

After this line, I don't know how to read/fetch/stream or whatever to serve up the request from AF to frontend. I've tried the following but it returns meta data and properties

```<code>const png = await bbc.download();
context.res = {body: png,  headers: {"Content-Type": "image/png"}};
</code>```

答:
Unsure if the best way but Works:</p>
```<code>const bbc = await blobServiceClient.getContainerClient("pngfiles").getBlockBlobClient(context.req.params.filename).downloadToBuffer();
context.res = {body: bbc, headers: {"Content-Type": "image/png"}};
</code>```

Body:
For this frontend request  I have the following Azure Function (AF) to access the image file at Storage Blob

function.json

"methods": ["get"],
"route": "img/{filename}"

index.js

const bbc = blobServiceClient.getContainerClient("pngfiles").getBlockBlobClient(context.req.params.filename);

After this line, I don't know how to read/fetch/stream or whatever to serve up the request from AF to frontend. I've tried the following but it returns meta data and properties

const png = await bbc.download();
context.res = {body: png,  headers: {"Content-Type": "image/png"}};

Body:
Unsure if the best way but Works:

const bbc = await blobServiceClient.getContainerClient("pngfiles").getBlockBlobClient(context.req.params.filename).downloadToBuffer();
context.res = {body: bbc, headers: {"Content-Type": "image/png"}};


问:
React testing library, how to get text from element
I'm trying to test a table being built using react testing library

I'm using debug which outputs

```<code><body>
    <div>
      <div
        class="table-wrapper"
      >
        <div
          class="table-component__header"
        />
        <table
          class="test-table"
        >
          <tbody>
            <tr>
              <td
                class="text-grid-item"
                data-testid="text-grid-item"
              >
                test table data
              </td>
            </tr>
          </tbody>
          <tfoot
            class="table_footer"
          >
            <tr>
              <td />
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
</body>
</code>```

I'm trying to assert test table data is there with

```<code>expect(findByTestId('text-grid-item')).toHaveTextContent('test table dat')
</code>```

but it fails with

```<code>received value must be a Node.
Received has type:  object
Received has value: {}
</code>```

How can I assert the text test table data is there

```<code>import React from 'react'
import { render } from '@testing-library/react'
import { Table } from './table'

const givenTableWithElement = (test: Array<TableElement>) => {
    const table = {
        tableEntries: [{ tableElements: test }],
        type: 'table',
        tableType: 'test'
    }
    return table
}

describe('Components should render depending on their prop type', () => {

    test('Given table element is text, when rendered, text table class should be returned', () => {
        const imageTableTest: TableProps = givenTableWithElement([
            {
                text: 'test table data',
                display: {
                    mobile: true,
                    wrap: false
                }
            }
        ])

        const { debug } = render(<Table {...imageTableTest} />)
        debug()

        const { getByTestId } = render(<Table {...imageTableTest} />)

        expect(findByTestId('text-grid-item')).toHaveTextContent('test table dat')
    })

})
</code>```

答:
You can just do getByText('test table data') without asserting anything.

getByText will fail your test if it cannot find the text it is looking for. If the text is there and your test passes, you essentially asserted that it is there even if you haven't used expect() assertion explicitly. Though be careful when using queryByText (or any other react-testing-library method that starts with query), using that will return null, so if it can't find the text it is looking for it won't fail you test and you will get a false positive.

If you still want to use an expect you can try doing something like:

```<code>const gridItemText = getByTestId('text-grid-item').innerHTML
expect(gridItemText).toBe('test table data')
</code>```

Body:
I'm trying to test a table being built using react testing library

I'm using debug which outputs

                test table data

I'm trying to assert test table data is there with

expect(findByTestId('text-grid-item')).toHaveTextContent('test table dat')

but it fails with

received value must be a Node.
Received has type:  object
Received has value: {}

How can I assert the text test table data is there

import React from 'react'
import { render } from '@testing-library/react'
import { Table } from './table'

const givenTableWithElement = (test: Array<TableElement>) => {
    const table = {
        tableEntries: [{ tableElements: test }],
        type: 'table',
        tableType: 'test'
    }
    return table
}

describe('Components should render depending on their prop type', () => {

    test('Given table element is text, when rendered, text table class should be returned', () => {
        const imageTableTest: TableProps = givenTableWithElement([
            {
                text: 'test table data',
                display: {
                    mobile: true,
                    wrap: false
                }
            }
        ])

        const { debug } = render(
)
        debug()

        const { getByTestId } = render(
)

        expect(findByTestId('text-grid-item')).toHaveTextContent('test table dat')
    })

})

Body:
You can just do getByText('test table data') without asserting anything.

getByText will fail your test if it cannot find the text it is looking for. If the text is there and your test passes, you essentially asserted that it is there even if you haven't used expect() assertion explicitly. Though be careful when using queryByText (or any other react-testing-library method that starts with query), using that will return null, so if it can't find the text it is looking for it won't fail you test and you will get a false positive.

If you still want to use an expect you can try doing something like:

const gridItemText = getByTestId('text-grid-item').innerHTML
expect(gridItemText).toBe('test table data')