问:
How to optimize search algorithm
I have 4 dropdown multi-select filters in row.

Which need to render and on every selected option.
I need to add that selected option in new array and update that current array -> object.property.selected = false/true.

I am searching trough array of objects, and one property of every object have array of objects.

You can found code example on this code-pen: https://codepen.io/nikolatrajkovicits/pen/JqpWOX?editors=0012

Here is how that array looks:

```<code>export const getFiltersList = () => [
  {
    title: 'Taxonomy',
    options: [
      {
        id: 0,
        name: 'Competitions',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 1,
        name: 'Events',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 2,
        name: 'Data',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 3,
        name: 'Organisations',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 4,
        name: 'Players',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 5,
        name: 'Teams',
        selected: false,
        key: 'Taxonomy'
      }
    ]
  },
  {
    title: 'Source',
    options: [
      {
        id: 0,
        name: 'Facebook',
        selected: false,
        key: 'Source'
      },
      {
        id: 1,
        name: 'Twitter',
        selected: false,
        key: 'Source'
      },
      {
        id: 2,
        name: 'Instagram',
        selected: false,
        key: 'Source'
      },
      {
        id: 3,
        name: 'Websites',
        selected: false,
        key: 'Source'
      }
    ]
  },
  {
    title: 'Timeframe',
    options: [
      {
        id: 0,
        name: 'Past hour',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 1,
        name: 'Past 24 hours',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 2,
        name: 'Past week',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 3,
        name: 'Past month',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 4,
        name: 'Past year',
        selected: false,
        key: 'Timeframe'
      }
    ]
  },
  {
    title: 'Location',
    options: [
      {
        id: 0,
        name: 'Location 1',
        selected: false,
        key: 'Location'
      },
      {
        id: 1,
        name: 'Location 2',
        selected: false,
        key: 'Location'
      },
      {
        id: 2,
        name: 'Location 3',
        selected: false,
        key: 'Location'
      },
      {
        id: 3,
        name: 'Location 4',
        selected: false,
        key: 'Location'
      }
    ]
  }
];

</code>```

Here is algorithm:

```<code>selectFilter = ({ id, key }) => {
    const { filtersList, selectedFilters } = this.state;
    const tempFilters = filtersList;
    const tempSelected = selectedFilters;
    const i = tempSelected.length;

    tempFilters.forEach((filter) => {
      if (filter.title === key) {
        filter.options.forEach((option) => {
          if (option.id === id) {
            option.selected = !option.selected;
            const isFilterExist = tempSelected.filter(
              (selectedFilter) => selectedFilter.name === option.name
            );
            if (!isFilterExist.length) {
              const selectedItem = { name: option.name, key, id };
              tempSelected[i] = selectedItem;
            }
          }
        });
      }
    });
    this.setState({
      filtersList: tempFilters,
      selectedFilters: tempSelected
    });
  };

</code>```

On code pen you can found version which is in pure javascript code.

How to make better cleaner faster search algo?

Any advice article, tutorial, comment?

答:
If I were you, I would change the structure of the Json object before I use it. For example: If the Json became a key, value pair where the key is the title and the value is the array that represents options. This will make you get rid of the first loop and you will get the list of option in o(1) like the complexity of a hash table.
Note: I assumed that the title here is unique.
Second Change I would make:you want to search by ID and from the example you mentioned the options array is sorted by id meaning first element has id =0 and it is at index 0 etc. so if the value of the new representation is an array the access of elements at index i is also o(1) by this you will get rid of the second loop too.
Note: if the title is not unique or the options ids are not sorted you need to update the example in order to get a better solution. </p>

Title: How to optimize search algorithm

Body:
I have 4 dropdown multi-select filters in row.

Which need to render and on every selected option.
I need to add that selected option in new array and update that current array -> object.property.selected = false/true.

I am searching trough array of objects, and one property of every object have array of objects.

You can found code example on this code-pen: https://codepen.io/nikolatrajkovicits/pen/JqpWOX?editors=0012

Here is how that array looks:

export const getFiltersList = () => [
  {
    title: 'Taxonomy',
    options: [
      {
        id: 0,
        name: 'Competitions',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 1,
        name: 'Events',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 2,
        name: 'Data',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 3,
        name: 'Organisations',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 4,
        name: 'Players',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 5,
        name: 'Teams',
        selected: false,
        key: 'Taxonomy'
      }
    ]
  },
  {
    title: 'Source',
    options: [
      {
        id: 0,
        name: 'Facebook',
        selected: false,
        key: 'Source'
      },
      {
        id: 1,
        name: 'Twitter',
        selected: false,
        key: 'Source'
      },
      {
        id: 2,
        name: 'Instagram',
        selected: false,
        key: 'Source'
      },
      {
        id: 3,
        name: 'Websites',
        selected: false,
        key: 'Source'
      }
    ]
  },
  {
    title: 'Timeframe',
    options: [
      {
        id: 0,
        name: 'Past hour',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 1,
        name: 'Past 24 hours',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 2,
        name: 'Past week',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 3,
        name: 'Past month',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 4,
        name: 'Past year',
        selected: false,
        key: 'Timeframe'
      }
    ]
  },
  {
    title: 'Location',
    options: [
      {
        id: 0,
        name: 'Location 1',
        selected: false,
        key: 'Location'
      },
      {
        id: 1,
        name: 'Location 2',
        selected: false,
        key: 'Location'
      },
      {
        id: 2,
        name: 'Location 3',
        selected: false,
        key: 'Location'
      },
      {
        id: 3,
        name: 'Location 4',
        selected: false,
        key: 'Location'
      }
    ]
  }
];

Here is algorithm:

selectFilter = ({ id, key }) => {
    const { filtersList, selectedFilters } = this.state;
    const tempFilters = filtersList;
    const tempSelected = selectedFilters;
    const i = tempSelected.length;

    tempFilters.forEach((filter) => {
      if (filter.title === key) {
        filter.options.forEach((option) => {
          if (option.id === id) {
            option.selected = !option.selected;
            const isFilterExist = tempSelected.filter(
              (selectedFilter) => selectedFilter.name === option.name
            );
            if (!isFilterExist.length) {
              const selectedItem = { name: option.name, key, id };
              tempSelected[i] = selectedItem;
            }
          }
        });
      }
    });
    this.setState({
      filtersList: tempFilters,
      selectedFilters: tempSelected
    });
  };

On code pen you can found version which is in pure javascript code.

How to make better cleaner faster search algo?

Any advice article, tutorial, comment?


来源: stackexchange

问:
left and right objects are evaluated / resolved during runtime or compile-time?
Referring to a book exercise...

Having the following code..

Left left = createLeftInstance ();
Right right = createRightInstance ();
```

<p>...and keeping in consideration that both the above mentioned methods can return instance of all the sub-classes of Left and Right, in Java the call of the following method...</p>

<pre class="lang-java prettyprint-override"><code>left.invoke (right);
</code>```

how is resolved:

A) basing on runtime type of left and compile-time of right

B) basing on compile-time type of left and runtime of right

C) basing on compile-time type of left and compile-time of right

D) basing on runtime type of left and runtime of right

答:
Java has A, it is called single dispatch:

the method overload is selected by the compiler, at compile-time (matching the compile-time type of right to the methods offered by the compile-time type of left)

the method invocation happens on the runtime type of left - as methods do not disappear, left certainly has a method with the same signature which was picked at compile-time. This act counts as "dispatch", and as it only depends on left (in runtime), it is "single".

Super simple demo using built-in println(Object) and println(char[]):

```<code>char c[]={'a','b','c'};
System.out.println(c);
Object o=c;
System.out.println(o);
</code>```

It results in something like

```<code>abc
[C@1540e19d
</code>```

The first line shows that println(char[]) concatenates the array of characters, the second line shows that the exact same array (one can add some check like println(o==c);) passed as Object in compile-time results in invoking the println(Object) overload, regardless of the runtime type.

B and C probably do not exist.

D is called multiple dispatch, when the method signature is also selected in runtime using the actual runtime type of the arguments, and the selected method is invoked on the runtime type of left. Java does not support that by default, it can be implemented using reflection, here is a single-argument example:

```<code>public static void trickyprintln(Object o) throws Exception {
    System.out.getClass().getMethod("println",o.getClass()).invoke(System.out,o);
}

public static void main (String[] args) throws Exception {
    char c[]={'a','b','c'};
    trickyprintln(c);
    Object o=c;
    trickyprintln(o);
}
</code>```

This one results in

```<code>abc
abc
</code>```

as println is picked manually, using the runtime type of the argument. So it is possible to do if someone really needs it in Java, but it does not happen automatically.

ContentLicense: CC BY-SA 4.0

Body:
Referring to a book exercise...

Having the following code..

Left left = createLeftInstance ();
Right right = createRightInstance ();

...and keeping in consideration that both the above mentioned methods can return instance of all the sub-classes of Left and Right, in Java the call of the following method...

left.invoke (right);

how is resolved:

A) basing on runtime type of left and compile-time of right

B) basing on compile-time type of left and runtime of right

C) basing on compile-time type of left and compile-time of right

D) basing on runtime type of left and runtime of right

Body:
Java has A, it is called single dispatch:

the method overload is selected by the compiler, at compile-time (matching the compile-time type of right to the methods offered by the compile-time type of left)

the method invocation happens on the runtime type of left - as methods do not disappear, left certainly has a method with the same signature which was picked at compile-time. This act counts as "dispatch", and as it only depends on left (in runtime), it is "single".

Super simple demo using built-in println(Object) and println(char[]):

char c[]={'a','b','c'};
System.out.println(c);
Object o=c;
System.out.println(o);

It results in something like

abc
[C@1540e19d

The first line shows that println(char[]) concatenates the array of characters, the second line shows that the exact same array (one can add some check like println(o==c);) passed as Object in compile-time results in invoking the println(Object) overload, regardless of the runtime type.

B and C probably do not exist.

D is called multiple dispatch, when the method signature is also selected in runtime using the actual runtime type of the arguments, and the selected method is invoked on the runtime type of left. Java does not support that by default, it can be implemented using reflection, here is a single-argument example:

public static void trickyprintln(Object o) throws Exception {
    System.out.getClass().getMethod("println",o.getClass()).invoke(System.out,o);
}

public static void main (String[] args) throws Exception {
    char c[]={'a','b','c'};
    trickyprintln(c);
    Object o=c;
    trickyprintln(o);
}

This one results in

abc
abc

as println is picked manually, using the runtime type of the argument. So it is possible to do if someone really needs it in Java, but it does not happen automatically.


问:
What defines a size of CollectionViewCell inside a TableViewCell?
I'm implementing UITableView that contains UICollectionView inside. Of course, my UITableViewCell has a UICollectionView, but the problem is I don't know how to configure the height of the UICollectionViewCell. I tried to set height constraint to view inside my UICollectionViewCell, but it does not affect. There are many ways to play with size:

Handle size of UITableViewCell

Set height constraint to UICollectionView inside UITableViewCell

Use method of UICollectionViewDelegateFlowLayout

Set height constraint to view inside UICollectionViewCell (my method)

The last way is the most appropriate for me, but I want to know why it does not work. Here is the configuration of UICollectionView:

```<code>lazy var booksCollectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    var booksCollectionView = UICollectionView(frame: contentView.bounds, collectionViewLayout: layout)
    booksCollectionView.backgroundColor = .clear
    booksCollectionView.translatesAutoresizingMaskIntoConstraints = false
    return booksCollectionView
}()
</code>```

Constraints:

```<code>booksCollectionView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
    booksCollectionView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
    booksCollectionView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
    booksCollectionView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
</code>```

Cell inside UICollectionView contains only UIView:

```<code>bookView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
    bookView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
    bookView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
    bookView.heightAnchor.constraint(equalToConstant: 440).isActive = true
</code>```

Changing the height of the bookView does not affect at all. Why that happens? How should I handle the height for UICollectionViewCell?

答:
Conform to protocol:UICollectionViewDelegateFlowLayout  and implement the following method:
collectionView(_:layout:sizeForItemAt:)

Body:
I'm implementing UITableView that contains UICollectionView inside. Of course, my UITableViewCell has a UICollectionView, but the problem is I don't know how to configure the height of the UICollectionViewCell. I tried to set height constraint to view inside my UICollectionViewCell, but it does not affect. There are many ways to play with size:

Handle size of UITableViewCell

Set height constraint to UICollectionView inside UITableViewCell

Use method of UICollectionViewDelegateFlowLayout

Set height constraint to view inside UICollectionViewCell (my method)

The last way is the most appropriate for me, but I want to know why it does not work. Here is the configuration of UICollectionView:

lazy var booksCollectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    var booksCollectionView = UICollectionView(frame: contentView.bounds, collectionViewLayout: layout)
    booksCollectionView.backgroundColor = .clear
    booksCollectionView.translatesAutoresizingMaskIntoConstraints = false
    return booksCollectionView
}()

Constraints:

booksCollectionView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
    booksCollectionView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
    booksCollectionView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
    booksCollectionView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true

Cell inside UICollectionView contains only UIView:

bookView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
    bookView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
    bookView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
    bookView.heightAnchor.constraint(equalToConstant: 440).isActive = true

Changing the height of the bookView does not affect at all. Why that happens? How should I handle the height for UICollectionViewCell?


问:
Rocketchat connection to secure MongoDB
I'm trying to secure mongodb added a rocketchat user with privileges and here is the query result:

```<code>rs01:PRIMARY> use admin
rs01:PRIMARY> show users
{
        "_id" : "admin.rocketchatuser",
        "user" : "rocketchatuser",
        "db" : "admin",
        "customData" : {

        },
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "admin"
                },
                {
                        "role" : "readWrite",
                        "db" : "local"
                },
                {
                        "role" : "dbOwner",
                        "db" : "rocketchat"
                }
        ]
}
</code>```

And here is my connection string:

```<code>MONGO_OPLOG_URL=mongodb://rocketchatuser:mypassword@localhost:27017/local?authSource=admin&replSet=rs01
MONGO_URL=mongodb://rocketchatuser:mypassword@localhost:27017/rocketchat?authSource=admin
</code>```

And here is mongodb log:

```<code>Unauthorized: not authorized on rocketchat to execute command
</code>```

But still getting connection refused error.

Any idea?

答:
Finally, I figured out the problem after re-follow instructions in this guide and  enabling logging from Rocket.Chat service and see that it requires to grant rocketuser to have a role clusterMonitor on admin database:

```<code>db.runCommand({ grantRolesToUser: "rocketchatuser" , roles: [{role: "clusterMonitor", db: "admin"}]})
</code>```

After granting the user it connected and started to run successfully.

Title: Rocketchat connection to secure MongoDB

Body:
I'm trying to secure mongodb added a rocketchat user with privileges and here is the query result:

rs01:PRIMARY> use admin
rs01:PRIMARY> show users
{
        "_id" : "admin.rocketchatuser",
        "user" : "rocketchatuser",
        "db" : "admin",
        "customData" : {

        },
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "admin"
                },
                {
                        "role" : "readWrite",
                        "db" : "local"
                },
                {
                        "role" : "dbOwner",
                        "db" : "rocketchat"
                }
        ]
}

And here is my connection string:

MONGO_OPLOG_URL=mongodb://rocketchatuser:mypassword@localhost:27017/local?authSource=admin&replSet=rs01
MONGO_URL=mongodb://rocketchatuser:mypassword@localhost:27017/rocketchat?authSource=admin

And here is mongodb log:

Unauthorized: not authorized on rocketchat to execute command

But still getting connection refused error.

Any idea?

Body:
Finally, I figured out the problem after re-follow instructions in this guide and  enabling logging from Rocket.Chat service and see that it requires to grant rocketuser to have a role clusterMonitor on admin database:

db.runCommand({ grantRolesToUser: "rocketchatuser" , roles: [{role: "clusterMonitor", db: "admin"}]})

After granting the user it connected and started to run successfully.


问:
Passing WebSocket parameters to a programmatical endpoint
My front-end code looks like this:

```<code>const ws = new WebSocket("wss://localhost/yeah?param1=value1&param2=value2");
</code>```

My endpoint at the backend is programmatical:

```<code>class YeahEndpoint extends Endpoint {
    ...
    @Override
    public void onOpen(Session session, EndpointConfig ec) {
        Map<String, String> params = session.getPathParameters(); <-- returns empty map! No param1 or param2.
    }
    ...
}
</code>```

As I was not able to find relevant information on the web, I need to ask this here: how a programmatical endpoint obtains the request parameters?

答: I simply should have used session.getQueryString() instead of session.getPathParameters().

Body:
My front-end code looks like this:

const ws = new WebSocket("wss://localhost/yeah?param1=value1&param2=value2");

My endpoint at the backend is programmatical:

class YeahEndpoint extends Endpoint {
    ...
    @Override
    public void onOpen(Session session, EndpointConfig ec) {
        Map<String, String> params = session.getPathParameters(); <-- returns empty map! No param1 or param2.
    }
    ...
}

As I was not able to find relevant information on the web, I need to ask this here: how a programmatical endpoint obtains the request parameters?


问:
array filter in python?
For example, I have two lists

```<code> A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements
</code>```

Is there a built-in function in python to do this?

ContentLicense: CC BY-SA 3.0

Title: array filter in python?

Body:
For example, I have two lists

 A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements

Is there a built-in function in python to do this?

Body: tuple(set([6, 7, 8, 9, 10, 11, 12]).difference([6, 9, 12]))


问:
Flutter text is not ellipsized in the list
I have a list of object. There is a name that can be long and according to design it should end with three dots if it can't fit

```<code>Container(
          height: 72,
          constraints: BoxConstraints(minWidth: double.infinity),
          child: Row(
            children: <Widget>[
              Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: CircleAvatar(
                  radius: 20.0,
                  backgroundImage: NetworkImage(_model._organizerLogo),
                  backgroundColor: Colors.transparent,
                ),
              ),
              Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.only(right: 8.0),
                      child: Text(
                        _model._eventName,
                        style: TextStyle(
                            fontSize: 15,
                            color: Colors.black,
                            fontWeight: FontWeight.w500),
                        textAlign: TextAlign.start,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    ...
                  ])
            ],
          ),
        )
</code>```

Wrapping Container in Flexible or Expandable didn't work.

How to make oversized text ellipsis? Thanks!

答:
Add Expanded to your Column to give it a fixed width based on the remaining space.

```<code>Container(
      height: 72,
      constraints: BoxConstraints(minWidth: double.infinity),
      child: Row(
        children: <Widget>[
          Container(
            margin: const EdgeInsets.only(left: 16.0, right: 16.0),
            child: CircleAvatar(
              radius: 20.0,
              backgroundImage: NetworkImage(_model._organizerLogo),
              backgroundColor: Colors.transparent,
            ),
          ),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  padding: EdgeInsets.only(right: 8.0),
                  child: Text(
                    _model._eventName,
                    style: TextStyle(
                        fontSize: 15,
                        color: Colors.black,
                        fontWeight: FontWeight.w500),
                    textAlign: TextAlign.start,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                ...
              ])
          ),
        ],
      ),
    )
</code>```

Body:
I have a list of object. There is a name that can be long and according to design it should end with three dots if it can't fit

Container(
          height: 72,
          constraints: BoxConstraints(minWidth: double.infinity),
          child: Row(
            children: <Widget>[
              Container(
                margin: const EdgeInsets.only(left: 16.0, right: 16.0),
                child: CircleAvatar(
                  radius: 20.0,
                  backgroundImage: NetworkImage(_model._organizerLogo),
                  backgroundColor: Colors.transparent,
                ),
              ),
              Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.only(right: 8.0),
                      child: Text(
                        _model._eventName,
                        style: TextStyle(
                            fontSize: 15,
                            color: Colors.black,
                            fontWeight: FontWeight.w500),
                        textAlign: TextAlign.start,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    ...
                  ])
            ],
          ),
        )

Wrapping Container in Flexible or Expandable didn't work.

How to make oversized text ellipsis? Thanks!

Body:
Add Expanded to your Column to give it a fixed width based on the remaining space.

Container(
      height: 72,
      constraints: BoxConstraints(minWidth: double.infinity),
      child: Row(
        children: <Widget>[
          Container(
            margin: const EdgeInsets.only(left: 16.0, right: 16.0),
            child: CircleAvatar(
              radius: 20.0,
              backgroundImage: NetworkImage(_model._organizerLogo),
              backgroundColor: Colors.transparent,
            ),
          ),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  padding: EdgeInsets.only(right: 8.0),
                  child: Text(
                    _model._eventName,
                    style: TextStyle(
                        fontSize: 15,
                        color: Colors.black,
                        fontWeight: FontWeight.w500),
                    textAlign: TextAlign.start,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                ...
              ])
          ),
        ],
      ),
    )


问:
C# regex to accept current/voltage value
I need a regex which can validate a input string if it is valid voltage or current.
Required format will be any number followed by 'V' or 'A' is valid.

I was thinking to split string and validate it but it not robust solution and hard to implement.

答:
try this
/\d+v/gi
string c = "12V" // number to validate

if(c.match(/\d+v/gi)!null)
{
number validated
}
else
{
not valid
}

```<code> /\d+v|\d+a/i
</code>```

\d => select all number
+ > select all numbers till it finds a not numeric value
v=>select v
/i => makes the match case insensitive
| => or operator

Body:
try this
/\d+v/gi
string c = "12V" // number to validate

if(c.match(/\d+v/gi)!null)
{
number validated
}
else
{
not valid
}

 /\d+v|\d+a/i

\d => select all number
+ > select all numbers till it finds a not numeric value
v=>select v
/i => makes the match case insensitive
| => or operator


问:
Customizing item-text in v-select
Please tell me if we can customize item-text for v-select ?

I want customize each item in v-select, something like this :

```<code>:item-text="item.name - item.description"
</code>```

答:
Here's an example in simple following code:

```<code><template>
  <v-select
    label="Names"
    v-model="name"
    :items="names"
    item-value="id"
    item-text="name"
    return-object
  >
    <template v-slot:selection="{ item }">
      {{ getText(item) }}
    </template>
    <template v-slot:item="{ item }">
      {{ getText(item) }}
    </template>
  </v-select>
</template>

<script>
export default {
  data: () => ({
    names: [
      { id: 1, name: 'Paul', age: 23 },
      { id: 2, name: 'Marcelo', age: 15 },
      { id: 3, name: 'Any', age: 30 },
    ],
    name: null,
  }),
  methods: {
    getText(item) => `${item.name} - ${item.text}`,
  },
}
</script>
</code>```

The following is the reference:
https://vuetifyjs.com/en/components/autocompletes#advanced-slots

Title: Customizing item-text in v-select

Body:
Please tell me if we can customize item-text for v-select ?

I want customize each item in v-select, something like this :

:item-text="item.name - item.description"

Body:
Here's an example in simple following code:

<template>
  <v-select
    label="Names"
    v-model="name"
    :items="names"
    item-value="id"
    item-text="name"
    return-object
  >
    <template v-slot:selection="{ item }">
      {{ getText(item) }}
    </template>
    <template v-slot:item="{ item }">
      {{ getText(item) }}
    </template>
  </v-select>
</template>

<script>
export default {
  data: () => ({
    names: [
      { id: 1, name: 'Paul', age: 23 },
      { id: 2, name: 'Marcelo', age: 15 },
      { id: 3, name: 'Any', age: 30 },
    ],
    name: null,
  }),
  methods: {
    getText(item) => `${item.name} - ${item.text}`,
  },
}
</script>

The following is the reference:
https://vuetifyjs.com/en/components/autocompletes#advanced-slots


问:
How can I populate a tableView having embedded collectionViews in its rows and organize them by type or category?
I have an event/venue management app & a view receives data for events in json format where each event has a category or type. How do I populate & organize events in collectionViews embedded in TableView cells where each TableView Cell is a category or type to display. Answers in Swift if possible

答:
Create a struct with all available properties and add an enum for categories

```<code>struct Event {
    enum Category {
        case a
        case b
        case c
    }
    var category: Category
    var eventName: String
    //...
}
</code>```

Create an 2 dimensional array of Event objects

```<code>var groupedEventsArr = [[Event]]()
</code>```

Once you received the data from the server create an array of Event objects.

```<code>let eventsArr:[Event] = //json parse
</code>```

Then group the array objects based on category

```<code>groupedEventsArr = Array(Dictionary(grouping: eventsArr, by: { $0.category }).values)
</code>```

Now use this array in tableview, collection view data source methods

//tableview

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return groupedEventsArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
    let category = groupedEventsArr[indexPath.row].first?.category
    return cell!
}
</code>```

//collection view

```<code>func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return groupedEventsArr[section].count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    let event = groupedEventsArr[indexPath.section][indexPath.item]
    return cell
}
</code>```

Body:
Create a struct with all available properties and add an enum for categories

struct Event {
    enum Category {
        case a
        case b
        case c
    }
    var category: Category
    var eventName: String
    //...
}

Create an 2 dimensional array of Event objects

var groupedEventsArr = [[Event]]()

Once you received the data from the server create an array of Event objects.

let eventsArr:[Event] = //json parse

Then group the array objects based on category

groupedEventsArr = Array(Dictionary(grouping: eventsArr, by: { $0.category }).values)

Now use this array in tableview, collection view data source methods

//tableview

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return groupedEventsArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
    let category = groupedEventsArr[indexPath.row].first?.category
    return cell!
}

//collection view

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return groupedEventsArr[section].count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    let event = groupedEventsArr[indexPath.section][indexPath.item]
    return cell
}


问:
Simple Java name based locks?
MySQL has a handy function:

```<code>SELECT GET_LOCK("SomeName")
</code>```

This can be used to create simple, but very specific, name-based locks for an application. However, it requires a database connection.

I have many situations like:

```<code>someMethod() {
    // do stuff to user A for their data for feature X
}
</code>```

It doesn't make sense to simply synchronize this method, because, for example, if this method is called for user B in the meantime, user B does not need to wait for user A to finish before it starts, only operations for the user A and feature X combination need to wait.

With the MySql lock I could do something like:

```<code>someMethod() {
    executeQuery("SELECT GET_LOCK('userA-featureX')")
    // only locked for user A for their data for feature X
    executeQuery("SELECT RELEASE_LOCK('userA-featureX')")
}
</code>```

Since Java locking is based on objects, it seems like I would need to create a new object to represent the situation for this lock and then put it in a static cache somewhere so all the threads can see it. Subsequent requests to lock for that situation would then locate the lock object in the cache and acquire its lock. I tried to create something like this, but then the lock cache itself needs synchronization. Also, it is difficult to detect when a lock object is no longer being used so that it can be removed from the cache.

I have looked at the Java concurrent packages, but nothing stands out as being able to handle something like this. Is there an easy way to implement this, or am I looking at this from the wrong perspective?

Edit:

To clarify, I am not looking to create a predefined pool of locks ahead of time, I would like to create them on demand. Some pseudo-code for what I am thinking of is:

```<code>LockManager.acquireLock(String name) {
    Lock lock;

    synchronized (map) {
        lock = map.get(name);

        // doesn't exist yet - create and store
        if(lock == null) {
            lock = new Lock();
            map.put(name, lock);
        }
    }

    lock.lock();
}

LockManager.releaseLock(String name) {
    // unlock
    // if this was the last hold on the lock, remove it from the cache
}
</code>```

答:
```<code>// pool of names that are being locked
HashSet<String> pool = new HashSet<String>();

lock(name)
    synchronized(pool)
        while(pool.contains(name)) // already being locked
            pool.wait();           // wait for release
        pool.add(name);            // I lock it

unlock(name)
    synchronized(pool)
        pool.remove(name);
        pool.notifyAll();
</code>```

Title: Simple Java name based locks?

Body:
MySQL has a handy function:

SELECT GET_LOCK("SomeName")

This can be used to create simple, but very specific, name-based locks for an application. However, it requires a database connection.

I have many situations like:

someMethod() {
    // do stuff to user A for their data for feature X
}

It doesn't make sense to simply synchronize this method, because, for example, if this method is called for user B in the meantime, user B does not need to wait for user A to finish before it starts, only operations for the user A and feature X combination need to wait.

With the MySql lock I could do something like:

someMethod() {
    executeQuery("SELECT GET_LOCK('userA-featureX')")
    // only locked for user A for their data for feature X
    executeQuery("SELECT RELEASE_LOCK('userA-featureX')")
}

Since Java locking is based on objects, it seems like I would need to create a new object to represent the situation for this lock and then put it in a static cache somewhere so all the threads can see it. Subsequent requests to lock for that situation would then locate the lock object in the cache and acquire its lock. I tried to create something like this, but then the lock cache itself needs synchronization. Also, it is difficult to detect when a lock object is no longer being used so that it can be removed from the cache.

I have looked at the Java concurrent packages, but nothing stands out as being able to handle something like this. Is there an easy way to implement this, or am I looking at this from the wrong perspective?

Edit:

To clarify, I am not looking to create a predefined pool of locks ahead of time, I would like to create them on demand. Some pseudo-code for what I am thinking of is:

LockManager.acquireLock(String name) {
    Lock lock;

    synchronized (map) {
        lock = map.get(name);

        // doesn't exist yet - create and store
        if(lock == null) {
            lock = new Lock();
            map.put(name, lock);
        }
    }

    lock.lock();
}

LockManager.releaseLock(String name) {
    // unlock
    // if this was the last hold on the lock, remove it from the cache
}


问:
Shell append redirection replaces existing text?
For our school assignment, we have to implement input/output redirection. I managed to get the input and output redirection work, but I am facing an issue with append redirection.

I am using testfile.txt:

```<code>test line 1
test line 2
</code>```

When the user types ls >> testfile.txt, I expect the output from ls to be added to the testfile. At this moment, the test lines get replaced by the output of the ls program.

The rights that I am using to open the files are the following:

```<code>    file = open(redirect.getNewFile().c_str(), O_WRONLY | O_TRUNC, S_IRWXU);
</code>```

Does anyone have an idea where it goes wrong?

Thanks in forward.

答: Replaced O_TRUNC with O_APPEND.</p>

Body:
For our school assignment, we have to implement input/output redirection. I managed to get the input and output redirection work, but I am facing an issue with append redirection.

I am using testfile.txt:

test line 1
test line 2

When the user types ls >> testfile.txt, I expect the output from ls to be added to the testfile. At this moment, the test lines get replaced by the output of the ls program.

The rights that I am using to open the files are the following:

    file = open(redirect.getNewFile().c_str(), O_WRONLY | O_TRUNC, S_IRWXU);

Does anyone have an idea where it goes wrong?

Thanks in forward.

Body: Replaced O_TRUNC with O_APPEND.


问:
Exit from while loop which started inside a async method
How to break the while loop which inside an async method. Please refer below code

I have tried many ways but none of them worked for me

```<code>async void TotalTimer(string time)
{
    while (true)
    {
        TimeSpan timesp = DateTime.Now - DateTime.Parse(time);
        TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
        await Task.Delay(1000);

        if (string.IsNullOrEmpty(time))
        {
            break;
        }
    }
}
</code>```

I need to stop and exit from the loop

Updated code:

```<code>async Task TotalTimer(CancellationToken token)
{
    var intime = await App.Database.GetRecentIn();
    InTime = DateTime.Parse(intime.datetime).ToString("hh:mm tt");

    while (!token.IsCancellationRequested)
    {
        TimeSpan timesp = DateTime.Now - DateTime.Parse(intime.datetime);
        TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
        Console.WriteLine(TotalTime); // to see it's working
        await Task.Delay(1000);

        if (token.IsCancellationRequested)
        {
            break;
        }
    }
}

void StatCounting()
{
    var cts = new CancellationTokenSource();
   _= TotalTimer(cts.Token);
}

void StopCounting()
{
    var cts = new CancellationTokenSource();
    cts.Cancel();
   _= TotalTimer(cts.Token);

    _=Finalize();
}
</code>```

答:
Using a break in an async method is perfectly fine.

This works fine:

```<code>async void Main()
{
    await TotalTimer();
    Console.WriteLine("Done.");
}

async Task TotalTimer()
{
    while (true)
    {
        await Task.Delay(1000);

        if (true)
        {
            break;
        }
    }
}
</code>```

It waits a second and then write Done. to the console.

Your code just doesn't change time so it's never hitting the break.

Other than that your async method should return a Task rather than a void.

Body:
How to break the while loop which inside an async method. Please refer below code

I have tried many ways but none of them worked for me

async void TotalTimer(string time)
{
    while (true)
    {
        TimeSpan timesp = DateTime.Now - DateTime.Parse(time);
        TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
        await Task.Delay(1000);

        if (string.IsNullOrEmpty(time))
        {
            break;
        }
    }
}

I need to stop and exit from the loop

Updated code:

async Task TotalTimer(CancellationToken token)
{
    var intime = await App.Database.GetRecentIn();
    InTime = DateTime.Parse(intime.datetime).ToString("hh:mm tt");

    while (!token.IsCancellationRequested)
    {
        TimeSpan timesp = DateTime.Now - DateTime.Parse(intime.datetime);
        TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
        Console.WriteLine(TotalTime); // to see it's working
        await Task.Delay(1000);

        if (token.IsCancellationRequested)
        {
            break;
        }
    }
}

void StatCounting()
{
    var cts = new CancellationTokenSource();
   _= TotalTimer(cts.Token);
}

void StopCounting()
{
    var cts = new CancellationTokenSource();
    cts.Cancel();
   _= TotalTimer(cts.Token);

    _=Finalize();
}

Body:
Using a break in an async method is perfectly fine.

This works fine:

async void Main()
{
    await TotalTimer();
    Console.WriteLine("Done.");
}

async Task TotalTimer()
{
    while (true)
    {
        await Task.Delay(1000);

        if (true)
        {
            break;
        }
    }
}

It waits a second and then write Done. to the console.

Your code just doesn't change time so it's never hitting the break.

Other than that your async method should return a Task rather than a void.


问:
How to fix "Padding is invalid and cannot be removed" when encrypting and decrypting in the same process
I am trying to encrypt and decrypt an xml file. The program trys to open, edit, and reencrypt the data, But I get the error "System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed." When I encrypt, then decrypt running the program twice, It works just fine, but the program creates an error when doing them both.

This is a very common error, but also a very vague one, with many different "scenarios". I've searched for a while one ways to fix it, and I've tried all of the "fixes" online. None have worked yet.

class Program
    {
        static void Main(string[] args)
        {
        }
        public static void encFile(string input, string password)
        {
            GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);

            FileEncrypt(input, password);

            ZeroMemory(gch.AddrOfPinnedObject(), password.Length * 2);
            gch.Free();
        }
        public static string output;
        public static void decFile(string input, string password)
        {
            GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);

            // Decrypt the file
            output = FileDecrypt(input, password);

        }

        [DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
        public static extern bool ZeroMemory(IntPtr Destination, int Length);

        ///
        /// Encrypts a file from its path and a plain password.
        ///
        /// <param name="inputFile"></param>
        /// <param name="password"></param>
        private static void FileEncrypt(string inputFile, string password)
        {
            File.WriteAllText(Path.GetDirectoryName(inputFile) + "\\" + Path.GetFileNameWithoutExtension(inputFile) + ".dat", Crypto.EncryptStringAES(File.ReadAllText(inputFile), "Password123!"));
        }

        ///
        /// Decrypts an encrypted file with the FileEncrypt method through its path and the plain password.
        ///
        /// <param name="inputFile"></param>
        /// <param name="outputFile"></param>
        /// <param name="password"></param>
        private static string FileDecrypt(string inputFile, string password)
        {
            return Crypto.DecryptStringAES(File.ReadAllText(inputFile), password);
        }
    }
    public class Crypto
    {

        //While an app specific salt is not the best practice for
        //password based encryption, it's probably safe enough as long as
        //it is truly uncommon. Also too much work to alter this answer otherwise.
        private static byte[] _salt = Encoding.ASCII.GetBytes("rxONBa*&e03!%76N9mBlbR#@Xl&A&w");

        ///
        /// Encrypt the given string using AES.  The string can be decrypted using
        /// DecryptStringAES().  The sharedSecret parameters must match.
        ///
        /// <param name="plainText">The text to encrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
        public static string EncryptStringAES(string plainText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentNullException("plainText");
            if (string.IsNullOrEmpty(sharedSecret))
                throw new ArgumentNullException("sharedSecret");

            string outStr = null;                       // Encrypted string to return
            RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create a RijndaelManaged object
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.Padding = PaddingMode.PKCS7;
                // Create a decryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    // prepend the IV
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            // Return the encrypted bytes from the memory stream.
            return outStr;
        }

        ///
        /// Decrypt the given string.  Assumes the string was encrypted using
        /// EncryptStringAES(), using an identical sharedSecret.
        ///
        /// <param name="cipherText">The text to decrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
        public static string DecryptStringAES(string cipherText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(cipherText))
                throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(sharedSecret))
                throw new ArgumentNullException("sharedSecret");

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create the streams used for decryption.
                byte[] bytes = Convert.FromBase64String(cipherText);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    // Create a RijndaelManaged object
                    // with the specified key and IV.
                    aesAlg = new RijndaelManaged();
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    // Get the initialization vector from the encrypted stream
                    aesAlg.IV = ReadByteArray(msDecrypt);
                    aesAlg.Padding = PaddingMode.PKCS7;
                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            return plaintext;
        }

        private static byte[] ReadByteArray(Stream s)
        {
            byte[] rawLength = new byte[sizeof(int)];
            if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
            {
                throw new SystemException("Stream did not contain properly formatted byte array");
            }

            byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
            if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
            {
                throw new SystemException("Did not read byte array properly");
            }

            return buffer;
        }
    }
```

<p>Running the following code that encrypts then decrypts will produce the error:</p>

<pre class="lang-cs prettyprint-override"><code>static void Main(string[] args)
        {
            string password = "Password123!";
            encFile(@"C:\DIR\test.xml", password);
            decFile(@"C:\DIR\test.dat", password);
            Console.WriteLine(output);
        }
</code>```

But if you try first running this code that only encrypts the file:

static void Main(string[] args)
        {
            string password = "Password123!";
            encFile(@"C:\DIR\test.xml", password);
        }
```

<p>and then decrypting the file in another process after the encryption:</p>

<pre class="lang-cs prettyprint-override"><code>static void Main(string[] args)
        {
            string password = "Password123!";
            decFile(@"C:\DIR\test.dat", password);
            Console.WriteLine(output);
        }
</code>```

Then the program will output the contents correctly, without an error.

How can I encrypt and decrypt the file in one run, without any errors.

答:
The variable password, and the parameter with the same name, point to the same constant string. The first of your methods will zero that string out.

```<code>    static void Main(string[] args)
    {
        string password = "Password123!";

        encFile(@"C:\KaliPatriot\test.xml", password);
        // password is now "\0\0\0\0\0\0\0\0\0"
        decFile(@"C:\KaliPatriot\test.dat", password);
        Console.WriteLine(output);
    }
</code>```

Using  a string like this is very dangerous. Strings are supposed (and assumed) to be immutable and .NET also uses interning for strings.

You have managed to get UB (Undefined Behaviour) in C#, not something to be proud of.

Body:
I am trying to encrypt and decrypt an xml file. The program trys to open, edit, and reencrypt the data, But I get the error "System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed." When I encrypt, then decrypt running the program twice, It works just fine, but the program creates an error when doing them both.

This is a very common error, but also a very vague one, with many different "scenarios". I've searched for a while one ways to fix it, and I've tried all of the "fixes" online. None have worked yet.

class Program
    {
        static void Main(string[] args)
        {
        }
        public static void encFile(string input, string password)
        {
            GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);

            FileEncrypt(input, password);

            ZeroMemory(gch.AddrOfPinnedObject(), password.Length * 2);
            gch.Free();
        }
        public static string output;
        public static void decFile(string input, string password)
        {
            GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);

            // Decrypt the file
            output = FileDecrypt(input, password);

        }

        [DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
        public static extern bool ZeroMemory(IntPtr Destination, int Length);

        ///
        /// Encrypts a file from its path and a plain password.
        ///
        /// <param name="inputFile"></param>
        /// <param name="password"></param>
        private static void FileEncrypt(string inputFile, string password)
        {
            File.WriteAllText(Path.GetDirectoryName(inputFile) + "\\" + Path.GetFileNameWithoutExtension(inputFile) + ".dat", Crypto.EncryptStringAES(File.ReadAllText(inputFile), "Password123!"));
        }

        ///
        /// Decrypts an encrypted file with the FileEncrypt method through its path and the plain password.
        ///
        /// <param name="inputFile"></param>
        /// <param name="outputFile"></param>
        /// <param name="password"></param>
        private static string FileDecrypt(string inputFile, string password)
        {
            return Crypto.DecryptStringAES(File.ReadAllText(inputFile), password);
        }
    }
    public class Crypto
    {

        //While an app specific salt is not the best practice for
        //password based encryption, it's probably safe enough as long as
        //it is truly uncommon. Also too much work to alter this answer otherwise.
        private static byte[] _salt = Encoding.ASCII.GetBytes("rxONBa*&e03!%76N9mBlbR#@Xl&A&w");

        ///
        /// Encrypt the given string using AES.  The string can be decrypted using
        /// DecryptStringAES().  The sharedSecret parameters must match.
        ///
        /// <param name="plainText">The text to encrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
        public static string EncryptStringAES(string plainText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentNullException("plainText");
            if (string.IsNullOrEmpty(sharedSecret))
                throw new ArgumentNullException("sharedSecret");

            string outStr = null;                       // Encrypted string to return
            RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create a RijndaelManaged object
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.Padding = PaddingMode.PKCS7;
                // Create a decryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    // prepend the IV
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            // Return the encrypted bytes from the memory stream.
            return outStr;
        }

        ///
        /// Decrypt the given string.  Assumes the string was encrypted using
        /// EncryptStringAES(), using an identical sharedSecret.
        ///
        /// <param name="cipherText">The text to decrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
        public static string DecryptStringAES(string cipherText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(cipherText))
                throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(sharedSecret))
                throw new ArgumentNullException("sharedSecret");

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create the streams used for decryption.
                byte[] bytes = Convert.FromBase64String(cipherText);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    // Create a RijndaelManaged object
                    // with the specified key and IV.
                    aesAlg = new RijndaelManaged();
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    // Get the initialization vector from the encrypted stream
                    aesAlg.IV = ReadByteArray(msDecrypt);
                    aesAlg.Padding = PaddingMode.PKCS7;
                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            return plaintext;
        }

        private static byte[] ReadByteArray(Stream s)
        {
            byte[] rawLength = new byte[sizeof(int)];
            if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
            {
                throw new SystemException("Stream did not contain properly formatted byte array");
            }

            byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
            if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
            {
                throw new SystemException("Did not read byte array properly");
            }

            return buffer;
        }
    }

Running the following code that encrypts then decrypts will produce the error:

static void Main(string[] args)
        {
            string password = "Password123!";
            encFile(@"C:\DIR\test.xml", password);
            decFile(@"C:\DIR\test.dat", password);
            Console.WriteLine(output);
        }

But if you try first running this code that only encrypts the file:

static void Main(string[] args)
        {
            string password = "Password123!";
            encFile(@"C:\DIR\test.xml", password);
        }

and then decrypting the file in another process after the encryption:

static void Main(string[] args)
        {
            string password = "Password123!";
            decFile(@"C:\DIR\test.dat", password);
            Console.WriteLine(output);
        }

Then the program will output the contents correctly, without an error.

How can I encrypt and decrypt the file in one run, without any errors.

Body:
The variable password, and the parameter with the same name, point to the same constant string. The first of your methods will zero that string out.

    static void Main(string[] args)
    {
        string password = "Password123!";

        encFile(@"C:\KaliPatriot\test.xml", password);
        // password is now "\0\0\0\0\0\0\0\0\0"
        decFile(@"C:\KaliPatriot\test.dat", password);
        Console.WriteLine(output);
    }

Using  a string like this is very dangerous. Strings are supposed (and assumed) to be immutable and .NET also uses interning for strings.

You have managed to get UB (Undefined Behaviour) in C#, not something to be proud of.


问:
SQL Query: Multiple parameters for 1 column
I have these database where I save some activities. This is how they relate with each other.

```<code>ACTIVITIES          WEEKDAYS           DAYPARTS

id                  id                 id
title               weekday            daypart
daypart_id
weekday_id
</code>```

For a filter button, I want to filter the activities on weekdays. So for example, they click on monday, they get all the activities for monday.

The problem is that one column can get multiple parameters, so for example, they can click on monday, but they can also click on tuesday, and wednesday.. and so on.

I try to do that with this code:

```<code>public function selectAllActivities($dayparts = false, $weekdays = false){
    $sql = "SELECT `activities`.*, `dayparts`.`daypart`, `weekdays`.`weekday`
    FROM `activities`
    INNER JOIN `dayparts` ON `dayparts`.`id` = `activities`.`daypart_id`
    INNER JOIN `weekdays` ON `weekdays`.`id` = `activities`.`weekday_id`";

  if (!empty($dayparts)) {
  $placeHolders = [];
  foreach ($dayparts as $key => $daypart) {
      $placeHolders[$key] = ':daypart_id'.$key;
  }
  $sql .= ' AND `daypart` IN ('.implode(', ',$placeHolders).')';
  }

  if (!empty($weekdays)) {
    $placeHolders = [];
    foreach ($weekdays as $key => $weekday) {
        $placeHoldersB[$key] = ':weekday_id'.$key;
    }
    $sql .= ' AND `weekday` IN ('.implode(', ',$placeHoldersB).')';
    }

    $stmt = $this->pdo->prepare($sql);

  if ($dayparts) {
    foreach ($dayparts as $key => $daypart) {
        $stmt->bindValue($placeHolders[$key], $daypart);
      }
  }
  if ($weekdays) {
    foreach ($weekdays as $key => $weekday) {
        $stmt->bindValue($placeHoldersB[$key], $weekday);
      }
  }
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
  }
</code>```

When I try to filter I get the following error:

```<code> Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/INT2_DEV/dao/ActivityDAO.php on line 15
</code>```

There is something wrong with the foreach funtion, but I dont really know what.

答:
Invalid argument supplied for foreach() in ...

This error is occurring because the variable that foreach is attempting to iterate over is not an array.

According to your logic, either $dayparts or $weekdays is not empty (i.e. !empty($dayparts) is true) and $dayparts is also true.

I would suggest using is_array($x) to test whether the variables are arrays prior to using them as such:

```<code>if (is_array($dayparts)) {
    ...
}
</code>```

Body:
I have these database where I save some activities. This is how they relate with each other.

ACTIVITIES          WEEKDAYS           DAYPARTS

id                  id                 id
title               weekday            daypart
daypart_id
weekday_id

For a filter button, I want to filter the activities on weekdays. So for example, they click on monday, they get all the activities for monday.

The problem is that one column can get multiple parameters, so for example, they can click on monday, but they can also click on tuesday, and wednesday.. and so on.

I try to do that with this code:

public function selectAllActivities($dayparts = false, $weekdays = false){
    $sql = "SELECT `activities`.*, `dayparts`.`daypart`, `weekdays`.`weekday`
    FROM `activities`
    INNER JOIN `dayparts` ON `dayparts`.`id` = `activities`.`daypart_id`
    INNER JOIN `weekdays` ON `weekdays`.`id` = `activities`.`weekday_id`";

  if (!empty($dayparts)) {
  $placeHolders = [];
  foreach ($dayparts as $key => $daypart) {
      $placeHolders[$key] = ':daypart_id'.$key;
  }
  $sql .= ' AND `daypart` IN ('.implode(', ',$placeHolders).')';
  }

  if (!empty($weekdays)) {
    $placeHolders = [];
    foreach ($weekdays as $key => $weekday) {
        $placeHoldersB[$key] = ':weekday_id'.$key;
    }
    $sql .= ' AND `weekday` IN ('.implode(', ',$placeHoldersB).')';
    }

    $stmt = $this->pdo->prepare($sql);

  if ($dayparts) {
    foreach ($dayparts as $key => $daypart) {
        $stmt->bindValue($placeHolders[$key], $daypart);
      }
  }
  if ($weekdays) {
    foreach ($weekdays as $key => $weekday) {
        $stmt->bindValue($placeHoldersB[$key], $weekday);
      }
  }
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
  }

When I try to filter I get the following error:

 Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/INT2_DEV/dao/ActivityDAO.php on line 15

There is something wrong with the foreach funtion, but I dont really know what.

Body:
Invalid argument supplied for foreach() in ...

This error is occurring because the variable that foreach is attempting to iterate over is not an array.

According to your logic, either $dayparts or $weekdays is not empty (i.e. !empty($dayparts) is true) and $dayparts is also true.

I would suggest using is_array($x) to test whether the variables are arrays prior to using them as such:

if (is_array($dayparts)) {
    ...
}


问:
How to remove duplicate words from a string comparing to other string in SQL
I need to check string2 if there are words that I already have in string1 and remove those.

```<code>declare @Text1 nvarchar(500) = 'apple, orange, pear'
declare @Text2 nvarchar(500) = 'banana, apple'
</code>```

The output should be 'banana'

Edit: I just realized I made the question not properly.
So, this is right:

```<code>DECLARE @Tab TABLE (Ingredients nvarchar(500))

insert @Tab select 'apple, orange, pear'

insert @Tab select 'banana, apple'

insert @Tab select 'pear, mango'

declare @Ingredients nvarchar(4000) = ''

select @Ingredients = @Ingredients + value + ',' from @Tab cross apply STRING_SPLIT(Ingredients, ',')

SELECT @Ingredients
</code>```

current result:
apple,orange,pear,banana,apple,pear,mango,

expected result:
apple,orange,pear,banana,mango,

答:
you can use something like this:

```<code>DECLARE @Text1 NVARCHAR(500)= 'apple, orange, pear';
DECLARE @Text2 NVARCHAR(500)= 'banana, apple, cucumber, pear';

--convert to xml for further split using nodes
declare @xmlText1 as xml =  convert(xml, Concat('<a>',replace(@Text1,',','</a><a>'),'</a>'))
declare @xmlText2 as xml =  convert(xml, Concat('<a>',replace(@Text2,',','</a><a>'),'</a>'))

--remove duplicates from @text2 that exist in @text1
;with cte (val) as (
        select ', ' + value
        from (
            select ltrim(n.value('.', 'VARCHAR(10)')) AS value
            from  @xmlText2.nodes('a') as t(n)
            except
            select ltrim(n.value('.', 'VARCHAR(10)')) AS value
            from  @xmlText1.nodes('a') as t(n)
        ) as t
        for xml path ('')
)
-- reassign @text2
select @Text2 = stuff(val,1,1,'') from cte

--output
select @Text2 as newText2
</code>```

result

Body:
I need to check string2 if there are words that I already have in string1 and remove those.

declare @Text1 nvarchar(500) = 'apple, orange, pear'
declare @Text2 nvarchar(500) = 'banana, apple'

The output should be 'banana'

Edit: I just realized I made the question not properly.
So, this is right:

DECLARE @Tab TABLE (Ingredients nvarchar(500))

insert @Tab select 'apple, orange, pear'

insert @Tab select 'banana, apple'

insert @Tab select 'pear, mango'

declare @Ingredients nvarchar(4000) = ''

select @Ingredients = @Ingredients + value + ',' from @Tab cross apply STRING_SPLIT(Ingredients, ',')

SELECT @Ingredients

current result:
apple,orange,pear,banana,apple,pear,mango,

expected result:
apple,orange,pear,banana,mango,

Body:
you can use something like this:

DECLARE @Text1 NVARCHAR(500)= 'apple, orange, pear';
DECLARE @Text2 NVARCHAR(500)= 'banana, apple, cucumber, pear';

--convert to xml for further split using nodes
declare @xmlText1 as xml =  convert(xml, Concat('<a>',replace(@Text1,',','</a><a>'),'</a>'))
declare @xmlText2 as xml =  convert(xml, Concat('<a>',replace(@Text2,',','</a><a>'),'</a>'))

--remove duplicates from @text2 that exist in @text1
;with cte (val) as (
        select ', ' + value
        from (
            select ltrim(n.value('.', 'VARCHAR(10)')) AS value
            from  @xmlText2.nodes('a') as t(n)
            except
            select ltrim(n.value('.', 'VARCHAR(10)')) AS value
            from  @xmlText1.nodes('a') as t(n)
        ) as t
        for xml path ('')
)
-- reassign @text2
select @Text2 = stuff(val,1,1,'') from cte

--output
select @Text2 as newText2

result


问:
How to compare a custom data type in haskell
I have a custom data type which I would like to compare.

```<code>data Tile = Wall | Ground | Storage | Box | Blank
</code>```

I would like to do instance-of-tile == Box

I've tried using == like so

```<code>tileToInteger :: Tile -> Integer
tileToInteger tile
  | tile == Blank || tile == Wall = 1
  | otherwise = 2
</code>```

I've also tried

```<code>tileToInteger :: Eq => Tile -> Integer
</code>```

The error message from stack build is

```<code>No instance for (Eq Tile) arising from a use of ‘==’
    • In the first argument of ‘(||)’, namely ‘tile == Blank’
      In the expression: tile == Blank || tile == Wall
      In a stmt of a pattern guard for an equation for ‘tileToInteger’: tile == Blank || tile == Wall
</code>```

Here's the full sample code

```<code>data Tile = Wall | Ground | Storage | Box | Blank

getTileAtXY :: Integer -> Integer -> Tile
getTileAtXY x y
  | x == 0 && y == 0 = Box
  | otherwise = Ground

tileToInteger :: Tile -> Integer
tileToInteger tile
  | tile == Blank || tile == Wall = 1
  | otherwise = 2

main :: IO ()
main = print (tileToInteger (getTileAtXY 1 0))
</code>```

Background

Exercise from Penn Engineering university course

Using stack version 1.9.3.1

答:
You can derive the methods for comparison automatically:

```<code>data Tile = Wall | Ground | Storage | Box | Blank deriving (Eq)
</code>```

And then you can use == and /= to compare Tiles for equality and inequality.

Body:
I have a custom data type which I would like to compare.

data Tile = Wall | Ground | Storage | Box | Blank

I would like to do instance-of-tile == Box

I've tried using == like so

tileToInteger :: Tile -> Integer
tileToInteger tile
  | tile == Blank || tile == Wall = 1
  | otherwise = 2

I've also tried

tileToInteger :: Eq => Tile -> Integer

The error message from stack build is

No instance for (Eq Tile) arising from a use of ‘==’
    • In the first argument of ‘(||)’, namely ‘tile == Blank’
      In the expression: tile == Blank || tile == Wall
      In a stmt of a pattern guard for an equation for ‘tileToInteger’: tile == Blank || tile == Wall

Here's the full sample code

data Tile = Wall | Ground | Storage | Box | Blank

getTileAtXY :: Integer -> Integer -> Tile
getTileAtXY x y
  | x == 0 && y == 0 = Box
  | otherwise = Ground

tileToInteger :: Tile -> Integer
tileToInteger tile
  | tile == Blank || tile == Wall = 1
  | otherwise = 2

main :: IO ()
main = print (tileToInteger (getTileAtXY 1 0))

Background

Exercise from Penn Engineering university course

Using stack version 1.9.3.1

Body:
You can derive the methods for comparison automatically:

data Tile = Wall | Ground | Storage | Box | Blank deriving (Eq)

And then you can use == and /= to compare Tiles for equality and inequality.


问:
How to call javascript function multiple times?
I am using an API from OpenWeatherMap on my website to show weather condition of just some specific places only, altogether in one page.
Here's the code:

  <input type="hidden" name="name" value="dehradun" id="cityName">
  <button onclick="getWeather()">Get weather of Dehradun</button>

  <input type="hidden" name="name" value="pune" id="cityName">
  <button onclick="getWeather()">Get weather of Pune</button> '

```

Suppose if i want to show weather condition of two places using the same Javascript function then its showing the same result for both the places(Of place (Dehradun) mentioned first in code).

Help me solve this problem.

答:
I have roughly added the working code below, when you click on a button it will show the whether report of that city in both the text, Try clicking on both the button and take a look:

<input type="hidden" name="name" value="dehradun" id="cityName2">
<button onclick="getWeather('dehradun')">Get weather of Dehradun</button>

<input type="hidden" name="name" value="pune" id="cityName1">
<button onclick="getWeather('pune')">Get weather of Pune</button>

```

Body:
I am using an API from OpenWeatherMap on my website to show weather condition of just some specific places only, altogether in one page.
Here's the code:

  <input type="hidden" name="name" value="dehradun" id="cityName">
  <button onclick="getWeather()">Get weather of Dehradun</button>

  <input type="hidden" name="name" value="pune" id="cityName">
  <button onclick="getWeather()">Get weather of Pune</button> '

Suppose if i want to show weather condition of two places using the same Javascript function then its showing the same result for both the places(Of place (Dehradun) mentioned first in code).

Help me solve this problem.

Body:
I have roughly added the working code below, when you click on a button it will show the whether report of that city in both the text, Try clicking on both the button and take a look:

<script src="https://code.jquery.com/jquery-3.0.0.js"></script>

<body>
<input type="hidden" name="name" value="dehradun" id="cityName2">
<button onclick="getWeather('dehradun')">Get weather of Dehradun</button>

<div class="weatherResponse"></div>
    <br><br>

<input type="hidden" name="name" value="pune" id="cityName1">
<button onclick="getWeather('pune')">Get weather of Pune</button>

 <br><br>
<div class="weatherResponse"></div>
<script>
 function getWeather(cityName){
$('.weatherResponse').html('');

var apiCall= 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&mode=json&units=metric&appid=d3d913fca612366a61837ea39a622480';
$.getJSON(apiCall,weatherCallback);

function weatherCallback(weatherData){
var cityName= weatherData.name;;
var country= weatherData.sys.country;
var description= weatherData.weather[0].description;
var temp= weatherData.main.temp;

$('.weatherResponse').append("The Weather in " + cityName + " " + country + " is currently " + description + " with temperature: " + temp);
}
}
</script>
</body>


答:
The error

```<code>No instance for (Eq Tile) arising from a use of ‘==’
</code>```

Says that you use (==) with two Tiles, but that the compiler did not found an instance of Eq Tile where you defined the (==) function for Tiles.

You can make it an instance of the Eq typeclass:

```<code>data Tile = Wall | Ground | Storage | Box | Blank <b>deriving Eq</b></code>```

If you automatically derive Eq, then Haskell considers two objects of Tile equal given the data constructors (Wall, Ground, ...) are the same, and all their arguments are the same. Since the data constructors of your Tile data type have no arguments, this thus simply means that Wall is equal to Wall, Ground is equal to Ground, etc.

In your function tileToInteger however, you do not need to use (==) at all, you can use pattern matching [Haskell-wiki], like:

```<code>tileToInteger :: Tile -> Integer
tileToInteger <b>Blank</b> = 1
tileToInteger <b>Wall</b> = 1
tileToInteger <b>_</b> = 2</code>```

You can implement the (==) function for Tiles with pattern matching, like:

```<code>instance Eq Tile where
    Wall == Wall = True
    Ground == Ground = True
    Storage == Storage = True
    Box == Box = True
    Blank == Blank = True
    _ == _ = False</code>```

The above is however equivalent to what deriving Eq will do, so usually one only implements Eq manually if two Tiles are considered equivalent in a different way.

Title: How to compare a custom data type in haskell

Body:
The error

No instance for (Eq Tile) arising from a use of ‘==’

Says that you use (==) with two Tiles, but that the compiler did not found an instance of Eq Tile where you defined the (==) function for Tiles.

You can make it an instance of the Eq typeclass:

data Tile = Wall | Ground | Storage | Box | Blank deriving Eq

If you automatically derive Eq, then Haskell considers two objects of Tile equal given the data constructors (Wall, Ground, ...) are the same, and all their arguments are the same. Since the data constructors of your Tile data type have no arguments, this thus simply means that Wall is equal to Wall, Ground is equal to Ground, etc.

In your function tileToInteger however, you do not need to use (==) at all, you can use pattern matching [Haskell-wiki], like:

tileToInteger :: Tile -> Integer
tileToInteger Blank = 1
tileToInteger Wall = 1
tileToInteger _ = 2

You can implement the (==) function for Tiles with pattern matching, like:

instance Eq Tile where
    Wall == Wall = True
    Ground == Ground = True
    Storage == Storage = True
    Box == Box = True
    Blank == Blank = True
    _ == _ = False

The above is however equivalent to what deriving Eq will do, so usually one only implements Eq manually if two Tiles are considered equivalent in a different way.


问:
Can not established Websocket secure connection on Firefox
I am stucked with Firefox. I could not make Websocket work on it. I use Tornado Websocket and I initialized it by code below:

```<code>app = Application([(r'/mypath/ws', WSHandler)])
http_server = HTTPServer(app, ssl_options={
                "certfile": "~/certs/websocket.crt",
                "keyfile": "~/certs/websocket.key"
            })
http_server.listen("443")
</code>```

And I initialized it on Javascript side like this:

```<code>var WS = new WebSocket("wss://websocket.localhost/mypath/ws");
</code>```

This code works fine on Chrome, meanwhile I created the cert by myself and run the page under HTTPS. But Firefox keeps saying that:

```<code>Firefox can't establish a connection to the server at wss://websocket.localhost/mypath/ws.
</code>```

I google it and found too many thoughts but none of'em worked for me :(

Any help will be appreciated.

答:
If it's a self-signed certificate, browsers won't show the dialog to accept the certificate if it's only used in a websocket.

You must first visit the requested url to see and accept the certificate warning, and then you can create the secure websocket.

For example if your websocket url is:

wss://localhost:44300/OpenWebSocket

then visit:

https://localhost:44300/OpenWebSocket

and accept the certificate warning

Body:
I am stucked with Firefox. I could not make Websocket work on it. I use Tornado Websocket and I initialized it by code below:

app = Application([(r'/mypath/ws', WSHandler)])
http_server = HTTPServer(app, ssl_options={
                "certfile": "~/certs/websocket.crt",
                "keyfile": "~/certs/websocket.key"
            })
http_server.listen("443")

And I initialized it on Javascript side like this:

var WS = new WebSocket("wss://websocket.localhost/mypath/ws");

This code works fine on Chrome, meanwhile I created the cert by myself and run the page under HTTPS. But Firefox keeps saying that:

Firefox can't establish a connection to the server at wss://websocket.localhost/mypath/ws.

I google it and found too many thoughts but none of'em worked for me :(

Any help will be appreciated.


问:
I'm trying to understand how substring call is working in this code?
I know how substring works, but I was trying to understand how it works in the code below. The goal was to find the longest common prefix in an array of strings. The string input was {flower, flow, fleece}. It looks like substring is just taking the entire word of flower, when it's not 0, each time, as 0 to length-1 is going to give the entire word.

```<code> public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    String prefix = strs[0];
    for (int i = 1; i < strs.length; i++)
        while (strs[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
            if (prefix.isEmpty()) return "";
        }
    return prefix;
}
</code>```

The output is fl. I'm just trying to understand why.

答:
0 to length-1 is going to give the entire word

No, it returns the word except the last char.

From: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)

public String substring(int beginIndex, int endIndex)
 Returns a
  new string that is a substring of this string.
The substring
  begins at the specified beginIndex and extends to the character at
  index endIndex - 1.

So what the code does is trims the last char at each iteration with this line:

```<code>prefix = prefix.substring(0, prefix.length() - 1);
</code>```

until it finds a common prefix.

Body:
I know how substring works, but I was trying to understand how it works in the code below. The goal was to find the longest common prefix in an array of strings. The string input was {flower, flow, fleece}. It looks like substring is just taking the entire word of flower, when it's not 0, each time, as 0 to length-1 is going to give the entire word.

 public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    String prefix = strs[0];
    for (int i = 1; i < strs.length; i++)
        while (strs[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
            if (prefix.isEmpty()) return "";
        }
    return prefix;
}

The output is fl. I'm just trying to understand why.

Body:
0 to length-1 is going to give the entire word

No, it returns the word except the last char.

From: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)

public String substring(int beginIndex, int endIndex)
 Returns a
  new string that is a substring of this string.
The substring
  begins at the specified beginIndex and extends to the character at
  index endIndex - 1.

So what the code does is trims the last char at each iteration with this line:

prefix = prefix.substring(0, prefix.length() - 1);

until it finds a common prefix.


Title: array filter in python?

Body:
For example, I have two lists

 A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements

Is there a built-in function in python to do this?

Body:
>>> a = set([6, 7, 8, 9, 10, 11, 12])
>>> sub_a = set([6, 9, 12])
>>> a - sub_a
set([8, 10, 11, 7])


问:
Why the default theme in Kendo-UI for Angular doesn't change the accent color?
I'm trying to change the accent color for an Angular application developed with Kendo-UI. After a bit of searching I managed to understand what I have to change, and that is the $accent variable from the default value #ff6358 to any color you want.

This link provides some help.

Also, the official documentation:

Customization

To customize the Default Theme in one swoop, use the colors which are defined in the scss/_variables.scss file. Any change you make to the content of this file is propagated to every component.

To style a specific component, apply the variables which are used in its specific .scss file.

After you build the theme by running the npm run build command, the complete theme that you can use in your project will be available in the dist/all.css file.

I did all those things and when I check my all.css file, it's the same one than before. Any help would be much appreciated.

答:
In Sass, the order of the declarations matters. You need to declare the new value of $accent first, and import Kendo's styles later, so they use the correct value.

```<code>$accent: #666666;
@import "~@progress/kendo-theme-default/scss/all";
</code>```

(Less, on the other hand, is lazily evaluated and it's the last declaration that counts.)

More on Sass and overriding here: https://thoughtbot.com/blog/sass-default

Body:
In Sass, the order of the declarations matters. You need to declare the new value of $accent first, and import Kendo's styles later, so they use the correct value.

$accent: #666666;
@import "~@progress/kendo-theme-default/scss/all";

(Less, on the other hand, is lazily evaluated and it's the last declaration that counts.)

More on Sass and overriding here: https://thoughtbot.com/blog/sass-default


问:
Android error "android.app.Application does not implement dagger.android.HasActivityInjector"
I'm trying to run my app and every time I click on a button and it calls a specific Activity (ExtendedActivity) I get the following error :

```<code>Process: com.converter.android.dailycope, PID: 28573
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.converter.android.dailycope/com.converter.android.dailycope.ui.extended.ExtendedActivity}: java.lang.RuntimeException: android.app.Application does not implement dagger.android.HasActivityInjector
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                   Caused by: java.lang.RuntimeException: android.app.Application does not implement dagger.android.HasActivityInjector
                      at dagger.android.AndroidInjection.inject(AndroidInjection.java:48)
                      at com.converter.android.dailycope.ui.base.BaseActivity.performDependencyInjection(BaseActivity.java:105)
                      at com.converter.android.dailycope.ui.base.BaseActivity.onCreate(BaseActivity.java:35)
                      at com.converter.android.dailycope.ui.extended.ExtendedActivity.onCreate(ExtendedActivity.java:34)
                      at android.app.Activity.performCreate(Activity.java:6251)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
</code>```

The error is on line super.onCreate(savedInstanceState)

    public class ExtendedActivity extends BaseActivity<ActivityExtendedBinding, ExtendedViewModel> {

    @Inject
    ViewModelProvider.Factory mViewModelFactory;
    ActivityExtendedBinding mActivityStartBinding;
    private ExtendedViewModel mExtendedViewModel;

    private String caps, horos, tipo;
    private String data, prefString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    (...)
```

<p>The class where I have the HasActivityInjector</p>

<pre class="lang-java prettyprint-override"><code>
    public class Cope extends Application implements HasActivityInjector {

    @Inject
    DispatchingAndroidInjector<Activity> activityDispatchingAndroidInjector;

    @Override
    public void onCreate() {
        super.onCreate();

        DaggerExtendedComponent.builder().application(this).build().inject(this);

        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }

    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return activityDispatchingAndroidInjector;
    }
}

</code>```

Can you please help me?

答:
If your implementation is correct then please check in manifest file if you have add/assigned the name of Application Tag.</p>

```<code> <application
    android:name=".base.BaseApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"/>
</code>```

Body:
I'm trying to run my app and every time I click on a button and it calls a specific Activity (ExtendedActivity) I get the following error :

Process: com.converter.android.dailycope, PID: 28573
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.converter.android.dailycope/com.converter.android.dailycope.ui.extended.ExtendedActivity}: java.lang.RuntimeException: android.app.Application does not implement dagger.android.HasActivityInjector
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                   Caused by: java.lang.RuntimeException: android.app.Application does not implement dagger.android.HasActivityInjector
                      at dagger.android.AndroidInjection.inject(AndroidInjection.java:48)
                      at com.converter.android.dailycope.ui.base.BaseActivity.performDependencyInjection(BaseActivity.java:105)
                      at com.converter.android.dailycope.ui.base.BaseActivity.onCreate(BaseActivity.java:35)
                      at com.converter.android.dailycope.ui.extended.ExtendedActivity.onCreate(ExtendedActivity.java:34)
                      at android.app.Activity.performCreate(Activity.java:6251)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)

The error is on line super.onCreate(savedInstanceState)

    public class ExtendedActivity extends BaseActivity<ActivityExtendedBinding, ExtendedViewModel> {

    @Inject
    ViewModelProvider.Factory mViewModelFactory;
    ActivityExtendedBinding mActivityStartBinding;
    private ExtendedViewModel mExtendedViewModel;

    private String caps, horos, tipo;
    private String data, prefString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    (...)

The class where I have the HasActivityInjector

    public class Cope extends Application implements HasActivityInjector {

    @Inject
    DispatchingAndroidInjector<Activity> activityDispatchingAndroidInjector;

    @Override
    public void onCreate() {
        super.onCreate();

        DaggerExtendedComponent.builder().application(this).build().inject(this);

        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }

    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return activityDispatchingAndroidInjector;
    }
}

Can you please help me?

Body:
If your implementation is correct then please check in manifest file if you have add/assigned the name of Application Tag.

 <application
    android:name=".base.BaseApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"/>