问:
Preprocessing PHP to remove functionality from built files
I've been reading about Phing and Ant and I'm not sure which, if either, of these tools are most useful for this scenario.

It could easily be debug statements etc, but I'll give you our literal scanario.

We have a free and premium version of a downloadable PHP app, and rather than including just a variable hidden somewhere and then doing:

```<code>if($premium == true) {
   echo 'some additional functionality';
} else {
    echo 'basic functionality';
}
</code>```

Obviously someone could then take the source and change that variable, and bang - they've stolen our code. And something like Ioncube etc is just totally unwieldy in my experience and support on hosting companies is just not good enough.

I would prefer something.. perhaps similar to this:

```<code>## if premium ##
echo 'some additional functionality';
## else ##
echo 'basic functionality';
## endif ##
</code>```

And then I would run two builds, one setting the premium to true and one to false, which would generate two files of simply:

```<code>echo 'some additional functionality';
</code>```

and

```<code>echo 'basic functionality';
</code>```

It would also be very helpful to be able to only include entire files based on this same condition passed to the build app.

I can't find a way to do this but I am open to any alternative ideas if possible.

Help would be outstanding,

UPDATE

Using the C preprocessor is great and looks like it does everything I need. However, I can't find how to do the following 3 things.

#1 I need to remove the comments generated into the output files. Below is an example of those.

```<code># 1 "./index.php"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "./index.php"
</code>```

I haven't found an example of how to do this in the manual page you linked me to.

#2 I need to make it recursively go through every discovered file. When I run my current code I get an error: ../target/./folder/test.php: No such file or directory

So basically I have my 'source' folder which I'm in, which contains a subfolder called 'folder' and it doesn't recreate that, nor the files inside it (test.php)

#3 I'm sure this one is easy - how can I get it to process .js files and probably .html just to be safe as well? In one call, I mean. I assume running it on .jpg etc etc files is a bad idea..

Thanks again!

答:
Disclaimer: I am totally sure this is not the most efficient way to do this!

--

I do this in 4 parts:

Clone the source directory structure in target

Parse the PHP and JS files from source into target

Copy over all the jpg, gif, css, etc files from source to target

Remove the comments added by the cpp call from all PHP and JS files in target

--

```<code>find ./ -type d -exec mkdir ../target/{} \;
find ./ -regextype posix-awk -regex "(.*.php|.*.js)" -exec cpp -E -D COMMERCIAL {} -o ../target/{} \;
find ./ -type f -regextype posix-extended -regex "(.*.jpg|.*.gif|.*.png|.*.css|.*.html|.*.txt|.*.xml|.*.ttf)" -exec cp -p --parents "{}" ../target \;
cd ../target
find ./ -regextype posix-awk -regex "(.*.php|.*.js)" -exec sed -i ./{} -e 's/#.*//;/^\s*$/d' \;</code>```

--

As I said, I'm sure this isn't hugely inefficient but that there is one .sh file that I execute and bang - I have my builds!

Body:
I've been reading about Phing and Ant and I'm not sure which, if either, of these tools are most useful for this scenario.

It could easily be debug statements etc, but I'll give you our literal scanario.

We have a free and premium version of a downloadable PHP app, and rather than including just a variable hidden somewhere and then doing:

if($premium == true) {
   echo 'some additional functionality';
} else {
    echo 'basic functionality';
}

Obviously someone could then take the source and change that variable, and bang - they've stolen our code. And something like Ioncube etc is just totally unwieldy in my experience and support on hosting companies is just not good enough.

I would prefer something.. perhaps similar to this:

## if premium ##
echo 'some additional functionality';
## else ##
echo 'basic functionality';
## endif ##

And then I would run two builds, one setting the premium to true and one to false, which would generate two files of simply:

echo 'some additional functionality';

and

echo 'basic functionality';

It would also be very helpful to be able to only include entire files based on this same condition passed to the build app.

I can't find a way to do this but I am open to any alternative ideas if possible.

Help would be outstanding,

UPDATE

Using the C preprocessor is great and looks like it does everything I need. However, I can't find how to do the following 3 things.

#1 I need to remove the comments generated into the output files. Below is an example of those.

# 1 "./index.php"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "./index.php"

I haven't found an example of how to do this in the manual page you linked me to.

#2 I need to make it recursively go through every discovered file. When I run my current code I get an error: ../target/./folder/test.php: No such file or directory

So basically I have my 'source' folder which I'm in, which contains a subfolder called 'folder' and it doesn't recreate that, nor the files inside it (test.php)

#3 I'm sure this one is easy - how can I get it to process .js files and probably .html just to be safe as well? In one call, I mean. I assume running it on .jpg etc etc files is a bad idea..

Thanks again!

Body:
Disclaimer: I am totally sure this is not the most efficient way to do this!

--

I do this in 4 parts:

Clone the source directory structure in target

Parse the PHP and JS files from source into target

Copy over all the jpg, gif, css, etc files from source to target

Remove the comments added by the cpp call from all PHP and JS files in target

--

find ./ -type d -exec mkdir ../target/{} \;
find ./ -regextype posix-awk -regex "(.*.php|.*.js)" -exec cpp -E -D COMMERCIAL {} -o ../target/{} \;
find ./ -type f -regextype posix-extended -regex "(.*.jpg|.*.gif|.*.png|.*.css|.*.html|.*.txt|.*.xml|.*.ttf)" -exec cp -p --parents "{}" ../target \;
cd ../target
find ./ -regextype posix-awk -regex "(.*.php|.*.js)" -exec sed -i ./{} -e 's/#.*//;/^\s*$/d' \;

--

As I said, I'm sure this isn't hugely inefficient but that there is one .sh file that I execute and bang - I have my builds!


来源: stackexchange

问:
Converting eval() to new Function()
Given an arbitrary eval(), is there a way to convert it to use new Function(), without breaking compatibility with any input (except for the change in scope)?

The only issue I can think of is that eval allows multiple statements, and returns the result of the last one, without having to add an explicit return. I cannot think of a way to emulate this with new Function():

```<code>let code = '4; 5'
> eval(code);
5
> new Function(code)();
undefined
> new Function('return ' + code)();
4
> new Function('return (' + code + ')')();
SyntaxError: Unexpected token ;
</code>```

Is there something I am missing or is eval() incompatible with new Function() in this case?

答: No, this is indeed impossible with Function(). The eval function is the only JavaScript feature that takes statement results into account.

ContentLicense: CC BY-SA 4.0

Title: Converting eval() to new Function()

Body:
Given an arbitrary eval(), is there a way to convert it to use new Function(), without breaking compatibility with any input (except for the change in scope)?

The only issue I can think of is that eval allows multiple statements, and returns the result of the last one, without having to add an explicit return. I cannot think of a way to emulate this with new Function():

let code = '4; 5'
> eval(code);
5
> new Function(code)();
undefined
> new Function('return ' + code)();
4
> new Function('return (' + code + ')')();
SyntaxError: Unexpected token ;

Is there something I am missing or is eval() incompatible with new Function() in this case?


问:
How to fix ORA-00937: not a single-group group function in my query in oracle sql?
When I run this SQL query:

```<code>SELECT id,
       managerID,
       MAX(salary)
  FROM DataTable
 WHERE id >
          ( SELECT id
              FROM DataTable
             WHERE salary <= 10
               AND managerID
            HAVING COUNT(*) > 1
          )
</code>```

I get this error:

```<code>ORA-00937: not a single-group group function
</code>```

What am I doing wrong?

答:
Your query is throwing an error because you cannot use having without using group by.

You are missing group by in outer query as well, whenever you use aggregate function you have to use group by

you have to give an alias to your sub-query

Replace your query with following.

```<code>select
  id,
  manager_id,
  max(salary)
from DataTable
where id > (
  select
    id
  from DataTable
  where salary <=10
  group by
    id
  having count(*)>1
) t
group by
   id,
   manager_id;
</code>```

Body:
When I run this SQL query:

SELECT id,
       managerID,
       MAX(salary)
  FROM DataTable
 WHERE id >
          ( SELECT id
              FROM DataTable
             WHERE salary <= 10
               AND managerID
            HAVING COUNT(*) > 1
          )

I get this error:

ORA-00937: not a single-group group function

What am I doing wrong?

Body:
Your query is throwing an error because you cannot use having without using group by.

You are missing group by in outer query as well, whenever you use aggregate function you have to use group by

you have to give an alias to your sub-query

Replace your query with following.

select
  id,
  manager_id,
  max(salary)
from DataTable
where id > (
  select
    id
  from DataTable
  where salary <=10
  group by
    id
  having count(*)>1
) t
group by
   id,
   manager_id;


问:
Google Custom Metrics tracking of latency data
I'm using external service, based on REST calls, and I want to track the time that took the service to respond to my requests. My code is written with C# (core v2.2)

I planning to count times for all the HTTP requests (with Stopwatch) and keep this information in a List<long>. Every 60 seconds I will write the tracked information from the list to Google Custom Metrics.

In the end, I expect to see the AVERAGE time of execution in a graph.

This is my code so far:

```<code>public class CustomMetricsWritter
{
    public CustomMetricsWritter(string projectId)
    {
        this.Client = MetricServiceClient.Create();
        this.ProjectId = projectId;
    }

    private MetricServiceClient Client { get; set; }

    public string ProjectId { get; private set; }

    public object CreateMetric(string metricType, string title, string description, string unit)
    {
        // Prepare custom metric descriptor.
        MetricDescriptor metricDescriptor = new MetricDescriptor();
        metricDescriptor.DisplayName = title;
        metricDescriptor.Description = description;
        metricDescriptor.MetricKind = MetricKind.Gauge;
        metricDescriptor.ValueType = MetricDescriptor.Types.ValueType.Double;
        metricDescriptor.Type = metricType;
        metricDescriptor.Unit = unit;

        CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
        {
            ProjectName = new ProjectName(this.ProjectId),
        };
        request.MetricDescriptor = metricDescriptor;
        // Make the request.
        return Client.CreateMetricDescriptor(request);
    }

    public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public async Task WriteTimeSeriesDataAsync(string metricDescriptor, TypedValue[] points, string machineName)
    {
        // Initialize request argument(s).
        ProjectName name = new ProjectName(this.ProjectId);
        // Prepare a data point.

        Timestamp timeStamp = new Timestamp();
        timeStamp.Seconds = (long)(DateTime.UtcNow - UnixEpoch).TotalSeconds;
        TimeInterval interval = new TimeInterval();
        interval.EndTime = timeStamp;

        // Prepare monitored resource.
        MonitoredResource resource = new MonitoredResource();
        resource.Type = "global";
        resource.Labels.Add("project_id", this.ProjectId);

        // Add newly created time series to list of time series to be written.
        List<TimeSeries> timeSeries = new List<TimeSeries>(points.Length);

        // Prepare custom metric.
        Metric metric = new Metric();
        metric.Type = metricDescriptor;
        metric.Labels.Add("machine", machineName);

        // Create a new time series using inputs.
        TimeSeries timeSeriesData = new TimeSeries();
        timeSeriesData.Metric = metric;
        timeSeriesData.Resource = resource;
        foreach (var point in points)
        {
            Point dataPoint = new Point();
            dataPoint.Value = point;
            dataPoint.Interval = interval;
            timeSeriesData.Points.Add(dataPoint);
        }
        timeSeries.Add(timeSeriesData);

        // Write time series data.
        await this.Client.CreateTimeSeriesAsync(name, timeSeries).ConfigureAwait(false);
    }
}
</code>```

I running this class with this code (create the metric and then fill it with dummy values):

```<code>try
{
    CustomMetricsWritter customMetricsWriter = new CustomMetricsWritter(Consts.GOOGLE_CLOUD_PROJECT);
    string metric = "custom.googleapis.com/web/latency";
    customMetricsWriter.CreateMetric(metric, "Execution Latency", "Calling REST service (MS).", "{INT64}");

    // Exception thrown in the next line ----->
    await customMetricsWriter.WriteTimeSeriesDataAsync(
        metric,
        new TypedValue[] {
        new TypedValue(){ Int64Value = 150},
        new TypedValue(){ Int64Value = 250},
        new TypedValue(){ Int64Value = 350},
        },
        "my-machine-type");
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
    throw;
}
</code>```

I getting back this thrown exception:

```<code>Grpc.Core.RpcException: Status(StatusCode=InvalidArgument, Detail="One or more TimeSeries could not be written: Field timeSeries[0].points had an invalid value: Only one point can be written per TimeSeries per request.: timeSeries[0]")
   at Google.Api.Gax.Grpc.ApiCallRetryExtensions.<>c__DisplayClass0_0`2.<<WithRetry>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at ***.CustomMetricsWritter.WriteTimeSeriesDataAsync(String metricDescriptor, TypedValue[] points, String machineName) in ***\GoogleCloud\CustomMetricsWritter.cs:line 131
   at Test.Program.MainAsync() in ***\Test\Program.cs:line 156
</code>```

What I'm doing wrong?

答:
I'm not a C# expert, but there are examples here:

https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/master/monitoring/api/QuickStart/QuickStart.cs

Body:
I'm using external service, based on REST calls, and I want to track the time that took the service to respond to my requests. My code is written with C# (core v2.2)

I planning to count times for all the HTTP requests (with Stopwatch) and keep this information in a List<long>. Every 60 seconds I will write the tracked information from the list to Google Custom Metrics.

In the end, I expect to see the AVERAGE time of execution in a graph.

This is my code so far:

public class CustomMetricsWritter
{
    public CustomMetricsWritter(string projectId)
    {
        this.Client = MetricServiceClient.Create();
        this.ProjectId = projectId;
    }

    private MetricServiceClient Client { get; set; }

    public string ProjectId { get; private set; }

    public object CreateMetric(string metricType, string title, string description, string unit)
    {
        // Prepare custom metric descriptor.
        MetricDescriptor metricDescriptor = new MetricDescriptor();
        metricDescriptor.DisplayName = title;
        metricDescriptor.Description = description;
        metricDescriptor.MetricKind = MetricKind.Gauge;
        metricDescriptor.ValueType = MetricDescriptor.Types.ValueType.Double;
        metricDescriptor.Type = metricType;
        metricDescriptor.Unit = unit;

        CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
        {
            ProjectName = new ProjectName(this.ProjectId),
        };
        request.MetricDescriptor = metricDescriptor;
        // Make the request.
        return Client.CreateMetricDescriptor(request);
    }

    public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public async Task WriteTimeSeriesDataAsync(string metricDescriptor, TypedValue[] points, string machineName)
    {
        // Initialize request argument(s).
        ProjectName name = new ProjectName(this.ProjectId);
        // Prepare a data point.

        Timestamp timeStamp = new Timestamp();
        timeStamp.Seconds = (long)(DateTime.UtcNow - UnixEpoch).TotalSeconds;
        TimeInterval interval = new TimeInterval();
        interval.EndTime = timeStamp;

        // Prepare monitored resource.
        MonitoredResource resource = new MonitoredResource();
        resource.Type = "global";
        resource.Labels.Add("project_id", this.ProjectId);

        // Add newly created time series to list of time series to be written.
        List<TimeSeries> timeSeries = new List<TimeSeries>(points.Length);

        // Prepare custom metric.
        Metric metric = new Metric();
        metric.Type = metricDescriptor;
        metric.Labels.Add("machine", machineName);

        // Create a new time series using inputs.
        TimeSeries timeSeriesData = new TimeSeries();
        timeSeriesData.Metric = metric;
        timeSeriesData.Resource = resource;
        foreach (var point in points)
        {
            Point dataPoint = new Point();
            dataPoint.Value = point;
            dataPoint.Interval = interval;
            timeSeriesData.Points.Add(dataPoint);
        }
        timeSeries.Add(timeSeriesData);

        // Write time series data.
        await this.Client.CreateTimeSeriesAsync(name, timeSeries).ConfigureAwait(false);
    }
}

I running this class with this code (create the metric and then fill it with dummy values):

try
{
    CustomMetricsWritter customMetricsWriter = new CustomMetricsWritter(Consts.GOOGLE_CLOUD_PROJECT);
    string metric = "custom.googleapis.com/web/latency";
    customMetricsWriter.CreateMetric(metric, "Execution Latency", "Calling REST service (MS).", "{INT64}");

    // Exception thrown in the next line ----->
    await customMetricsWriter.WriteTimeSeriesDataAsync(
        metric,
        new TypedValue[] {
        new TypedValue(){ Int64Value = 150},
        new TypedValue(){ Int64Value = 250},
        new TypedValue(){ Int64Value = 350},
        },
        "my-machine-type");
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
    throw;
}

I getting back this thrown exception:

Grpc.Core.RpcException: Status(StatusCode=InvalidArgument, Detail="One or more TimeSeries could not be written: Field timeSeries[0].points had an invalid value: Only one point can be written per TimeSeries per request.: timeSeries[0]")
   at Google.Api.Gax.Grpc.ApiCallRetryExtensions.<>c__DisplayClass0_0`2.<<WithRetry>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at ***.CustomMetricsWritter.WriteTimeSeriesDataAsync(String metricDescriptor, TypedValue[] points, String machineName) in ***\GoogleCloud\CustomMetricsWritter.cs:line 131
   at Test.Program.MainAsync() in ***\Test\Program.cs:line 156

What I'm doing wrong?


问:
OpenIDConnect Certified Relying Party Servers vs Certified OpenID Provider Servers
I was looking at the OpenIDConnect developer section https://openid.net/developers/certified/. There are multiple sections like:

Certified Relying Party Libraries

Certified Relying Party Servers and Services

Certified OpenID Provider Libraries

Certified OpenID Provider Servers and Services

Certified OpenID Providers for Logout Profiles

I think I understand the difference between relying party (e.g. client app) and OpenID Provider (Authorization server) but I could not find details on what the above items mean.

答:
Most companies focus on coding UIs and APIs - these components are referred to in the jargon as 'relying parties'. It makes complete sense to plug in certified libraries to do the intricate security work.

Most companies do not build an OpenID Provider Server, since it is a job for security experts. Instead it is common to plug in a low cost cloud solution from a provider such as Microsoft / Amazon / Google.

As an example have a look at my SPA and API Tutorial which uses these moving parts:

Web UI uses a certified library called OIDC Client

Web API uses a certified library called Open Id Client

Both interact with a trial / developer version of Okta as the OpenID Provider


问:
Building PCA components on arrays
I'm trying to build principal components on array rows across multiple columns-

```<code>import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn.decomposition import PCA

df = pd.DataFrame(np.random.randn(5, 10), columns=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])
df['arr1'] = df[['a', 'b', 'c', 'd', 'e']].values.tolist()
df['arr2'] = df[['f', 'g', 'h', 'i', 'j']].values.tolist()

df['arr1'] = [preprocessing.scale(row) for row in df['arr1']]
df['arr2'] = [preprocessing.scale(row) for row in df['arr2']]
df

X = df.loc[:, 'arr1':'arr2']
pca = PCA(.95)
pca.fit(X)
pca.transform(X)
</code>```

Which gives the error-

```<code>ValueError: setting an array element with a sequence.
</code>```

I tried converting arr1 and arr2 by np.array(list(df.arr1)) but this just maintains the first value from each array.

In my real dataset, there are 200-300 elements in each array.

答:
fit and transform needs a 2D array input, what you are passing isn't one.
This works:

```<code>arr = [X.loc[0]['arr1'].tolist(), X.loc[0]['arr2'].tolist()]
pca.fit(arr)
pca.transform(arr)
</code>```

Title: Building PCA components on arrays

Body:
I'm trying to build principal components on array rows across multiple columns-

import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn.decomposition import PCA

df = pd.DataFrame(np.random.randn(5, 10), columns=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])
df['arr1'] = df[['a', 'b', 'c', 'd', 'e']].values.tolist()
df['arr2'] = df[['f', 'g', 'h', 'i', 'j']].values.tolist()

df['arr1'] = [preprocessing.scale(row) for row in df['arr1']]
df['arr2'] = [preprocessing.scale(row) for row in df['arr2']]
df

X = df.loc[:, 'arr1':'arr2']
pca = PCA(.95)
pca.fit(X)
pca.transform(X)

Which gives the error-

ValueError: setting an array element with a sequence.

I tried converting arr1 and arr2 by np.array(list(df.arr1)) but this just maintains the first value from each array.

In my real dataset, there are 200-300 elements in each array.

Body:
fit and transform needs a 2D array input, what you are passing isn't one.
This works:

arr = [X.loc[0]['arr1'].tolist(), X.loc[0]['arr2'].tolist()]
pca.fit(arr)
pca.transform(arr)


问:
How to ingest data effectively in Neo4j
I  am looking for advice on the best way to handle data going into Neo4j.

I have a set of structured data, CSV format which relates to journeys. The data is:

"JourneyID"   - unique ref#/ Primary Key e.g 1234

"StartID"  - ref#  , this is a station e.g Station1

"EndIID" - ref# this is a station, e.g Station1 (start and end can be the same)

"Time" – integer e.g. 24

Assume I have 100 journeys/rows of data, showing journeys between 10 different stations.

I can see and work with this data in SQL or Excel. I want to work with this in Neo4j.

This is what I currently have:

StartID with JourneyID as a label
EndID with Journey ID as a label

This means that each row from the CSV for a station is its own node. I then created a relationship between Start and End using the JourneyID (primary key)
 the effect was just  100 node connected to 100 nodes. E.g connection from Station1 and Station 2, Station 1 and Station 3, and Station 1 and Station 4. It didn’t show the relationship between Starting Station1 and Ending Station1, 2 and 3 - which is what I want to show.

How best do I model this data so that graph sees 10 unique StartID, connecting to the different EndIDs – showing the relationships between them?

Thanks in advance

(new to Graphs!)

答:
This sample query, which uses MERGE to avoid creating duplicate nodes and relationships, should help you get started:</p>

```<code>LOAD CSV WITH HEADERS FROM 'file://input.csv' AS row
MERGE (start:Station {id: row.StartID})
MERGE (end:Station {id: row.EndID})
MERGE (j:Journey {id: row.JourneyID})
ON CREATE SET j.time = row.Time
MERGE (j)-[:FROM]->(start)
MERGE (j)-[:TO]->(end)
</code>```

Title: How to ingest data effectively in Neo4j

Body:
This sample query, which uses MERGE to avoid creating duplicate nodes and relationships, should help you get started:

LOAD CSV WITH HEADERS FROM 'file://input.csv' AS row
MERGE (start:Station {id: row.StartID})
MERGE (end:Station {id: row.EndID})
MERGE (j:Journey {id: row.JourneyID})
ON CREATE SET j.time = row.Time
MERGE (j)-[:FROM]->(start)
MERGE (j)-[:TO]->(end)


问:
How do I get the columns that a statsmodels / patsy formula depends on?
Suppose I have a pandas dataframe:

```<code>df = pd.DataFrame({'x1': [0, 1, 2, 3, 4],
                   'x2': [10, 9, 8, 7, 6],
                   'x3': [.1, .1, .2, 4, 8],
                   'y': [17, 18, 19, 20, 21]})
</code>```

Now I fit a statsmodels model using a formula (which uses patsy under the hood):

```<code>import statsmodels.formula.api as smf
fit = smf.ols(formula='y ~ x1:x2', data=df).fit()
</code>```

What I want is a list of the columns of df that fit depends on, so that I can use fit.predict() on another dataset. If I try list(fit.params.index), for example, I get:

```<code>['Intercept', 'x1:x2']
</code>```

I've tried recreating the patsy design matrix, and using design_info, but I still only ever get x1:x2. What I want is:

```<code>['x1', 'x2']
</code>```

Or even:

```<code>['Intercept', 'x1', 'x2']
</code>```

How can I get this from just the fit object?

答: ols.exog_names and ols.endog_names should do it

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have a pandas dataframe:

df = pd.DataFrame({'x1': [0, 1, 2, 3, 4],
                   'x2': [10, 9, 8, 7, 6],
                   'x3': [.1, .1, .2, 4, 8],
                   'y': [17, 18, 19, 20, 21]})

Now I fit a statsmodels model using a formula (which uses patsy under the hood):

import statsmodels.formula.api as smf
fit = smf.ols(formula='y ~ x1:x2', data=df).fit()

What I want is a list of the columns of df that fit depends on, so that I can use fit.predict() on another dataset. If I try list(fit.params.index), for example, I get:

['Intercept', 'x1:x2']

I've tried recreating the patsy design matrix, and using design_info, but I still only ever get x1:x2. What I want is:

['x1', 'x2']

Or even:

['Intercept', 'x1', 'x2']

How can I get this from just the fit object?


Title: Python Dataframes: Merging two dataframes according to a condition (Pandas)

Body:
Let say that I have this two DataFrames:

DATAFRAME 1
    onset  offset
0       1     200
1     201     400
2     401     600
3     601     800
4     801    1000
5    1001    1200
6    1201    1400
7    1401    1600
8    1601    1800
9    1801    2000
10   2001    2200
11   2201    2400
12   2401    2600
13   2601    2800
14   2801    3000
15   3001    3200
16   3201    3400
17   3401    3600
18   3601    3800
19   3801    4000
20   4001    4200
21   4201    4400
22   4401    4600
23   4601    4800
24   4801    5000
25   5001    5200
26   5201    5400
27   5401    5600
28   5601    5800
29   5801    6000
DATAFRAME 2
   onset rhythm_name  rhythm_code  offset
0      1         NSR          100    2760
1   2761  JUNCTIONAL         4000    3938
2   3939         NSR          100    6000

My goal is to merge both dataframes with the onset-offset intervals and add their respective rhythm_name and rhythm_code to get something like this:

    onset  offset  rhythm_name  rhythm_code
0       1     200        NSR          100
1     201     400        NSR          100
2     401     600        NSR          100
3     601     800        NSR          100
4     801    1000        NSR          100
5    1001    1200        NSR          100
6    1201    1400        NSR          100
7    1401    1600        NSR          100
8    1601    1800        NSR          100
9    1801    2000        NSR          100
10   2001    2200        NSR          100
11   2201    2400        NSR          100
12   2401    2600        NSR          100
13   2601    2800        Null         Null
14   2801    3000  JUNCTIONAL         4000
15   3001    3200  JUNCTIONAL         4000
16   3201    3400  JUNCTIONAL         4000
17   3401    3600  JUNCTIONAL         4000
18   3601    3800  JUNCTIONAL         4000
19   3801    4000        Null         Null
20   4001    4200        NSR          100
21   4201    4400        NSR          100
22   4401    4600        NSR          100
23   4601    4800        NSR          100
24   4801    5000        NSR          100
25   5001    5200        NSR          100
26   5201    5400        NSR          100
27   5401    5600        NSR          100
28   5601    5800        NSR          100
29   5801    6000        NSR          100

What can I use to do this? I can`t find a way to solve this problem. I have tried something like:

df1["rhythm_name"] = df2[(df1['onset'] >= df2['onset']) & (df1['offset'] <= df2['offset'])])

And I get this:

ValueError: Can only compare identically-labeled Series objects

I made a script to reproduce the problem:

df1 = pd.DataFrame()
onsets = []
for i in range(0,30):
  onset = i * 200 + 1
  onsets.append(onset)
df1['onset'] = onsets
df1['offset'] = df1["onset"]+200-1

df2 = {'onset': [1, 2761, 3939],
       'offset': [2760, 3938, 6000],
       'rhythm_name': ["NSR", "JUNCTIONAL", "NSR"],
       'rhythm_code': [100, 4000, 100]}

Body:
You can pd.merge_asof, and mask the second condition:

dfm = pd.merge_asof(df1, df2, on='onset', direction='backward', suffixes=('','_y'))
dfm[['rhythm_name', 'rhythm_code']] = (dfm[['rhythm_name', 'rhythm_code']]
                                          .where(dfm['offset'] <= dfm['offset_y']))
dfm.drop('offset_y', axis=1)

Output:

    onset  offset rhythm_name  rhythm_code
0       1     200         NSR        100.0
1     201     400         NSR        100.0
2     401     600         NSR        100.0
3     601     800         NSR        100.0
4     801    1000         NSR        100.0
5    1001    1200         NSR        100.0
6    1201    1400         NSR        100.0
7    1401    1600         NSR        100.0
8    1601    1800         NSR        100.0
9    1801    2000         NSR        100.0
10   2001    2200         NSR        100.0
11   2201    2400         NSR        100.0
12   2401    2600         NSR        100.0
13   2601    2800         NaN          NaN
14   2801    3000  JUNCTIONAL       4000.0
15   3001    3200  JUNCTIONAL       4000.0
16   3201    3400  JUNCTIONAL       4000.0
17   3401    3600  JUNCTIONAL       4000.0
18   3601    3800  JUNCTIONAL       4000.0
19   3801    4000         NaN          NaN
20   4001    4200         NSR        100.0
21   4201    4400         NSR        100.0
22   4401    4600         NSR        100.0
23   4601    4800         NSR        100.0
24   4801    5000         NSR        100.0
25   5001    5200         NSR        100.0
26   5201    5400         NSR        100.0
27   5401    5600         NSR        100.0
28   5601    5800         NSR        100.0
29   5801    6000         NSR        100.0


问:
Plugin capabilities for Firefox
I am wondering what is the extent of functionality that add-ons/plugins can provide with Firefox. For example, can we edit the way Firefox reads and writes to its Sqlite database?   </p>

<p>I am considering a project where we would encrypt the contents of this database when writing to it, and decrypt from it when reading from it. It would be cool if we could do this through the use of a plugin or add-on. Does anyone know if this is feasible or not? </p>

答:
You can create a new SQLLite DB and write to it via a firefox plugin. See https://developer.mozilla.org/en/storage

I've done this previously for a Firebug plugin that I've created. From your plugin you do something like this:

```<code> var file = Components.classes["@mozilla.org/file/directory_service;1"]
    .getService(Components.interfaces.nsIProperties)
    .get("ProfD", Components.interfaces.nsIFile);
    file.append("rttplog.sqlite");

    var storageService = Components.classes["@mozilla.org/storage/service;1"]
           .getService(Components.interfaces.mozIStorageService);
    this.mDBConn = storageService.openDatabase(file);
    this.mDBConn.executeSimpleSQL("CREATE TEMP TABLE log (id INTEGER, type VARCHAR, message TEXT)");
</code>```

Inserting:

```<code> var statement = this.mDBConn.createStatement("INSERT INTO log VALUES(:id, :type, :message)");
        statement.params.id = id;
        statement.params.type = type;
        statement.params.message = message;
        statement.execute();
</code>```

Selecting:

```<code>var statement = this.mDBConn.createStatement("SELECT id FROM log WHERE message LIKE :query ESCAPE '/' ");
        var escaped = statement.escapeStringForLIKE(query, "/");
        statement.params.query = "%" + escaped + "%";
        return statement.executeAsync(callback);
</code>```

Hope that helps.

Title: Plugin capabilities for Firefox

Body:
I am wondering what is the extent of functionality that add-ons/plugins can provide with Firefox. For example, can we edit the way Firefox reads and writes to its Sqlite database?

I am considering a project where we would encrypt the contents of this database when writing to it, and decrypt from it when reading from it. It would be cool if we could do this through the use of a plugin or add-on. Does anyone know if this is feasible or not?

Body:
You can create a new SQLLite DB and write to it via a firefox plugin. See https://developer.mozilla.org/en/storage

I've done this previously for a Firebug plugin that I've created. From your plugin you do something like this:

 var file = Components.classes["@mozilla.org/file/directory_service;1"]
    .getService(Components.interfaces.nsIProperties)
    .get("ProfD", Components.interfaces.nsIFile);
    file.append("rttplog.sqlite");

    var storageService = Components.classes["@mozilla.org/storage/service;1"]
           .getService(Components.interfaces.mozIStorageService);
    this.mDBConn = storageService.openDatabase(file);
    this.mDBConn.executeSimpleSQL("CREATE TEMP TABLE log (id INTEGER, type VARCHAR, message TEXT)");

Inserting:

 var statement = this.mDBConn.createStatement("INSERT INTO log VALUES(:id, :type, :message)");
        statement.params.id = id;
        statement.params.type = type;
        statement.params.message = message;
        statement.execute();

Selecting:

var statement = this.mDBConn.createStatement("SELECT id FROM log WHERE message LIKE :query ESCAPE '/' ");
        var escaped = statement.escapeStringForLIKE(query, "/");
        statement.params.query = "%" + escaped + "%";
        return statement.executeAsync(callback);

Hope that helps.


问:
For loop in python- to generate output containing list of items
I am new to programming and to python, currently using python3 via annoconda/jupyter. My input (test_Set) is list of quality score codes from a fastq file. The loop converts the quality score codes into quality scores. The following is the code I used

```<code>test_set=['.GA', '<AG', '#<<']
output1=[]
output2=[]
for i in test_set:
    s=i
    for j in range(len(s)):
        qs=ord(s[j])-33
        output1.append(qs)
    output2.append(output1)
</code>```

The outputs i have are:

```<code> output1: [13, 38, 32, 27, 32, 38, 2, 27, 27]
 output2: [[13, 38, 32, 27, 32, 38, 2, 27, 27],
          [13, 38, 32, 27, 32, 38, 2, 27, 27],
          [13, 38, 32, 27, 32, 38, 2, 27, 27]]
</code>```

But the output i am trying to achieve is :

```<code>desired_output: [[13, 38, 32], [27, 32, 38], [2, 27, 27]]
</code>```

I would like to know what I am doing wrong with my loops and how to change them to achieve the desired output.
Thank you and appreciate any help, including resources to understand for and while loops

答:
You almost got it right. You only need to "reset" output1 in every pass of the for loop.

Here's a simplified version that does what you want:

```<code>test_set = ['.GA', '<AG', '#<<']
output2 = []

for s in test_set:
    output1 = [ord(c)-33 for c in s]
    output2.append(output1)
</code>```

Because the string s is itself an iterable, you don't need to use the len(range(s)) to index into it. Technically, you could do it in a one-liner, if you find it understandable-enough:

```<code>[[ord(c)-33 for c in s] for s in test_set]
</code>```

Body:
I am new to programming and to python, currently using python3 via annoconda/jupyter. My input (test_Set) is list of quality score codes from a fastq file. The loop converts the quality score codes into quality scores. The following is the code I used

test_set=['.GA', '<AG', '#<<']
output1=[]
output2=[]
for i in test_set:
    s=i
    for j in range(len(s)):
        qs=ord(s[j])-33
        output1.append(qs)
    output2.append(output1)

The outputs i have are:

 output1: [13, 38, 32, 27, 32, 38, 2, 27, 27]
 output2: [[13, 38, 32, 27, 32, 38, 2, 27, 27],
          [13, 38, 32, 27, 32, 38, 2, 27, 27],
          [13, 38, 32, 27, 32, 38, 2, 27, 27]]

But the output i am trying to achieve is :

desired_output: [[13, 38, 32], [27, 32, 38], [2, 27, 27]]

I would like to know what I am doing wrong with my loops and how to change them to achieve the desired output.
Thank you and appreciate any help, including resources to understand for and while loops

Body:
You almost got it right. You only need to "reset" output1 in every pass of the for loop.

Here's a simplified version that does what you want:

test_set = ['.GA', '<AG', '#<<']
output2 = []

for s in test_set:
    output1 = [ord(c)-33 for c in s]
    output2.append(output1)

Because the string s is itself an iterable, you don't need to use the len(range(s)) to index into it. Technically, you could do it in a one-liner, if you find it understandable-enough:

[[ord(c)-33 for c in s] for s in test_set]


问:
Gradle sync failed: The file or directory is corrupted and unreadable in android studio
Please Help, Android studio is not working and this error is comes.
I also reinstall the android studio but same error is comes.

答:
There is no need to uninstall Android Studio and maybe an issue occurs during the Gradle build time and Gradle cannot load data in the metadata folder or you have multiple data folder in the Gradle file.

Follow the below steps

Go to "C:\Users\PC\.gradle\caches\modules-2"

Close the Android Studio

Delete any metadata folder available from that listing or you can delete or rename the metadata folder as per your project given the error.

Start the android studio and ensuring that you have internet connections

Wait for Gradle to download some files and sync then

Everything should work well after doing that

I have followed the above steps and got success.


问:
Make socket class available to entire app
I have the following class which I will use to display an alert regardless of which page the user is on within the app.

What is the best way to make this class accessible to all pages with in the app? Do I need to include it in every page and then call it in the init method of that page?

```<code>class SocketHelper{

  connect(){
SocketIO socketIO = SocketIOManager().createSocketIO("http://someurl", "/", query: "userId=123",socketStatusCallback: _socketStatus);
socketIO.init();
socketIO.subscribe("somealert", _onReceiveAlert);
socketIO.connect();
  }

  _onReceiveAlert(){
    // todo
  }

  _socketStatus(){
    // todo
  }

}
</code>```

答:
It seems like you are looking for some sort of state management solution. There are a lot of different options for state management on flutter including Provider, Bloc, Redux, MobX and others.

If you only need to do it for this one thing in the app, I would recommend Provider, given its easy to use and is a wrapper for InheritedWidget.

If you don't want to use a package for it, you could just use InheritedWidget as well. Just wrap your app in the InheritedWidget, and you should have access to the socket all the way down your widget tree.

But given that you have those two functions that update the socket state, I would really recommend Provider with ChangeNotifier.

Body:
I have the following class which I will use to display an alert regardless of which page the user is on within the app.

What is the best way to make this class accessible to all pages with in the app? Do I need to include it in every page and then call it in the init method of that page?

class SocketHelper{

  connect(){
SocketIO socketIO = SocketIOManager().createSocketIO("http://someurl", "/", query: "userId=123",socketStatusCallback: _socketStatus);
socketIO.init();
socketIO.subscribe("somealert", _onReceiveAlert);
socketIO.connect();
  }

  _onReceiveAlert(){
    // todo
  }

  _socketStatus(){
    // todo
  }

}


问:
Conditional views with binding not working
I'm trying to implement two conditional views on a main view. The condition whether each view should be hidden or not, are stored inside the conditional views view model as a observed object. I don't get any errors and the hiding condition is getting updated (which you can see by the changing color of the view), but is apparently not passed to the main view.

(Same ViewModel for both views)

```<code>class ProjectsViewModel: ObservableObject {
    @Published var showExtendedProjectsView: Bool = false

}
</code>```

(Same example view for both)

```<code>struct ProjectsView: View {

    @ObservedObject var vm = ProjectsViewModel()

    var body: some View {

        Button(action: {
            self.vm.showExtendedProjectsView.toggle()
        }, label: {
            ZStack {
                Rectangle()
                    .foregroundColor(self.vm.showExtendedProjectsView ? Color.green : Color.red)
                Text("Press")
            }
        })
    }
}
</code>```

This part is not working:

```<code>struct Test2: View {

    let view1 = ProjectsView()
    let view2 = ProjectsView()

    var body: some View {

        VStack {
            if !view2.vm.showExtendedProjectsView {
                view1
            } else {
                EmptyView()
            }

            if !view1.vm.showExtendedProjectsView {
                view2
            } else {
                EmptyView()
            }
        }
    }
}
</code>```

答:
If you want your Test2View to refresh itself, it needs to observe something (or its State needs to be changed). In this case the Test2View can observe its children' ProjectsViewModels:

```<code>struct Test2: View {
    let view1 = ProjectsView()
    let view2 = ProjectsView()

    @ObservedObject var vm1: ProjectsViewModel
    @ObservedObject var vm2: ProjectsViewModel

    init() {
        vm1 = view1.vm
        vm2 = view2.vm
    }

    var body: some View {
        VStack {
            if !vm2.showExtendedProjectsView {
                view1
            } else {
                EmptyView()
            }

            if !vm1.showExtendedProjectsView {
                view2
            } else {
                EmptyView()
            }
        }
    }
}
</code>```

Body:
I'm trying to implement two conditional views on a main view. The condition whether each view should be hidden or not, are stored inside the conditional views view model as a observed object. I don't get any errors and the hiding condition is getting updated (which you can see by the changing color of the view), but is apparently not passed to the main view.

(Same ViewModel for both views)

class ProjectsViewModel: ObservableObject {
    @Published var showExtendedProjectsView: Bool = false

}

(Same example view for both)

struct ProjectsView: View {

    @ObservedObject var vm = ProjectsViewModel()

    var body: some View {

        Button(action: {
            self.vm.showExtendedProjectsView.toggle()
        }, label: {
            ZStack {
                Rectangle()
                    .foregroundColor(self.vm.showExtendedProjectsView ? Color.green : Color.red)
                Text("Press")
            }
        })
    }
}

This part is not working:

struct Test2: View {

    let view1 = ProjectsView()
    let view2 = ProjectsView()

    var body: some View {

        VStack {
            if !view2.vm.showExtendedProjectsView {
                view1
            } else {
                EmptyView()
            }

            if !view1.vm.showExtendedProjectsView {
                view2
            } else {
                EmptyView()
            }
        }
    }
}

Body:
If you want your Test2View to refresh itself, it needs to observe something (or its State needs to be changed). In this case the Test2View can observe its children' ProjectsViewModels:

struct Test2: View {
    let view1 = ProjectsView()
    let view2 = ProjectsView()

    @ObservedObject var vm1: ProjectsViewModel
    @ObservedObject var vm2: ProjectsViewModel

    init() {
        vm1 = view1.vm
        vm2 = view2.vm
    }

    var body: some View {
        VStack {
            if !vm2.showExtendedProjectsView {
                view1
            } else {
                EmptyView()
            }

            if !vm1.showExtendedProjectsView {
                view2
            } else {
                EmptyView()
            }
        }
    }
}


问:
Function that yield or return all situation of small and Capital letters
Is there any function that  can take a "string" and yield all situation of small and Capital letters  every time i call function in a loop which is possible.for example:

i give "string" to function

and it yield all of situation like:

```<code>"String"
"sTring"
"stRing"
"strIng"
"striNg"
"strinG"
"STring"
"StRing"
"StrIng"
"StriNg"
"StrinG"
...
</code>```

I am new in python and i do not have any idea i though there might be a library or function that can do that.

答:
Regarding 'it can not dodge number and cuz error', there are two ways around it (Which you can modify the function to):

Add a try / except in each iteration as in:

```<code>try:

except:
    continue
</code>```

Check if the 'char' is a numeric value, using the isnumeric() function as in:

```<code>> if char.isnumeric():
>         continue
</code>```

Body:
Is there any function that  can take a "string" and yield all situation of small and Capital letters  every time i call function in a loop which is possible.for example:

i give "string" to function

and it yield all of situation like:

"String"
"sTring"
"stRing"
"strIng"
"striNg"
"strinG"
"STring"
"StRing"
"StrIng"
"StriNg"
"StrinG"
...

I am new in python and i do not have any idea i though there might be a library or function that can do that.

Body:
Regarding 'it can not dodge number and cuz error', there are two ways around it (Which you can modify the function to):

Add a try / except in each iteration as in:

try:

except:
    continue

Check if the 'char' is a numeric value, using the isnumeric() function as in:

> if char.isnumeric():
>         continue


问:
Read .mp4 file from firebase storage using fs to send that video to tenserflow model
my graduation project is to convert video into text.
I'm trying to read video uploaded in Firebase storage & sent from android app, to send it to TenserFlow model.
but I can't read the video.

here is my function:

```<code>exports.readVideo = functions.storage
.object()
.onFinalize(async (object) => {
    const bucket = admin.storage().bucket(object.bucket);
    const tempFilePath = path.join(os.tmpdir(), object.name);
    console.log(tempFilePath);
    console.log('download');
    // note download
    await bucket
        .file(object.name!)
        .download({
            destination: tempFilePath,
        })
        .then()
        .catch((err) => {
            console.log({
                type: 'download',
                err: err,
            });
        });
    console.log('read');
    // note read
    let stream = await bucket
        .file(object.name!)
        .createReadStream({
            start: 10000,
            end: 20000,
        })
        .on('error', function (err) {
            console.log('error 1');
            console.log({ error: err });
        })
         await new Promise((resolve, reject) => {
            console.log('error 2');
            stream.on('finish', resolve);
            console.log('error 3');
            stream.on('error', reject);
            console.log("end!")
            stream.on('end', resolve);
        }).catch((error) => {
            // successMessage is whatever we passed in the resolve(...) function above.
            // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
            console.log("oups! " + error)
        });

    console.log('tempFile size2', fs.statSync(tempFilePath).size);

    return fs.unlinkSync(tempFilePath);
});
</code>```

and I got that error:

Function execution took 60008 ms, finished with status: 'timeout'

答:
As the error message shows, the regular file system on Cloud Functions is read only. The only place you can write to is /tmp, as also shown in the documentation on file system access in Cloud Functions. I'm not sure why os.tmpdir() doesn't give you a location at that path, but you might want to hard-code the directory.

One thing to keep in mind: /tmp is a RAM disk and not a physical disk, so your allocated memory will need to have enough space for the files you write to it.

Body:
my graduation project is to convert video into text.
I'm trying to read video uploaded in Firebase storage & sent from android app, to send it to TenserFlow model.
but I can't read the video.

here is my function:

exports.readVideo = functions.storage
.object()
.onFinalize(async (object) => {
    const bucket = admin.storage().bucket(object.bucket);
    const tempFilePath = path.join(os.tmpdir(), object.name);
    console.log(tempFilePath);
    console.log('download');
    // note download
    await bucket
        .file(object.name!)
        .download({
            destination: tempFilePath,
        })
        .then()
        .catch((err) => {
            console.log({
                type: 'download',
                err: err,
            });
        });
    console.log('read');
    // note read
    let stream = await bucket
        .file(object.name!)
        .createReadStream({
            start: 10000,
            end: 20000,
        })
        .on('error', function (err) {
            console.log('error 1');
            console.log({ error: err });
        })
         await new Promise((resolve, reject) => {
            console.log('error 2');
            stream.on('finish', resolve);
            console.log('error 3');
            stream.on('error', reject);
            console.log("end!")
            stream.on('end', resolve);
        }).catch((error) => {
            // successMessage is whatever we passed in the resolve(...) function above.
            // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
            console.log("oups! " + error)
        });

    console.log('tempFile size2', fs.statSync(tempFilePath).size);

    return fs.unlinkSync(tempFilePath);
});

and I got that error:

Function execution took 60008 ms, finished with status: 'timeout'


问:
Enable auto (self)-closing tags for JSX in MDX file
I am moving a website to Gatsby. For article posts, the original source was written as HTML files. I want to take advantage of using MDX for those content. However, copy-paste tons of articles from HTML to MDX produce much pain. Particularly, MDX parser usually complains about Expected corresponding JSX closing tag for ...
I wonder if prettier or any formatter can help with auto adding self-closing tags for MDX files.

Example:

```<code><img
  class="wp-image-1221 size-full"
  src="/assets/images/articles-news/Yasmin_pic_4.png"
  alt=""
  width="504"
  height="377"
>
</code>```

Expected formatted output

```<code><img
  class="wp-image-1221 size-full"
  src="/assets/images/articles-news/Yasmin_pic_4.png"
  alt=""
  width="504"
  height="377"
/>

// or

<img
  class="wp-image-1221 size-full"
  src="/assets/images/articles-news/Yasmin_pic_4.png"
  alt=""
  width="504"
  height="377"
></img>
</code>```

答:
The Prettier MDX parser fails at parsing tags that are not self-closing, like the img in your example (playground). However, if you use the HTML parser, Prettier will add the closing / (playground).

Use the --parser option to format using the HTML parser (note that you need to do it before adding your MDX frontmatter, otherwise the HTML parser won't be able to parse the files either):

prettier --parser html --write ./my-html-files-from-wordpress
```

<p>Once the elements are all (self-)closing, you can switch back to using Prettier's inferred parser (MDX for .mdx files):</p>

<pre class="lang-sh prettyprint-override"><code>prettier --write ./my-formatted-mdx-files
</code>```

Body:
I am moving a website to Gatsby. For article posts, the original source was written as HTML files. I want to take advantage of using MDX for those content. However, copy-paste tons of articles from HTML to MDX produce much pain. Particularly, MDX parser usually complains about Expected corresponding JSX closing tag for ...
I wonder if prettier or any formatter can help with auto adding self-closing tags for MDX files.

Example:

Expected formatted output

// or

Body:
The Prettier MDX parser fails at parsing tags that are not self-closing, like the img in your example (<a href="https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAlgWwOYB0oAEBYANgIYDOFAvLiAO4AOAtFmdnMwIwBMPXBCugBenAGYBXEiTr4iFAE5haIAPSUKcGBVVsOOsgpjpScCsyhx6OgJqVM6KAH1GJpwBYAdIyh4QcgjISGBVZQgJ6dAATGAALFQBWAAZ3MKJYuHRsWJC6AGYAdgKwgD4QABoQCEZjaApkUEMFCHoABUMEepQg+jIAT3rKgCMFMjAAay0AZUYxx2xkGAUJOEqczBIAdVj0eApZsDgpzt30ADddvuRwKgqQR00jVtHsTDJkMSDNSoArCgAPABCowm0zImDgABlHHAPl9ViA-v8pvMSHAAIoSCDwOEkb4gWYKR7XTBRf53RgKRwwTbROLIAAcSUqlIgmk2o0Y10pZjgCjOsMqAEcsfBntUuiBKBY4HAonK7go4CL0Ernuw3rj8ZoHItlgihL40ZjsbCkJ88QiYGQhrSYrFkDxKksyOgSPMAMIQTCalBmBJ3CSaAAqNq6FvxZxWAEkoPLYFMwFSagBBONTGB9NFauAAX1zQA" rel="nofollow noreferrer">playground). However, if you use the HTML parser, Prettier will add the closing / (<a href="https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAlgWwOYB0oAEBYANgIYDOFAvLiAO4AOAtFmdnMwIwBMPXBCugBenAGYBXEiTr4iFAE5haIAPSUKcGBVVsOOsgpjpScCsyhx6OgJqVM6KAH1GJpwBYAdIyh4QcgjISGBVZQgJ6dAATGAALFQBWAAZ3MKJYuHRsWJC6AGYAdgKwgD4QABoQCEZjaApkUEMFCHoABUMEepQg+jIAT3rKgCMFMjAAay0AZUYxx2xkGAUJOEqczBIAdVj0eApZsDgpzt30ADddvuRwKgqQR00jVtHsTDJkMSDNSoArCgAPABCowm0zImDgABlHHAPl9ViA-v8pvMSHAAIoSCDwOEkb4gWYKR7XdYkO6MBSOGCbaJxZAADiSlQpEE0m1GjGuFLMcAUZ1hlQAjlj4M9ql0QJQLHA4FFZXcFHBhehFc92G9cfjNA5FssEUJfGjMdjYUhPniETAyEMaTFYsgeJUlmR0CR5gBhCCYDUoMwJO4STQAFWtXXN+LOKwAklA5bApmBKTUAIKxqYwPpozVwAC+OaAA" rel="nofollow noreferrer">playground).

Use the --parser option to format using the HTML parser (note that you need to do it before adding your MDX frontmatter, otherwise the HTML parser won't be able to parse the files either):

prettier --parser html --write ./my-html-files-from-wordpress

Once the elements are all (self-)closing, you can switch back to using Prettier's inferred parser (MDX for .mdx files):

prettier --write ./my-formatted-mdx-files


问:
How to center a string using String.format?
```<code>public class Divers {
  public static void main(String args[]){

     String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
     System.out.format(format, "FirstName", "Init.", "LastName");
     System.out.format(format, "Real", "", "Gagnon");
     System.out.format(format, "John", "D", "Doe");

     String ex[] = { "John", "F.", "Kennedy" };

     System.out.format(String.format(format, (Object[])ex));
  }
}
</code>```

output:

```<code>|FirstName |Init.     |LastName            |
|Real      |          |Gagnon              |
|John      |D         |Doe                 |
|John      |F.        |Kennedy             |
</code>```

I want the output to be centered. If I do not use '-' flag the output will be aligned to the right.

I did not find a flag to center text in the API.

This article has some information about format, but nothing on centre justify.

答:
This is another way to place a string in center.</p>

```<code>public static void center(String s, int length, CharSequence ch) {
    /* It works as follows
     * String centerString = String.format("|%" + (length - s.length()) + "s", s);
     * centerString = String.format("%" + -length + "s|", centerString);
     * System.out.println(centerString);
     */

    String centerString = String.format("%-" + length + "s|", String.format("|%" + (length - s.length()) + "s", s));
    System.out.println(centerString);
}
</code>```

Body:
public class Divers {
  public static void main(String args[]){

     String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
     System.out.format(format, "FirstName", "Init.", "LastName");
     System.out.format(format, "Real", "", "Gagnon");
     System.out.format(format, "John", "D", "Doe");

     String ex[] = { "John", "F.", "Kennedy" };

     System.out.format(String.format(format, (Object[])ex));
  }
}

output:

|FirstName |Init.     |LastName            |
|Real      |          |Gagnon              |
|John      |D         |Doe                 |
|John      |F.        |Kennedy             |

I want the output to be centered. If I do not use '-' flag the output will be aligned to the right.

I did not find a flag to center text in the API.

This article has some information about format, but nothing on centre justify.

Body:
This is another way to place a string in center.

public static void center(String s, int length, CharSequence ch) {
    /* It works as follows
     * String centerString = String.format("|%" + (length - s.length()) + "s", s);
     * centerString = String.format("%" + -length + "s|", centerString);
     * System.out.println(centerString);
     */

    String centerString = String.format("%-" + length + "s|", String.format("|%" + (length - s.length()) + "s", s));
    System.out.println(centerString);
}


问:
Insert new value in Dictionary at specific point
I would like insert a new value in my dictionary not at the end , but at a given position , like linsert function, it's important for me to keep the order of my dictionary.

My new value : dict set mydict ford wheels 4
 My dictionary :

```<code>set mydict {mercedes {wheels 4} opel {wheels 4}}
</code>```

I would like this result :mercedes {wheels 4} ford {wheels 4} opel {wheels 4}

and not this :mercedes {wheels 4} opel {wheels 4} ford {wheels 4}

答:
The order maintained by dictionaries is that of first insertion; where the key is not already in the dictionary, it always goes at the end. (It had to go somewhere consistent.) There's no operation to put it elsewhere.

But you can make one! The trick is to know that dicts can be “type-punned” to lists efficiently. Indeed, dicts deliberately have the same formatting rules as lists (subject to the constraint that there must be an even number of elements, and duplicate keys get dropped). That means you can use linsert to do the tricky bit (assuming you use numeric indices and not end-relative ones).

```<code>proc dict_set_at {dictionaryVar index key value} {
    upvar 1 $dictionaryVar d
    if {[dict exists $d $key]} {
        dict set d $key $value
    } else {
        set d [linsert $d [expr {$index * 2}] $key $value]
    }
    return $d
}

# Demo code
set mydict {mercedes {wheels 4} opel {wheels 4}}
dict_set_at mydict 1 ford {wheels 4}
puts $mydict
#  mercedes {wheels 4} ford {wheels 4} opel {wheels 4}
</code>```

One key caveat: this is not as efficient as plain old dict set. But it does work.

Body:
I would like insert a new value in my dictionary not at the end , but at a given position , like linsert function, it's important for me to keep the order of my dictionary.

My new value : dict set mydict ford wheels 4
 My dictionary :

set mydict {mercedes {wheels 4} opel {wheels 4}}

I would like this result :mercedes {wheels 4} ford {wheels 4} opel {wheels 4}

and not this :mercedes {wheels 4} opel {wheels 4} ford {wheels 4}

Body:
The order maintained by dictionaries is that of first insertion; where the key is not already in the dictionary, it always goes at the end. (It had to go somewhere consistent.) There's no operation to put it elsewhere.

But you can make one! The trick is to know that dicts can be “type-punned” to lists efficiently. Indeed, dicts deliberately have the same formatting rules as lists (subject to the constraint that there must be an even number of elements, and duplicate keys get dropped). That means you can use linsert to do the tricky bit (assuming you use numeric indices and not end-relative ones).

proc dict_set_at {dictionaryVar index key value} {
    upvar 1 $dictionaryVar d
    if {[dict exists $d $key]} {
        dict set d $key $value
    } else {
        set d [linsert $d [expr {$index * 2}] $key $value]
    }
    return $d
}

# Demo code
set mydict {mercedes {wheels 4} opel {wheels 4}}
dict_set_at mydict 1 ford {wheels 4}
puts $mydict
#  mercedes {wheels 4} ford {wheels 4} opel {wheels 4}

One key caveat: this is not as efficient as plain old dict set. But it does work.


问:
How to set mail attachments without saving file in database?
I have created simple application form and i was trying to upload file and send it as email attachment. And i did it with this approach:

```<code>class ApplyController < ApplicationController

  def prepare_email_content
    ApplyMailer.with(params).apply.deliver_now
  end

end
</code>```

```<code>class ApplyMailer < ApplicationMailer

  def apply
    @company = Company.find(params[:company_id])

    @candidate = params[:name]
    @candidate_mail = params[:email]

    @email = @company.email

    attachments[params[:cv].original_filename] = params[:cv].read

    mail to: @email, subject: 'Hello'
  end
end
</code>```

```<code><h1>APPLY</h1>
<%= form_tag(apply_path, method: :post, multipart: true) do %>
  <%= label_tag(:name, "First and last name:") %>
  <%= text_field_tag(:name) %>
  <%= label_tag(:email, "Email:") %>
  <%= text_field_tag(:email) %>
  <%= hidden_field_tag :company_id, params[:company_id] %>
  <%= file_field_tag 'cv' %>
  <%= submit_tag "Search", :name => nil %>
<% end %>

<%= link_to 'All offers', hello_path %>
</code>```

Everything was working fine - i have tested application and it was fine. Then i have developed my application and when i come back to testing i started getting this error:

On the way i have installed some gems and updated few of them. I was checking out to commit where this feature was working and it is. But i'm not able to find any differences in my code. There were some changes in /.idea folder but i don't know if any of this files could trigger this issue.

I'm using rails 6.0.3 and ruby 2.5.8

EDIT

I can see that there is a problem inside called methods. Looks like it cannot find @sort_order value and it sets data value as nil. But i have no idea how to change working of this.

答:
Replace the line you're attaching the file with

```<code>attachments["#{params[:cv].original_filename}"] = File.read(params[:cv].path)
</code>```

Even though you're not saving the file, there is a still a local path to grab the file from.

Also, you should really consider passing the parameters to the mailer from the controller, rather than passing params in its entirety. That way if the information or format of the upload is incorrect, you can redirect back to the form and bypass sending the email.

Body:
I have created simple application form and i was trying to upload file and send it as email attachment. And i did it with this approach:

class ApplyController < ApplicationController

  def prepare_email_content
    ApplyMailer.with(params).apply.deliver_now
  end

end

class ApplyMailer < ApplicationMailer

  def apply
    @company = Company.find(params[:company_id])

    @candidate = params[:name]
    @candidate_mail = params[:email]

    @email = @company.email

    attachments[params[:cv].original_filename] = params[:cv].read

    mail to: @email, subject: 'Hello'
  end
end

APPLY

<%= form_tag(apply_path, method: :post, multipart: true) do %>
  <%= label_tag(:name, "First and last name:") %>
  <%= text_field_tag(:name) %>
  <%= label_tag(:email, "Email:") %>
  <%= text_field_tag(:email) %>
  <%= hidden_field_tag :company_id, params[:company_id] %>
  <%= file_field_tag 'cv' %>
  <%= submit_tag "Search", :name => nil %>
<% end %>

<%= link_to 'All offers', hello_path %>

Everything was working fine - i have tested application and it was fine. Then i have developed my application and when i come back to testing i started getting this error:

On the way i have installed some gems and updated few of them. I was checking out to commit where this feature was working and it is. But i'm not able to find any differences in my code. There were some changes in /.idea folder but i don't know if any of this files could trigger this issue.

I'm using rails 6.0.3 and ruby 2.5.8

EDIT

I can see that there is a problem inside called methods. Looks like it cannot find @sort_order value and it sets data value as nil. But i have no idea how to change working of this.

Body:
Replace the line you're attaching the file with

attachments["#{params[:cv].original_filename}"] = File.read(params[:cv].path)

Even though you're not saving the file, there is a still a local path to grab the file from.

Also, you should really consider passing the parameters to the mailer from the controller, rather than passing params in its entirety. That way if the information or format of the upload is incorrect, you can redirect back to the form and bypass sending the email.


问:
How to create a new repo at Github using git bash?
How can I create a new repository from my machine using git bash?

I followed the below steps:

```<code>mkdir ~/Hello-World

cd ~/Hello-World

git init

touch README

git add README

git commit -m 'first commit'

git remote add origin https://github.com/username/Hello-World.git

git push origin master
</code>```

But I'm getting "Fatal error: did you run update-server-info on the server? "

答:
Overview

Command 'git' do not allow you to create repo but it's possible to create new repo at github from BASH script. All solutions use user/password authentication which is deplicated but stil in use. Authentication must be done using personal access token.
Below there are solutions:

3rd party application

https://github.com/github/hub

```<code>sudo apt install hub;
cd <folder with code>;
hub init;
hub create -p -d "<repo description>" -h "<project site>" \
"user_name>/<repo_name>";
</code>```

More options: https://hub.github.com/hub-create.1.html

Pure BASH

```<code>REPONAME="TEST";
DOMAIN="www.example.com";
DESCRIPTION="Repo Description";
GITHUB_USER="github_user";

FOLDER="$HOME/temp/$REPONAME";
mkdir -p "$FOLDER"; cd "$FOLDER";

read -r -d '' JSON_TEMPLATE << EOF
{
  "name" : "%s",
  "description" : "%s",
  "homepage" : "%s",
  "visibility" : "private",
  "private" : true,
  "has_issues" : false,
  "has_downloads" : false,
  "has_wiki" : false,
  "has_projects" : false
}
EOF

JSON_OUTPUT=$(printf "$JSON_TEMPLATE" "$REPO_NAME" \
  "$DESCRIPTION" "http://$DOMAIN");

# https://developer.github.com/v3/repos/#create-an-organization-repository
curl -u ${GITHUB_USER} https://api.github.com/user/repos \
  -d "$JSON_OUTPUT"
</code>```

Body:
How can I create a new repository from my machine using git bash?

I followed the below steps:

mkdir ~/Hello-World

cd ~/Hello-World

git init

touch README

git add README

git commit -m 'first commit'

git remote add origin https://github.com/username/Hello-World.git

git push origin master

But I'm getting "Fatal error: did you run update-server-info on the server? "

Body:
Overview

Command 'git' do not allow you to create repo but it's possible to create new repo at github from BASH script. All solutions use user/password authentication which is deplicated but stil in use. Authentication must be done using personal access token.
Below there are solutions:

3rd party application

https://github.com/github/hub

sudo apt install hub;
cd <folder with code>;
hub init;
hub create -p -d "<repo description>" -h "<project site>" \
"user_name>/<repo_name>";

More options: https://hub.github.com/hub-create.1.html

Pure BASH

REPONAME="TEST";
DOMAIN="www.example.com";
DESCRIPTION="Repo Description";
GITHUB_USER="github_user";

FOLDER="$HOME/temp/$REPONAME";
mkdir -p "$FOLDER"; cd "$FOLDER";

read -r -d '' JSON_TEMPLATE << EOF
{
  "name" : "%s",
  "description" : "%s",
  "homepage" : "%s",
  "visibility" : "private",
  "private" : true,
  "has_issues" : false,
  "has_downloads" : false,
  "has_wiki" : false,
  "has_projects" : false
}
EOF

JSON_OUTPUT=$(printf "$JSON_TEMPLATE" "$REPO_NAME" \
  "$DESCRIPTION" "http://$DOMAIN");

# https://developer.github.com/v3/repos/#create-an-organization-repository
curl -u ${GITHUB_USER} https://api.github.com/user/repos \
  -d "$JSON_OUTPUT"


问:
Is it possible to prevent triggering the error callback of an AJAX request after calling abort on the request?
My first issue was that I was looking for a way to automatically abort an AJAX request if the user navigated away from a page while the request was being made. I found this helpful solution which solved that problem. Now my issue is that upon aborting specific AJAX requests within my application, the user is directed to an error page (I believe this is the behavior intended in some of the error callbacks) and I do not want that to be the behavior in the case when the user simply just navigated to a different page during the request.

What i'm hoping to do is continue using the solution linked above, but modify it in a way that will prevent the execution of the error callback. I understand that I can check for the status and readystate properties inside of an error callback, but this would mean I would have to include these checks in all of my AJAX requests across my application and that just isn't very maintainable. My goal is to have this logic all in one place or at least in as few places as possible.

I've tried the following with no luck. It appears that the local error callback is executed first, and then execution proceeds to the global handler and by then its too late.

Any help is greatly appreciated. Thank you

```<code>function onPageLoaded() {
    var jqxhrs = [];

    $(window).bind("beforeunload", function (event) {
        $.each(jqxhrs, function (idx, jqxhr) {
            if (jqxhr) {
                jqxhr.abort();
            }
        });
    });

    $(document).ajaxError(function (e, jqXHR, ajaxSettings, thrownError) {
        if (jqXHR.status === 0 || jqXHR.readyState === 0) {
            return;
        }
    });

    function registerJqxhr(event, jqxhr, settings) {
        jqxhrs.push(jqxhr);
    }

    function unregisterJqxhr(event, jqxhr, settings) {
        var idx = $.inArray(jqxhr, jqxhrs);
        jqxhrs.splice(idx, 1);
    }

    $(document).ajaxSend(registerJqxhr);
    $(document).ajaxComplete(unregisterJqxhr);
}
</code>```

答:
you can try this somewhere in your code </p>

```<code>   var response=Promise.all([ajaxcall1,ajaxcall2,ajaxcall3,....])
</code>```

<p>if one of this promises is not resolved so you can handle the error </p>

```<code>response.then((resp)=> //your code to handle resp )
.catch ((error)=>{ //handle error here})
</code>```

Body:
My first issue was that I was looking for a way to automatically abort an AJAX request if the user navigated away from a page while the request was being made. I found this helpful solution which solved that problem. Now my issue is that upon aborting specific AJAX requests within my application, the user is directed to an error page (I believe this is the behavior intended in some of the error callbacks) and I do not want that to be the behavior in the case when the user simply just navigated to a different page during the request.

What i'm hoping to do is continue using the solution linked above, but modify it in a way that will prevent the execution of the error callback. I understand that I can check for the status and readystate properties inside of an error callback, but this would mean I would have to include these checks in all of my AJAX requests across my application and that just isn't very maintainable. My goal is to have this logic all in one place or at least in as few places as possible.

I've tried the following with no luck. It appears that the local error callback is executed first, and then execution proceeds to the global handler and by then its too late.

Any help is greatly appreciated. Thank you

function onPageLoaded() {
    var jqxhrs = [];

    $(window).bind("beforeunload", function (event) {
        $.each(jqxhrs, function (idx, jqxhr) {
            if (jqxhr) {
                jqxhr.abort();
            }
        });
    });

    $(document).ajaxError(function (e, jqXHR, ajaxSettings, thrownError) {
        if (jqXHR.status === 0 || jqXHR.readyState === 0) {
            return;
        }
    });

    function registerJqxhr(event, jqxhr, settings) {
        jqxhrs.push(jqxhr);
    }

    function unregisterJqxhr(event, jqxhr, settings) {
        var idx = $.inArray(jqxhr, jqxhrs);
        jqxhrs.splice(idx, 1);
    }

    $(document).ajaxSend(registerJqxhr);
    $(document).ajaxComplete(unregisterJqxhr);
}

Body:
you can try this somewhere in your code

   var response=Promise.all([ajaxcall1,ajaxcall2,ajaxcall3,....])

if one of this promises is not resolved so you can handle the error

response.then((resp)=> //your code to handle resp )
.catch ((error)=>{ //handle error here})


问:
Ionic 4: The "src" content of an "img" tag is not updating when I change it from the controller in IOS
I am developing an app for Android and IOS.

I have a profile page where the user can change profile pictures. The photo appears in the view and is changed in real time.

My code is like this in the view:

```<code><img alt="logo" style="width:15vh; height:15vh; border-radius: 50%;" src="{{pictureusuariomenu}}">
</code>```

pictureusuariomenu is a variable found in the controller.

With that variable what I do is, it is the URL of the image that I upload, I update it there.  here is the function:

```<code>updateStoredImages(name) {
    this.storage.get(STORAGE_KEY).then(images => {
        let arr = JSON.parse(images);
        if (!arr) {
            let newImages = [name];
            this.storage.set(STORAGE_KEY, JSON.stringify(newImages));
        } else {
            arr.push(name);
            this.storage.set(STORAGE_KEY, JSON.stringify(arr));
        }

        let filePath = this.file.dataDirectory + name;
        let resPath = this.pathForImage(filePath);
       // alert(resPath);
        this.urlImage=resPath;

        let newEntry = {
            name: name,
            path: resPath,
            filePath: filePath
        };
        this.images=[]; //borrar las imagenes anteriores (no crear la lista de imagenes)
        this.images = [newEntry, ...this.images];
        this.urlImage = this.images[0].path;
        this.colocarImagenEnProfile(this.urlImage);
        this.ref.detectChanges(); // trigger change detection cycle
    });
}
</code>```

In this line:

```<code>this.colocarImagenEnProfile(this.urlImage);
</code>```

What I do is:

```<code>colocarImagenEnProfile(newFileName){
    this.pictureusuariomenu=newFileName;
}
</code>```

Now in android is working fine this way of updating the profile image in view:

Before:

After:

But in IOS this isn't working.   The view is not updated at all

Before:

After:

Nothing appears, just a few letters. But the view doesn't update in IOS.

What could it be?

My specifications:

答:
you forgot to bind it. put it instead of your HTML tag:

```<code><img alt="logo" style="width:15vh; height:15vh; border-radius: 50%;" [src]="pictureusuariomenu">
</code>```

I don't know why but you have to bind it that way.
also, you have to use window.Ionic.WebView.convertFileSrc(); function, if using angular you need to sanitize it. like this:

```<code>this.sanitize.bypassSecurityTrustResourceUrl(window.Ionic.WebView.convertFileSrc(path))
</code>```

Body:
I am developing an app for Android and IOS.

I have a profile page where the user can change profile pictures. The photo appears in the view and is changed in real time.

My code is like this in the view:

pictureusuariomenu is a variable found in the controller.

With that variable what I do is, it is the URL of the image that I upload, I update it there.  here is the function:

updateStoredImages(name) {
    this.storage.get(STORAGE_KEY).then(images => {
        let arr = JSON.parse(images);
        if (!arr) {
            let newImages = [name];
            this.storage.set(STORAGE_KEY, JSON.stringify(newImages));
        } else {
            arr.push(name);
            this.storage.set(STORAGE_KEY, JSON.stringify(arr));
        }

        let filePath = this.file.dataDirectory + name;
        let resPath = this.pathForImage(filePath);
       // alert(resPath);
        this.urlImage=resPath;

        let newEntry = {
            name: name,
            path: resPath,
            filePath: filePath
        };
        this.images=[]; //borrar las imagenes anteriores (no crear la lista de imagenes)
        this.images = [newEntry, ...this.images];
        this.urlImage = this.images[0].path;
        this.colocarImagenEnProfile(this.urlImage);
        this.ref.detectChanges(); // trigger change detection cycle
    });
}

In this line:

this.colocarImagenEnProfile(this.urlImage);

What I do is:

colocarImagenEnProfile(newFileName){
    this.pictureusuariomenu=newFileName;
}

Now in android is working fine this way of updating the profile image in view:

Before:

After:

But in IOS this isn't working.   The view is not updated at all

Before:

After:

Nothing appears, just a few letters. But the view doesn't update in IOS.

What could it be?

My specifications:

Body:
you forgot to bind it. put it instead of your HTML tag:

<img alt="logo" style="width:15vh; height:15vh; border-radius: 50%;" [src]="pictureusuariomenu">

I don't know why but you have to bind it that way.
also, you have to use window.Ionic.WebView.convertFileSrc(); function, if using angular you need to sanitize it. like this:

this.sanitize.bypassSecurityTrustResourceUrl(window.Ionic.WebView.convertFileSrc(path))


问:
angular2 - Get DOM element of inner component in outer component's controller?
Example:

outer.html

```<code><div *ngFor="let x of y; let i = index">
        <inner-c></inner-c>
</div>
</code>```

inner-c.html

```<code><div #bar>
    <div class="row no-gutters mt-3 mb-3 ml-5 mr-5">
        foo
    </div>
</div>
</code>```

How to get access to #bar DOM element list in outer.component.ts controller? Is that possible?

I tried

@ContentChildren('bar') inputElems: QueryList<ElementRef>; and @ViewChildren('bar') inputElems: QueryList<ElementRef>;

in  outer.component.ts but those return an empty list.

答:
I don't believe you can directly access the elements from other components. You could however set up an event emitter in the child component to emit the ElementRef of the child element. Try the following

inner-c.component.ts

import { Component, ViewChild, ElementRef, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'inner-c',
  templateUrl: './inner-c.component.html',
  styleUrls: ['./inner-c.component.css']
})
export class InnerCComponent {
  @Output() childElement = new EventEmitter();
  @ViewChild('bar')
  set viewChild(list: ElementRef){
    this.childElement.emit(list);
  }

  constructor() {
  }
}
```

<p>inner-c.component.html</p>

<pre class="lang-html prettyprint-override"><code><div #bar>
  <div class="row no-gutters mt-3 mb-3 ml-5 mr-5">
    foo
  </div>
</div>
</code>```

app.component.ts

export class AppComponent {
  y = [0, 1, 2, 3, 4];

  childElement(event) {
    console.log(event);
  }
}
```

<p>app.component.html</p>

<pre class="lang-html prettyprint-override"><code><div *ngFor="let x of y; let i = index">
  <inner-c (childElement)="childElement($event)"></inner-c>
</div>
</code>```

Body:
Example:

outer.html

        <inner-c></inner-c>

inner-c.html

        foo

How to get access to #bar DOM element list in outer.component.ts controller? Is that possible?

I tried

@ContentChildren('bar') inputElems: QueryList<ElementRef>; and @ViewChildren('bar') inputElems: QueryList<ElementRef>;

in  outer.component.ts but those return an empty list.

Body:
I don't believe you can directly access the elements from other components. You could however set up an event emitter in the child component to emit the ElementRef of the child element. Try the following

inner-c.component.ts

import { Component, ViewChild, ElementRef, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'inner-c',
  templateUrl: './inner-c.component.html',
  styleUrls: ['./inner-c.component.css']
})
export class InnerCComponent {
  @Output() childElement = new EventEmitter();
  @ViewChild('bar')
  set viewChild(list: ElementRef){
    this.childElement.emit(list);
  }

  constructor() {
  }
}

inner-c.component.html

<div #bar>
  <div class="row no-gutters mt-3 mb-3 ml-5 mr-5">
    foo
  </div>
</div>

app.component.ts

export class AppComponent {
  y = [0, 1, 2, 3, 4];

  childElement(event) {
    console.log(event);
  }
}

app.component.html

<div *ngFor="let x of y; let i = index">
  <inner-c (childElement)="childElement($event)"></inner-c>
</div>


问:
Laravel sanctum unauthenticated
I am using Laravel sanctum in my project with angular as frontend. Getting unauthenticated from the second api request. Please let me know where am I going wrong

Frontend-> 127.0.0.1:4200

Backend-> localhost:8888

.env config

SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=127.0.0.1

Added middleware auth:sanctum to the routes group in api.php

Ref: https://prnt.sc/rm9ejy

答:
For anyone using Laravel Homestead, use your actual domain.</p>

```<code>SANCTUM_STATEFUL_DOMAINS=homestead.test
</code>```

Title: Laravel sanctum unauthenticated

Body:
For anyone using Laravel Homestead, use your actual domain.

SANCTUM_STATEFUL_DOMAINS=homestead.test


问:
Go's time doesn't work under the docker image from scratch
Go code:

```<code>package main

import (
    "fmt"
    "time"
)

func main() {
    var local,_ = time.LoadLocation("Asia/Shanghai")
    fmt.Println(time.Now())
    fmt.Println(time.Now().In(local))
}
</code>```

Dockerfile:

```<code>FROM scratch
COPY ./main /main
CMD [ "/main" ]
</code>```

build.sh:

```<code>rm -rf main
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o main  .
docker build -t hello-go .
docker run hello-go
</code>```

All the file are in one folder named hello-go. When I run my Go code in my osx. It works.

➜  hello-go go run main.go
2017-12-13 21:50:53.482933 +0800 CST m=+0.000350077
2017-12-13 21:50:53.483007 +0800 CST
```

<p>When i build the docker image and start it. one error like this:</p>

```➜  hello-go ./build.sh
Sending build context to Docker daemon  1.937MB
Step 1/3 : FROM scratch
 --->
Step 2/3 : COPY ./main /main
 ---> 80da783f6c5d
Step 3/3 : CMD /main
 ---> Running in 85cb022b3ce2
 ---> 485ddd3a08dd
Removing intermediate container 85cb022b3ce2
Successfully built 485ddd3a08dd
Successfully tagged hello-go:latest
2017-12-13 13:52:59.861173734 +0000 UTC m=+0.000252335
panic: time: missing Location in call to Time.In

goroutine 1 [running]:
time.Time.In(0xbe846a0ef355744e, 0x4d607, 0x539b80, 0x0, 0x0, 0x0, 0xc420037f70)
        /usr/local/go/src/time/time.go:1073 +0xc0
main.main()
        /Users/liujichun/Desktop/workspace/docker/hello-go/main.go:11 +0xee
➜  hello-go
```

I know the scratch image is empty. What should i do to make it.

答:
Docker FROM alphine

```<code>RUN apk --no-cache add tzdata
</code>```

see answer in:
https://stackoverflow.com/a/62159987/4143613

Body:
Go code:

package main

import (
    "fmt"
    "time"
)

func main() {
    var local,_ = time.LoadLocation("Asia/Shanghai")
    fmt.Println(time.Now())
    fmt.Println(time.Now().In(local))
}

Dockerfile:

FROM scratch
COPY ./main /main
CMD [ "/main" ]

build.sh:

rm -rf main
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o main  .
docker build -t hello-go .
docker run hello-go

All the file are in one folder named hello-go. When I run my Go code in my osx. It works.

➜  hello-go go run main.go
2017-12-13 21:50:53.482933 +0800 CST m=+0.000350077
2017-12-13 21:50:53.483007 +0800 CST

When i build the docker image and start it. one error like this:

➜  hello-go ./build.sh
Sending build context to Docker daemon  1.937MB
Step 1/3 : FROM scratch
 --->
Step 2/3 : COPY ./main /main
 ---> 80da783f6c5d
Step 3/3 : CMD /main
 ---> Running in 85cb022b3ce2
 ---> 485ddd3a08dd
Removing intermediate container 85cb022b3ce2
Successfully built 485ddd3a08dd
Successfully tagged hello-go:latest
2017-12-13 13:52:59.861173734 +0000 UTC m=+0.000252335
panic: time: missing Location in call to Time.In

goroutine 1 [running]:
time.Time.In(0xbe846a0ef355744e, 0x4d607, 0x539b80, 0x0, 0x0, 0x0, 0xc420037f70)
        /usr/local/go/src/time/time.go:1073 +0xc0
main.main()
        /Users/liujichun/Desktop/workspace/docker/hello-go/main.go:11 +0xee
➜  hello-go

I know the scratch image is empty. What should i do to make it.

Body:
Docker FROM alphine

RUN apk --no-cache add tzdata

see answer in:
https://stackoverflow.com/a/62159987/4143613


问:
Website not identifying multiple tables during webscrape
I've been trying to learn web scraping techniques and hit a wall on this one issue. I know VBA isn't the best tool for web scraping but at my job we don't have the ability to use Python or other tools. Only Excel and VBA. Main goal is scrape table data from various websites and for the most part with sites using one table it is fine but I came across a website with multiple tables and I wasn't able to isolate that table or even pull all the tables onto an Excel sheet. My current code only picks up the first Table and I tried modifying the code to pick up the point per game table and I could not figure it out.

If anyone can help, I've been at this for days.

Thanks in advance.

```<code>    Sub GetHTMLDocumentXML()

Dim XMLPage As New MSXML2.XMLHTTP60
Dim HTMLDOC As New MSHTML.HTMLDocument

XMLPage.Open "GET", "https://www.basketball-reference.com/teams/TOR/2020.html", False
XMLPage.send

HTMLDOC.body.innerHTML = XMLPage.responseText

ProcessHTMLPage HTMLDOC

End Sub

Sub ProcessHTMLPage(HTMLPage As MSHTML.HTMLDocument)

    Dim HTMLTable As MSHTML.IHTMLElement
    Dim HTMLTables As MSHTML.IHTMLElementCollection
    Dim HTMLRow As MSHTML.IHTMLElement
    Dim HTMLCell As MSHTML.IHTMLElement
    Dim RowNum As Long, ColNum As Integer

    Set HTMLTables = HTMLPage.getElementsByTagName("table")

    For Each HTMLTable In HTMLTables

    With Worksheets("Sheet1")
        .Range("A1").Value = HTMLTable.className
        .Range("B1").Value = Now
    End With

        RowNum = 2

        For Each HTMLRow In HTMLTable.getElementsByTagName("tr")
           'Debug.Print vbTab & HTMLRow.innerText
            ColNum = 1
            For Each HTMLCell In HTMLRow.Children
                Cells(RowNum, ColNum) = HTMLCell.innerText
                ColNum = ColNum + 1
            Next HTMLCell

            RowNum = RowNum + 1
        Next HTMLRow

    Next HTMLTable

End Sub
</code>```

答:
Most of the tabular content in that page are not dynamic; rather, they are commented out. To interact with them you need to first kick out those vicious signs  which do not let your script access them.

This is how you can scrape the table titled as Per Game using xhr:

```<code>Sub FetchData()
    Dim post As Object, trow As Object
    Dim S$, R&, C&

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.basketball-reference.com/teams/TOR/2020.html", False
        .send
        S = Replace(Replace(.responseText, "<!--", ""), "-->", "")
    End With

    With CreateObject("HTMLFile")
        .body.innerHTML = S
        For Each post In .getElementById("per_game").Rows
            For Each trow In post.Cells
                C = C + 1: Cells(R + 1, C) = trow.innerText
            Next trow
            C = 0: R = R + 1
        Next post
    End With
End Sub
</code>```

Body:
I've been trying to learn web scraping techniques and hit a wall on this one issue. I know VBA isn't the best tool for web scraping but at my job we don't have the ability to use Python or other tools. Only Excel and VBA. Main goal is scrape table data from various websites and for the most part with sites using one table it is fine but I came across a website with multiple tables and I wasn't able to isolate that table or even pull all the tables onto an Excel sheet. My current code only picks up the first Table and I tried modifying the code to pick up the point per game table and I could not figure it out.

If anyone can help, I've been at this for days.

Thanks in advance.

    Sub GetHTMLDocumentXML()

Dim XMLPage As New MSXML2.XMLHTTP60
Dim HTMLDOC As New MSHTML.HTMLDocument

XMLPage.Open "GET", "https://www.basketball-reference.com/teams/TOR/2020.html", False
XMLPage.send

HTMLDOC.body.innerHTML = XMLPage.responseText

ProcessHTMLPage HTMLDOC

End Sub

Sub ProcessHTMLPage(HTMLPage As MSHTML.HTMLDocument)

    Dim HTMLTable As MSHTML.IHTMLElement
    Dim HTMLTables As MSHTML.IHTMLElementCollection
    Dim HTMLRow As MSHTML.IHTMLElement
    Dim HTMLCell As MSHTML.IHTMLElement
    Dim RowNum As Long, ColNum As Integer

    Set HTMLTables = HTMLPage.getElementsByTagName("table")

    For Each HTMLTable In HTMLTables

    With Worksheets("Sheet1")
        .Range("A1").Value = HTMLTable.className
        .Range("B1").Value = Now
    End With

        RowNum = 2

        For Each HTMLRow In HTMLTable.getElementsByTagName("tr")
           'Debug.Print vbTab & HTMLRow.innerText
            ColNum = 1
            For Each HTMLCell In HTMLRow.Children
                Cells(RowNum, ColNum) = HTMLCell.innerText
                ColNum = ColNum + 1
            Next HTMLCell

            RowNum = RowNum + 1
        Next HTMLRow

    Next HTMLTable

End Sub

Body:
Most of the tabular content in that page are not dynamic; rather, they are commented out. To interact with them you need to first kick out those vicious signs <!--, --> which do not let your script access them.

This is how you can scrape the table titled as Per Game using xhr:

Sub FetchData()
    Dim post As Object, trow As Object
    Dim S$, R&, C&

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.basketball-reference.com/teams/TOR/2020.html", False
        .send
        S = Replace(Replace(.responseText, "<!--", ""), "-->", "")
    End With

    With CreateObject("HTMLFile")
        .body.innerHTML = S
        For Each post In .getElementById("per_game").Rows
            For Each trow In post.Cells
                C = C + 1: Cells(R + 1, C) = trow.innerText
            Next trow
            C = 0: R = R + 1
        Next post
    End With
End Sub


问:
composer require laravel/ui. Don't install illuminate/console v7.12.0
I am working on bagiato(laravel). When I run the command "composer require laravel/ui" this error comes.</p>

```<code>Your requirements could not be resolved to an installable set of packages.
Problem 1
    - Conclusion: don't install illuminate/console v7.12.0
    - don't install illuminate/console 7.x-dev|don't install laravel/framework v6.18.15
    - don't install illuminate/console 7.x-dev|remove laravel/framework v6.18.15
    - don't install illuminate/console 7.x-dev|don't install laravel/framework v6.18.15
    - Installation request for illuminate/console ^7.12 -> satisfiable by illuminate/console[7.x-dev, v7.12.0].
    - Installation request for laravel/framework (locked at v6.18.15, required as ^6.0) -> satisfiable by laravel/framework[v6.18.15].
</code>```

答:
You are trying to install the wrong version of laravel/ui.

laravel/ui version 1 is what you want.  Version 2 is trying to install and only laravel 7+ supports it.

composer require vendor/package:version

composer require laravel/ui:1.2.0 <- latest version of laravel/ui that works with Laravel 6

Body:
I am working on bagiato(laravel). When I run the command "composer require laravel/ui" this error comes.

Your requirements could not be resolved to an installable set of packages.
Problem 1
    - Conclusion: don't install illuminate/console v7.12.0
    - don't install illuminate/console 7.x-dev|don't install laravel/framework v6.18.15
    - don't install illuminate/console 7.x-dev|remove laravel/framework v6.18.15
    - don't install illuminate/console 7.x-dev|don't install laravel/framework v6.18.15
    - Installation request for illuminate/console ^7.12 -> satisfiable by illuminate/console[7.x-dev, v7.12.0].
    - Installation request for laravel/framework (locked at v6.18.15, required as ^6.0) -> satisfiable by laravel/framework[v6.18.15].


问:
How to wordwrap a long string in ion-item
IONIC has two problems about word-wrap in ion-item:

String would be truncated by the dots appended at the end, how to show full content without dots ?

Automatic line breaks and responsive are not working in Firefox (Chrome is ok), how to fix this problem in Firefox ?

```<code><div class="row responsive-sm">
    <div class="col">
        <div class="item item-body">
            <ion-item class="wrap" style="word-wrap: break-word; word-break: break-all;">
            #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion
            </ion-item>
        </div>
    </div>
</div>
</code>```

Here is Full HTML to show the problem
codepen

答:
You can do it with CSS without adding ionic's volatile-garbage to your HTML like so

I think that means style any ion-label inside an ion-item with the following style...

Body:
IONIC has two problems about word-wrap in ion-item:

String would be truncated by the dots appended at the end, how to show full content without dots ?

Automatic line breaks and responsive are not working in Firefox (Chrome is ok), how to fix this problem in Firefox ?

            <ion-item class="wrap" style="word-wrap: break-word; word-break: break-all;">
            #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion #fashion
            </ion-item>

Here is Full HTML to show the problem
codepen


问:
For loop in python- to generate output containing list of items
I am new to programming and to python, currently using python3 via annoconda/jupyter. My input (test_Set) is list of quality score codes from a fastq file. The loop converts the quality score codes into quality scores. The following is the code I used

```<code>test_set=['.GA', '<AG', '#<<']
output1=[]
output2=[]
for i in test_set:
    s=i
    for j in range(len(s)):
        qs=ord(s[j])-33
        output1.append(qs)
    output2.append(output1)
</code>```

The outputs i have are:

```<code> output1: [13, 38, 32, 27, 32, 38, 2, 27, 27]
 output2: [[13, 38, 32, 27, 32, 38, 2, 27, 27],
          [13, 38, 32, 27, 32, 38, 2, 27, 27],
          [13, 38, 32, 27, 32, 38, 2, 27, 27]]
</code>```

But the output i am trying to achieve is :

```<code>desired_output: [[13, 38, 32], [27, 32, 38], [2, 27, 27]]
</code>```

I would like to know what I am doing wrong with my loops and how to change them to achieve the desired output.
Thank you and appreciate any help, including resources to understand for and while loops

答:
```<code>test_set=['.GA', '<AG', '#<<']
output=[]
for i in test_set:
    aux = []
    for j in range(len(i)):
        qs=ord(s[j])-33
        aux.append(qs)
    output.append(aux)
</code>```

Body:
I am new to programming and to python, currently using python3 via annoconda/jupyter. My input (test_Set) is list of quality score codes from a fastq file. The loop converts the quality score codes into quality scores. The following is the code I used

test_set=['.GA', '<AG', '#<<']
output1=[]
output2=[]
for i in test_set:
    s=i
    for j in range(len(s)):
        qs=ord(s[j])-33
        output1.append(qs)
    output2.append(output1)

The outputs i have are:

 output1: [13, 38, 32, 27, 32, 38, 2, 27, 27]
 output2: [[13, 38, 32, 27, 32, 38, 2, 27, 27],
          [13, 38, 32, 27, 32, 38, 2, 27, 27],
          [13, 38, 32, 27, 32, 38, 2, 27, 27]]

But the output i am trying to achieve is :

desired_output: [[13, 38, 32], [27, 32, 38], [2, 27, 27]]

I would like to know what I am doing wrong with my loops and how to change them to achieve the desired output.
Thank you and appreciate any help, including resources to understand for and while loops