问:
IN operator in SQL Statement Does not work?
In SQL Server, I have a table MyTable, with the following 3 columns, P(bigint), F(bigint), D(bigint).

Now what I need to do is to group all records by same P value, then in each group, calculate the following value:

```<code>V = ABS((P & 0xFFFFFFFF) * 256 - F)
</code>```

for each record, and delete all records in the group, except for the one with the minimum value of V.

So I write the SQL statement as follows:

```<code>DELETE FROM MyTable WHERE (P, ABS((P & 0xFFFFFFFF) * 256 - F)) NOT IN (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) FROM MyTable GROUP BY P HAVING COUNT(*) > 1)
</code>```

But in SQL Server, I will get the following error:

```<code>Msg 4145 SQL Server An expression of non-boolean type specified in a context where a condition is expected,near ','
</code>```

Why? Also whether bitwise and & works in SQL Server 2005? I only have SQL Server 2008 R2 and the online document at https://learn.microsoft.com/en-us/sql/t-sql/language-elements/bitwise-and-transact-sql?view=sql-server-ver15 does not indicate whether it support 2005 & 2008.

Update1

P, F, D are all bigint type.

Update2

With the helps of others, I finally write a query with NOT EXISTS, as follows:

Method 1: DELETE t FROM MyTable t WHERE NOT EXISTS (SELECT 1 FROM (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
  FROM MyTable GROUP BY P) tt WHERE tt.P = t.P AND tt.minpf = ABS((t.P & 0xFFFFFFFF) * 256 - t.F))

Note: I remove the HAVE COUNT(*) > 1, otherwise, the statement will also delete those records who are in a group with only one record.

Though it works, I doubt its performance. Since in most of the groups(group by P), there will only be one record, while calculating the minpf in such a group and then delete the record with the calculated value <> minpf is wasting time(no records are deleted in such a group). So just wonder if there are better way to do the same thing?

Update 3

I test the performance of my method(method 1) with the two methods Gordon provided(with minor revision)

Method 2:

DELETE t
    FROM MyTable t LEFT JOIN
         (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
          FROM MyTable
          GROUP BY P
         ) tt
         ON tt.p = t.p AND tt.minpf = (tt.P & 0xFFFFFFFF) * 256 - tt.F)
    WHERE tt.P IS NULL;

Method 3:

DELETE t FROM (SELECT t.*,
                 ROW_NUMBER() OVER (PARTITION BY P ORDER BY ABS((P & 0xFFFFFFFF) * 256 - F)) as seqnum
          FROM MyTable t
         ) t
     WHERE seqnum > 1;

The performance data are below:

First Test:

(22721 rows affected)
Method 1:16094

(22721 rows affected)
Method 2:17156

(22721 rows affected)
Method 3:12188

Second Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27562

(22721 rows affected)
Method 3:11625

3rd Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27359

(22721 rows affected)
Method 3:11578

So based on the test, method 3 has the best performance.

答:
IN statements do work, but they do not work in the way you use them - simple like that. The content of IN is a list of compare values, not another sql statement.

In your case you do not IN - you do delete form select with join and use that to define the rows to delete.

Body:
In SQL Server, I have a table MyTable, with the following 3 columns, P(bigint), F(bigint), D(bigint).

Now what I need to do is to group all records by same P value, then in each group, calculate the following value:

V = ABS((P & 0xFFFFFFFF) * 256 - F)

for each record, and delete all records in the group, except for the one with the minimum value of V.

So I write the SQL statement as follows:

DELETE FROM MyTable WHERE (P, ABS((P & 0xFFFFFFFF) * 256 - F)) NOT IN (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) FROM MyTable GROUP BY P HAVING COUNT(*) > 1)

But in SQL Server, I will get the following error:

Msg 4145 SQL Server An expression of non-boolean type specified in a context where a condition is expected,near ','

Why? Also whether bitwise and & works in SQL Server 2005? I only have SQL Server 2008 R2 and the online document at https://learn.microsoft.com/en-us/sql/t-sql/language-elements/bitwise-and-transact-sql?view=sql-server-ver15 does not indicate whether it support 2005 & 2008.

Update1

P, F, D are all bigint type.

Update2

With the helps of others, I finally write a query with NOT EXISTS, as follows:

Method 1: DELETE t FROM MyTable t WHERE NOT EXISTS (SELECT 1 FROM (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
  FROM MyTable GROUP BY P) tt WHERE tt.P = t.P AND tt.minpf = ABS((t.P & 0xFFFFFFFF) * 256 - t.F))

Note: I remove the HAVE COUNT(*) > 1, otherwise, the statement will also delete those records who are in a group with only one record.

Though it works, I doubt its performance. Since in most of the groups(group by P), there will only be one record, while calculating the minpf in such a group and then delete the record with the calculated value <> minpf is wasting time(no records are deleted in such a group). So just wonder if there are better way to do the same thing?

Update 3

I test the performance of my method(method 1) with the two methods Gordon provided(with minor revision)

Method 2:

DELETE t
    FROM MyTable t LEFT JOIN
         (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
          FROM MyTable
          GROUP BY P
         ) tt
         ON tt.p = t.p AND tt.minpf = (tt.P & 0xFFFFFFFF) * 256 - tt.F)
    WHERE tt.P IS NULL;

Method 3:

DELETE t FROM (SELECT t.*,
                 ROW_NUMBER() OVER (PARTITION BY P ORDER BY ABS((P & 0xFFFFFFFF) * 256 - F)) as seqnum
          FROM MyTable t
         ) t
     WHERE seqnum > 1;

The performance data are below:

First Test:

(22721 rows affected)
Method 1:16094

(22721 rows affected)
Method 2:17156

(22721 rows affected)
Method 3:12188

Second Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27562

(22721 rows affected)
Method 3:11625

3rd Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27359

(22721 rows affected)
Method 3:11578

So based on the test, method 3 has the best performance.


来源: stackexchange

问:
Remove or Filter values out of an Array using for loop or a function
I have an Array and i would like to  Filter or delete the following urls from my Array every time they appear:

```<code>"https://basueUrl.com/Claim"
"https://basueUrl.com/ExplanationOfBenefit"
</code>```

My Array

```<code>Array= [
        "https://basueUrl.com/Patient"
        "https://basueUrl.com/Organization"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/Practitioner"
        "https://basueUrl.com/Encounter"
        "https://basueUrl.com/Condition"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/ExplanationOfBenefit"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/ExplanationOfBenefit"
        "https://basueUrl.com/ExplanationOfBenefit"
        ]
</code>```

First Solution I have tried for loop but did not work?

```<code>   for( var i = 0; i < Array.length; i++){
   if ( Array[i] === "https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim") {
    Array.splice(i, 1);
    i--;
   }
}
console.log(Array);

</code>```

Second Solution I tried making a remove method did not work either.

```<code>function arrayRemove(Array, value) {

   return Array.filter(function(ele){
       return ele != value;
   });
}
var result = arrayRemove(Array,"https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim");

</code>```

Any suggestion please?

答:
Please see below the way you can achieve the above mentioned scenario.</p>

```<code>arr.filter(ele=>ele!=="https://basueUrl.com/Claim"
&& ele!=="https://basueUrl.com/ExplanationOfBenefit");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an Array and i would like to  Filter or delete the following urls from my Array every time they appear:

"https://basueUrl.com/Claim"
"https://basueUrl.com/ExplanationOfBenefit"

My Array

Array= [
        "https://basueUrl.com/Patient"
        "https://basueUrl.com/Organization"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/Practitioner"
        "https://basueUrl.com/Encounter"
        "https://basueUrl.com/Condition"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/ExplanationOfBenefit"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/ExplanationOfBenefit"
        "https://basueUrl.com/ExplanationOfBenefit"
        ]

First Solution I have tried for loop but did not work?

   for( var i = 0; i < Array.length; i++){
   if ( Array[i] === "https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim") {
    Array.splice(i, 1);
    i--;
   }
}
console.log(Array);

Second Solution I tried making a remove method did not work either.

function arrayRemove(Array, value) {

   return Array.filter(function(ele){
       return ele != value;
   });
}
var result = arrayRemove(Array,"https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim");

Any suggestion please?

Body:
Please see below the way you can achieve the above mentioned scenario.

arr.filter(ele=>ele!=="https://basueUrl.com/Claim"
&& ele!=="https://basueUrl.com/ExplanationOfBenefit");


问:
Is there any specific way to override search_indexes of oscar core search app?
I am using Haystack with solr back-end in Django-Oscar. I want to override ProductIndex class of core search_indexes. But, the problem is it's not working with the regular way.

Firstly, I forked the search app like other oscar apps. And I created custom ProductIndex class inside search_indexes.py file.

I also tried excluding core search_indexes in setting. But, it's not taking from the overridden app.

My custom class looks like:

```<code>from oscar.apps.search.search_indexes import ProductIndex as AbstractProductIndex

class ProductIndex(AbstractProductIndex):
    def index_queryset(self, using=None):
        # Only index browsable products (not each individual child product)
        return self.get_model().objects.all().order_by('-date_updated')

    def read_queryset(self, using=None):
        return self.get_model().objects.all().base_queryset()
</code>```

The ProductIndex class is supposed to run from my overridden app but, instead it's using core ProductIndex app.

Updated:

I have done according to the documentation and all other forked apps are working fine.
If I delete the index_queryset method in oscar search app, my custom method works. But, that is not what I want.

Forked apps in setting file:

```<code>] + get_core_apps(
    ['shipping', 'customer','promotions', 'search','checkout','catalogue',
    'partner','order','dashboard','dashboard.catalogue','dashboard.orders'],
)
</code>```

And I have to import all from search_indexes in my init file of forked app. Otherwise, the search_indexes.py won't work at all. This is what I have done in my init file:

```<code>from .search_indexes import *
</code>```

答:
I dont see your stack and logs but If you use haystack with django-oscar.
Im almost sure the problem is with SearchIndex, with log smthng like ..models.Product has more than one SearchIndex please exclude one..

Its possible to exclude it in your settings.py
Smth like:

```<code>    HAYSTACK_CONNECTIONS = {
        'default': {
            ..
            ..
            'EXCLUDED_INDEXES': ['apps.search.search_indexes.ProductIndex'],
}
</code>```

Body:
I am using Haystack with solr back-end in Django-Oscar. I want to override ProductIndex class of core search_indexes. But, the problem is it's not working with the regular way.

Firstly, I forked the search app like other oscar apps. And I created custom ProductIndex class inside search_indexes.py file.

I also tried excluding core search_indexes in setting. But, it's not taking from the overridden app.

My custom class looks like:

from oscar.apps.search.search_indexes import ProductIndex as AbstractProductIndex

class ProductIndex(AbstractProductIndex):
    def index_queryset(self, using=None):
        # Only index browsable products (not each individual child product)
        return self.get_model().objects.all().order_by('-date_updated')

    def read_queryset(self, using=None):
        return self.get_model().objects.all().base_queryset()

The ProductIndex class is supposed to run from my overridden app but, instead it's using core ProductIndex app.

Updated:

I have done according to the documentation and all other forked apps are working fine.
If I delete the index_queryset method in oscar search app, my custom method works. But, that is not what I want.

Forked apps in setting file:

] + get_core_apps(
    ['shipping', 'customer','promotions', 'search','checkout','catalogue',
    'partner','order','dashboard','dashboard.catalogue','dashboard.orders'],
)

And I have to import all from search_indexes in my init file of forked app. Otherwise, the search_indexes.py won't work at all. This is what I have done in my init file:

from .search_indexes import *

Body:
I dont see your stack and logs but If you use haystack with django-oscar.
Im almost sure the problem is with SearchIndex, with log smthng like ..models.Product has more than one SearchIndex please exclude one..

Its possible to exclude it in your settings.py
Smth like:

    HAYSTACK_CONNECTIONS = {
        'default': {
            ..
            ..
            'EXCLUDED_INDEXES': ['apps.search.search_indexes.ProductIndex'],
}


问:
What is a simple and efficient way to find rows with time-interval overlaps in SQL?
I have two tables, both with start time and end time fields. I need to find, for each row in the first table, all of the rows in the second table where the time intervals intersect.

For example:

```<code>           <-----row 1 interval------->
<---find this--> <--and this--> <--and this-->
</code>```

Please phrase your answer in the form of a SQL WHERE-clause, AND consider the case where the end time in the second table may be NULL.

Target platform is SQL Server 2005, but solutions from other platforms may be of interest also.

答:
And what, if you want to analyse such an overlap on a minute precision with 70m+ rows?
the only solution i could make up myself was a time dimension table for the join

else the dublicate-handling became a headache .. and the processing cost where astronomical

OwnerDisplayName: Steven A. Lowe

ContentLicense: CC BY-SA 3.0

Body:
I have two tables, both with start time and end time fields. I need to find, for each row in the first table, all of the rows in the second table where the time intervals intersect.

For example:

           <-----row 1 interval------->
<---find this--> <--and this--> <--and this-->

Please phrase your answer in the form of a SQL WHERE-clause, AND consider the case where the end time in the second table may be NULL.

Target platform is SQL Server 2005, but solutions from other platforms may be of interest also.


问:
Clear plots generated by ipywidgets.observe
I have an ipywidget that generates a plot each time the selection changes. Currently the plots are appended to each other; however, I would like to have only one plot (the latest).

```<code>import ipywidgets as widgets
import matplotlib.pyplot as plt
def f(change):
    if change['type'] == 'change' and change['name'] == 'value':
        plt.close('all')  # seems to have no effect
        plt.plot([0, 1],[0, 10])
        plt.title(change['new'])
        plt.show()

w = widgets.Select(options=[0, 1])
w.observe(f)
display(w)
</code>```

I tried without success:

using plt.close('all')

splitting the code into two cells (even if this seems not practical for the real application)

Note: I'm not using interactive since I do not want to run all functions when any parameter changes.

答:
Try sending your charts to an Output widget, which can be used as a context manager, and then cleared with out.clear_output().

import ipywidgets as widgets
import matplotlib.pyplot as plt
%matplotlib inline
out = widgets.Output(layout = widgets.Layout(height='300px'))

def f(change):
    if change['type'] == 'change' and change['name'] == 'value':
        with out:
            plt.plot([0, 1],[0, 10])
            plt.title(change['new'])
            out.clear_output()
            plt.show()

w = widgets.Select(options=[0, 1])
w.observe(f)
display(w)
display(out)
```

Body:
I have an ipywidget that generates a plot each time the selection changes. Currently the plots are appended to each other; however, I would like to have only one plot (the latest).

import ipywidgets as widgets
import matplotlib.pyplot as plt
def f(change):
    if change['type'] == 'change' and change['name'] == 'value':
        plt.close('all')  # seems to have no effect
        plt.plot([0, 1],[0, 10])
        plt.title(change['new'])
        plt.show()

w = widgets.Select(options=[0, 1])
w.observe(f)
display(w)

I tried without success:

using plt.close('all')

splitting the code into two cells (even if this seems not practical for the real application)

Note: I'm not using interactive since I do not want to run all functions when any parameter changes.


问:
How to copy non-ts files to dist when building typescript?
I have Mail module in folder with this structure:

```<code>- Mail
  - templates
      - <Handlebars files>
  - mail.module.ts
</code>```

When I build (compile) TypeScript project, my template folder is not included in build folder.
How to move those kind of files into dist when building?

Is it different for development vs production builds?

答:
TS compiler doesn't handle files that are other than TypeScript or JS (e.g. .ts, .js, .tsx, etc.).

One way of doing it, just running cp to copy those files after you compile NestJS. In your package.json replace the line

"build": "nest build",
```

<p>with </p>

<pre class="lang-js prettyprint-override"><code>"build": "nest build && cp ./Mail/templates ./build",
</code>```

Ideally, I would switch to Webpack (or similar) to transpile TypeScript and copy artifacts. NestJs has a basic example on how to build with Webpack here. To extend it to have a "copy" phase, install copy-webpack-plugin npm package and add those additions in webpack config file:

const copyFiles = require('copy-webpack-plugin');
// ... omitted for abbreviation

module.exports = function(options) {
   return {
   // ... omitted for abbreviation
   ,
    plugins: [
      // ... omitted for abbreviation
      new copyFiles([
            { from: 'Mail/templates', to: 'templates' }
        ])
    ]
}
```

Body:
I have Mail module in folder with this structure:

- Mail
  - templates
      - <Handlebars files>
  - mail.module.ts

When I build (compile) TypeScript project, my template folder is not included in build folder.
How to move those kind of files into dist when building?

Is it different for development vs production builds?

Body:
TS compiler doesn't handle files that are other than TypeScript or JS (e.g. .ts, .js, .tsx, etc.).

One way of doing it, just running cp to copy those files after you compile NestJS. In your package.json replace the line

"build": "nest build",

with

"build": "nest build && cp ./Mail/templates ./build",

Ideally, I would switch to Webpack (or similar) to transpile TypeScript and copy artifacts. NestJs has a basic example on how to build with Webpack here. To extend it to have a "copy" phase, install copy-webpack-plugin npm package and add those additions in webpack config file:

const copyFiles = require('copy-webpack-plugin');
// ... omitted for abbreviation

module.exports = function(options) {
   return {
   // ... omitted for abbreviation
   ,
    plugins: [
      // ... omitted for abbreviation
      new copyFiles([
            { from: 'Mail/templates', to: 'templates' }
        ])
    ]
}


问:
Javascript regex to check if a value begins with a number followed by anything else
How would i go about doing a regex to see if it begins with a number and any character can follow after. My current expression is

```<code>var validaddress = /^[0-9][A-Za-z0-9]+$/;
</code>```

But this isn't the right way. Im new to this, help anyone?

答:
What you looking for is: var validaddress = /^\d.*$/;

\d - Matches any digit

.* - Matches any character except newline zero or more times.

Or replace .* with .+, if you are looking for at least 1 character.

Body:
How would i go about doing a regex to see if it begins with a number and any character can follow after. My current expression is

var validaddress = /^[0-9][A-Za-z0-9]+$/;

But this isn't the right way. Im new to this, help anyone?


问:
Reading in gzipped data from S3 in Ruby
My company has data messages (json) stored in gzipped files on Amazon S3. I want to use Ruby to iterate through the files and do some analytics. I started to use the 'aws/s3' gem, and get get each file as an object:

```<code>#<AWS::S3::S3Object:0x4xxx4760 '/my.company.archive/data/msg/20131030093336.json.gz'>
</code>```

But once I have this object, I do not know how to unzip it or even access the data inside of it.

答:
The S3Object documentation is updated and the stream method is no longer available: https://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/S3Object.html

So, the best way to read data from an S3 object would be this:

```<code>json_data = Zlib::GzipReader.new(StringIO.new(your_object.read)).read
</code>```

Title: Reading in gzipped data from S3 in Ruby

Body:
My company has data messages (json) stored in gzipped files on Amazon S3. I want to use Ruby to iterate through the files and do some analytics. I started to use the 'aws/s3' gem, and get get each file as an object:

#<AWS::S3::S3Object:0x4xxx4760 '/my.company.archive/data/msg/20131030093336.json.gz'>

But once I have this object, I do not know how to unzip it or even access the data inside of it.

Body:
The S3Object documentation is updated and the stream method is no longer available: https://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/S3Object.html

So, the best way to read data from an S3 object would be this:

json_data = Zlib::GzipReader.new(StringIO.new(your_object.read)).read


问:
Where do I have to put @DeclareRoles?
I basically understand the functions of @DeclareRoles and @RolesAllowed, but I'm not sure where to add the @DeclareRoles correctly. I testet with a  vaadin application with ejb session beans and cdi in glassfish 4. The application is packed as war not as ear.

@DeclareRoles on no class:

Obviously nothing works. HttpServletRequest.isUserInRole() and SessionContext.isCallerInRole() are always returning false. @RolesAllowed always denies access.

@DeclareRoles on the Servlet:

@RolesAllowed and HttpServletRequest.isUserInRole() are working as expected. SessionContext.isCallerInRole() is always returning false.

@DeclareRoles on a session bean:

@RolesAllowed, HttpServletRequest.isUserInRole() and SessionContext.isCallerInRole() are working as expected. Even if SessionContext.isCallerInRole() is called in a different session bean than the one with @DeclareRoles

My question now are:

Where is the right place to put @DeclareRoles?

Is it ok to set it only once or should it annotate every bean that uses SessionContext.isCallerInRole() or @RolesAllowed?

答:
Method permissions can be specified on the class, the business methods of the class, or both. Method permissions can be specified on a method of the bean class to override the method permissions value specified on the entire bean class. The following annotations are used to specify method permissions:

@DeclareRoles: Specifies all the roles that the application will use, including roles not specifically named in a @RolesAllowed annotation. The set of security roles the application uses is the total of the security roles defined in the @DeclareRoles and @RolesAllowed annotations.

The @DeclareRoles annotation is specified on a bean class, where it serves to declare roles that can be tested (for example, by calling isCallerInRole) from within the methods of the annotated class. When declaring the name of a role used as a parameter to the isCallerInRole(String roleName) method, the declared name must be the same as the parameter value.

The following example code demonstrates the use of the @DeclareRoles annotation:

```<code>@DeclareRoles("BusinessAdmin")
public class Calculator {
    ...
}
</code>```

The syntax for declaring more than one role is as shown in the following example:

```<code>@DeclareRoles({"Administrator", "Manager", "Employee"})
</code>```

@RolesAllowed("list-of-roles"): Specifies the security roles permitted to access methods in an application. This annotation can be specified on a class or on one or more methods. When specified at the class level, the annotation applies to all methods in the class. When specified on a method, the annotation applies to that method only and overrides any values specified at the class level.

To specify that no roles are authorized to access methods in an application, use the @DenyAll annotation. To specify that a user in any role is authorized to access the application, use the @PermitAll annotation.

When used in conjunction with the @DeclareRoles annotation, the combined set of security roles is used by the application.

The following example code demonstrates the use of the @RolesAllowed annotation:

```<code>@DeclareRoles({"Administrator", "Manager", "Employee"})
public class Calculator {

    @RolesAllowed("Administrator")
    public void setNewRate(int rate) {
        ...
    }
}
</code>```

@PermitAll: Specifies that all security roles are permitted to execute the specified method or methods. The user is not checked against a database to ensure that he or she is authorized to access this application.

This annotation can be specified on a class or on one or more methods. Specifying this annotation on the class means that it applies to all methods of the class. Specifying it at the method level means that it applies to only that method.

The following example code demonstrates the use of the @PermitAll annotation:

```<code>import javax.annotation.security.*;
@RolesAllowed("RestrictedUsers")
public class Calculator {

    @RolesAllowed("Administrator")
    public void setNewRate(int rate) {
        //...
    }
    @PermitAll
    public long convertCurrency(long amount) {
        //...
    }
}
</code>```

@DenyAll: Specifies that no security roles are permitted to execute the specified method or methods. This means that these methods are excluded from execution in the Java EE container.

The following example code demonstrates the use of the @DenyAll annotation:

```<code>import javax.annotation.security.*;
@RolesAllowed("Users")
public class Calculator {
    @RolesAllowed("Administrator")
    public void setNewRate(int rate) {
        //...
    }
    @DenyAll
    public long convertCurrency(long amount) {
        //...
    }
}
</code>```

The following code snippet demonstrates the use of the @DeclareRoles annotation with the isCallerInRole method. In this example, the @DeclareRoles annotation declares a role that the enterprise bean PayrollBean uses to make the security check by using isCallerInRole("payroll") to verify that the caller is authorized to change salary data:

```<code>@DeclareRoles("payroll")
@Stateless
public class PayrollBean implements Payroll {

    @Resource SessionContext ctx;

    public void updateEmployeeInfo(EmplInfo info) {

        oldInfo = ... read from database;

        // The salary field can be changed only by callers
        // who have the security role "payroll"
        Principal callerPrincipal = ctx.getCallerPrincipal();
        if (info.salary != oldInfo.salary && !ctx.isCallerInRole("payroll")) {
            throw new SecurityException(...);
        }
        ...
    }
    ...
}
</code>```

The following example code illustrates the use of the @RolesAllowed annotation:

```<code>@RolesAllowed("admin")
public class SomeClass {
    public void aMethod () {...}
    public void bMethod () {...}
    ...
}

@Stateless
public class MyBean extends SomeClass implements A  {

    @RolesAllowed("HR")
    public void aMethod () {...}

    public void cMethod () {...}
    ...
}
</code>```

More information:

Securing Enterprise Beans

Title: Where do I have to put @DeclareRoles?

Body:
Method permissions can be specified on the class, the business methods of the class, or both. Method permissions can be specified on a method of the bean class to override the method permissions value specified on the entire bean class. The following annotations are used to specify method permissions:

@DeclareRoles: Specifies all the roles that the application will use, including roles not specifically named in a @RolesAllowed annotation. The set of security roles the application uses is the total of the security roles defined in the @DeclareRoles and @RolesAllowed annotations.

The @DeclareRoles annotation is specified on a bean class, where it serves to declare roles that can be tested (for example, by calling isCallerInRole) from within the methods of the annotated class. When declaring the name of a role used as a parameter to the isCallerInRole(String roleName) method, the declared name must be the same as the parameter value.

The following example code demonstrates the use of the @DeclareRoles annotation:

@DeclareRoles("BusinessAdmin")
public class Calculator {
    ...
}

The syntax for declaring more than one role is as shown in the following example:

@DeclareRoles({"Administrator", "Manager", "Employee"})

@RolesAllowed("list-of-roles"): Specifies the security roles permitted to access methods in an application. This annotation can be specified on a class or on one or more methods. When specified at the class level, the annotation applies to all methods in the class. When specified on a method, the annotation applies to that method only and overrides any values specified at the class level.

To specify that no roles are authorized to access methods in an application, use the @DenyAll annotation. To specify that a user in any role is authorized to access the application, use the @PermitAll annotation.

When used in conjunction with the @DeclareRoles annotation, the combined set of security roles is used by the application.

The following example code demonstrates the use of the @RolesAllowed annotation:

@DeclareRoles({"Administrator", "Manager", "Employee"})
public class Calculator {

    @RolesAllowed("Administrator")
    public void setNewRate(int rate) {
        ...
    }
}

@PermitAll: Specifies that all security roles are permitted to execute the specified method or methods. The user is not checked against a database to ensure that he or she is authorized to access this application.

This annotation can be specified on a class or on one or more methods. Specifying this annotation on the class means that it applies to all methods of the class. Specifying it at the method level means that it applies to only that method.

The following example code demonstrates the use of the @PermitAll annotation:

import javax.annotation.security.*;
@RolesAllowed("RestrictedUsers")
public class Calculator {

    @RolesAllowed("Administrator")
    public void setNewRate(int rate) {
        //...
    }
    @PermitAll
    public long convertCurrency(long amount) {
        //...
    }
}

@DenyAll: Specifies that no security roles are permitted to execute the specified method or methods. This means that these methods are excluded from execution in the Java EE container.

The following example code demonstrates the use of the @DenyAll annotation:

import javax.annotation.security.*;
@RolesAllowed("Users")
public class Calculator {
    @RolesAllowed("Administrator")
    public void setNewRate(int rate) {
        //...
    }
    @DenyAll
    public long convertCurrency(long amount) {
        //...
    }
}

The following code snippet demonstrates the use of the @DeclareRoles annotation with the isCallerInRole method. In this example, the @DeclareRoles annotation declares a role that the enterprise bean PayrollBean uses to make the security check by using isCallerInRole("payroll") to verify that the caller is authorized to change salary data:

@DeclareRoles("payroll")
@Stateless
public class PayrollBean implements Payroll {

    @Resource SessionContext ctx;

    public void updateEmployeeInfo(EmplInfo info) {

        oldInfo = ... read from database;

        // The salary field can be changed only by callers
        // who have the security role "payroll"
        Principal callerPrincipal = ctx.getCallerPrincipal();
        if (info.salary != oldInfo.salary && !ctx.isCallerInRole("payroll")) {
            throw new SecurityException(...);
        }
        ...
    }
    ...
}

The following example code illustrates the use of the @RolesAllowed annotation:

@RolesAllowed("admin")
public class SomeClass {
    public void aMethod () {...}
    public void bMethod () {...}
    ...
}

@Stateless
public class MyBean extends SomeClass implements A  {

    @RolesAllowed("HR")
    public void aMethod () {...}

    public void cMethod () {...}
    ...
}

More information:

Securing Enterprise Beans


问:
VueJS - jest: How to test/spy the methods which are getting called inside the watcher?
Sample Code from the VueJs components. Note that I'm trying to cover the watcher as well as the method</p>

```<code>computed: {
              ...mapGetters({
               resourceLinks: `tools/${storeGetters.resourceLinks}`,
            }),
        },
        methods: {
              formatData(data) {
                this.setSocialLinks();
            },
        },
    },
        watch: {
            resourceLinks(data) {
                this.formatData(data);
            },
        },
</code>```

Body:
Sample Code from the VueJs components. Note that I'm trying to cover the watcher as well as the method

computed: {
              ...mapGetters({
               resourceLinks: `tools/${storeGetters.resourceLinks}`,
            }),
        },
        methods: {
              formatData(data) {
                this.setSocialLinks();
            },
        },
    },
        watch: {
            resourceLinks(data) {
                this.formatData(data);
            },
        },

Body: expect(wrapper.vm.$options.watch.resourceLinks.call(wrapper.vm, resourceLinks1));


问:
JavaScript get clipboard plain text with enter data on paste event (Cross browser)
How can a web application detect a paste event and retrieve the data to be pasted?

I would like to remove all HTML tags, CSS and other things except plain text and enter.

It will also work in all major browser like Google Chrome, Firefox, IE, Edge, Safari, Opera etc.

```<code><div placeholder="Share Something ?" contenteditable="true" id="post"></div>

if (document.querySelector('#post[contenteditable]')) {
    document.querySelector('#post[contenteditable]').addEventListener("paste", function(e) {
      e.preventDefault();
      var text = e.clipboardData.getData("text");
      document.execCommand("insertHTML", false, text);
    });
}
</code>```

答:
$("#inputText").bind("paste", function(e){
    var pastedData = e.originalEvent.clipboardData.getData('text');
    var regex = /^[a-zA-Z0-9@]+$/;
   if (regex.test(pastedData) !== true) {
      alert("You can enter only plain text");
        setTimeout(function(){
         $("#inputText").html('');
        },100)
    } else {
      alert("Valid text");
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#inputText {
  border:1px solid #000;
}</code>```

```

You can bind paste event on the input text box. For plain text, you have to use a regular expression to validate the text.

Body:
How can a web application detect a paste event and retrieve the data to be pasted?

I would like to remove all HTML tags, CSS and other things except plain text and enter.

It will also work in all major browser like Google Chrome, Firefox, IE, Edge, Safari, Opera etc.

if (document.querySelector('#post[contenteditable]')) {
    document.querySelector('#post[contenteditable]').addEventListener("paste", function(e) {
      e.preventDefault();
      var text = e.clipboardData.getData("text");
      document.execCommand("insertHTML", false, text);
    });
}

Body:
$("#inputText").bind("paste", function(e){
    var pastedData = e.originalEvent.clipboardData.getData('text');
    var regex = /^[a-zA-Z0-9@]+$/;
   if (regex.test(pastedData) !== true) {
      alert("You can enter only plain text");
        setTimeout(function(){
         $("#inputText").html('');
        },100)
    } else {
      alert("Valid text");
    }
});

#inputText {
  border:1px solid #000;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div placeholder="Share Something ?" id="inputText" contenteditable="true"></div>

You can bind paste event on the input text box. For plain text, you have to use a regular expression to validate the text.


问:
Integrity Error when trying to upload to MySQL DB in python
I have this code which currently lets me update a school's data in mySQL database, if the id already exists. However, what I am also trying to achieve, is that if the ID doesn't exist in the DB, it inserts those values. Here is the code I've got so far:

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/dbName'
db = SQLAlchemy(app)

class Example(db.Model):
    __tablename__ = 'schools'
    _id = db.Column('_id', db.Unicode, primary_key=True)
    establishmentNumber = db.Column('establishmentNumber', db.Unicode)

    def __init__(self, id, establishmentNumber):
        self.id = id
        self.establishmentNumber = establishmentNumber

update_this = Example.query.filter_by(_id=school._id.iloc[0]).first()

update_this.establishmentNumber = 'bob'
db.session.commit()

examples = Example.query.all()
examples

for ex in examples:
    print (ex.establishmentNumber)
</code>```

This will update correctly, however, when I try to add a completely new school to the db, with this code:

```<code>new_ex = Example('5c12345scl', 'fifth')
db.session.add(new_ex)
db.session.commit()
</code>```

I get this error:

```<code>IntegrityError: (MySQLdb._exceptions.IntegrityError) (1364, "Field '_id' doesn't have a default value")
[SQL: INSERT INTO schools (`establishmentNumber`) VALUES (%s)]
[parameters: ('fifth',)]
(Background on this error at: http://sqlalche.me/e/gkpj)
</code>```

Does anyone know how to get rid of this error?

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
UPDATE
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

The above is working now. I am now trying to combine the add and update functions so that it checks if the id exists in the table. If not, it inserts a new row. If it does, then it just updates the values. Below is my code so far, thanks to @James Summers:

```<code>class Example(db.Model):
    __tablename__ = 'schools'
    _id = db.Column('_id', db.Unicode, primary_key=True)
    establishmentNumber = db.Column('establishmentNumber', db.Unicode)
    laCode = db.Column('laCode', db.Unicode)
    urn = db.Column('urn', db.Unicode)
    name = db.Column('name', db.Unicode)
    phaseOfEducation = db.Column('phaseOfEducation', db.Unicode)
    wondeID = db.Column('wondeID', db.Unicode)

    def __init__(self, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
        self._id = _id
        self.establishmentNumber = establishmentNumber
        self.laCode = laCode
        self.urn = urn
        self.name = name
        self.phaseOfEducation = phaseOfEducation
        self.wondeID = wondeID

        def add_or_update(self, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
            update_this = Example.query.filter_by(_id=school._id.iloc[0]).first()

            if not update_this:
                new_ex = Example(school._id.iloc[0], school.establishmentNumber.iloc[0], school.laCode.iloc[0], school.urn.iloc[0], school.name.iloc[0], school.phaseOfEducation.iloc[0], school.wondeID.iloc[0])
                db.session.add(new_ex)
                db.session.commit()

            else:
                update_this.establishmentNumber = 'hello'
                db.session.commit()

            return new_ex
</code>```

It is not producing any errors, but it's not adding or updating either. Can anyone see what I've done wrong?

答:
Thanks to @Akina's comments. I realised the problem was with this function's code:

```<code>def __init__(self, id, establishmentNumber):
    self.id = id
    self.establishmentNumber = establishmentNumber
</code>```

I had written the id without the underscore, so this is the fixed version:

```<code>def __init__(self, _id, establishmentNumber):
    self._id = _id
    self.establishmentNumber = establishmentNumber
</code>```

Body:
I have this code which currently lets me update a school's data in mySQL database, if the id already exists. However, what I am also trying to achieve, is that if the ID doesn't exist in the DB, it inserts those values. Here is the code I've got so far:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/dbName'
db = SQLAlchemy(app)

class Example(db.Model):
    __tablename__ = 'schools'
    _id = db.Column('_id', db.Unicode, primary_key=True)
    establishmentNumber = db.Column('establishmentNumber', db.Unicode)

    def __init__(self, id, establishmentNumber):
        self.id = id
        self.establishmentNumber = establishmentNumber

update_this = Example.query.filter_by(_id=school._id.iloc[0]).first()

update_this.establishmentNumber = 'bob'
db.session.commit()

examples = Example.query.all()
examples

for ex in examples:
    print (ex.establishmentNumber)

This will update correctly, however, when I try to add a completely new school to the db, with this code:

new_ex = Example('5c12345scl', 'fifth')
db.session.add(new_ex)
db.session.commit()

I get this error:

IntegrityError: (MySQLdb._exceptions.IntegrityError) (1364, "Field '_id' doesn't have a default value")
[SQL: INSERT INTO schools (`establishmentNumber`) VALUES (%s)]
[parameters: ('fifth',)]
(Background on this error at: http://sqlalche.me/e/gkpj)

Does anyone know how to get rid of this error?

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
UPDATE
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

The above is working now. I am now trying to combine the add and update functions so that it checks if the id exists in the table. If not, it inserts a new row. If it does, then it just updates the values. Below is my code so far, thanks to @James Summers:

class Example(db.Model):
    __tablename__ = 'schools'
    _id = db.Column('_id', db.Unicode, primary_key=True)
    establishmentNumber = db.Column('establishmentNumber', db.Unicode)
    laCode = db.Column('laCode', db.Unicode)
    urn = db.Column('urn', db.Unicode)
    name = db.Column('name', db.Unicode)
    phaseOfEducation = db.Column('phaseOfEducation', db.Unicode)
    wondeID = db.Column('wondeID', db.Unicode)

    def __init__(self, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
        self._id = _id
        self.establishmentNumber = establishmentNumber
        self.laCode = laCode
        self.urn = urn
        self.name = name
        self.phaseOfEducation = phaseOfEducation
        self.wondeID = wondeID

        def add_or_update(self, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
            update_this = Example.query.filter_by(_id=school._id.iloc[0]).first()

            if not update_this:
                new_ex = Example(school._id.iloc[0], school.establishmentNumber.iloc[0], school.laCode.iloc[0], school.urn.iloc[0], school.name.iloc[0], school.phaseOfEducation.iloc[0], school.wondeID.iloc[0])
                db.session.add(new_ex)
                db.session.commit()

            else:
                update_this.establishmentNumber = 'hello'
                db.session.commit()

            return new_ex

It is not producing any errors, but it's not adding or updating either. Can anyone see what I've done wrong?

Body:
Thanks to @Akina's comments. I realised the problem was with this function's code:

def __init__(self, id, establishmentNumber):
    self.id = id
    self.establishmentNumber = establishmentNumber

I had written the id without the underscore, so this is the fixed version:

def __init__(self, _id, establishmentNumber):
    self._id = _id
    self.establishmentNumber = establishmentNumber


答:
Try /^[0-9]/ as the regular expression.

If it only needs to start with a number, I'd only check that...

Title: Javascript regex to check if a value begins with a number followed by anything else


问:
Flutter - change color on another button tap
I have 5x5 grid of 5xTableRow -> 5xFittedBox. With the tap on the top right button, I want it to shuffle colors that are described in an array (see image).

I tried with the "OnChanged" and "onPressed", but the problem is I don't know how to access each element individually

I read that I should use "setState" function to force flutter to redraw certain elements, but the problem is where do I put said function?

Also is there an easy way to give widgets and children some kind of identifier (for example class = "something" or id = "something")
The point of that is that I want to use for loop to recolor all 25 boxes, and after that I want to store those 25 boxes in an array to use for later condition checking.

```<code>var colorArr = [0xffd61745, 0xff3569bc, 0xffffffff, 0xfff4862a, 0xffeaed19, 0xff329f64,
0xff000000];
//playArr is used to store values from 0-5 which corresponds each color => colorArr[playArr[n]]
var playArr = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
void shuffleBox() {
  for (var i = 0; i<playArr.length;i++) {
    playArr[i] = new Random().nextInt(6);
    print(playArr[i]);
  }
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      centerTitle: true,
      title: Container(
        child: Text(
          'Table Widget',
          style: TextStyle(
            fontSize: 20.0,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      actions: <Widget>[
        IconButton(
          icon: Icon(Icons.shuffle),
          onPressed: shuffleBox,
        ),
      ],
    ),
    body: SingleChildScrollView(
      padding: EdgeInsets.only(top: 12),
      child: Table(
        border: null,
        defaultVerticalAlignment: TableCellVerticalAlignment.top,
        children: <TableRow>[
          TableRow(children: <Widget>[
            //this is what i want recolored and/or redrawn
            FittedBox(
              fit: BoxFit.contain,
              child: Container(
                margin: EdgeInsets.all(2),
                color: Color(a),
                width: 48.0,
                height: 48.0,
              ),
            ),
            FittedBox -> repeated 5x, then TableRow again
</code>```

答:
This the working solution

```<code>final colorArr = [0xffd61745, 0xff3569bc, 0xffffffff, 0xfff4862a, 0xffeaed19, 0xff329f64,
0xff000000];
//playArr is used to store values from 0-5 which corresponds each color => colorArr[playArr[n]]
var playArr = [];

  @override
 void  initState(){
   _genereateList();
   super.initState();
 }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: [
          IconButton(icon: Icon(Icons.shuffle),onPressed: _shuffle,)
        ]
      ),
      body: Center(
        child : GridView.builder(
          itemCount: 25,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 5),
          itemBuilder : (ctx, index)=>Card(
            child: Text(playArr[index].toString()),
            color: Color(colorArr[playArr[index]])
          )
        )
      ),
    );
  }

  _genereateList(){
    playArr = List.generate(25,(int index)=>Random().nextInt(colorArr.length-1));
    setState((){});
  }
  _shuffle(){
     playArr.shuffle(Random());
    setState((){});
  }
</code>```

EDIT: if you want to update a cell just change his value.
Let say you want to change item at 3rd Column 5th raw

```<code>update(int index){
setState((){
playArr[index] = 3; //Index of the new color you want to switch to
});
}
</code>```

Then simply call it like this

```<code>update(22); //3rd Column 5th raw
</code>```

Body:
I have 5x5 grid of 5xTableRow -> 5xFittedBox. With the tap on the top right button, I want it to shuffle colors that are described in an array (see image).

I tried with the "OnChanged" and "onPressed", but the problem is I don't know how to access each element individually

I read that I should use "setState" function to force flutter to redraw certain elements, but the problem is where do I put said function?

Also is there an easy way to give widgets and children some kind of identifier (for example class = "something" or id = "something")
The point of that is that I want to use for loop to recolor all 25 boxes, and after that I want to store those 25 boxes in an array to use for later condition checking.

var colorArr = [0xffd61745, 0xff3569bc, 0xffffffff, 0xfff4862a, 0xffeaed19, 0xff329f64,
0xff000000];
//playArr is used to store values from 0-5 which corresponds each color => colorArr[playArr[n]]
var playArr = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
void shuffleBox() {
  for (var i = 0; i<playArr.length;i++) {
    playArr[i] = new Random().nextInt(6);
    print(playArr[i]);
  }
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      centerTitle: true,
      title: Container(
        child: Text(
          'Table Widget',
          style: TextStyle(
            fontSize: 20.0,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      actions: <Widget>[
        IconButton(
          icon: Icon(Icons.shuffle),
          onPressed: shuffleBox,
        ),
      ],
    ),
    body: SingleChildScrollView(
      padding: EdgeInsets.only(top: 12),
      child: Table(
        border: null,
        defaultVerticalAlignment: TableCellVerticalAlignment.top,
        children: <TableRow>[
          TableRow(children: <Widget>[
            //this is what i want recolored and/or redrawn
            FittedBox(
              fit: BoxFit.contain,
              child: Container(
                margin: EdgeInsets.all(2),
                color: Color(a),
                width: 48.0,
                height: 48.0,
              ),
            ),
            FittedBox -> repeated 5x, then TableRow again

Body:
This the working solution

final colorArr = [0xffd61745, 0xff3569bc, 0xffffffff, 0xfff4862a, 0xffeaed19, 0xff329f64,
0xff000000];
//playArr is used to store values from 0-5 which corresponds each color => colorArr[playArr[n]]
var playArr = [];

  @override
 void  initState(){
   _genereateList();
   super.initState();
 }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: [
          IconButton(icon: Icon(Icons.shuffle),onPressed: _shuffle,)
        ]
      ),
      body: Center(
        child : GridView.builder(
          itemCount: 25,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 5),
          itemBuilder : (ctx, index)=>Card(
            child: Text(playArr[index].toString()),
            color: Color(colorArr[playArr[index]])
          )
        )
      ),
    );
  }

  _genereateList(){
    playArr = List.generate(25,(int index)=>Random().nextInt(colorArr.length-1));
    setState((){});
  }
  _shuffle(){
     playArr.shuffle(Random());
    setState((){});
  }

EDIT: if you want to update a cell just change his value.
Let say you want to change item at 3rd Column 5th raw

update(int index){
setState((){
playArr[index] = 3; //Index of the new color you want to switch to
});
}

Then simply call it like this

update(22); //3rd Column 5th raw


问:
Ajax got 500 Internal Server Error when using json_encode()
I had tried to use a simple Ajax request with JS and PHP. My code:

test.js

```<code>$(document).ready(function () {
    $.ajax({
        url: window.location.href + 'test.php',
        type: 'GET',
        data: { 'testing': 'hey' },
        success: function (data) {
            console.log(data);
        },
        error: function (xhr, desc, err) {
            console.log(xhr);
            console.log('Details: ' + desc + '\nError: ' + err);
        }
    });

});
</code>```

test.php

```<code><?php
include('../db.php');
header('Content-Type: application/json');

$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";

$json = json_encode($myObj);

echo $json;
</code>```

index.php

```<code><?php
include('db.php');

// ...
?>
<script src="./webroot/test.js" type="text/javascript"></script>
</code>```

However, it produced a 500 error. I have tested with both Ajax post and Ajax get and got the same result. However, if I didn't use json_encode and just echo out instead, the error disappears and I could see the message on the console.

test2.php

```<code><?php
include('../db.php');

echo "this thing will work even though I didn't need";
</code>```

I have checked the php error_log, got nothing. Add "header('Access-Control-Allow-Origin: *');", still the same. Echo json_last_error(), no response to even see the error.

The console:

At this rate, I would be unable to use any JS-library.
Any help would be really appreciated.

Edit: the $ before json_encode() is actually a typo I wrote while asking question. My current code didn't have it and still got 500.
Edit2: Another typo. My current code did close tag properly.

答:
you getting error 500 because of wrong syntax in your php file
test.php

update the code of test.php with below code

```<code> <?php
  include('../db.php');
    header('Content-Type: application/json');
    $myObj = array();
    $myObj['name'] = "John";
    $myObj['age'] = 30;
    $myObj['city'] = "New York";
    $json = json_encode($myObj);
    echo $json;
</code>```

and I don't know that you are using some framework because you are not closing your PHP end tag end of file ?> make sure to clear this as well.

Body:
I had tried to use a simple Ajax request with JS and PHP. My code:

test.js

$(document).ready(function () {
    $.ajax({
        url: window.location.href + 'test.php',
        type: 'GET',
        data: { 'testing': 'hey' },
        success: function (data) {
            console.log(data);
        },
        error: function (xhr, desc, err) {
            console.log(xhr);
            console.log('Details: ' + desc + '\nError: ' + err);
        }
    });

});

test.php

<?php
include('../db.php');
header('Content-Type: application/json');

$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";

$json = json_encode($myObj);

echo $json;

index.php

<?php
include('db.php');

// ...
?>

However, it produced a 500 error. I have tested with both Ajax post and Ajax get and got the same result. However, if I didn't use json_encode and just echo out instead, the error disappears and I could see the message on the console.

test2.php

<?php
include('../db.php');

echo "this thing will work even though I didn't need";

I have checked the php error_log, got nothing. Add "header('Access-Control-Allow-Origin: *');", still the same. Echo json_last_error(), no response to even see the error.

The console:

At this rate, I would be unable to use any JS-library.
Any help would be really appreciated.

Edit: the $ before json_encode() is actually a typo I wrote while asking question. My current code didn't have it and still got 500.
Edit2: Another typo. My current code did close tag properly.

Body:
you getting error 500 because of wrong syntax in your php file
test.php

update the code of test.php with below code

 <?php
  include('../db.php');
    header('Content-Type: application/json');
    $myObj = array();
    $myObj['name'] = "John";
    $myObj['age'] = 30;
    $myObj['city'] = "New York";
    $json = json_encode($myObj);
    echo $json;

and I don't know that you are using some framework because you are not closing your PHP end tag end of file ?> make sure to clear this as well.


问:
.NET Charting - Series Template

The Mission: Apply a generic template to chart series.

My Template File:

```<code><Chart BackColor="211, 223, 240" Width="250" Height="100" BackGradientStyle="TopBottom" BackSecondaryColor="Blue" BorderColor="26, 59, 105" BorderWidth="2">
  <Series>
    <series _Template_="All" Color="Black" BorderColor="180, 26, 59, 105">
    </series>
  </Series>
</Chart>
</code>```

The styles applied to "Chart" work just fine.  However, nothing applied to the Series template works; it merely contains the default styling.

My function that returns the chart image:

```<code>    private FileContentResult ImageCall(string config)
    {
        System.Web.UI.DataVisualization.Charting.Chart chart = new System.Web.UI.DataVisualization.Charting.Chart();

        if (config.Length > 0)
        {
            chart.Serializer.IsTemplateMode = true;
            chart.Serializer.IsResetWhenLoading = false;
            chart.Serializer.SerializableContent = "*.*";
            chart.Serializer.Load(config);
        }

        Series s2 = new Series("Series1");
        s2.ChartArea = "Area1";
        s2.ChartType = SeriesChartType.Column;
        s2.Points.Add(new DataPoint
        {
            AxisLabel = "Value1",
            YValues = new double[] { 1 }
        });
        s2.Points.Add(new DataPoint
        {
            AxisLabel = "Value2",
            YValues = new double[] { 2 }
        });
        chart.Series.Add(s2);

        ChartArea ca1 = new ChartArea("Area1");
        chart.ChartAreas.Add(ca1);

        using (var ms = new MemoryStream())
        {
            chart.SaveImage(ms, ChartImageFormat.Png);
            ms.Seek(0, SeekOrigin.Begin);

            return File(ms.ToArray(), "image/png", "mychart.png");
        }
    }
</code>```

Here's what it looks like (crappy, I know... it's merely illustrative):

Note that the bars are unstyled while the chart seems to style just fine.

The documentation regarding built-in .NET charting is woefully thin.  Can anyone help me get my generic templates to work?  There's a big green check mark in it for you!

I'm probably missing something obvious.  Thanks!

答:
Sigh

So the fix, like I thought, was simple.  Let the world know that templates can only be applied to object on the chart after they are added to the chart.  You cannot pre-set the styles then add the series, you need to add the series then set the style.

Here's the updated code:

```<code>private FileContentResult ImageCall(string config)
{
    System.Web.UI.DataVisualization.Charting.Chart chart = new System.Web.UI.DataVisualization.Charting.Chart();

    Series s2 = new Series("Series1");
    s2.ChartArea = "Area1";
    s2.ChartType = SeriesChartType.Column;
    s2.Points.Add(new DataPoint
    {
        AxisLabel = "Value1",
        YValues = new double[] { 1 }
    });
    s2.Points.Add(new DataPoint
    {
        AxisLabel = "Value2",
        YValues = new double[] { 2 }
    });
    chart.Series.Add(s2);

    ChartArea ca1 = new ChartArea("Area1");
    chart.ChartAreas.Add(ca1);

            //REPOSITIONED
    if (config.Length > 0)
    {
        chart.Serializer.IsTemplateMode = true;
        chart.Serializer.IsResetWhenLoading = false;
        chart.Serializer.SerializableContent = "*.*";
        chart.Serializer.Load(config);
    }

    using (var ms = new MemoryStream())
    {
        chart.SaveImage(ms, ChartImageFormat.Png);
        ms.Seek(0, SeekOrigin.Begin);

        return File(ms.ToArray(), "image/png", "mychart.png");
    }
}
</code>```

Title: .NET Charting - Series Template

Body:
The Mission: Apply a generic template to chart series.

My Template File:

<Chart BackColor="211, 223, 240" Width="250" Height="100" BackGradientStyle="TopBottom" BackSecondaryColor="Blue" BorderColor="26, 59, 105" BorderWidth="2">
  <Series>
    <series _Template_="All" Color="Black" BorderColor="180, 26, 59, 105">
    </series>
  </Series>
</Chart>

The styles applied to "Chart" work just fine.  However, nothing applied to the Series template works; it merely contains the default styling.

My function that returns the chart image:

    private FileContentResult ImageCall(string config)
    {
        System.Web.UI.DataVisualization.Charting.Chart chart = new System.Web.UI.DataVisualization.Charting.Chart();

        if (config.Length > 0)
        {
            chart.Serializer.IsTemplateMode = true;
            chart.Serializer.IsResetWhenLoading = false;
            chart.Serializer.SerializableContent = "*.*";
            chart.Serializer.Load(config);
        }

        Series s2 = new Series("Series1");
        s2.ChartArea = "Area1";
        s2.ChartType = SeriesChartType.Column;
        s2.Points.Add(new DataPoint
        {
            AxisLabel = "Value1",
            YValues = new double[] { 1 }
        });
        s2.Points.Add(new DataPoint
        {
            AxisLabel = "Value2",
            YValues = new double[] { 2 }
        });
        chart.Series.Add(s2);

        ChartArea ca1 = new ChartArea("Area1");
        chart.ChartAreas.Add(ca1);

        using (var ms = new MemoryStream())
        {
            chart.SaveImage(ms, ChartImageFormat.Png);
            ms.Seek(0, SeekOrigin.Begin);

            return File(ms.ToArray(), "image/png", "mychart.png");
        }
    }

Here's what it looks like (crappy, I know... it's merely illustrative):

Note that the bars are unstyled while the chart seems to style just fine.

The documentation regarding built-in .NET charting is woefully thin.  Can anyone help me get my generic templates to work?  There's a big green check mark in it for you!

I'm probably missing something obvious.  Thanks!

Body:
Sigh

So the fix, like I thought, was simple.  Let the world know that templates can only be applied to object on the chart after they are added to the chart.  You cannot pre-set the styles then add the series, you need to add the series then set the style.

Here's the updated code:

private FileContentResult ImageCall(string config)
{
    System.Web.UI.DataVisualization.Charting.Chart chart = new System.Web.UI.DataVisualization.Charting.Chart();

    Series s2 = new Series("Series1");
    s2.ChartArea = "Area1";
    s2.ChartType = SeriesChartType.Column;
    s2.Points.Add(new DataPoint
    {
        AxisLabel = "Value1",
        YValues = new double[] { 1 }
    });
    s2.Points.Add(new DataPoint
    {
        AxisLabel = "Value2",
        YValues = new double[] { 2 }
    });
    chart.Series.Add(s2);

    ChartArea ca1 = new ChartArea("Area1");
    chart.ChartAreas.Add(ca1);

            //REPOSITIONED
    if (config.Length > 0)
    {
        chart.Serializer.IsTemplateMode = true;
        chart.Serializer.IsResetWhenLoading = false;
        chart.Serializer.SerializableContent = "*.*";
        chart.Serializer.Load(config);
    }

    using (var ms = new MemoryStream())
    {
        chart.SaveImage(ms, ChartImageFormat.Png);
        ms.Seek(0, SeekOrigin.Begin);

        return File(ms.ToArray(), "image/png", "mychart.png");
    }
}


问:
"ComponentDidMount" hook triggers memory-leaks if i'm requesting data from the server
I'm slowly trying to remove "Redux" from my workflow, lets say part of components receives required data from the server, when they are be rendered on the screen (in ComponentDidMounth hook), rendering of that components controlled by html5 history router,so if the user starts jumping quickly between routes, in the console comes memory lick warning

can you please tell me some smart way how to fix it. thanks ))

also please show examples with latest react api (HOOKS)

```<code>const Posts = () => {

    const [posts,setPosts] = useState([]);

    useEffect(() => {
        getPosts()
            .then(posts => setPosts(posts))
    },[])

    return (
        <div>
            {/* rendering of posts */}
        </div>
    )
}

const Personal = () => {

    const [profileInfo,setProfileInfo] = useState({});

    useEffect(() => {
        getProfileInfo()
            .then(profileInfo => setProfileInfo(profileInfo))
    },[])

    return (
        <div>
            {/* rendering of personal info.... */}
        </div>
    )
}

const Content = () => {

    return (
        <div className="Content">
            <Switch>
                <Route path="/posts" component={Posts} />
                <Route path="/personal" component={Personal} />
            </Switch>
        </div>
    )
}
</code>```

another Component called sidebar controlls navigation between this components

答:
So there are a couple of ways you could use for your situation and i have listed them starting with the simplest option.

The first option allows the browser to complete the request but only updates the state with response from the latest request;

useEffect(() => {
        let cancelled = false;

        function fetchData() {
            fetch(url).then(response => response.json())
               .then(result => {
                  if(!cancelled){
                    setData(result)
                }
            });
        }

        fetchData();

        return () => {
            cancelled = true;
        };

    }, [your deps])

```

<ol start="2">
<li><strong>Ignoring responses from former api calls</strong>
You might also want to ignore responses from former api calls.</li>
</ol>

<pre class="lang-js prettyprint-override"><code>
// A ref to store the last issued pending request
const lastPromise = useRef();

useEffect(() => {

   function fetchData(){
      const currentPromise = fetch(url)
        .then(response => response);

       // store the promise to the ref
       lastPromise.current = currentPromise;

       // handle the result with filtering
       currentPromise.then(result => {
           if (currentPromise === lastPromise.current) {
            setData(result);
           }
       });
   }

  // fire the api request
  fetchData();

}, [your deps]);

</code>```

Cancelling and ignoring
Sometimes it is better to cancel former api requests in-flight: the browser can avoid parsing the response and prevent some useless CPU/Network usage. fetch and axios support cancellation using AbortSignal:

```<code>
useEffect(() => {
  // Create the current request's abort controller
  const abortController = new AbortController();

  function fetchData(){
   fetch(url, { signal: abortController.signal })
    .then(data => data)
    // Set the result, if not aborted
    .then(
      result => {
        // IMPORTANT: we still need to filter the results here,
        // in case abortion happens during the delay.
        // In real apps, abortion could happen when you are parsing the json,
        // with code like "fetch().then(res => res.json())"
        // but also any other async then() you execute after the fetch
        if (abortController.signal.aborted) {
          return;
        }
        setState(newState);
      },
    );
  }

  fetchData();

  // Trigger the abortion in useEffect's cleanup function
  return () => {
    abortController.abort();
  };
}, [your deps]);

</code>```

So you can just chose what suits your use case. Hope that helped.

Body:
I'm slowly trying to remove "Redux" from my workflow, lets say part of components receives required data from the server, when they are be rendered on the screen (in ComponentDidMounth hook), rendering of that components controlled by html5 history router,so if the user starts jumping quickly between routes, in the console comes memory lick warning

can you please tell me some smart way how to fix it. thanks ))

also please show examples with latest react api (HOOKS)

const Posts = () => {

    const [posts,setPosts] = useState([]);

    useEffect(() => {
        getPosts()
            .then(posts => setPosts(posts))
    },[])

    return (

            {/* rendering of posts */}

    )
}

const Personal = () => {

    const [profileInfo,setProfileInfo] = useState({});

    useEffect(() => {
        getProfileInfo()
            .then(profileInfo => setProfileInfo(profileInfo))
    },[])

    return (

            {/* rendering of personal info.... */}

    )
}

const Content = () => {

    return (

            <Switch>
                <Route path="/posts" component={Posts} />
                <Route path="/personal" component={Personal} />
            </Switch>

    )
}

another Component called sidebar controlls navigation between this components

Body:
So there are a couple of ways you could use for your situation and i have listed them starting with the simplest option.

The first option allows the browser to complete the request but only updates the state with response from the latest request;

useEffect(() => {
        let cancelled = false;

        function fetchData() {
            fetch(url).then(response => response.json())
               .then(result => {
                  if(!cancelled){
                    setData(result)
                }
            });
        }

        fetchData();

        return () => {
            cancelled = true;
        };

    }, [your deps])

Ignoring responses from former api calls
You might also want to ignore responses from former api calls.

// A ref to store the last issued pending request
const lastPromise = useRef();

useEffect(() => {

   function fetchData(){
      const currentPromise = fetch(url)
        .then(response => response);

       // store the promise to the ref
       lastPromise.current = currentPromise;

       // handle the result with filtering
       currentPromise.then(result => {
           if (currentPromise === lastPromise.current) {
            setData(result);
           }
       });
   }

  // fire the api request
  fetchData();

}, [your deps]);

Cancelling and ignoring
Sometimes it is better to cancel former api requests in-flight: the browser can avoid parsing the response and prevent some useless CPU/Network usage. fetch and axios support cancellation using AbortSignal:

useEffect(() => {
  // Create the current request's abort controller
  const abortController = new AbortController();

  function fetchData(){
   fetch(url, { signal: abortController.signal })
    .then(data => data)
    // Set the result, if not aborted
    .then(
      result => {
        // IMPORTANT: we still need to filter the results here,
        // in case abortion happens during the delay.
        // In real apps, abortion could happen when you are parsing the json,
        // with code like "fetch().then(res => res.json())"
        // but also any other async then() you execute after the fetch
        if (abortController.signal.aborted) {
          return;
        }
        setState(newState);
      },
    );
  }

  fetchData();

  // Trigger the abortion in useEffect's cleanup function
  return () => {
    abortController.abort();
  };
}, [your deps]);

So you can just chose what suits your use case. Hope that helped.


答:
PHP has some built-in functions to handle JSON.

Objects in PHP can be converted into JSON by using the PHP function json_encode():

```<code>include('../db.php');
header('Content-Type: application/json');

$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";

$myJSON = json_encode($myObj);

echo $myJSON;
</code>```

Demo

Title: Ajax got 500 Internal Server Error when using json_encode()

Body:
PHP has some built-in functions to handle JSON.

Objects in PHP can be converted into JSON by using the PHP function json_encode():

include('../db.php');
header('Content-Type: application/json');

$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";

$myJSON = json_encode($myObj);

echo $myJSON;

Demo


问:
Under the hood, how does rxjs listen for changes
Since browsers' DOM API works via an event loop and to listen for changes on the dom we register event handlers.

What does RXJS behind the scene implement for subscribers to listen for changes in data.

I could be entirely missing the plot here. (I use them day to day but would like to know under the hood how they work with the DOM APIs).

I understand observer pattern but that is a design abstraction, how the core RXJS operates with the DOM is what I am looking for.

答:
Observables are just functions. They do not provide anything special under the hood, they just offer whatever the Javascript platform, browser or node, offers with a different powerful paradigm. The power of RxJS lays in the rich set of functions and operators which can be composed in transformation pipelines. This is where the magic of Observables comes from.

Consider the following example which wraps the readline function provided by the fs module of Node.

```<code>const readLineObs = (filePath: string): Observable<string> => {
  return Observable.create(
    (observer: Observer<string>): TeardownLogic => {
      const rl = readline.createInterface({
        input: fs.createReadStream(filePath),
        crlfDelay: Infinity
      });

      rl.on("line", (line: string) => {
        observer.next(line);
      });
      rl.on("close", () => {
        observer.complete();
      });
    }
  );
};
</code>```

This code relies on Node apis to do the work of reading a file line by line, but offers the result as an Observable. The advantage is that you can use the Observable operators to process the results, like in the following example

```<code>readLinesObs('my_path_to_file').pipe(
  filter(line => line[0] === 'A'), // take only the lines which start with A
  map((line, i) => i + '_' + line),  // add a line number at the start of the line
  take(10),  // just take the first 10 lines
  // do all other types of transformations you may need
)
</code>```

Body:
Observables are just functions. They do not provide anything special under the hood, they just offer whatever the Javascript platform, browser or node, offers with a different powerful paradigm. The power of RxJS lays in the rich set of functions and operators which can be composed in transformation pipelines. This is where the magic of Observables comes from.

Consider the following example which wraps the readline function provided by the fs module of Node.

const readLineObs = (filePath: string): Observable<string> => {
  return Observable.create(
    (observer: Observer<string>): TeardownLogic => {
      const rl = readline.createInterface({
        input: fs.createReadStream(filePath),
        crlfDelay: Infinity
      });

      rl.on("line", (line: string) => {
        observer.next(line);
      });
      rl.on("close", () => {
        observer.complete();
      });
    }
  );
};

This code relies on Node apis to do the work of reading a file line by line, but offers the result as an Observable. The advantage is that you can use the Observable operators to process the results, like in the following example

readLinesObs('my_path_to_file').pipe(
  filter(line => line[0] === 'A'), // take only the lines which start with A
  map((line, i) => i + '_' + line),  // add a line number at the start of the line
  take(10),  // just take the first 10 lines
  // do all other types of transformations you may need
)


问:
Variables within app.config/web.config
Is it is possible to do something like the following in the app.config or web.config files?

```<code><appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>
</code>```

I then want to access Dir2 in my code by simply saying:

```<code> ConfigurationManager.AppSettings["Dir2"]
</code>```

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

答:
A slightly more complicated, but far more flexible, alternative is to create a class that represents a configuration section.  In your app.config / web.config file, you can have this:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <!-- This section must be the first section within the <configuration> node -->
    <configSections>
        <section name="DirectoryInfo" type="MyProjectNamespace.DirectoryInfoConfigSection, MyProjectAssemblyName" />
    </configSections>

    <DirectoryInfo>
        <Directory MyBaseDir="C:\MyBase" Dir1="Dir1" Dir2="Dir2" />
    </DirectoryInfo>
</configuration>
</code>```

Then, in your .NET code (I'll use C# in my example), you can create two classes like this:

```<code>using System;
using System.Configuration;

namespace MyProjectNamespace {

    public class DirectoryInfoConfigSection : ConfigurationSection {

        [ConfigurationProperty("Directory")]
        public DirectoryConfigElement Directory {
            get {
                return (DirectoryConfigElement)base["Directory"];
            }
    }

    public class DirectoryConfigElement : ConfigurationElement {

        [ConfigurationProperty("MyBaseDir")]
        public String BaseDirectory {
            get {
                return (String)base["MyBaseDir"];
            }
        }

        [ConfigurationProperty("Dir1")]
        public String Directory1 {
            get {
                return (String)base["Dir1"];
            }
        }

        [ConfigurationProperty("Dir2")]
        public String Directory2 {
            get {
                return (String)base["Dir2"];
            }
        }
        // You can make custom properties to combine your directory names.
        public String Directory1Resolved {
            get {
                return System.IO.Path.Combine(BaseDirectory, Directory1);
            }
        }
    }
}
</code>```

Finally, in your program code, you can access your app.config variables, using your new classes, in this manner:

```<code>DirectoryInfoConfigSection config =
  (DirectoryInfoConfigSection)ConfigurationManager.GetSection("DirectoryInfo");
String dir1Path = config.Directory.Directory1Resolved;  // This value will equal "C:\MyBase\Dir1"
</code>```

OwnerDisplayName: DeeStackOverflow

ContentLicense: CC BY-SA 2.5

Title: Variables within app.config/web.config

Body:
Is it is possible to do something like the following in the app.config or web.config files?

<appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>

I then want to access Dir2 in my code by simply saying:

 ConfigurationManager.AppSettings["Dir2"]

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

LastEditorDisplayName: LFSR Consulting

Body:
A slightly more complicated, but far more flexible, alternative is to create a class that represents a configuration section.  In your app.config / web.config file, you can have this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <!-- This section must be the first section within the <configuration> node -->
    <configSections>
        <section name="DirectoryInfo" type="MyProjectNamespace.DirectoryInfoConfigSection, MyProjectAssemblyName" />
    </configSections>

    <DirectoryInfo>
        <Directory MyBaseDir="C:\MyBase" Dir1="Dir1" Dir2="Dir2" />
    </DirectoryInfo>
</configuration>

Then, in your .NET code (I'll use C# in my example), you can create two classes like this:

using System;
using System.Configuration;

namespace MyProjectNamespace {

    public class DirectoryInfoConfigSection : ConfigurationSection {

        [ConfigurationProperty("Directory")]
        public DirectoryConfigElement Directory {
            get {
                return (DirectoryConfigElement)base["Directory"];
            }
    }

    public class DirectoryConfigElement : ConfigurationElement {

        [ConfigurationProperty("MyBaseDir")]
        public String BaseDirectory {
            get {
                return (String)base["MyBaseDir"];
            }
        }

        [ConfigurationProperty("Dir1")]
        public String Directory1 {
            get {
                return (String)base["Dir1"];
            }
        }

        [ConfigurationProperty("Dir2")]
        public String Directory2 {
            get {
                return (String)base["Dir2"];
            }
        }
        // You can make custom properties to combine your directory names.
        public String Directory1Resolved {
            get {
                return System.IO.Path.Combine(BaseDirectory, Directory1);
            }
        }
    }
}

Finally, in your program code, you can access your app.config variables, using your new classes, in this manner:

DirectoryInfoConfigSection config =
  (DirectoryInfoConfigSection)ConfigurationManager.GetSection("DirectoryInfo");
String dir1Path = config.Directory.Directory1Resolved;  // This value will equal "C:\MyBase\Dir1"

OwnerDisplayName: Matt Hamsmith

LastEditorDisplayName: Matt Hamsmith


问:
CakePHP Forgot Password / Ticket component help
I'm using the following tutorial to build a password reset form: http://bakery.cakephp.org/articles/eimermusic/2007/10/23/ticket-component-resetting-user-passwords

However when I submit the form I get the following error: Fatal error: Class 'Ticket' not found in /Users/cameron/Sites/thehive/app/controllers/components/tickets.php on line 60

And Line 60 is this: $ticketObj = new Ticket();

Any ideas what the problem is and how to fix it thanks?

答:
Hey... it would make sense if you post your Ticket model class here. Looking back at the tutorial, I don't understand why the duplicates

```<code><?php //why duplicate
<?php //why duplicate
class Ticket extends AppModel
{
    var $name = 'Ticket';
}
?> //why duplicate
?> //why duplicate
</code>```

. I am not sure if that would cause problem as I have never tried it before. If you copy the code as is, that might be the issue. I am not sure....

Body:
Hey... it would make sense if you post your Ticket model class here. Looking back at the tutorial, I don't understand why the duplicates

<?php //why duplicate
<?php //why duplicate
class Ticket extends AppModel
{
    var $name = 'Ticket';
}
?> //why duplicate
?> //why duplicate

. I am not sure if that would cause problem as I have never tried it before. If you copy the code as is, that might be the issue. I am not sure....


问:
Got "Fatal error: Index out of range" : show index in list item for swiftui
Updated: error: Type '_' has no member '1', if put a if closure(if !self.showMarkedOnly || name.marked {}) inside list-foreach, why?

Code version 4:

```<code>struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    var marked: Bool
    init(_ name: String, marked: Bool = false) { self.name = name; self.marked = marked }
}

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) { Text("show marked only") }
            List {
                ForEach(Array(zip(0..., list)), id: \.1.id) { index, name in
//                    if !self.showMarkedOnly || name.marked {
                        HStack {
                            Text("\(index)").foregroundColor(name.marked ? .red : .gray)
                            Spacer()
                            Text("\(name.name)")
                        }
                        .background(Color.gray.opacity(0.001))
                        .onTapGesture {
                            self.list.remove(at: index)
                        }
//                    }
                }
            }
        }
    }
}
</code>```

=========

Updated: I found the issue of Code version 2, I must provide a id for ForEach. And Code version 2 updated.

I found a graceful way to show index, It avoids self.list[index]. But I found an error "Type '_' has no member '1'" occurred in some complex code.

Code version 3:

```<code>var body: some View {
        List {
            ForEach(Array(zip(0..., list)), id: \.1.id) { index, name in // a error occurs in some complex code: "Type '_' has no member '1'"
                HStack {
                    Text("\(index)")
                    Spacer()
                    Text("\(name.name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list.remove(at: index)
                }
            }
        }
    }
</code>```

I show a list, and remove the item I tapped. It's Code version 1, it works fine.
When I add index into the list item using indices(Code veriosn 2), got "Fatal error: Index out of range" after tapping.

Code version 1:

```<code>struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    init(_ name: String) { self.name = name }
}

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3"), Name("test4"), Name("test5"), Name("test6"), Name("test7"), Name("test8")]

    var body: some View {
        List {
            ForEach(list) { name in
                HStack {
                    Text("\(0)")
                    Spacer()
                    Text("\(name.name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list = self.list.filter { $0 != name }
                }
            }
        }
    }
}
</code>```

Code version 2:

```<code>struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3"), Name("test4"), Name("test5"), Name("test6"), Name("test7"), Name("test8")]

    var body: some View {
        List {
            //ForEach(list.indices) { index in
            ForEach(list.indices, id: \.self) { index in
                HStack {
                    Text("\(index)")
                    Spacer()
                    Text("\(self.list[index].name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list.remove(at: index)
                }
            }
        }
    }
}
</code>```

答:
That is because SwiftUI reloads its content basing on original data provided.
You could solve it by modifying your

ForEach(list) { item in
    HStack {
        Text("\(item.id)")
        Spacer()
        Text("\(item.name)")
    }
    .onTapGesture {
        guard let itemIndex = self.list.firstIndex(of: item) else { return }
        self.list.remove(at:itemIndex)
    }
}
```

<p><strong>Otherwise</strong>, you could solve your issue using built-in <code>.onDelete()</code> method (you delete items by swiping them):</p>

<pre class="lang-swift prettyprint-override"><code>var body: some View {
    List {
        ForEach(list) { item in
            HStack {
                Text("\(item.id)")
                Spacer()
                Text("\(item.name)")
            }
            .background(Color.gray.opacity(0.001))
        }.onDelete(perform: delete)
    }
}

func delete(at offsets: IndexSet) {
    list.remove(atOffsets: offsets)
}
</code>```

Body:
Updated: error: Type '_' has no member '1', if put a if closure(if !self.showMarkedOnly || name.marked {}) inside list-foreach, why?

Code version 4:

struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    var marked: Bool
    init(_ name: String, marked: Bool = false) { self.name = name; self.marked = marked }
}

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) { Text("show marked only") }
            List {
                ForEach(Array(zip(0..., list)), id: \.1.id) { index, name in
//                    if !self.showMarkedOnly || name.marked {
                        HStack {
                            Text("\(index)").foregroundColor(name.marked ? .red : .gray)
                            Spacer()
                            Text("\(name.name)")
                        }
                        .background(Color.gray.opacity(0.001))
                        .onTapGesture {
                            self.list.remove(at: index)
                        }
//                    }
                }
            }
        }
    }
}

=========

Updated: I found the issue of Code version 2, I must provide a id for ForEach. And Code version 2 updated.

I found a graceful way to show index, It avoids self.list[index]. But I found an error "Type '_' has no member '1'" occurred in some complex code.

Code version 3:

var body: some View {
        List {
            ForEach(Array(zip(0..., list)), id: \.1.id) { index, name in // a error occurs in some complex code: "Type '_' has no member '1'"
                HStack {
                    Text("\(index)")
                    Spacer()
                    Text("\(name.name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list.remove(at: index)
                }
            }
        }
    }

I show a list, and remove the item I tapped. It's Code version 1, it works fine.
When I add index into the list item using indices(Code veriosn 2), got "Fatal error: Index out of range" after tapping.

Code version 1:

struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    init(_ name: String) { self.name = name }
}

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3"), Name("test4"), Name("test5"), Name("test6"), Name("test7"), Name("test8")]

    var body: some View {
        List {
            ForEach(list) { name in
                HStack {
                    Text("\(0)")
                    Spacer()
                    Text("\(name.name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list = self.list.filter { $0 != name }
                }
            }
        }
    }
}

Code version 2:

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3"), Name("test4"), Name("test5"), Name("test6"), Name("test7"), Name("test8")]

    var body: some View {
        List {
            //ForEach(list.indices) { index in
            ForEach(list.indices, id: \.self) { index in
                HStack {
                    Text("\(index)")
                    Spacer()
                    Text("\(self.list[index].name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list.remove(at: index)
                }
            }
        }
    }
}

Body:
That is because SwiftUI reloads its content basing on original data provided.
You could solve it by modifying your

ForEach(list) { item in
    HStack {
        Text("\(item.id)")
        Spacer()
        Text("\(item.name)")
    }
    .onTapGesture {
        guard let itemIndex = self.list.firstIndex(of: item) else { return }
        self.list.remove(at:itemIndex)
    }
}

Otherwise, you could solve your issue using built-in .onDelete() method (you delete items by swiping them):

var body: some View {
    List {
        ForEach(list) { item in
            HStack {
                Text("\(item.id)")
                Spacer()
                Text("\(item.name)")
            }
            .background(Color.gray.opacity(0.001))
        }.onDelete(perform: delete)
    }
}

func delete(at offsets: IndexSet) {
    list.remove(atOffsets: offsets)
}


问:
Check for variable (int that updates) in a list that grows
I've got a long list of items that is updating information on a server using the 'requests' package.
To make my code run faster, I want to try to reduce to 'requestst.put()' by doing it only after a certain amount is reached, let's say 20 in the example code below.
Using watchdog observer it checks for incoming files, based on a certain string in the name of the file and then has to process it per option. Where for each of the certain string I += 1 the amount and then in each option also the total --> both numbers have to be taken in the requests (process code part).

I tried to do this the following way:

```<code>...
if "_4_" in text_file:
    Sec_totaal += 1
    alles_totaal += 1
    lijstje_Sec = list(range(0,Sec_totaal,20)
    if Sec_totaal in lijstje_Sec:
        #process code
if "_5_" in text_file:
    Fac_totaal += 1
    alles_totaal += 1
    lijstje_Fac = list(range(0,Fac_totaal,20)
    if Fac_totaal in lijstje_Fac:
        #process code
...
</code>```

For some reason the process code doesn't even run the 'if' part (checked it first with a 'print()'), while the list is growing as expected and the output of totaal of each option should does match something in the list when printed. Or is checking a variable in a list not possible?

答:
range is right-exclusive, that is range(a, b) creates a range [a, b[.

So you can never find b in range(a, b), that's literally not possible.

That aside, you don't need to reify range to a list, it behaves pretty much like a list except free. Also skipping around is usually done using % e.g. to do something every 20, you do it if i % 20 == 0.

Body:
I've got a long list of items that is updating information on a server using the 'requests' package.
To make my code run faster, I want to try to reduce to 'requestst.put()' by doing it only after a certain amount is reached, let's say 20 in the example code below.
Using watchdog observer it checks for incoming files, based on a certain string in the name of the file and then has to process it per option. Where for each of the certain string I += 1 the amount and then in each option also the total --> both numbers have to be taken in the requests (process code part).

I tried to do this the following way:

...
if "_4_" in text_file:
    Sec_totaal += 1
    alles_totaal += 1
    lijstje_Sec = list(range(0,Sec_totaal,20)
    if Sec_totaal in lijstje_Sec:
        #process code
if "_5_" in text_file:
    Fac_totaal += 1
    alles_totaal += 1
    lijstje_Fac = list(range(0,Fac_totaal,20)
    if Fac_totaal in lijstje_Fac:
        #process code
...

For some reason the process code doesn't even run the 'if' part (checked it first with a 'print()'), while the list is growing as expected and the output of totaal of each option should does match something in the list when printed. Or is checking a variable in a list not possible?