问:
Identify Partition Key Column from a table using PySpark
I need help to find the unique partitions column names for a Hive table using PySpark. The table might have multiple partition columns and preferable the output should return a list of the partition columns for the Hive Table.

It would be great if the result would also include the datatype of the partitioned columns.

Any suggestions will be helpful.

答:
The following snippet

Gets the columns for the given table

Filters out partition columns

Extracts (name, datatype) tuples from the partition columns

# s: pyspark.sql.session.SparkSession
# table: str

# 1.  Get table columns for given table
columns = s.catalog.listColumns(table)

# 2. Filter out partition columns
partition_columns = list(filter(lambda c: c.isPartition , columns))

# 3. Now you can extract the name and dataType (among other attributes)
[ (c.name, c.dataType) for c in partition_columns ]
```


来源: stackexchange

问:
what is the proper way to use proxies with requests in python
Requests is not honoring the proxies flag.

There is something I am missing about making a request over a proxy with python requests library.

If I enable the OS system proxy, then it works, but if I make the request with just requests module proxies setting, the remote machine will not see the proxy set in requests, but will see my real ip, it is as if not proxy was set.

The bellow example will show this effect, at the time of this post the bellow proxy is alive but any working proxy should replicate the effect.

```<code>import requests

proxy ={
  'http:': 'https://143.208.200.26:7878',
  'https:': 'http://143.208.200.26:7878'
}
data = requests.get(url='http://ip-api.com/json', proxies=proxy).json()
print('Ip: %s\nCity: %s\nCountry: %s' % (data['query'], data['city'], data['country']))
</code>```

I also tried changing the proxy_dict format:

```<code>proxy ={
          'http:': '143.208.200.26:7878',
          'https:': '143.208.200.26:7878'
       }
</code>```

But still it has not effect.

I am using:
-Windows 10
-python 3.9.6
-urllib 1.25.8

Many thanks in advance for any response to help sort this out.

答:
Ok is working yea !!! .
The credits for solving this goes to (Olvin Rogh) Thanks Olvin for your help and pointing out my problem. I was adding colon ":" inside the keys
This code is working now.</p>
```<code>PROXY = {'https': 'https://143.208.200.26:7878',
         'http': 'http://143.208.200.26:7878'}

with requests.Session() as session:
    session.proxies = PROXY
    r = session.get('http://ip-api.com/json')
    print(json.dumps(r.json(), indent=2))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Requests is not honoring the proxies flag.

There is something I am missing about making a request over a proxy with python requests library.

If I enable the OS system proxy, then it works, but if I make the request with just requests module proxies setting, the remote machine will not see the proxy set in requests, but will see my real ip, it is as if not proxy was set.

The bellow example will show this effect, at the time of this post the bellow proxy is alive but any working proxy should replicate the effect.

import requests

proxy ={
  'http:': 'https://143.208.200.26:7878',
  'https:': 'http://143.208.200.26:7878'
}
data = requests.get(url='http://ip-api.com/json', proxies=proxy).json()
print('Ip: %s\nCity: %s\nCountry: %s' % (data['query'], data['city'], data['country']))

I also tried changing the proxy_dict format:

proxy ={
          'http:': '143.208.200.26:7878',
          'https:': '143.208.200.26:7878'
       }

But still it has not effect.

I am using:
-Windows 10
-python 3.9.6
-urllib 1.25.8

Many thanks in advance for any response to help sort this out.

Body:
Ok is working yea !!! .
The credits for solving this goes to (Olvin Rogh) Thanks Olvin for your help and pointing out my problem. I was adding colon ":" inside the keys
This code is working now.

PROXY = {'https': 'https://143.208.200.26:7878',
         'http': 'http://143.208.200.26:7878'}

with requests.Session() as session:
    session.proxies = PROXY
    r = session.get('http://ip-api.com/json')
    print(json.dumps(r.json(), indent=2))


问:
Accessing elements in Python dictionary
bit of a strange question, but I was trying to come up with different ways to get around this.

Let's say I have the following Dictionary:

```<code>dict={

    'Animal':['Cat', 'Dog', 'Ocelot'],
    'Humans':['Jack', 'Jill', 'Frank'],
    'Fruit':['Apple', 'Orange', 'Banana']
}
</code>```

Is there a way to access just the third element of every key?
The output being 'Ocelot' 'Frank 'Banana'

I know that the notation for single key is Dictionary(KEY)[ITEM PLACE] but is there a way to do this without specifying the key?

Thanks

答:
We could do this in one line if needed:

list(map(lambda x:x[2], dict.values()))
```
<pre class="lang-py prettyprint-override"><code>>>> dict={
...
...     'Animal':['Cat', 'Dog', 'Ocelot'],
...     'Humans':['Jack', 'Jill', 'Frank'],
...     'Fruit':['Apple', 'Orange', 'Banana']
... }
>>> dict
{'Animal': ['Cat', 'Dog', 'Ocelot'], 'Humans': ['Jack', 'Jill', 'Frank'], 'Fruit': ['Apple', 'Orange', 'Banana']}
>>> list(map(lambda x:x[2], dict.values()))
['Ocelot', 'Frank', 'Banana']
</code>```

Title: Accessing elements in Python dictionary

Body:
bit of a strange question, but I was trying to come up with different ways to get around this.

Let's say I have the following Dictionary:

dict={

    'Animal':['Cat', 'Dog', 'Ocelot'],
    'Humans':['Jack', 'Jill', 'Frank'],
    'Fruit':['Apple', 'Orange', 'Banana']
}

Is there a way to access just the third element of every key?
The output being 'Ocelot' 'Frank 'Banana'

I know that the notation for single key is Dictionary(KEY)[ITEM PLACE] but is there a way to do this without specifying the key?

Thanks

Body:
We could do this in one line if needed:

list(map(lambda x:x[2], dict.values()))

>>> dict={
...
...     'Animal':['Cat', 'Dog', 'Ocelot'],
...     'Humans':['Jack', 'Jill', 'Frank'],
...     'Fruit':['Apple', 'Orange', 'Banana']
... }
>>> dict
{'Animal': ['Cat', 'Dog', 'Ocelot'], 'Humans': ['Jack', 'Jill', 'Frank'], 'Fruit': ['Apple', 'Orange', 'Banana']}
>>> list(map(lambda x:x[2], dict.values()))
['Ocelot', 'Frank', 'Banana']


问:
JavaScript: Create function that returns an object whose keys match the elements in the array of values using callbacks
My objective is as follows:

Construct a function multiMap that will accept two arrays - an array of values and an array of callbacks. multiMap will return an object whose keys match the elements in the array of values. The corresponding values that are assigned to the keys will be arrays consisting of outputs from the array of callbacks, where the input to each callback is the key.

I tried the code below:

```<code>const multiMap = (arrOne, arrTwo) => {

  let newObj = {};

  for (let i=0; i<arrOne.length; i++){
    let element = arrOne[i];

    console.log(i)

    newObj[element] = arrTwo[i](element);
  }
  return newObj;
}

// Uncomment these to check your work!
function uppercaser(str) { return str.toUpperCase(); }
function capitalize(str) { return str[0].toUpperCase() + str.slice(1).toLowerCase(); }
function repeater(str) { return str + str; }

// arrOne
const items = ['catfood', 'glue', 'beer'];
// arrTwo
const functions = [uppercaser, capitalize, repeater];

console.log(multiMap(items, functions));
</code>```

My code returns: { catfood: 'CATFOOD', glue: 'Glue', beer: 'beerbeer' }

I want it to return: { catfood: ['CATFOOD', 'Catfood', 'catfoodcatfood'], glue: ['GLUE', 'Glue', 'glueglue'], beer: ['BEER', 'Beer', 'beerbeer'] }, 'Beer', 'beerbeer'] }

What am I doing wrong?

Note: I know I can use modifying functions (i.e. reduce) to do this but I want to figure it out first using for loop.

答:
A more functional solution would be,

const multiMap = (arrVals, arrCallbacks) => arrVals.reduce((acc, curr) => {
  acc[curr] = arrCallbacks.map(cb => cb(curr));
  return acc;
}, {});

console.log(multiMap(['catfood', 'glue', 'beer'], [(str) => str.toUpperCase(), (str) => str[0].toUpperCase() + str.slice(1).toLowerCase(), (str) => str + str]));
// should log: { catfood: ['CATFOOD', 'Catfood', 'catfoodcatfood'], glue: ['GLUE', 'Glue', 'glueglue'], beer: ['BEER', 'Beer', 'beerbeer'] }```

Body:
My objective is as follows:

Construct a function multiMap that will accept two arrays - an array of values and an array of callbacks. multiMap will return an object whose keys match the elements in the array of values. The corresponding values that are assigned to the keys will be arrays consisting of outputs from the array of callbacks, where the input to each callback is the key.

I tried the code below:

const multiMap = (arrOne, arrTwo) => {

  let newObj = {};

  for (let i=0; i<arrOne.length; i++){
    let element = arrOne[i];

    console.log(i)

    newObj[element] = arrTwo[i](element);
  }
  return newObj;
}

// Uncomment these to check your work!
function uppercaser(str) { return str.toUpperCase(); }
function capitalize(str) { return str[0].toUpperCase() + str.slice(1).toLowerCase(); }
function repeater(str) { return str + str; }

// arrOne
const items = ['catfood', 'glue', 'beer'];
// arrTwo
const functions = [uppercaser, capitalize, repeater];

console.log(multiMap(items, functions));

My code returns: { catfood: 'CATFOOD', glue: 'Glue', beer: 'beerbeer' }

I want it to return: { catfood: ['CATFOOD', 'Catfood', 'catfoodcatfood'], glue: ['GLUE', 'Glue', 'glueglue'], beer: ['BEER', 'Beer', 'beerbeer'] }, 'Beer', 'beerbeer'] }

What am I doing wrong?

Note: I know I can use modifying functions (i.e. reduce) to do this but I want to figure it out first using for loop.


问:
What is the function of the stepControl property on mat-step directives?
On the Angular Material stepper there is a stepControl property on each mat-step that contains a form.  What does the stepControl property do?

```<code><mat-step [stepControl]="registrationForm">
</code>```

It seems like the function would be to disallow moving to the next step if the form is not valid, but just wanted to double check.

答:
Correct, however, if any form validation is not compulsory you can use the isOptional property to ignore that form's validity and proceed to the next step.

<mat-step [stepControl]="registrationForm" [optional]="isOptional">
```
<p>Similarly if you are not using Reactive Forms you can use another property called <code>completed</code> to allow the user to proceed to the next step only if completed is true</p>
<pre class="lang-js prettyprint-override"><code><mat-step [completed]="isCompleted">
</code>```

Body:
On the Angular Material stepper there is a stepControl property on each mat-step that contains a form.  What does the stepControl property do?

<mat-step [stepControl]="registrationForm">

It seems like the function would be to disallow moving to the next step if the form is not valid, but just wanted to double check.

Body:
Correct, however, if any form validation is not compulsory you can use the isOptional property to ignore that form's validity and proceed to the next step.

<mat-step [stepControl]="registrationForm" [optional]="isOptional">

Similarly if you are not using Reactive Forms you can use another property called completed to allow the user to proceed to the next step only if completed is true

<mat-step [completed]="isCompleted">


问:
How to set DEFAULT ON UPDATE CURRENT_TIMESTAMP in Postgres with SQLAlchemy?
This is a sister question to How to set DEFAULT ON UPDATE CURRENT_TIMESTAMP in mysql with sqlalchemy?, but focused on Postgres instead of MySQL.

Say we want to create a table users with a column datemodified that updates by default to the current timestamp whenever a row is updated. The solution given in the sister PR for MySQL is:

user = Table(
    "users",
    Metadata,
    Column(
        "datemodified",
        TIMESTAMP,
        server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"),
    ),
)
```

How can I get the same functionality with a Postgres backend?

答:
Eventually I implemented this using triggers as suggested by a_horse_with_no_name in the comments. Full SQLAlchemy implementation and integration with Alembic follow.

SQLAlchemy implementation

# models.py

class User(Base):
    __tablename__ = "user"
    id = Column(Integer, primary_key=True)
    name = Column(Text)
    created_at = Column(DateTime, server_default=sqlalchemy.func.now(), nullable=False)
    updated_at = Column(DateTime)
```
<pre class="lang-py prettyprint-override"><code># your_application_code.py

import sqlalchemy as sa

create_refresh_updated_at_func = """
    CREATE FUNCTION {schema}.refresh_updated_at()
    RETURNS TRIGGER
    LANGUAGE plpgsql AS
    $func$
    BEGIN
       NEW.updated_at := now();
       RETURN NEW;
    END
    $func$;
    """

create_trigger = """
    CREATE TRIGGER trig_{table}_updated BEFORE UPDATE ON {schema}.{table}
    FOR EACH ROW EXECUTE PROCEDURE {schema}.refresh_updated_at();
    """

my_schema = "foo"
engine.execute(sa.text(create_refresh_updated_at_func.format(schema=my_schema)))
engine.execute(sa.text(create_trigger.format(schema=my_schema, table="user")))

</code>```

Integration with Alembic

In my case it was important to integrate the trigger creation with Alembic, and to add the trigger to n dimension tables (all of them having an updated_at column).

# alembic/versions/your_version.py

import sqlalchemy as sa

create_refresh_updated_at_func = """
    CREATE FUNCTION {schema}.refresh_updated_at()
    RETURNS TRIGGER
    LANGUAGE plpgsql AS
    $func$
    BEGIN
       NEW.updated_at := now();
       RETURN NEW;
    END
    $func$;
    """

create_trigger = """
    CREATE TRIGGER trig_{table}_updated BEFORE UPDATE ON {schema}.{table}
    FOR EACH ROW EXECUTE PROCEDURE {schema}.refresh_updated_at();
    """

def upgrade():
    op.create_table(..., schema="foo")
    ...

    # Add updated_at triggers for all tables
    op.execute(sa.text(create_refresh_updated_at_func.format(schema="foo")))
    for table in MY_LIST_OF_TABLES:
        op.execute(sa.text(create_trigger.format(schema="foo", table=table)))

def downgrade():
    op.drop_table(..., schema="foo")
    ...

    op.execute(sa.text("DROP FUNCTION foo.refresh_updated_at() CASCADE"))
```

Body:
This is a sister question to How to set DEFAULT ON UPDATE CURRENT_TIMESTAMP in mysql with sqlalchemy?, but focused on Postgres instead of MySQL.

Say we want to create a table users with a column datemodified that updates by default to the current timestamp whenever a row is updated. The solution given in the sister PR for MySQL is:

user = Table(
    "users",
    Metadata,
    Column(
        "datemodified",
        TIMESTAMP,
        server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"),
    ),
)

How can I get the same functionality with a Postgres backend?

Body:
Eventually I implemented this using triggers as suggested by a_horse_with_no_name in the comments. Full SQLAlchemy implementation and integration with Alembic follow.

SQLAlchemy implementation

# models.py

class User(Base):
    __tablename__ = "user"
    id = Column(Integer, primary_key=True)
    name = Column(Text)
    created_at = Column(DateTime, server_default=sqlalchemy.func.now(), nullable=False)
    updated_at = Column(DateTime)

# your_application_code.py

import sqlalchemy as sa

create_refresh_updated_at_func = """
    CREATE FUNCTION {schema}.refresh_updated_at()
    RETURNS TRIGGER
    LANGUAGE plpgsql AS
    $func$
    BEGIN
       NEW.updated_at := now();
       RETURN NEW;
    END
    $func$;
    """

create_trigger = """
    CREATE TRIGGER trig_{table}_updated BEFORE UPDATE ON {schema}.{table}
    FOR EACH ROW EXECUTE PROCEDURE {schema}.refresh_updated_at();
    """

my_schema = "foo"
engine.execute(sa.text(create_refresh_updated_at_func.format(schema=my_schema)))
engine.execute(sa.text(create_trigger.format(schema=my_schema, table="user")))

Integration with Alembic

In my case it was important to integrate the trigger creation with Alembic, and to add the trigger to n dimension tables (all of them having an updated_at column).

# alembic/versions/your_version.py

import sqlalchemy as sa

create_refresh_updated_at_func = """
    CREATE FUNCTION {schema}.refresh_updated_at()
    RETURNS TRIGGER
    LANGUAGE plpgsql AS
    $func$
    BEGIN
       NEW.updated_at := now();
       RETURN NEW;
    END
    $func$;
    """

create_trigger = """
    CREATE TRIGGER trig_{table}_updated BEFORE UPDATE ON {schema}.{table}
    FOR EACH ROW EXECUTE PROCEDURE {schema}.refresh_updated_at();
    """

def upgrade():
    op.create_table(..., schema="foo")
    ...

    # Add updated_at triggers for all tables
    op.execute(sa.text(create_refresh_updated_at_func.format(schema="foo")))
    for table in MY_LIST_OF_TABLES:
        op.execute(sa.text(create_trigger.format(schema="foo", table=table)))

def downgrade():
    op.drop_table(..., schema="foo")
    ...

    op.execute(sa.text("DROP FUNCTION foo.refresh_updated_at() CASCADE"))


问:
Why helm template function is not resolveing $labels var?
I am defining a PrometheusRule  as follow:

```<code>prometheusRule:
  rules:
    - alert: SSLCertExpiringSoon
      expr: probe_ssl_earliest_cert_expiry - time() < 86400 * 10
      for: 0m
      labels:
        severity: warning
      annotations:
        summary: Blackbox SSL certificate will expire soon (instance {{ $labels.instance }})
        description: "SSL certificate expires in 30 days\n  VALUE = {{ $value }}\n  LABELS = {{ $labels }}"
</code>```

And the template yml from helm chart:

```<code>{{- if .Values.prometheusRule.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: {{ template "prometheus-blackbox-exporter.fullname" . }}
  {{- with .Values.prometheusRule.namespace }}
  namespace: {{ . }}
  {{- end }}
  labels:
    {{- include "prometheus-blackbox-exporter.labels" . | nindent 4 }}
    {{- with .Values.prometheusRule.additionalLabels -}}
{{- toYaml . | nindent 4 -}}
    {{- end }}
spec:
  {{- with .Values.prometheusRule.rules }}
  groups:
    - name: {{ template "prometheus-blackbox-exporter.name" $ }}
      rules: {{ tpl (toYaml .) $ | nindent 8 }}
  {{- end }}
{{- end }}
</code>```

when I run helm template, tpl func it is not resolving the $labels and $values vars. When I remove annotations then the helm template is not complaining anymore. Where do fail?

error:

```<code>Error: template: prometheus-blackbox-exporter/templates/prometheusrule.yaml:18:16: executing "prometheus-blackbox-exporter/templates/prometheusrule.yaml" at <tpl (toYaml .) $>: error calling tpl: error during tpl function execution for "- alert: SSLCertExpiringSoon\n  annotations:\n    summary: Blackbox SSL certificate will expire soon (instance {{ $labels.instance\n      }})\n  expr: probe_ssl_earliest_cert_expiry - time() < 86400 * 10\n  for: 0m\n  labels:\n    release: prometheus\n    severity: warning\n- alert: SSLCertExpiringSoon\n  annotations: null\n  expr: probe_ssl_earliest_cert_expiry - time() < 86400 * 3\n  for: 0m\n  labels:\n    severity: critical": parse error at (prometheus-blackbox-exporter/templates/prometheusrule.yaml:3): undefined variable "$labels"
</code>```

答:
The working version of syntax is as follow:</p>
```<code>{{ `{{` }} $value }}
</code>```

Body:
I am defining a PrometheusRule  as follow:

prometheusRule:
  rules:
    - alert: SSLCertExpiringSoon
      expr: probe_ssl_earliest_cert_expiry - time() < 86400 * 10
      for: 0m
      labels:
        severity: warning
      annotations:
        summary: Blackbox SSL certificate will expire soon (instance {{ $labels.instance }})
        description: "SSL certificate expires in 30 days\n  VALUE = {{ $value }}\n  LABELS = {{ $labels }}"

And the template yml from helm chart:

{{- if .Values.prometheusRule.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: {{ template "prometheus-blackbox-exporter.fullname" . }}
  {{- with .Values.prometheusRule.namespace }}
  namespace: {{ . }}
  {{- end }}
  labels:
    {{- include "prometheus-blackbox-exporter.labels" . | nindent 4 }}
    {{- with .Values.prometheusRule.additionalLabels -}}
{{- toYaml . | nindent 4 -}}
    {{- end }}
spec:
  {{- with .Values.prometheusRule.rules }}
  groups:
    - name: {{ template "prometheus-blackbox-exporter.name" $ }}
      rules: {{ tpl (toYaml .) $ | nindent 8 }}
  {{- end }}
{{- end }}

when I run helm template, tpl func it is not resolving the $labels and $values vars. When I remove annotations then the helm template is not complaining anymore. Where do fail?

error:

Error: template: prometheus-blackbox-exporter/templates/prometheusrule.yaml:18:16: executing "prometheus-blackbox-exporter/templates/prometheusrule.yaml" at <tpl (toYaml .) $>: error calling tpl: error during tpl function execution for "- alert: SSLCertExpiringSoon\n  annotations:\n    summary: Blackbox SSL certificate will expire soon (instance {{ $labels.instance\n      }})\n  expr: probe_ssl_earliest_cert_expiry - time() < 86400 * 10\n  for: 0m\n  labels:\n    release: prometheus\n    severity: warning\n- alert: SSLCertExpiringSoon\n  annotations: null\n  expr: probe_ssl_earliest_cert_expiry - time() < 86400 * 3\n  for: 0m\n  labels:\n    severity: critical": parse error at (prometheus-blackbox-exporter/templates/prometheusrule.yaml:3): undefined variable "$labels"

Body:
The working version of syntax is as follow:

{{ `{{` }} $value }}


问:
Inheritable static methods in Node.js?
I have the following structure:

First file:

```<code>Base = function() {
};

Base.something = function() {
  return "bla";
};

if (typeof module !== 'undefined' && "exports" in module) {
  module.exports = Base;
}
</code>```

Second file:

```<code>var
  util = require('util'),
  Base = require('./base.js');

FooBar = function() {
};
util.inherits(FooBar, Base);
</code>```

But FooBar.something is undefined. How can I inherit static methods in node.js?

答:
I've found an another solution which is better, because I would use only one library to achieve the same functionality.

This library is the oop by Felix Geisendörfer, he also wrote a tutorial at nodeguide.com but it's outdated a bit. But here is a working example for the same problem:

```<code>var
  oop = require('oop'),

  Base = require('./base.js');

FooBar = function() {
  oop.mixin(this, Base);
};
oop.extend(FooBar, Base);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Inheritable static methods in Node.js?

Body:
I have the following structure:

First file:

Base = function() {
};

Base.something = function() {
  return "bla";
};

if (typeof module !== 'undefined' && "exports" in module) {
  module.exports = Base;
}

Second file:

var
  util = require('util'),
  Base = require('./base.js');

FooBar = function() {
};
util.inherits(FooBar, Base);

But FooBar.something is undefined. How can I inherit static methods in node.js?

Body:
I've found an another solution which is better, because I would use only one library to achieve the same functionality.

This library is the oop by Felix Geisendörfer, he also wrote a tutorial at nodeguide.com but it's outdated a bit. But here is a working example for the same problem:

var
  oop = require('oop'),

  Base = require('./base.js');

FooBar = function() {
  oop.mixin(this, Base);
};
oop.extend(FooBar, Base);


问:
Flask - Creating dynamic URL based on user input
I'm trying to create a dynamic URL based on user's input from an HTML form.

For example, if a user types in 'AAPL' or 'KO', the next page should be:
webapp.com/result/AAPL or webapp.com/result/KO

index.html:

```<code><div class="cell" id="cell-1-2">
  <span class="data" style="text-align: center;">
      <form action="{{ url_for('ticker_result', variable='variable') }}" method="POST">
      <input type="text" name="variable" placeholder="search ticker or company" maxlength="4"
             font-size="24px" style="text-transform:uppercase">
      <input class="button" type="submit" value="Search" onclick="tickerSymbol();">
    </form>
  </span>
</div>
</code>```

I've tried renaming the 'variable' part to several different things and nothing works so I'm just stuck at this point.

main.py:

```<code># Routing to the homepage
@app.route("/")
def markert_hours_today():
    return render_template(
        "index.html")

# Routing to the result page
@app.route("/result/<variable>", methods = ["GET", "POST"])
def ticker_result(variable):
    if request.method == "POST":
        result = request.form["variable"]
        return render_template(
            "result.html",
            result=result)
</code>```

When I run the local environment, and type in a ticker symbol, the next URL is:
webapp.com/result/variable

I'm assuming it's HTML that I need to edit? I've read the quickstart documentation for Flask which isn't making sense to me and looked up similar questions but I can't seem to find an answer to this.

答:
You are coming at it from the wrong way. When Jinja creates index.html based on your template you can't know what variable is going to be, so how is Jinja supposed to know?

What you need to do is send the form back to the same route and then redirect the user to whatever they typed in. So something like this:

```<code>from flask import request, redirect, url_for

@app.route("/", methods=['GET', 'POST'])
def markert_hours_today():
    if request.method == 'POST':
        result = request.form['variable']
        return redirect(url_for('ticker_result', variable=result)
    return render_template("index.html")
</code>```

Edit: forgot to rename variable from user_input to result.

Body:
I'm trying to create a dynamic URL based on user's input from an HTML form.

For example, if a user types in 'AAPL' or 'KO', the next page should be:
webapp.com/result/AAPL or webapp.com/result/KO

index.html:

      <form action="{{ url_for('ticker_result', variable='variable') }}" method="POST">
      <input type="text" name="variable" placeholder="search ticker or company" maxlength="4"
             font-size="24px" style="text-transform:uppercase">
      <input class="button" type="submit" value="Search" onclick="tickerSymbol();">
    </form>

I've tried renaming the 'variable' part to several different things and nothing works so I'm just stuck at this point.

main.py:

# Routing to the homepage
@app.route("/")
def markert_hours_today():
    return render_template(
        "index.html")

# Routing to the result page
@app.route("/result/<variable>", methods = ["GET", "POST"])
def ticker_result(variable):
    if request.method == "POST":
        result = request.form["variable"]
        return render_template(
            "result.html",
            result=result)

When I run the local environment, and type in a ticker symbol, the next URL is:
webapp.com/result/variable

I'm assuming it's HTML that I need to edit? I've read the quickstart documentation for Flask which isn't making sense to me and looked up similar questions but I can't seem to find an answer to this.

Body:
You are coming at it from the wrong way. When Jinja creates index.html based on your template you can't know what variable is going to be, so how is Jinja supposed to know?

What you need to do is send the form back to the same route and then redirect the user to whatever they typed in. So something like this:

from flask import request, redirect, url_for

@app.route("/", methods=['GET', 'POST'])
def markert_hours_today():
    if request.method == 'POST':
        result = request.form['variable']
        return redirect(url_for('ticker_result', variable=result)
    return render_template("index.html")

Edit: forgot to rename variable from user_input to result.


问:
Check if two numbers have same digits
I need to write a program which will check if two numbers have same digits.
For example:

```<code>a = 4423, b = 2433;
</code>```

Even though their digits don't appear the same amount if times, they have same digits.

```<code>#include <stdio.h>
#include <stdlib.h>
int same_digit(int a, int b) {
  int n = abs(a), i;
  int count[10];
  for (i = 0; i < 10; ++i) {
    count[i] = 0;
  }
  while (n > 0) {
    count[n % 10]++;
    n = n / 10;
  }
  n = abs(b);
  while (n > 0) {
    count[n % 10]--;
    n = n / 10;
  }
  for (i = 0; i < 10; ++i)
    if (count[i] != 0)
      return 0;
  return 1;
}
int main() {
  int a, b;
  scanf("%d", &a);
  scanf("%d", &b);
  if (same_digit(a, b)) printf("Yes");
  else printf("No");
  return 0;
}
</code>```

Problem with my code is that this literally checks if they have same digits. How could I modify this code to return 1 if all digits from a are present in b, and all digits from b are present in a, no matter how many times they are present.

答:
You need to store which digits have occurred in both numbers. For example, for both numbers, you could define an array of 10 bool elements, where the first element specifies whether the digit 0 occurred, the second element whether the digit 1 occurred, etc. Since you need two such arrays, you could make an array of 2 of these arrays, giving you a 2D array. That way, you can process both arrays in the same loop.

After you have filled both arrays, you can compare them, in order to determine whether both numbers use the same digits.

Also, it may be better to change the return type of same_digit to bool.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

bool same_digit( int a, int b )
{
    int numbers[2] = { a, b };
    bool occurred[2][10] = { {false} };

    //determine which digits are used by the individual numbers
    //and fill the two arrays accordingly
    for ( int i = 0; i < 2; i++ )
    {
        int n = abs( numbers[i] );

        while ( n > 0 )
        {
            occurred[i][n%10] = true;
            n = n / 10;
        }
    }

    //determine whether both numbers use the same digits
    for ( int i = 0; i < 10; i++ )
        if ( occurred[0][i] != occurred[1][i] )
            return false;

    return true;
}

//the following code has not been modified
int main() {
  int a, b;
  scanf("%d", &a);
  scanf("%d", &b);
  if (same_digit(a, b)) printf("Yes");
  else printf("No");
  return 0;
}
</code>```

Title: Check if two numbers have same digits

Body:
I need to write a program which will check if two numbers have same digits.
For example:

a = 4423, b = 2433;

Even though their digits don't appear the same amount if times, they have same digits.

#include <stdio.h>
#include <stdlib.h>
int same_digit(int a, int b) {
  int n = abs(a), i;
  int count[10];
  for (i = 0; i < 10; ++i) {
    count[i] = 0;
  }
  while (n > 0) {
    count[n % 10]++;
    n = n / 10;
  }
  n = abs(b);
  while (n > 0) {
    count[n % 10]--;
    n = n / 10;
  }
  for (i = 0; i < 10; ++i)
    if (count[i] != 0)
      return 0;
  return 1;
}
int main() {
  int a, b;
  scanf("%d", &a);
  scanf("%d", &b);
  if (same_digit(a, b)) printf("Yes");
  else printf("No");
  return 0;
}

Problem with my code is that this literally checks if they have same digits. How could I modify this code to return 1 if all digits from a are present in b, and all digits from b are present in a, no matter how many times they are present.

Body:
You need to store which digits have occurred in both numbers. For example, for both numbers, you could define an array of 10 bool elements, where the first element specifies whether the digit 0 occurred, the second element whether the digit 1 occurred, etc. Since you need two such arrays, you could make an array of 2 of these arrays, giving you a 2D array. That way, you can process both arrays in the same loop.

After you have filled both arrays, you can compare them, in order to determine whether both numbers use the same digits.

Also, it may be better to change the return type of same_digit to bool.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

bool same_digit( int a, int b )
{
    int numbers[2] = { a, b };
    bool occurred[2][10] = { {false} };

    //determine which digits are used by the individual numbers
    //and fill the two arrays accordingly
    for ( int i = 0; i < 2; i++ )
    {
        int n = abs( numbers[i] );

        while ( n > 0 )
        {
            occurred[i][n%10] = true;
            n = n / 10;
        }
    }

    //determine whether both numbers use the same digits
    for ( int i = 0; i < 10; i++ )
        if ( occurred[0][i] != occurred[1][i] )
            return false;

    return true;
}

//the following code has not been modified
int main() {
  int a, b;
  scanf("%d", &a);
  scanf("%d", &b);
  if (same_digit(a, b)) printf("Yes");
  else printf("No");
  return 0;
}


问:
Google Cloud PubSub Lite subscription in C#
I'm writing a software with C# language and I need to create a subscription to a Pub/Sub Lite in Google Cloud.
I understood that I can't user the Google.Cloud.PubSub.V1 nuget package because it doesn't work with the Lite version.
I found Google.Apis.PubsubLite.V1 nuget package but I haven't found an example of how I can create a subscription and read data from the Pub/Sub Lite.
How I can do that?</p>

答:
Unfortunately C# language is not supported. You can create from console or terminal using the gcloud pubsub lite-subscriptions create command.

If you want to use the API, these languages are supported:

Python

Java

GO

You can see this official documentation.


问:
Sequentially take a window of rows from array (python)
I have an array of size nxm and want to take the first 10 rows and perform calculations, then take the next 10 rows perform calculations, etc. But this is hard coded, how can I make a loop?

Code Attempted:

```<code>import numpy as np
total = []
x= np.random.random((100,4))
a = np.average(x[:10])
total.append(a)
a = np.average(x[10:20])
total.append(a)
a = np.average(x[20:30])
....
</code>```

Goal:

```<code>for *this array*:
# to something
# append value
# go back and get next 10 values
</code>```

答:
It looks like you want the following.

```<code>import numpy as np
x = np.random.random((100,4))
L = 10
k = 100//L
total = [np.average(x[L*i:L*(i+1)]) for i in range(k)]
</code>```

If you'd rather implement this using a loop rather than list comprehension,

```<code>import numpy as np
x = np.random.random((100,4))
L = 10
k = 100//L
total = []
for i in range(k):
    total.append(np.average(x[L*i:L*(i+1)]))
</code>```

As an alternative, here's an approach using a 3-dimensional reshape.

```<code>x= np.random.random((100,4))

L = 10 #window length
n = x.shape[1] #number of columns
total = a.reshape(-1,10,n).mean(axis = (1,2))
</code>```

Body:
I have an array of size nxm and want to take the first 10 rows and perform calculations, then take the next 10 rows perform calculations, etc. But this is hard coded, how can I make a loop?

Code Attempted:

import numpy as np
total = []
x= np.random.random((100,4))
a = np.average(x[:10])
total.append(a)
a = np.average(x[10:20])
total.append(a)
a = np.average(x[20:30])
....

Goal:

for *this array*:
# to something
# append value
# go back and get next 10 values

Body:
It looks like you want the following.

import numpy as np
x = np.random.random((100,4))
L = 10
k = 100//L
total = [np.average(x[L*i:L*(i+1)]) for i in range(k)]

If you'd rather implement this using a loop rather than list comprehension,

import numpy as np
x = np.random.random((100,4))
L = 10
k = 100//L
total = []
for i in range(k):
    total.append(np.average(x[L*i:L*(i+1)]))

As an alternative, here's an approach using a 3-dimensional reshape.

x= np.random.random((100,4))

L = 10 #window length
n = x.shape[1] #number of columns
total = a.reshape(-1,10,n).mean(axis = (1,2))


问:
Color change onhover?
How do you make a simple square that when you hover (or mouseover) the whole thing changes color?

Thanks for the help!

答:
Here it is:</p>

```<code><style type="text/css">
div.test
{
width: 115px;
height: 115px;
background-color: blue;
}
div.test:hover
{
background-color: red;
}
</style>
<div class="test"></div>
</code>```

Title: Color change onhover?

Body:
Here it is:

<style type="text/css">
div.test
{
width: 115px;
height: 115px;
background-color: blue;
}
div.test:hover
{
background-color: red;
}
</style>
<div class="test"></div>


问:
Python: Change Step Loops Dynamically in Python

I have records in a spreadsheet and I need to partition group by ID_CLI.

My code is

```<code>Import pandas as pd

data = pd.read_excel('ReadSheet.xlsx')
step = 5
count = 0

for i in range(0, len(data), step):
    df = data[i:i + step]
    count += 1

    df.to_excel('SpreadSheet_'+count+'.xlsx')

</code>```

I need read the step in next position of the ID_CLI (step 6), and if is equal to the current one (step 5) it iterates +1 in my step, otherwise step = 5. Repeat in all records of my SpreadSheet keeping my original step = 5, and Iterates if next (ID_CLI) is equal current one

My Original SpreadSheet

I need some condicition like this:

```<code>if ID_CLI[step + 1] == ID_CLI[step]:
      step += 1
else:
      step = step
</code>```
```<code>POSITION    ID_CLI  NAME_CLI
1           1       Bruce Wayne
2           1       Bruce Wayne
3           2       Prakash Dahal
4           2       Prakash Dahal
5           3       Peter Parker
6           3       Peter Parker
7           4       Black Panther
8           4       Black Panther
9           4       Black Panther
10          4       Black Panther
11          5       Tony Stark
12          6       Doctor Strange
13          6       Doctor Strange
14          6       Doctor Strange
15          6       Doctor Strange
16          6       Doctor Strange
17          6       Doctor Strange
18          6       Doctor Strange
19          7       Ciclops
20          7       Ciclops
21          7       Ciclops
22          7       Ciclops
23          7       Ciclops
24          8       Nocturn
</code>```

OUTPUT

```<code>
**SpreadSheet_1.xlsx**
POSITION    ID_CLI  NAME_CLI
1           1       Bruce Wayne
2           1       Bruce Wayne
3           2       Prakash Dahal
4           2       Prakash Dahal
5           3       Peter Parker # step = 5 and ID_CLI Equals next ID_CLI
6           3       Peter Parker # step = 6 and ID_CLI Different next ID_CLI from step 7

**SpreadSheet_2.xlsx**
POSITION    ID_CLI  NAME_CLI
7           4       Black Panther
8           4       Black Panther
9           4       Black Panther
10          4       Black Panther
11          5       Tony Stark # step = 5 and ID_CLI Different next ID_CLI from step 6

**SpreadSheet_3.xlsx**
POSITION    ID_CLI  NAME_CLI
12          6       Doctor Strange
13          6       Doctor Strange
14          6       Doctor Strange
15          6       Doctor Strange
16          6       Doctor Strange # step = 5 and ID_CLI Equals next ID_CLI from step 6
17          6       Doctor Strange # step = 6 and ID_CLI Equals next ID_CLI from step 7
18          6       Doctor Strange # step = 7 and ID_CLI Different next ID_CLI from step 8

**SpreadSheet_4.xlsx**
POSITION    ID_CLI  NAME_CLI
19          7       Ciclops
20          7       Ciclops
21          7       Ciclops
22          7       Ciclops
23          7       Ciclops # step = 5 and ID_CLI Different next ID_CLI from step 6

**SpreadSheet_4.xlsx**
POSITION    ID_CLI  NAME_CLI
24          8       Nocturn # End Records

</code>```

答:
This should work.</p>
```<code>"""
- creates chunk for size of 5
- if duplicate data is in 5th place and 6th place, it will increase chunk size until the final duplicate data place is found and creates its chunk.
"""

step = 5
a = 0

df = pd.read_excel('sample.xlsx')
df['POSITION'] = df['POSITION'].astype(int)
df['ID_CLI'] = df['ID_CLI'].astype(int)
df['POS_INDEX'] = df['POSITION']
df = df.set_index('POS_INDEX')

while True:
    if step >= len(df):
        a += 1
        df.loc[1:step].to_excel(f'SpreadSheet_{a}.xlsx', index=False)
        break

    if df.loc[step,'NAME_CLI'] == df.loc[step+1,'NAME_CLI']:
        while df.loc[step,'NAME_CLI'] == df.loc[step+1,'NAME_CLI']:
            step += 1
        a += 1
        df.loc[1:step].to_excel(f'SpreadSheet_{a}.xlsx', index=False)
        df.drop(list(range(1,step+1)), axis=0,inplace=True) #droping chunk to create new df
        df.index = list(range(1,len(df)+1))
        df.index.name = 'POS_INDEX'
        step=5
    else:
        step = 5
        a += 1
        df.loc[1:step].to_excel(f'SpreadSheet_{a}.xlsx', index=False)
        df.drop(list(range(1,step+1)), axis=0,inplace=True)
        df.index = list(range(1,len(df)+1))
        df.index.name = 'POS_INDEX'
</code>```

Body:
I have records in a spreadsheet and I need to partition group by ID_CLI.

My code is

Import pandas as pd

data = pd.read_excel('ReadSheet.xlsx')
step = 5
count = 0

for i in range(0, len(data), step):
    df = data[i:i + step]
    count += 1

    df.to_excel('SpreadSheet_'+count+'.xlsx')

I need read the step in next position of the ID_CLI (step 6), and if is equal to the current one (step 5) it iterates +1 in my step, otherwise step = 5. Repeat in all records of my SpreadSheet keeping my original step = 5, and Iterates if next (ID_CLI) is equal current one

My Original SpreadSheet

I need some condicition like this:

if ID_CLI[step + 1] == ID_CLI[step]:
      step += 1
else:
      step = step

POSITION    ID_CLI  NAME_CLI
1           1       Bruce Wayne
2           1       Bruce Wayne
3           2       Prakash Dahal
4           2       Prakash Dahal
5           3       Peter Parker
6           3       Peter Parker
7           4       Black Panther
8           4       Black Panther
9           4       Black Panther
10          4       Black Panther
11          5       Tony Stark
12          6       Doctor Strange
13          6       Doctor Strange
14          6       Doctor Strange
15          6       Doctor Strange
16          6       Doctor Strange
17          6       Doctor Strange
18          6       Doctor Strange
19          7       Ciclops
20          7       Ciclops
21          7       Ciclops
22          7       Ciclops
23          7       Ciclops
24          8       Nocturn

OUTPUT

**SpreadSheet_1.xlsx**
POSITION    ID_CLI  NAME_CLI
1           1       Bruce Wayne
2           1       Bruce Wayne
3           2       Prakash Dahal
4           2       Prakash Dahal
5           3       Peter Parker # step = 5 and ID_CLI Equals next ID_CLI
6           3       Peter Parker # step = 6 and ID_CLI Different next ID_CLI from step 7

**SpreadSheet_2.xlsx**
POSITION    ID_CLI  NAME_CLI
7           4       Black Panther
8           4       Black Panther
9           4       Black Panther
10          4       Black Panther
11          5       Tony Stark # step = 5 and ID_CLI Different next ID_CLI from step 6

**SpreadSheet_3.xlsx**
POSITION    ID_CLI  NAME_CLI
12          6       Doctor Strange
13          6       Doctor Strange
14          6       Doctor Strange
15          6       Doctor Strange
16          6       Doctor Strange # step = 5 and ID_CLI Equals next ID_CLI from step 6
17          6       Doctor Strange # step = 6 and ID_CLI Equals next ID_CLI from step 7
18          6       Doctor Strange # step = 7 and ID_CLI Different next ID_CLI from step 8

**SpreadSheet_4.xlsx**
POSITION    ID_CLI  NAME_CLI
19          7       Ciclops
20          7       Ciclops
21          7       Ciclops
22          7       Ciclops
23          7       Ciclops # step = 5 and ID_CLI Different next ID_CLI from step 6

**SpreadSheet_4.xlsx**
POSITION    ID_CLI  NAME_CLI
24          8       Nocturn # End Records

Body:
This should work.

"""
- creates chunk for size of 5
- if duplicate data is in 5th place and 6th place, it will increase chunk size until the final duplicate data place is found and creates its chunk.
"""

step = 5
a = 0

df = pd.read_excel('sample.xlsx')
df['POSITION'] = df['POSITION'].astype(int)
df['ID_CLI'] = df['ID_CLI'].astype(int)
df['POS_INDEX'] = df['POSITION']
df = df.set_index('POS_INDEX')

while True:
    if step >= len(df):
        a += 1
        df.loc[1:step].to_excel(f'SpreadSheet_{a}.xlsx', index=False)
        break

    if df.loc[step,'NAME_CLI'] == df.loc[step+1,'NAME_CLI']:
        while df.loc[step,'NAME_CLI'] == df.loc[step+1,'NAME_CLI']:
            step += 1
        a += 1
        df.loc[1:step].to_excel(f'SpreadSheet_{a}.xlsx', index=False)
        df.drop(list(range(1,step+1)), axis=0,inplace=True) #droping chunk to create new df
        df.index = list(range(1,len(df)+1))
        df.index.name = 'POS_INDEX'
        step=5
    else:
        step = 5
        a += 1
        df.loc[1:step].to_excel(f'SpreadSheet_{a}.xlsx', index=False)
        df.drop(list(range(1,step+1)), axis=0,inplace=True)
        df.index = list(range(1,len(df)+1))
        df.index.name = 'POS_INDEX'


问:
Circular relationship in UML Diagram Class
I have a problem in my diagram class.
here is the logic :

user can create a campaign

user can make donation ( transaction in the image ) to a campaign

user have a lis of donations to different campaigns

campaign have a list of donations from different users

the problem : since its not recommended , i want to avoid the circular relationship but i don't know how ?
any help ?

答: This is not a circular relationship. What you see is a simple Association (as you mentioned for noting the creation) and the other is an Association Class. This is used to note the Transactions between User and Compaign (guess that's a typo here).


问:
React Native I can not store an array with AsyncStorage
I am newbie in React Native and I am trying to store and get an array with AsyncStorage in ReactNative.

I have two problems.

First, I do not know why but when I storage data, it only works the second time but I am calling first the set of useState.

```<code>const handleAddTask = () => {
    Keyboard.dismiss();
    setTaskItems([...taskItems, task]);
    storeData(taskItems);
  };
</code>```

Second, how can I call the getData function to get all the data and show it? Are there something like .onInit, .onInitialize... in ReactNative? Here is my full code

```<code>const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);

  const handleAddTask = () => {
    Keyboard.dismiss();
    setTaskItems([...taskItems, task]);
    storeData(taskItems);
  };

  const completeTask = (index) => {
    var itemsCopy = [...taskItems];
    itemsCopy.splice(index, 1);
    setTaskItems(itemsCopy);
    storeData(taskItems);
  }

  const storeData = async (value) => {
    try {
      await AsyncStorage.setItem('@tasks', JSON.stringify(value))
      console.log('store', JSON.stringify(taskItems));
    } catch (e) {
      console.log('error');
    }
  }

  const getData = async () => {
    try {
      const value = await AsyncStorage.getItem('@tasks')
      if(value !== null) {
        console.log('get', JSON.parse(value));
      }
    } catch(e) {
      console.log('error get');
    }
  }
</code>```

答:
Even if you're update state setTaskItems([...taskItems, task]) before save new data in local storage, storeData(taskItems) executed before state updated and save old state data.

Refactor handleAddTask as below.

  const handleAddTask = () => {
   Keyboard.dismiss();

const newTaskItems = [...taskItems, task]
    setTaskItems(newTaskItems);
    storeData(newTaskItems);
  };

```

Body:
I am newbie in React Native and I am trying to store and get an array with AsyncStorage in ReactNative.

I have two problems.

First, I do not know why but when I storage data, it only works the second time but I am calling first the set of useState.

const handleAddTask = () => {
    Keyboard.dismiss();
    setTaskItems([...taskItems, task]);
    storeData(taskItems);
  };

Second, how can I call the getData function to get all the data and show it? Are there something like .onInit, .onInitialize... in ReactNative? Here is my full code

const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);

  const handleAddTask = () => {
    Keyboard.dismiss();
    setTaskItems([...taskItems, task]);
    storeData(taskItems);
  };

  const completeTask = (index) => {
    var itemsCopy = [...taskItems];
    itemsCopy.splice(index, 1);
    setTaskItems(itemsCopy);
    storeData(taskItems);
  }

  const storeData = async (value) => {
    try {
      await AsyncStorage.setItem('@tasks', JSON.stringify(value))
      console.log('store', JSON.stringify(taskItems));
    } catch (e) {
      console.log('error');
    }
  }

  const getData = async () => {
    try {
      const value = await AsyncStorage.getItem('@tasks')
      if(value !== null) {
        console.log('get', JSON.parse(value));
      }
    } catch(e) {
      console.log('error get');
    }
  }


问:
List names of all documents in subcollection - Firebase Flutter
I am new to Flutter and Firebase.
I am trying to get all document Names in a certain collection.
Each user has documents which contains todo items.

I already tried it with getting a document snapshot and returning the reference id, but firstly this is a id, not the name, and secondly the id changes on every execution?

```<code>Future<String> getLists() async {
    DocumentReference doc_ref = FirebaseFirestore.instance
        .collection('userTodos')
        .doc(userID)
        .collection('lists')
        .doc();
    DocumentSnapshot docSnap = await doc_ref.get();
    return docSnap.reference.id;
  }
</code>```

I know that it's not possible to get subcollection on mobile apps, but the names of documents should be possible right?

This is how my Firebase looks like:

Firebase Screenshot

I mean, I could create a document which has all document names as items, but this way it would reduce code and would be nicer.
Thanks for your help!

UPDATE:

This is my console Output each time the function is called and I print it to the console.

Console Output

答:
I have solved it with trial and error:
You have to itterate through all documents and then add the id's to a list:</p>
```<code>Future<List> getLists() async {
  List<String> userLists = [];
  CollectionReference col_ref = FirebaseFirestore.instance
      .collection('userTodos')
      .doc(userID)
      .collection('Lists');
  QuerySnapshot docSnap = await col_ref.get();
  docSnap.docs.forEach((elements) {
    userLists.add(elements.id);
  });
  return userLists;
}
</code>```

Body:
I am new to Flutter and Firebase.
I am trying to get all document Names in a certain collection.
Each user has documents which contains todo items.

I already tried it with getting a document snapshot and returning the reference id, but firstly this is a id, not the name, and secondly the id changes on every execution?

Future<String> getLists() async {
    DocumentReference doc_ref = FirebaseFirestore.instance
        .collection('userTodos')
        .doc(userID)
        .collection('lists')
        .doc();
    DocumentSnapshot docSnap = await doc_ref.get();
    return docSnap.reference.id;
  }

I know that it's not possible to get subcollection on mobile apps, but the names of documents should be possible right?

This is how my Firebase looks like:

Firebase Screenshot

I mean, I could create a document which has all document names as items, but this way it would reduce code and would be nicer.
Thanks for your help!

UPDATE:

This is my console Output each time the function is called and I print it to the console.

Console Output

Body:
I have solved it with trial and error:
You have to itterate through all documents and then add the id's to a list:

Future<List> getLists() async {
  List<String> userLists = [];
  CollectionReference col_ref = FirebaseFirestore.instance
      .collection('userTodos')
      .doc(userID)
      .collection('Lists');
  QuerySnapshot docSnap = await col_ref.get();
  docSnap.docs.forEach((elements) {
    userLists.add(elements.id);
  });
  return userLists;
}


问:
How do you parse a poorly formatted HTML file?
I have to parse a series of web pages in order to import data into an application. Each type of web page provides the same kind of data. The problem is that the HTML of each page is different, so the location of the data varies. Another problem is that the HTML code is poorly formatted, making it impossible to use a XML-like parser.

So far, the best strategy I can think of, is to define a template for each kind of page, like:

Template A:

```<code><html>
...
  <tr><td>Table column that is missing a td
      <td> Another table column</td></tr>
  <tr><td>$data_item_1$</td>
...
</html>
</code>```

Template B:

```<code><html>
...
  <ul><li>Yet another poorly formatted page <li>$data_item_1$</td></tr>
...
</html>
</code>```

This way I would only need one single parser for all the pages, that would compare each page with its template and retrieving the $data_item_1$, $data_item_2$, etc.  Still, it is going to be a lot of work.  Can you think of any simpler solution? Any library that can help?

Thanks

答:
As mentioned here and on other SO answers before, Beautiful Soup can parse weird HTML.

Beautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping. Three features make it powerful:

Beautiful Soup won't choke if you give it bad markup. It yields a parse tree that makes approximately as much sense as your original document. This is usually good enough to collect the data you need and run away.

Beautiful Soup provides a few simple methods and Pythonic idioms for navigating, searching, and modifying a parse tree: a toolkit for dissecting a document and extracting what you need. You don't have to create a custom parser for each application.

Beautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. You don't have to think about encodings, unless the document doesn't specify an encoding and Beautiful Soup can't autodetect one. Then you just have to specify the original encoding.

Beautiful Soup parses anything you give it, and does the tree traversal stuff for you. You can tell it "Find all the links", or "Find all the links of class externalLink", or "Find all the links whose urls match "foo.com", or "Find the table heading that's got bold text, then give me that text."

OwnerDisplayName: ivo

ContentLicense: CC BY-SA 2.5

Body:
I have to parse a series of web pages in order to import data into an application. Each type of web page provides the same kind of data. The problem is that the HTML of each page is different, so the location of the data varies. Another problem is that the HTML code is poorly formatted, making it impossible to use a XML-like parser.

So far, the best strategy I can think of, is to define a template for each kind of page, like:

Template A:

...

Table column that is missing a td
       Another table column

$data_item_1$
...

Template B:

...

Yet another poorly formatted page
$data_item_1$

...

This way I would only need one single parser for all the pages, that would compare each page with its template and retrieving the $data_item_1$, $data_item_2$, etc.  Still, it is going to be a lot of work.  Can you think of any simpler solution? Any library that can help?

Thanks

LastEditorDisplayName: Eddie

OwnerDisplayName: gimel


问:
SwiftUI - How to pass EnvironmentObject into View Model?
I'm looking to create an EnvironmentObject that can be accessed by the View Model (not just the view).

The Environment object tracks the application session data, e.g. loggedIn, access token etc, this data will be passed into the view models (or service classes where needed) to allow calling of an API to pass data from this EnvironmentObjects.

I have tried to pass in the session object to the initialiser of the view model class from the view but get an error.

how can I access/pass the EnvironmentObject into the view model using SwiftUI?

答:
Solution for: iOS 14/15+

Here's how you might interact with an Environment Object from a View Model, without having to inject it on instantiation:

Define the Environment Object:

import Combine

final class MyAuthService: ObservableObject {
    @Published private(set) var isSignedIn = false

    func signIn() {
        isSignedIn = true
    }
}
```
<ol>
<li>Create a View to own and pass around the Environment Object:</li>
</ol>
<pre class="lang-swift prettyprint-override"><code>import SwiftUI

struct MyEntryPointView: View {
    @StateObject var auth = MyAuthService()

    var body: some View {
        content
            .environmentObject(auth)
    }

    @ViewBuilder private var content: some View {
        if auth.isSignedIn {
            Text("Yay, you're all signed in now!")
        } else {
            MyAuthView()
        }
    }
}
</code>```

Define the View Model with methods that take the Environment Object as an argument:

extension MyAuthView {
    @MainActor final class ViewModel: ObservableObject {
        func signIn(with auth: MyAuthService) {
            auth.signIn()
        }
    }
}
```
<ol start="3">
<li>Create a View that owns the View Model, receives the Environment Object, and calls the appropriate method:</li>
</ol>
<pre class="lang-swift prettyprint-override"><code>struct MyAuthView: View {
    @EnvironmentObject var auth: MyAuthService
    @StateObject var viewModel = ViewModel()

    var body: some View {
        Button {
            viewModel.signIn(with: auth)
        } label: {
            Text("Sign In")
        }
    }
}
</code>```

Preview it for completeness:

struct MyEntryPointView_Previews: PreviewProvider {
    static var previews: some View {
        MyEntryPointView()
    }
}
```

Body:
Solution for: iOS 14/15+

Here's how you might interact with an Environment Object from a View Model, without having to inject it on instantiation:

Define the Environment Object:

import Combine

final class MyAuthService: ObservableObject {
    @Published private(set) var isSignedIn = false

    func signIn() {
        isSignedIn = true
    }
}

Create a View to own and pass around the Environment Object:

import SwiftUI

struct MyEntryPointView: View {
    @StateObject var auth = MyAuthService()

    var body: some View {
        content
            .environmentObject(auth)
    }

    @ViewBuilder private var content: some View {
        if auth.isSignedIn {
            Text("Yay, you're all signed in now!")
        } else {
            MyAuthView()
        }
    }
}

Define the View Model with methods that take the Environment Object as an argument:

extension MyAuthView {
    @MainActor final class ViewModel: ObservableObject {
        func signIn(with auth: MyAuthService) {
            auth.signIn()
        }
    }
}

Create a View that owns the View Model, receives the Environment Object, and calls the appropriate method:

struct MyAuthView: View {
    @EnvironmentObject var auth: MyAuthService
    @StateObject var viewModel = ViewModel()

    var body: some View {
        Button {
            viewModel.signIn(with: auth)
        } label: {
            Text("Sign In")
        }
    }
}

Preview it for completeness:

struct MyEntryPointView_Previews: PreviewProvider {
    static var previews: some View {
        MyEntryPointView()
    }
}


问:
Pandas groupby with "Wide" data
My dataframes are in a "wide" format, such that columns contain data for different entities, and rows are dates, e.g. product costs through time:

```<code>import pandas as pd

cost = pd.DataFrame([[10,20,30,40],[11,22,33,44],[111,222,333,444]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))
</code>```
```<code>            Knife  Fork  Spoon  Spatula
2022-01-01     10    20     30       40
2022-01-02     11    22     33       44
2022-01-03    111   222    333      444
</code>```

I have a similar dataframe that places each data point in one of two groups (1 or 2):

```<code>grp = pd.DataFrame([[1,2,1,2],[1,1,2,2],[2,1,1,2]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))
</code>```
```<code>            Knife  Fork  Spoon  Spatula
2022-01-01      1     2      1        2
2022-01-02      1     1      2        2
2022-01-03      2     1      1        2
</code>```

I want to do an aggregate groupby-style mean on each of the groups for each date. As such, this is my desired output, showing the averages for groups 1 and 2:

```<code>avg =  pd.DataFrame([[(10+30)/2,(20+40)/2],[(11+22)/2,(33+44)/2],[(111+444)/2,(222+333)/2]], columns=[1,2], index=pd.date_range('2022-01-01','2022-01-03'))
</code>```
```<code>                1      2
2022-01-01   20.0   30.0
2022-01-02   16.5   38.5
2022-01-03  277.5  277.5
</code>```

I've tried to melt each dataframe, reindex, merge, groupby, aggregate and pivot but it's a real mess (esp the reindexing).

It seems to me there must be a better way to aggregate this kind of "wide" data? My actual data is way bigger (and with more groups), hence a desire for efficiency.

How can I most efficiently gain my desired output?

答:
The plan is to stack each frame, join them, groupby by date/group, and unstack:

```<code>dfm = cost.stack().to_frame(name = 'cost').join(grp.stack().to_frame(name = 'group'))
dfm.reset_index().groupby(['level_0','group']).mean().unstack()
</code>```

output:

```<code>    cost
group          1    2
   level_0
2022-01-01  20.0    30.0
2022-01-02  16.5    38.5
2022-01-03  277.5   277.5
</code>```

Title: Pandas groupby with "Wide" data

Body:
My dataframes are in a "wide" format, such that columns contain data for different entities, and rows are dates, e.g. product costs through time:

import pandas as pd

cost = pd.DataFrame([[10,20,30,40],[11,22,33,44],[111,222,333,444]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))

            Knife  Fork  Spoon  Spatula
2022-01-01     10    20     30       40
2022-01-02     11    22     33       44
2022-01-03    111   222    333      444

I have a similar dataframe that places each data point in one of two groups (1 or 2):

grp = pd.DataFrame([[1,2,1,2],[1,1,2,2],[2,1,1,2]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))

            Knife  Fork  Spoon  Spatula
2022-01-01      1     2      1        2
2022-01-02      1     1      2        2
2022-01-03      2     1      1        2

I want to do an aggregate groupby-style mean on each of the groups for each date. As such, this is my desired output, showing the averages for groups 1 and 2:

avg =  pd.DataFrame([[(10+30)/2,(20+40)/2],[(11+22)/2,(33+44)/2],[(111+444)/2,(222+333)/2]], columns=[1,2], index=pd.date_range('2022-01-01','2022-01-03'))

                1      2
2022-01-01   20.0   30.0
2022-01-02   16.5   38.5
2022-01-03  277.5  277.5

I've tried to melt each dataframe, reindex, merge, groupby, aggregate and pivot but it's a real mess (esp the reindexing).

It seems to me there must be a better way to aggregate this kind of "wide" data? My actual data is way bigger (and with more groups), hence a desire for efficiency.

How can I most efficiently gain my desired output?

Body:
The plan is to stack each frame, join them, groupby by date/group, and unstack:

dfm = cost.stack().to_frame(name = 'cost').join(grp.stack().to_frame(name = 'group'))
dfm.reset_index().groupby(['level_0','group']).mean().unstack()

output:

    cost
group          1    2
   level_0
2022-01-01  20.0    30.0
2022-01-02  16.5    38.5
2022-01-03  277.5   277.5


问:
What is replacing .then(data => console.log(data)) with just .then(console.log) called?
I saw the following code in a React application.

```<code>getData()
        .then(res => res.json())
        .then(console.log)
</code>```

And it behaves exactly the same as I would use

```<code>getAllStudents()
        .then(res => res.json())
        .then(data => console.log(data))
</code>```

So in the first example the called function console.log somehow implicitly knows it should take the data as parameter and show it in the console. That function is not even called with console.log()

Could you please tell me what this shortcut concept is called? I would like to read more about it, but I don't know how exactly I should use it.

答:
It is called "point free style" or tacit programming.

See e.g. https://en.wikipedia.org/wiki/Tacit_programming

Edit: The above case may not exactly be tacit programming, as that involves defining functions without explicitly mentioning their arguments ("tacit" = "implicit"), and here you are merely using an already defined function as an argument. But a function definition

```<code>const log = console.log
</code>```

would be a tacit function, as opposed to

```<code>const log = data => console.log(data)
</code>```

so the concept is at least closely related to the difference in the question.

Body:
I saw the following code in a React application.

getData()
        .then(res => res.json())
        .then(console.log)

And it behaves exactly the same as I would use

getAllStudents()
        .then(res => res.json())
        .then(data => console.log(data))

So in the first example the called function console.log somehow implicitly knows it should take the data as parameter and show it in the console. That function is not even called with console.log()

Could you please tell me what this shortcut concept is called? I would like to read more about it, but I don't know how exactly I should use it.

Body:
It is called "point free style" or tacit programming.

See e.g. https://en.wikipedia.org/wiki/Tacit_programming

Edit: The above case may not exactly be tacit programming, as that involves defining functions without explicitly mentioning their arguments ("tacit" = "implicit"), and here you are merely using an already defined function as an argument. But a function definition

const log = console.log

would be a tacit function, as opposed to

const log = data => console.log(data)

so the concept is at least closely related to the difference in the question.


问:
Apple Mach-O Linker (id) Error
I have an error below:

```<code>ld /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator/uniText.app/uniText normal i386
    cd "/Volumes/Data/Documents/XCode Projects/Trans SMS"
    setenv MACOSX_DEPLOYMENT_TARGET 10.6
    setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk -L/Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator -F/Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator -filelist /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Intermediates/uniText.build/Debug-iphonesimulator/uniText.build/Objects-normal/i386/uniText.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -framework SystemConfiguration -framework MessageUI -framework AddressBook -framework AddressBookUI -framework CoreTelephony -lsqlite3.0 -framework UIKit -framework Foundation -framework CoreGraphics -o /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator/uniText.app/uniText

ld: duplicate symbol _OBJC_IVAR_$_FMDatabase.databasePath in /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Intermediates/uniText.build/Debug-iphonesimulator/uniText.build/Objects-normal/i386/FMDatabase-566DC6D59187887D.o and /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Intermediates/uniText.build/Debug-iphonesimulator/uniText.build/Objects-normal/i386/FMDatabase-566DC6D59187887D.o for architecture i386
collect2: ld returned 1 exit status
Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 failed with exit code 1
</code>```

Could someone help me out?
It used to work properly before.
I have no idea what I have changed in the project sources.
But I am sure that I never changed anything in that FMDatabase.h and .m.

答: The relevant portion of your error is ld: duplicate symbol _OBJC_IVAR_$_FMDatabase.databasePath.  For some reason, the linker (ld) is trying to link FMDatabase twice.  Check to see if you have multiple copies of it in your project.

Title: Apple Mach-O Linker (id) Error

Body:
I have an error below:

ld /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator/uniText.app/uniText normal i386
    cd "/Volumes/Data/Documents/XCode Projects/Trans SMS"
    setenv MACOSX_DEPLOYMENT_TARGET 10.6
    setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk -L/Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator -F/Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator -filelist /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Intermediates/uniText.build/Debug-iphonesimulator/uniText.build/Objects-normal/i386/uniText.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -framework SystemConfiguration -framework MessageUI -framework AddressBook -framework AddressBookUI -framework CoreTelephony -lsqlite3.0 -framework UIKit -framework Foundation -framework CoreGraphics -o /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator/uniText.app/uniText

ld: duplicate symbol _OBJC_IVAR_$_FMDatabase.databasePath in /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Intermediates/uniText.build/Debug-iphonesimulator/uniText.build/Objects-normal/i386/FMDatabase-566DC6D59187887D.o and /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Intermediates/uniText.build/Debug-iphonesimulator/uniText.build/Objects-normal/i386/FMDatabase-566DC6D59187887D.o for architecture i386
collect2: ld returned 1 exit status
Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 failed with exit code 1

Could someone help me out?
It used to work properly before.
I have no idea what I have changed in the project sources.
But I am sure that I never changed anything in that FMDatabase.h and .m.


答:
One approach to try:</p>
```<code># Convert each DataFrame into a MultiIndexed Series,
# with dates in the outer level and items in inner level
cost_long = cost.stack().rename('cost')
group_long = grp.stack().rename('group')

# Align long Series on date and item,
# name the MultiIndex levels for clarity,
# calculate mean cost by date and group,
# unstack inner level of MultiIndex (group) into columns
res = (pd.concat([cost_long, group_long], axis=1)
         .rename_axis(['date', 'item'])
         .groupby(['date', 'group'])['cost']
         .mean()
         .unstack()
      )

# Delete names of index and columns to match expected output
res.index.name = None
res.columns.name = None

print(res)
                1      2
2022-01-01   20.0   30.0
2022-01-02   16.5   38.5
2022-01-03  277.5  277.5
</code>```

Title: Pandas groupby with "Wide" data

Body:
One approach to try:

# Convert each DataFrame into a MultiIndexed Series,
# with dates in the outer level and items in inner level
cost_long = cost.stack().rename('cost')
group_long = grp.stack().rename('group')

# Align long Series on date and item,
# name the MultiIndex levels for clarity,
# calculate mean cost by date and group,
# unstack inner level of MultiIndex (group) into columns
res = (pd.concat([cost_long, group_long], axis=1)
         .rename_axis(['date', 'item'])
         .groupby(['date', 'group'])['cost']
         .mean()
         .unstack()
      )

# Delete names of index and columns to match expected output
res.index.name = None
res.columns.name = None

print(res)
                1      2
2022-01-01   20.0   30.0
2022-01-02   16.5   38.5
2022-01-03  277.5  277.5


问:
Align logo in left with link on the right navbar
I wanna to put a logo in the left of the navigation.
The links are set to justify-content: flex-end;

I tried to make a div element and make it important with !important property.

.navbar {
  background-color: #242931;
  top: 0%;
  text-align: center;
  justify-content: flex-end;
  display: flex;
}

.left-nav {
  justify-content: flex-start !important;
  display: flex !important;
}

.navbar a {
  color: #b7c2d0;
  font-family: cubano;
  font-size: 1.15rem;
  text-decoration: none;
  margin-right: 15px;
  margin-left: 15px;
  padding: 24px;
}

.navbar a:hover {
  -webkit-background-clip: text;
  background-image: linear-gradient(to right, #ff6e00, #ff9400, #ffb900, #f8dc00, #e9ff00);
  background-clip: text;
  color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar">
  <div class="left-nav">
    example
  </div>
  Guides
  Clips
  Leaderborard
  Support the server
  Help
  Rules
</div></code>```

答:
Nest the right-nav in a div also. Then you can use justify-content: space-between; which will space out the two divs. Then you can add align-items: center; to make them align.

.navbar {
  background-color: #242931;
  top: 0%;
  text-align: center;
  justify-content: space-between;
  display: flex;
  align-items: center;
}

.left-nav {
  justify-content: flex-start !important;
  display: flex !important;
}

.navbar a {
  color: #b7c2d0;
  font-family: cubano;
  font-size: 1.15rem;
  text-decoration: none;
  margin-right: 15px;
  margin-left: 15px;
  padding: 24px;
}

.navbar a:hover {
  -webkit-background-clip: text;
  background-image: linear-gradient(to right, #ff6e00, #ff9400, #ffb900, #f8dc00, #e9ff00);
  background-clip: text;
  color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar">
  <div class="left-nav">
    example
  </div>
  <div class="right-nav">
    Guides
    Clips
    Leaderborard
    Support the server
    Help
    Rules
  </div>
</div></code>```

Body:
I wanna to put a logo in the left of the navigation.
The links are set to justify-content: flex-end;

I tried to make a div element and make it important with !important property.

.navbar {
  background-color: #242931;
  top: 0%;
  text-align: center;
  justify-content: flex-end;
  display: flex;
}

.left-nav {
  justify-content: flex-start !important;
  display: flex !important;
}

.navbar a {
  color: #b7c2d0;
  font-family: cubano;
  font-size: 1.15rem;
  text-decoration: none;
  margin-right: 15px;
  margin-left: 15px;
  padding: 24px;
}

.navbar a:hover {
  -webkit-background-clip: text;
  background-image: linear-gradient(to right, #ff6e00, #ff9400, #ffb900, #f8dc00, #e9ff00);
  background-clip: text;
  color: transparent;
}

    example

  Guides
  Clips
  Leaderborard
  Support the server
  Help
  Rules

Body:
Nest the right-nav in a div also. Then you can use justify-content: space-between; which will space out the two divs. Then you can add align-items: center; to make them align.

.navbar {
  background-color: #242931;
  top: 0%;
  text-align: center;
  justify-content: space-between;
  display: flex;
  align-items: center;
}

.left-nav {
  justify-content: flex-start !important;
  display: flex !important;
}

.navbar a {
  color: #b7c2d0;
  font-family: cubano;
  font-size: 1.15rem;
  text-decoration: none;
  margin-right: 15px;
  margin-left: 15px;
  padding: 24px;
}

.navbar a:hover {
  -webkit-background-clip: text;
  background-image: linear-gradient(to right, #ff6e00, #ff9400, #ffb900, #f8dc00, #e9ff00);
  background-clip: text;
  color: transparent;
}

<div class="navbar">
  <div class="left-nav">
    <a href="">example</a>
  </div>
  <div class="right-nav">
    <a href="Others HTML pages/Guides.html" target="_blank">Guides</a>
    <a href="#" target="_blank">Clips</a>
    <a href="#" target="_blank">Leaderborard</a>
    <a href="Others HTML pages/Support the server.html" target="_blank">Support the server</a>
    <a href="Others HTML pages/Help.html" target="_blank">Help</a>
    <a href="Others HTML pages/Rules.html" target="_blank">Rules</a>
  </div>
</div>


问:
R changing excel values during importing with read_excel
I am importing an excel file into R, however, some of the values are changing from the original value by adding a significant number of decimal places.

i.e The original value may be 77.21 but is changed to 72.209999999999994. I figure it has something to do with floating point numbers?

I know this example would round back to 72.21, however, sometimes it is occurring on much smaller numbers.
I also need to ensure the reported value in the excel sheet is what is getting imported.

Does anyone have ideas how to manage this?

Here is a sample of how the data is stored in excel

sample  Ni    Co      Al2O3    Fe2O3  S  etc....

84564 <0.005 <0.005    2.65     77.21  0.052

84107 <0.005 <0.005     2.64     77.18  0.051

....

the "<" less than indicated below detection and is handled else where.

my code is : data <- read_excel(file.path)

what I get in R is

sample  Ni    Co        Al2O3                    Fe2O3         S

84564 <0.005 <0.005  2.6499999999999999 77.209999999999994 0.051999999999999998

84107 <0.005 <0.005  2.6400000000000001 77.180000000000007 0.050999999999999997

Some fields need to be round 2 decimals places and some 3 or 4.  My main concern is that numbers may get rounded or modified beyond the detection limit.

答:
I had the same issue after I added text values in data frame of Excel. After I removed such fields the problem gone. It is only first row of the table can be text.
My solution was to use two excel files for import: One with only digits and second with text values.</p>


问:
Want to know how to populate data from One block to another?
I have two database Datablock

In the First Block I have a Item called parameter name with LOV. While selecting that LOV ,it should populate Next Item Also that is Section

Now What i want is when I am selecting the Parameter name LOV from First Data Block. I want to populate the corresponding data in the list Value of the Second Data Block

For this i used post text item -->Inside that I used go block But it throws illegal restriction Error

Now I am out of ideas

答:
If I understood you correctly, you're talking about cascading LoVs. If that's so, then the 1st LoV query looks like this:

```<code>select parameter_name, section
from some_table
where some_condition;
</code>```

You set it to populate appropriate fields in the 1st data block (one of them is :block_1.parameter_name).

The second block's LoV would then "reference" the first block's field:

```<code>select another_column
from another_table
where parameter_name = :block_1.parameter_name     --> this
  and other_conditions;
</code>```

You don't need any triggers; once you display 2nd block field's list of values, it'll use that where clause and display only values that match the condition.

Body:
If I understood you correctly, you're talking about cascading LoVs. If that's so, then the 1st LoV query looks like this:

select parameter_name, section
from some_table
where some_condition;

You set it to populate appropriate fields in the 1st data block (one of them is :block_1.parameter_name).

The second block's LoV would then "reference" the first block's field:

select another_column
from another_table
where parameter_name = :block_1.parameter_name     --> this
  and other_conditions;

You don't need any triggers; once you display 2nd block field's list of values, it'll use that where clause and display only values that match the condition.


答:
I've tried to melt each dataframe, reindex, merge, groupby, aggregate and pivot but it's a real mess (esp the reindexing).

So, is this what you tried?

```<code>import pandas as pd

cost_data = [[10,20,30,40],[11,22,33,44],[111,222,333,444]]
grp_data = [[1,2,1,2],[1,1,2,2],[2,1,1,2]]
utensils = ['Knife','Fork','Spoon','Spatula']
dates = pd.date_range('2022-01-01','2022-01-03')
cost = pd.DataFrame(cost_data, columns=utensils, index=dates)
grp = pd.DataFrame(grp, columns=utensils, index=dates)

cost_melted = (
    cost
    .melt(var_name='utensil', value_name='cost', ignore_index=False)
    .rename_axis('date')
    .reset_index()
)
grp_melted = (
    grp
    .melt(var_name='utensil', value_name='group', ignore_index=False)
    .rename_axis('date')
    .reset_index()
)
avg = (
    cost_melted
    .merge(grp_melted, on=['date', 'utensil'])
    .groupby(['date', 'group'])
    .mean()
    .reset_index()
    .pivot('date', 'group', 'cost')
)

print(avg)
</code>```

That prints your expected output:

```<code>group           1      2
date
2022-01-01   20.0   30.0
2022-01-02   16.5   38.5
2022-01-03  277.5  277.5
</code>```

Title: Pandas groupby with "Wide" data

Body:
I've tried to melt each dataframe, reindex, merge, groupby, aggregate and pivot but it's a real mess (esp the reindexing).

So, is this what you tried?

import pandas as pd

cost_data = [[10,20,30,40],[11,22,33,44],[111,222,333,444]]
grp_data = [[1,2,1,2],[1,1,2,2],[2,1,1,2]]
utensils = ['Knife','Fork','Spoon','Spatula']
dates = pd.date_range('2022-01-01','2022-01-03')
cost = pd.DataFrame(cost_data, columns=utensils, index=dates)
grp = pd.DataFrame(grp, columns=utensils, index=dates)

cost_melted = (
    cost
    .melt(var_name='utensil', value_name='cost', ignore_index=False)
    .rename_axis('date')
    .reset_index()
)
grp_melted = (
    grp
    .melt(var_name='utensil', value_name='group', ignore_index=False)
    .rename_axis('date')
    .reset_index()
)
avg = (
    cost_melted
    .merge(grp_melted, on=['date', 'utensil'])
    .groupby(['date', 'group'])
    .mean()
    .reset_index()
    .pivot('date', 'group', 'cost')
)

print(avg)

That prints your expected output:

group           1      2
date
2022-01-01   20.0   30.0
2022-01-02   16.5   38.5
2022-01-03  277.5  277.5


答:
You don't need any div

simply assign margin-right: auto
to the first a (logo)

.navbar {
  display: flex;
  gap: 2em;
}
.navbar a:first-child {
  margin-right: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar">
  LOGO
  two
  three
</div></code>```

If you want to separate those two groups, wrap the actual navigation into a  tag (and for better SEO), and use instead a margin-left: auto on it. The principle is the same:

.navbar {
  display: flex;
}

.navbar nav {
  display: flex;
  gap: 2em;
  margin-left: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar">
  LOGO
  <nav>
    two
    three
  </nav>
</div></code>```

Title: Align logo in left with link on the right navbar

Body:
You don't need any div

simply assign margin-right: auto
to the first a (logo)

.navbar {
  display: flex;
  gap: 2em;
}
.navbar a:first-child {
  margin-right: auto;
}

<div class="navbar">
  <a href="#!">LOGO</a>
  <a href="#!">two</a>
  <a href="#!">three</a>
</div>

If you want to separate those two groups, wrap the actual navigation into a <nav> tag (and for better SEO), and use instead a margin-left: auto on it. The principle is the same:

.navbar {
  display: flex;
}

.navbar nav {
  display: flex;
  gap: 2em;
  margin-left: auto;
}

<div class="navbar">
  <a href="#!">LOGO</a>
  <nav>
    <a href="#!">two</a>
    <a href="#!">three</a>
  </nav>
</div>


问:
In TinyLog what is the platform independent format character for new line in tinylog.properties
In tinylog.properties what do you you specify as the platform independant character for new line ?</p>

答:
In tinylog.properties, you can use Unix like new lines \n or Windows like new lines \r\n. Both should work platform independently on all common JVMs and Android devices.

However, you cannot change the line separator for log files via tinylog.properties. The default line separator can only be changed for the entire JVM via system properties. You can do it via your command line, e.g. java -jar MyApp.jar -Dline.separator=$'\n' on Linux.


问:
pyodbc connection string sql server authentication
I know this question has been asked many times on the web resulting in many different solutions none which have worked for me.

For my scenario I'm attempting to do a simple connection to a MS Sql database connecting just with Service account username and password using windows authentication isn't an option for my task.

This is the connection string that I am providing:

```<code>databaseConnection = 'DRIVER={SQL Server}; SERVER=ServerName; Database=DatbaseName; UID=UserId; PWD=password;'
</code>```

This is the error I receive when trying to run the script:

```<code>    dbConnection = pyodbc.connect(DATABASE.databaseConnection)
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver]
[SQL Server]Cannot open database "XXXX" requested by the login. The login failed.
(4060) (SQLDriverConnect); [42000] [Microsoft][ODBC SQL Server Driver]
[SQL Server]Cannot open database "XXXX" requested by the login. The login failed. (4060)')
</code>```

Is there anything incorrect about this connection string? I have double checked the username and password by copy and pasting it into SQL Server Management Studio and logging into the database from there and it is successful.

答:
Configure the MSSQL server in the obdc datasources and give the name with the pyodbc connection as below.My userdsn name is MyConnection

```<code>import pyodbc

cnxn = pyodbc.connect('DSN=MyConnection')
cursor = cnxn.cursor()
cursor.execute("SELECT TOP (1000) [DepartmentID]      ,[Name]      ,[GroupName]      ,[ModifiedDate]  FROM ["
               "AdventureWorks2019].[HumanResources].[Department]")
rows = cursor.fetchall()
for row in rows:
    print(row.DepartmentID, row.Name)
</code>```

It is working for me. Let me know if there are any other ways to do this.

Body:
I know this question has been asked many times on the web resulting in many different solutions none which have worked for me.

For my scenario I'm attempting to do a simple connection to a MS Sql database connecting just with Service account username and password using windows authentication isn't an option for my task.

This is the connection string that I am providing:

databaseConnection = 'DRIVER={SQL Server}; SERVER=ServerName; Database=DatbaseName; UID=UserId; PWD=password;'

This is the error I receive when trying to run the script:

    dbConnection = pyodbc.connect(DATABASE.databaseConnection)
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver]
[SQL Server]Cannot open database "XXXX" requested by the login. The login failed.
(4060) (SQLDriverConnect); [42000] [Microsoft][ODBC SQL Server Driver]
[SQL Server]Cannot open database "XXXX" requested by the login. The login failed. (4060)')

Is there anything incorrect about this connection string? I have double checked the username and password by copy and pasting it into SQL Server Management Studio and logging into the database from there and it is successful.

Body:
Configure the MSSQL server in the obdc datasources and give the name with the pyodbc connection as below.My userdsn name is MyConnection

import pyodbc

cnxn = pyodbc.connect('DSN=MyConnection')
cursor = cnxn.cursor()
cursor.execute("SELECT TOP (1000) [DepartmentID]      ,[Name]      ,[GroupName]      ,[ModifiedDate]  FROM ["
               "AdventureWorks2019].[HumanResources].[Department]")
rows = cursor.fetchall()
for row in rows:
    print(row.DepartmentID, row.Name)

It is working for me. Let me know if there are any other ways to do this.


问:
how to use some variables defined in one fucntion in another function?
I have a function defined as below:

def mod2():
   while true:
       I = raw_results[0]
       Q = raw_results[1]
```

Now I want to define another function def plot_mod() to plot this I,Q. How can I achieve this?

答:
You'd pass the I and Q as parameters to the plot_mod() function.

Ignoring the while true:

def mod2():
    I = raw_results[0]
    Q = raw_results[1]
    plot_mod(I, Q)
```

Body:
I have a function defined as below:

def mod2():
   while true:
       I = raw_results[0]
       Q = raw_results[1]

Now I want to define another function def plot_mod() to plot this I,Q. How can I achieve this?


问:
How does this code work? The result doesnt make sense to me and doesnt appear in the debugger
```<code>    #include <iostream>

using namespace std;

int f(int n, int m){
    if (n==1)
        return 0;
    else
        return f(n-1, m) + m;
}

int main()
{

cout << f(3874, 1000);
cout << endl;
    return 0;
}
</code>```

The result is 3873000. Why is n multiplied by m after deducting 1 and how does the function work in detail please?

答:
The algorithm solves the recurrence

```<code>F(n) = F(n-1) + m
</code>```

with

```<code>F(1) = 0.
</code>```

(I removed m as an argument, as its value is constant).

We have

```<code>F(n) = F(n-1) + m = F(n-2) + 2m = F(n-3) + 3m = ... = F(1) + (n-1)m.
</code>```

As written elsewhere, the recursion depth is n, which is dangerous.

Body:
    #include <iostream>

using namespace std;

int f(int n, int m){
    if (n==1)
        return 0;
    else
        return f(n-1, m) + m;
}

int main()
{

cout << f(3874, 1000);
cout << endl;
    return 0;
}

The result is 3873000. Why is n multiplied by m after deducting 1 and how does the function work in detail please?

Body:
The algorithm solves the recurrence

F(n) = F(n-1) + m

with

F(1) = 0.

(I removed m as an argument, as its value is constant).

We have

F(n) = F(n-1) + m = F(n-2) + 2m = F(n-3) + 3m = ... = F(1) + (n-1)m.

As written elsewhere, the recursion depth is n, which is dangerous.


问:
Karate - Not able to establish connection with pkcs12 keystore and password
I am not able to establish connection with pkcs12 keystore and password. I have a crt certificate and key file for the same. Converted the same to PFX using openssl and followed the instructions as per the link https://github.com/intuit/karate#x509-certificate-authentication. Still facing timeout issues. I try with crt and key file in postman settings, it does work.

```<code>* configure ssl = { keyStore: 'classpath:sdfnon-prod.pfx', keyStorePassword: '*****', keyStoreType: 'pkcs12' }
</code>```

Can you please suggest me, if there is something else that needs to be configured.

答:
I experienced a similar issue until a figured that the line

```<code>* configure ssl = { trustAll: true }
</code>```

should go above the

```<code>* configure ssl = {...}
</code>```

line in a feature file

Is interesting to me that adding the ssl info into the karate-config.js didn't need the trustAll flag set

Body:
I am not able to establish connection with pkcs12 keystore and password. I have a crt certificate and key file for the same. Converted the same to PFX using openssl and followed the instructions as per the link https://github.com/intuit/karate#x509-certificate-authentication. Still facing timeout issues. I try with crt and key file in postman settings, it does work.

* configure ssl = { keyStore: 'classpath:sdfnon-prod.pfx', keyStorePassword: '*****', keyStoreType: 'pkcs12' }

Can you please suggest me, if there is something else that needs to be configured.

Body:
I experienced a similar issue until a figured that the line

* configure ssl = { trustAll: true }

should go above the

* configure ssl = {...}

line in a feature file

Is interesting to me that adding the ssl info into the karate-config.js didn't need the trustAll flag set


问:
Need help creating a Regex
I need a regex to validate:

just numbers

it have to start with the number 20

the five number needs to be 0 or 1

the seven number needs to be 1, 2 or 3

Title: Need help creating a Regex

Body:
I would go with

^20\d{2}[01]\d[1-3]\d*$


问:
Get selection from controlled MUI Autocomplete with async data and react-hook-form
I'm using a controlled autocomplete field in a form.
The data comes from my redux store; if the array is empty, I initialize it in a useEffect:

```<code>  const collectionList = useSelector((state) => state.collectionList);
  const { collections } = collectionList;

  useEffect(() => {
    if (collections.length === 0) dispatch(listCollections());
  }, []);
</code>```

Here is the Autocomplete input :

```<code>const ControlledAutocomplete = ({ options, control, name, label }) => {
  return (
   <Controller
     render={({ field }) => (
       <Autocomplete
         {...field}
         options={options}
         getOptionLabel={(option) => option.name || ""}
         isOptionEqualToValue={(option, value) => option.id === value.id}
         renderInput={(params) => (
           <MyTextField {...params} label={label} />
         )}
       />
     )}
    onChange={([, obj]) => obj.id}
    name={name}
    control={control}
    defaultValue=""
  />
)}
</code>```

And finally in the form :

```<code><ControlledAutocomplete
  control={control}
  name="collection"
  options={collections}
  label="Collection"
 />
</code>```

I'm having this errors in the console :

useAutocomplete.js:219 MUI: The value provided to Autocomplete is invalid.
None of the options match with {}.
You can use the isOptionEqualToValue prop to customize the equality test.

...probably when the data is still not available? And I'm also unable to select a value from the options... I'm kinda lost here, all the doc I found seems in a language from another galaxy! A bit of help would be greatly appreciated!!!

答:
so... i got this one working doing like this:

```<code>const ControlledAutocomplete = ({ options, control, name, label, setValue }) => {
  return (
    <Controller
      render={({ field }) => (
        <Autocomplete
          {...field}
          onChange={(ev, val) => setValue(name, val)}
          options={options  || []}
          getOptionLabel={(option) => option.name || ""}
          isOptionEqualToValue={(option, value) => {
            if(value.id) return option.id === value.id
            return true
          }}
          renderInput={(params) => (
            <MyTextField {...params} label={label} />
          )}
        />
      )}
      name={name}
      control={control}
    />
  );
}
</code>```

and I'm using it in the form :

```<code><ControlledAutocomplete
  control={control}
  name="category"
  options={categories}
  label="Category"
  setValue={setValue}
/>
</code>```

with initialization of 'categories' in the useEffect:

```<code>useEffect(() => {
  if (categories.length === 0) dispatch(listCategories());
}, []);
</code>```

and the hook from react-hook-form :

```<code>const {
  register,
  handleSubmit,
  formState: { errors },
  control,
  reset,
  setValue,
} = useForm({
  defaultValues: defaultValues,
  resolver: yupResolver(validationSchema),
});
</code>```

This one is not easy; not documented enough I think... it compiles without errors or warnings but I have no idea if it is the proper way to do! Anyway, I hope it helps...

Body:
I'm using a controlled autocomplete field in a form.
The data comes from my redux store; if the array is empty, I initialize it in a useEffect:

  const collectionList = useSelector((state) => state.collectionList);
  const { collections } = collectionList;

  useEffect(() => {
    if (collections.length === 0) dispatch(listCollections());
  }, []);

Here is the Autocomplete input :

const ControlledAutocomplete = ({ options, control, name, label }) => {
  return (
   <Controller
     render={({ field }) => (
       <Autocomplete
         {...field}
         options={options}
         getOptionLabel={(option) => option.name || ""}
         isOptionEqualToValue={(option, value) => option.id === value.id}
         renderInput={(params) => (
           <MyTextField {...params} label={label} />
         )}
       />
     )}
    onChange={([, obj]) => obj.id}
    name={name}
    control={control}
    defaultValue=""
  />
)}

And finally in the form :

<ControlledAutocomplete
  control={control}
  name="collection"
  options={collections}
  label="Collection"
 />

I'm having this errors in the console :

useAutocomplete.js:219 MUI: The value provided to Autocomplete is invalid.
None of the options match with {}.
You can use the isOptionEqualToValue prop to customize the equality test.

...probably when the data is still not available? And I'm also unable to select a value from the options... I'm kinda lost here, all the doc I found seems in a language from another galaxy! A bit of help would be greatly appreciated!!!

Body:
so... i got this one working doing like this:

const ControlledAutocomplete = ({ options, control, name, label, setValue }) => {
  return (
    <Controller
      render={({ field }) => (
        <Autocomplete
          {...field}
          onChange={(ev, val) => setValue(name, val)}
          options={options  || []}
          getOptionLabel={(option) => option.name || ""}
          isOptionEqualToValue={(option, value) => {
            if(value.id) return option.id === value.id
            return true
          }}
          renderInput={(params) => (
            <MyTextField {...params} label={label} />
          )}
        />
      )}
      name={name}
      control={control}
    />
  );
}

and I'm using it in the form :

<ControlledAutocomplete
  control={control}
  name="category"
  options={categories}
  label="Category"
  setValue={setValue}
/>

with initialization of 'categories' in the useEffect:

useEffect(() => {
  if (categories.length === 0) dispatch(listCategories());
}, []);

and the hook from react-hook-form :

const {
  register,
  handleSubmit,
  formState: { errors },
  control,
  reset,
  setValue,
} = useForm({
  defaultValues: defaultValues,
  resolver: yupResolver(validationSchema),
});

This one is not easy; not documented enough I think... it compiles without errors or warnings but I have no idea if it is the proper way to do! Anyway, I hope it helps...