问:
LINQ - Order By and Distinct by different fields. Skip & Take distinct values
I'm trying to ORDER BY some fields but SELECT DISTINCT by another field, and after that apply a Skip & Take

Code:

```<code>var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();
</code>```

But I'm getting this exception:

System.NotSupportedException: 'The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.'

I understand the reason (the set is being changed between the ordering and the skipping) but can I work around this issue without querying the database more than once (edit: and not fetching more entities than its supposed to)?

EDIT:
I don't think there's an optimal solution for that, so what I did was fetch the values and then paginated them. *sigh*

```<code>var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .ToArray()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();
</code>```

答:
You should add .OrderBy(e => e) before Skip.

```<code>var result = entities.OrderBy(e => e.OrderField)
                 .Select(e => e.SelectField)
                 .Distinct()
                 .OrderBy(e => e)
                 .Skip(skip)
                 .Take(take)
                 .ToArray();
</code>```

Read the following post to have a better understanding

The method 'Skip' is only supported for sorted input in LINQ to Entities

Body:
I'm trying to ORDER BY some fields but SELECT DISTINCT by another field, and after that apply a Skip & Take

Code:

var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();

But I'm getting this exception:

System.NotSupportedException: 'The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.'

I understand the reason (the set is being changed between the ordering and the skipping) but can I work around this issue without querying the database more than once (edit: and not fetching more entities than its supposed to)?

EDIT:
I don't think there's an optimal solution for that, so what I did was fetch the values and then paginated them. *sigh*

var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .ToArray()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();

Body:
You should add .OrderBy(e => e) before Skip.

var result = entities.OrderBy(e => e.OrderField)
                 .Select(e => e.SelectField)
                 .Distinct()
                 .OrderBy(e => e)
                 .Skip(skip)
                 .Take(take)
                 .ToArray();

Read the following post to have a better understanding

The method 'Skip' is only supported for sorted input in LINQ to Entities


来源: stackexchange

问:
Visualising two very different distributions in one plot
This is more of a "how would you do it" than a "how to do it" question.

I have two groups, "a" and "b". "b" consists of responses that are normally distributed, more or less, bounded between 0-1. "a", however, is mostly 1-s.

The process that generated the data is a questionnaire. People in group "b" made mistakes, people in group "a" mostly figured it out.

How do I visualise these data side by side? Boxplots are messed up because the median of one of the groups is basically 1. Violin plots mess up the widths.

Here is a reproducible example with the rough idea.

```<code>library(tidyverse)

d = tibble(
  val= c(
    rnorm(100, mean = 0.5, sd = 0.25),
    rnorm(5, mean = 0.5, sd = 0.25),
    rep(1, 95)
  ),
  var = c(
    rep('a', 100), rep('b', 100)
  )
) %>%
  filter(
    val >= 0,
    val <= 1
         )

d %>%
  ggplot(aes(x = var, y = val)) +
  geom_jitter() +
  geom_violin()

# No.

d %>%
  ggplot(aes(x = var, y = val)) +
  geom_boxplot()

# No-no.

</code>```

答:
One way to address this is to use a violin plot (or box plot) while ignoring the 1's, and then just adding the points for the ones separately to clarify that they're there. You'll need to explain this in a caption, though. The fact is the data is what it is, and if you have bad data, no amount of playing around with visualization is going to fix that.

```<code>d %>% filter(!(val==1 & var=="b"))  %>%
    ggplot(aes(x = var, y = val)) +
    geom_jitter() +
    geom_violin() + geom_jitter(data=filter(d,val==1 & var=="b"),height=0)
</code>```

Although the best option really depends on what the data represents, and why so many people made the mistake of choosing 1. Did they mistake it for a binary choice between 0 and 1 and preferred the 1? If so, it might be a good idea to randomly spread those ones over the top half of the scale (by subtracting a random number between 0 and 0.5 from each), and graphing it this way. But that's quite an assumption to make, and I would be very wary of manipulating data in such a way. It might be that your best option is just give up on this as unusable data, and move on (or collapse all the data into the binary, if that's usable).

ContentLicense: CC BY-SA 4.0

Body:
This is more of a "how would you do it" than a "how to do it" question.

I have two groups, "a" and "b". "b" consists of responses that are normally distributed, more or less, bounded between 0-1. "a", however, is mostly 1-s.

The process that generated the data is a questionnaire. People in group "b" made mistakes, people in group "a" mostly figured it out.

How do I visualise these data side by side? Boxplots are messed up because the median of one of the groups is basically 1. Violin plots mess up the widths.

Here is a reproducible example with the rough idea.

library(tidyverse)

d = tibble(
  val= c(
    rnorm(100, mean = 0.5, sd = 0.25),
    rnorm(5, mean = 0.5, sd = 0.25),
    rep(1, 95)
  ),
  var = c(
    rep('a', 100), rep('b', 100)
  )
) %>%
  filter(
    val >= 0,
    val <= 1
         )

d %>%
  ggplot(aes(x = var, y = val)) +
  geom_jitter() +
  geom_violin()

# No.

d %>%
  ggplot(aes(x = var, y = val)) +
  geom_boxplot()

# No-no.

Body:
One way to address this is to use a violin plot (or box plot) while ignoring the 1's, and then just adding the points for the ones separately to clarify that they're there. You'll need to explain this in a caption, though. The fact is the data is what it is, and if you have bad data, no amount of playing around with visualization is going to fix that.

d %>% filter(!(val==1 & var=="b"))  %>%
    ggplot(aes(x = var, y = val)) +
    geom_jitter() +
    geom_violin() + geom_jitter(data=filter(d,val==1 & var=="b"),height=0)

Although the best option really depends on what the data represents, and why so many people made the mistake of choosing 1. Did they mistake it for a binary choice between 0 and 1 and preferred the 1? If so, it might be a good idea to randomly spread those ones over the top half of the scale (by subtracting a random number between 0 and 0.5 from each), and graphing it this way. But that's quite an assumption to make, and I would be very wary of manipulating data in such a way. It might be that your best option is just give up on this as unusable data, and move on (or collapse all the data into the binary, if that's usable).


问:
nginx location redirect all but specific domain with any subdomain and any path
I am trying to do a redirect using location regex.I want everything to be redirected to 404 exept from the examplesite.com with every possible path and subdomain.examplesite.com should be redirected to my server.

```<code>examplesite.com redirect
https://m.examplesite.com redirect
www.examplesite.com/something redirect
everything else redirect to 404
</code>```

This is my config:

```<code>location ~ ^(?!(.?)examplesite.com/?(.*)) {
return 404;
}

location / {
return 302 $scheme://192.168.1.1/index.html; #this is a local web server
}
</code>```

which must be wrong because it redirects every examplesite.com i tried to 404.

答: I think you can try this ^((?!examplesite.com).)*$ - Any url which does not have examplesite.com can be redirected to 404 and If the URL has examplesite.com in it then regardless of its position then it wont match.</p>

Body:
I am trying to do a redirect using location regex.I want everything to be redirected to 404 exept from the examplesite.com with every possible path and subdomain.examplesite.com should be redirected to my server.

examplesite.com redirect
https://m.examplesite.com redirect
www.examplesite.com/something redirect
everything else redirect to 404

This is my config:

location ~ ^(?!(.?)examplesite.com/?(.*)) {
return 404;
}

location / {
return 302 $scheme://192.168.1.1/index.html; #this is a local web server
}

which must be wrong because it redirects every examplesite.com i tried to 404.


问:
LDAP attribute is missing in ldap python result3 function result but comes in ldapsearch command result
We have python application which reads entries from ldap and updates the users in other database. Now the problem I got in to is, When I run

```<code>ldapsearch 'sAMAccountName=myID`
</code>```

I am able to get attribute employeeID successfully.

But from python code I am not able to print employeeID attribute.

My python code is as given below:

```<code>import ldap
import datetime
conn = ldap.initialize('ldap://url:port')
conn.simple_bind_s('CN=ABC,OU=XYZ,OU=AAA,DC=users,DC=net', 'password')
from ldap.controls import SimplePagedResultsControl

LDAP_ATTRS = ['*']
LDAP_FILTER = (
        '(&(sAMAccountName=myId))'
)

pager = SimplePagedResultsControl(
            criticality=True,
            size=1500000,
            cookie=''
        )

msgid = conn.search_ext(
                'DC=users,DC=net', ldap.SCOPE_SUBTREE,
                LDAP_FILTER.format(''),
                LDAP_ATTRS, serverctrls=[pager]
            )

rtype, rdata, rmsgid, serverctrls = conn.result3(msgid)

for dn, entry in rdata:
        for ent in entry:
            print(ent)
</code>```

I have no clue why I am not able to print one of attribute (employeeID). Which comes by ldapsearch command.

EDIT

First I doubted at some assumption like user should have permission to read attribute. But I am not sure my assumption is correct.

As I am new to python and also ldap, I read about ldap schema and reading the result about result according to schema. It will be helpful if anyone explains their understanding so that it will help for analyzing and understanding.

答:
Have you tried specifically specifying "employeeID" in your attributes list (LDAP_ATTRS) instead of "*" in your search_ext call to see if that returns the employeeID?

Or try not specifying an attributes list as the documentation in https://www.python-ldap.org/en/latest/reference/ldap.html#ldap.LDAPObject.search
says "The retrieved attributes can be limited with the attrlist parameter. If attrlist is None, all the attributes of each entry are returned."

Body:
We have python application which reads entries from ldap and updates the users in other database. Now the problem I got in to is, When I run

ldapsearch 'sAMAccountName=myID`

I am able to get attribute employeeID successfully.

But from python code I am not able to print employeeID attribute.

My python code is as given below:

import ldap
import datetime
conn = ldap.initialize('ldap://url:port')
conn.simple_bind_s('CN=ABC,OU=XYZ,OU=AAA,DC=users,DC=net', 'password')
from ldap.controls import SimplePagedResultsControl

LDAP_ATTRS = ['*']
LDAP_FILTER = (
        '(&(sAMAccountName=myId))'
)

pager = SimplePagedResultsControl(
            criticality=True,
            size=1500000,
            cookie=''
        )

msgid = conn.search_ext(
                'DC=users,DC=net', ldap.SCOPE_SUBTREE,
                LDAP_FILTER.format(''),
                LDAP_ATTRS, serverctrls=[pager]
            )

rtype, rdata, rmsgid, serverctrls = conn.result3(msgid)

for dn, entry in rdata:
        for ent in entry:
            print(ent)

I have no clue why I am not able to print one of attribute (employeeID). Which comes by ldapsearch command.

EDIT

First I doubted at some assumption like user should have permission to read attribute. But I am not sure my assumption is correct.

As I am new to python and also ldap, I read about ldap schema and reading the result about result according to schema. It will be helpful if anyone explains their understanding so that it will help for analyzing and understanding.


问:
Creating cookies by calling PHP website from Node API
We have our current website in PHP. We are currently upgrading it in Node. We will upgrade it step by step so we'll have some pages in PHP and some other in Node.
Problem is, when users will connect we have to make sure they have a session in both PHP and Node, so they won't have to connect twice.

In PHP we create a PHPSESSID cookie and we store all the data in a session file in /tmp.
In Node we use a JWT token.

What i am trying to achieve right now is: when and user connects with a page that runs on Node, it has to create a PHPSESSID cookie and the session file, so when he will navigate to another page that runs on PHP he will still be connected.

The PHP website and the Node API have the same domain but run on a different port.

Right now what my code does is:

I call the signIn function from the Node API

It creates the JWT token and the user is connected properly in Node

I call the PHP website like this: http://www.mysite.local/ajax/login?user=user&pass=pwd

It creates the session file correctly

It creates the PHPSESSID cookie

But when i check the cookies of my domain, the PHPSESSID doesn't appear. But it does after i create it and print $_COOKIE in PHP.
And because of that PHP can't find any PHPSESSID cookie and can't access the session file.

I'm using Node with GraphQL and Apollo, and PHP with Zend Framework 1.12

Here is how i call PHP with Node:

```<code>const url = `http://www.mysite.local/ajax/login?email=${data.email}&password=${data.password}`
const headers = {
  Referer: 'http://www.mysite.local/auth'
}
await fetch(url, { method: 'GET', headers: headers })
</code>```

The sessions in PHP are managed by Zend

I'm testing on Firefox.

答:
HTTP cookies work like this:

The client sends an HTTP request to the server

The server responds with an HTTP response which includes a Set-Cookie header

The client then stores the cookie

Later on, the client sends another HTTP request to the same server. Since it has a stored cookie, the cookie is including in the request headers.

Browsers will, in general, automatically store cookies. (There are some edge cases, like Ajax requests only handling cookies in cross-origin requests if withCredentials is enabled).

Server-side code will, in general, not automatically store cookies. When dealing with server-side code you usually need to explicitly deal with cookies, usually by configuring a cookie jar library (e.g. fetch-cookie).

You are making an HTTP request from the browser to Node.js.

Node.js is making an HTTP request to PHP.

PHP is responding with a cookie (I assume)

Node.js is ignoring the cookie

Node.js is making an HTTP response to the browser

The browser gets the HTTP response (with no Set-Cookie header in it).

At no point does Node.js either read the cookie from the request it made to PHP or copy that cookie in the response it makes to the browser.

That is what you need to do.

(And then you'll need to continue to proxy requests to the PHP through the Node.js because the cookie stored in the browser would be associated with the Node.js server).

Body:
We have our current website in PHP. We are currently upgrading it in Node. We will upgrade it step by step so we'll have some pages in PHP and some other in Node.
Problem is, when users will connect we have to make sure they have a session in both PHP and Node, so they won't have to connect twice.

In PHP we create a PHPSESSID cookie and we store all the data in a session file in /tmp.
In Node we use a JWT token.

What i am trying to achieve right now is: when and user connects with a page that runs on Node, it has to create a PHPSESSID cookie and the session file, so when he will navigate to another page that runs on PHP he will still be connected.

The PHP website and the Node API have the same domain but run on a different port.

Right now what my code does is:

I call the signIn function from the Node API

It creates the JWT token and the user is connected properly in Node

I call the PHP website like this: http://www.mysite.local/ajax/login?user=user&pass=pwd

It creates the session file correctly

It creates the PHPSESSID cookie

But when i check the cookies of my domain, the PHPSESSID doesn't appear. But it does after i create it and print $_COOKIE in PHP.
And because of that PHP can't find any PHPSESSID cookie and can't access the session file.

I'm using Node with GraphQL and Apollo, and PHP with Zend Framework 1.12

Here is how i call PHP with Node:

const url = `http://www.mysite.local/ajax/login?email=${data.email}&password=${data.password}`
const headers = {
  Referer: 'http://www.mysite.local/auth'
}
await fetch(url, { method: 'GET', headers: headers })

The sessions in PHP are managed by Zend

I'm testing on Firefox.


问:
JQuery Contains vs Equals
I have a form and I need help to modify this statement to be equals, not contains:

```<code>$('<h2>Basic Information</h2>').insertBefore($('h3:contains("Field1")').parent().parent());
</code>```

Thanks as always-

答:
If you want to find the h3 that has exactly that text you can use a jquery filter function.
Basically you search through all h3 and find just the ones that have just that word as their text. Also use trim() so you clear the white spaces

Here are 2 solutions.

you can add your other .parent() ) selectors. ALso there could be a more elegant solution to select it's parent. But without knowing your HTML i cannot help you with that. Share your HTML if you need further assistance

$('
Basic Information
').insertBefore($("h3")
  .filter((i, heading) => $(heading).text().trim() === "Field1"))

// on multiple lines

// var heading = $("h3")
//  .filter((i, heading) => $(heading).text().trim() === "Field1")
// $('
Basic Information
').insertBefore($(heading))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>
  Field1
</h3>
<h3>
  Field1 2
</h3>
<h3>
  Field1
</h3></code>```

Title: JQuery Contains vs Equals

Body:
I have a form and I need help to modify this statement to be equals, not contains:

$('
Basic Information
').insertBefore($('h3:contains("Field1")').parent().parent());

Thanks as always-

Body:
If you want to find the h3 that has exactly that text you can use a jquery filter function.
Basically you search through all h3 and find just the ones that have just that word as their text. Also use trim() so you clear the white spaces

Here are 2 solutions.

you can add your other .parent() ) selectors. ALso there could be a more elegant solution to select it's parent. But without knowing your HTML i cannot help you with that. Share your HTML if you need further assistance

$('<h2>Basic Information</h2>').insertBefore($("h3")
  .filter((i, heading) => $(heading).text().trim() === "Field1"))

// on multiple lines

// var heading = $("h3")
//  .filter((i, heading) => $(heading).text().trim() === "Field1")
// $('<h2>Basic Information</h2>').insertBefore($(heading))

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>
  Field1
</h3>
<h3>
  Field1 2
</h3>
<h3>
  Field1
</h3>


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

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

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

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

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

答:
I'm struggling a bit with what you want, but you can add an override file to the app settings then have that override file set on a per environment basis.</p>

```<code><appSettings file="..\OverrideSettings.config">
</code>```

OwnerDisplayName: DeeStackOverflow

ContentLicense: CC BY-SA 2.5

Title: Variables within app.config/web.config

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

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

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

 ConfigurationManager.AppSettings["Dir2"]

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

LastEditorDisplayName: LFSR Consulting

Body:
I'm struggling a bit with what you want, but you can add an override file to the app settings then have that override file set on a per environment basis.

<appSettings file="..\OverrideSettings.config">

OwnerDisplayName: Andrew Barrett


问:
COUNT_BIG in Indexed View
```<code>CREATE TABLE test2 (
id INTEGER,
name VARCHAR(10),
family VARCHAR(10),
amount INTEGER)

CREATE VIEW dbo.test2_v WITH SCHEMABINDING
AS
SELECT id, SUM(amount) as amount
-- , COUNT_BIG(*) as tmp
FROM dbo.test2
GROUP BY id

CREATE UNIQUE CLUSTERED INDEX vIdx ON test2_v(id)
</code>```

I have error with this code:

Cannot create index on view
  'test.dbo.test2_v' because its select
  list does not include a proper use of
  COUNT_BIG. Consider adding
  COUNT_BIG(*) to select list.

I can create view like this:

```<code>CREATE VIEW dbo.test2_v WITH SCHEMABINDING
    AS
    SELECT id, SUM(amount) as amount, COUNT_BIG(*) as tmp
    FROM dbo.test2
    GROUP BY id
</code>```

But I'm just wondering what is purpose of this column in this case?

答:
You need COUNT_BIG in this case because of the fact you are using GROUP BY.

This is one of many limitations of Indexed Views and because of these restrictions, Indexed Views can't be used in many places or the usage of it is NOT as effective as it could have been. Unfortunately, it is how it works currently. Sucks, it narrows the scope of usage.

http://technet.microsoft.com/en-us/library/cc917715.aspx

ContentLicense: CC BY-SA 3.0

Title: COUNT_BIG in Indexed View

Body:
CREATE TABLE test2 (
id INTEGER,
name VARCHAR(10),
family VARCHAR(10),
amount INTEGER)

CREATE VIEW dbo.test2_v WITH SCHEMABINDING
AS
SELECT id, SUM(amount) as amount
-- , COUNT_BIG(*) as tmp
FROM dbo.test2
GROUP BY id

CREATE UNIQUE CLUSTERED INDEX vIdx ON test2_v(id)

I have error with this code:

Cannot create index on view
  'test.dbo.test2_v' because its select
  list does not include a proper use of
  COUNT_BIG. Consider adding
  COUNT_BIG(*) to select list.

I can create view like this:

CREATE VIEW dbo.test2_v WITH SCHEMABINDING
    AS
    SELECT id, SUM(amount) as amount, COUNT_BIG(*) as tmp
    FROM dbo.test2
    GROUP BY id

But I'm just wondering what is purpose of this column in this case?


问:
How do you use Reactive Forms in an Angular Elements custom element?
I'm trying to create an Angular Elements component to embed in a hosted web page, and I want my component to contain an Angular reactive form.

Build fails with error: "Can't bind to 'formGroup' since it isn't a known property of 'form'."

Can anyone identify what I'm doing wrong?

Edit: This is Angular 9 and TypeScript 3.7 running on the latest version of the Angular CLI. Stackblitz: https://stackblitz.com/edit/angular-57wq1s

Edit 2: The updated Stackblitz code no longer throws a compile-time error, but the control does not finish rendering. The Submit button does not render. If I remove the 'formControlName' directive from the password input, the component does render completely.

Edit 3: StackBlitz seems to be working now, but if I download to my computer, npm install and ng serve, I get the problem where it renders the textbox but not the button.

Index.html

```<code><!doctype html>
<html lang="en">
<body>
  <app-password-reset></app-password-reset>
</body>
</html>
</code>```

app.module.ts

```<code>@NgModule({
  declarations: [],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  entryComponents: [PasswordResetComponent],
  providers: [],
})
export class AppModule {
  constructor(injector: Injector) {
    const passwordResetElement = createCustomElement(PasswordResetComponent, {injector});
    customElements.define('app-password-reset', passwordResetElement);
  }

  ngDoBootstrap(): void { }
}
</code>```

password-reset.component.ts

```<code>@Component({
  template: `
    <form [formGroup]="resetForm" (ngSubmit)="formSubmit($event)">
      <input type="password" formControlName="password">
      <button type="submit">Reset Password</button>
    </form>`
})
export class PasswordResetComponent {

  constructor(private fb: FormBuilder) { }

  resetForm = this.fb.group({
    password: [null, Validators.required],
  });

  formSubmit(event: Event) {
    alert('it works');
  }

}
</code>```

答:
First Import FormsModule in your app.module.ts

You can use FormBuilder to build your form and set the password using Validators. It's easy to use and facilitate working.

Here's how I do it.

Html Page

```<code><form [formGroup]='addEventForm' (ngSubmit)='addEvent(addEventForm.value)'>
</form>
</code>```

Component.ts

```<code>import { FormGroup, FormBuilder, Validators } from '@angular/forms';

addEventForm: FormGroup;
  constructor(formBuilder: FormBuilder) {
this.addEventForm = formBuilder.group({
  title: [null, Validators.required],
  location: [null, Validators.required],
  description: [null, Validators.required],
  startDateValue: [null, Validators.required],
  endDateValue: [null, Validators.required],
  startTime: [null, Validators.required],
  endTime: [null, Validators.required],
  eventType: ['payed'],
  price: ''
});
}
</code>```

Please note that you need to import FormBuilder.

Hope that helps you a little bit.

Body:
I'm trying to create an Angular Elements component to embed in a hosted web page, and I want my component to contain an Angular reactive form.

Build fails with error: "Can't bind to 'formGroup' since it isn't a known property of 'form'."

Can anyone identify what I'm doing wrong?

Edit: This is Angular 9 and TypeScript 3.7 running on the latest version of the Angular CLI. Stackblitz: https://stackblitz.com/edit/angular-57wq1s

Edit 2: The updated Stackblitz code no longer throws a compile-time error, but the control does not finish rendering. The Submit button does not render. If I remove the 'formControlName' directive from the password input, the component does render completely.

Edit 3: StackBlitz seems to be working now, but if I download to my computer, npm install and ng serve, I get the problem where it renders the textbox but not the button.

Index.html

<!doctype html>

  <app-password-reset></app-password-reset>

app.module.ts

@NgModule({
  declarations: [],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  entryComponents: [PasswordResetComponent],
  providers: [],
})
export class AppModule {
  constructor(injector: Injector) {
    const passwordResetElement = createCustomElement(PasswordResetComponent, {injector});
    customElements.define('app-password-reset', passwordResetElement);
  }

  ngDoBootstrap(): void { }
}

password-reset.component.ts

@Component({
  template: `
    <form [formGroup]="resetForm" (ngSubmit)="formSubmit($event)">
      <input type="password" formControlName="password">
      <button type="submit">Reset Password</button>
    </form>`
})
export class PasswordResetComponent {

  constructor(private fb: FormBuilder) { }

  resetForm = this.fb.group({
    password: [null, Validators.required],
  });

  formSubmit(event: Event) {
    alert('it works');
  }

}

Body:
First Import FormsModule in your app.module.ts

You can use FormBuilder to build your form and set the password using Validators. It's easy to use and facilitate working.

Here's how I do it.

Html Page

<form [formGroup]='addEventForm' (ngSubmit)='addEvent(addEventForm.value)'>
</form>

Component.ts

import { FormGroup, FormBuilder, Validators } from '@angular/forms';

addEventForm: FormGroup;
  constructor(formBuilder: FormBuilder) {
this.addEventForm = formBuilder.group({
  title: [null, Validators.required],
  location: [null, Validators.required],
  description: [null, Validators.required],
  startDateValue: [null, Validators.required],
  endDateValue: [null, Validators.required],
  startTime: [null, Validators.required],
  endTime: [null, Validators.required],
  eventType: ['payed'],
  price: ''
});
}

Please note that you need to import FormBuilder.

Hope that helps you a little bit.


问:
Define struct field with circular reference
I have the following code where a struct field depends on a struct field that is not declared yet, because that struct in turn might depend on the struct that I am trying to declare.

How can I design this so that it compiles? Or am I missing an obvious way to get rid of the union struct for keeping several struct definitions together?

```<code>typedef struct expression {
    expression_type type;
    union {
        bool_expression bool;
        identifier_expression ident;
        integer_expression _int;
        prefix_expression prefix;
        infix_expression infix;

        // TODO: Fix this
        if_expression _if;
    };
} expression;

typedef struct statement {
    token token;
    identifier name;
    expression * value;
} statement;

typedef struct block_statement {
    token token;
    statement *statements;
} block_statement;

typedef struct if_expression {
    token token;
    expression condition;
    block_statement *consequence;
    block_statement *alternative;
} if_expression;
</code>```

答:
You can't, in this case.

if_expression contains an expression which in turn contains an if_expression. If you solve this problem by using pointers, you can reorder your definitions and use struct expression* to create a pointer to a struct that has not yet been defined.

Body:
I have the following code where a struct field depends on a struct field that is not declared yet, because that struct in turn might depend on the struct that I am trying to declare.

How can I design this so that it compiles? Or am I missing an obvious way to get rid of the union struct for keeping several struct definitions together?

typedef struct expression {
    expression_type type;
    union {
        bool_expression bool;
        identifier_expression ident;
        integer_expression _int;
        prefix_expression prefix;
        infix_expression infix;

        // TODO: Fix this
        if_expression _if;
    };
} expression;

typedef struct statement {
    token token;
    identifier name;
    expression * value;
} statement;

typedef struct block_statement {
    token token;
    statement *statements;
} block_statement;

typedef struct if_expression {
    token token;
    expression condition;
    block_statement *consequence;
    block_statement *alternative;
} if_expression;


问:
I cant figure out how to send an array out of the optimization.minimize function
I am building a Python application for use in sientific computing.
The application is a Model Predicive Controler (MPC) and I am using scipy.optimize.minimize function as the optimization algorithm.

```<code>solution_guess = minimize(objectiveFunction,
                                  U_guess,
                                  arg_guess,
                                  callback= None,
                                  method = "SLSQP")
</code>```

where the objective function is a self made function where a simulation of my system is executed.
it looks some like this:

```<code>def objectiveFunction(x,*arg):
    U_test = x
    dt_test = arg[0]
    setpoint_test = arg[1]
    pred_horizion_length_test = arg[2]
    initStateValue_test = arg[3]
    # Defining Model Arrays
    NS_pred_horizion_test = int(pred_horizion_length_test/dt_test)+1
    pred_horizion_array_test = np.linspace(0, pred_horizion_length_test, NS_pred_horizion_test)
    SP_array_test = np.zeros(NS_pred_horizion_test) + setpoint_test
    Y_array_test = SP_array_test * 0

    # Defining parameters for the testing model
    timeDelay_test = 50
    initDelayValue_test = 0
    K_test = 4
    Tc1_test = 30
    Tc2_test = 60

    # Defining Model Object
    obj_model_test = model.secDegModel(dt = dt_test,
                                      K = K_test,
                                      Tc1 = Tc1_test,
                                      Tc2 = Tc2_test,
                                      timeDelay = timeDelay_test,
                                      initStateValue = initStateValue_test,
                                      initDelayValue = initDelayValue_test
                                      )

    ###########################################
    #|||||||||||||||||||||||||||||||||||||||||#
    #     Testing Values for U on Model       #
    #|||||||||||||||||||||||||||||||||||||||||#
    ###########################################

    # Running simulation of "real" model function
    for k in range(NS_pred_horizion_test):
        Y_array_test[k] = obj_model_test.run(u_k = U_test)

    error = np.sum(abs(SP_array_test-Y_array_test))
    return error
</code>```

What i struggle with no is how to get back the Y_array_test array so I can plot it every time the optimization is done. I tryed using global variables but i did not get it to work nor do I think its good coding manner to use global variables. does any one know a nice way to solv my problem? maybe using callback function? (if callback is the way to go, I do not fully understand how this method works or how to implement it in a nice way)

答:
Why don't you just do the following?

Modify your objectiveFunction as follows

```<code>from numpy import savez

def objectiveFunction(x,*arg):
.
.
.
.
.

# Running simulation of "real" model function
for k in range(NS_pred_horizion_test):
    Y_array_test[k] = obj_model_test.run(u_k = U_test)
# Just save Y_array_test in a file
# Add some call_no if you don't want to overwrite
# then filename would be 'Y_array_test_' + str(call_no)
# You could increment this call_no, every time by
# call_no = call_no + 1
savez(file_name, Y_array_test)
# Then you could plot it outside using matplotlib
error = np.sum(abs(SP_array_test-Y_array_test))
return error
</code>```

Body:
I am building a Python application for use in sientific computing.
The application is a Model Predicive Controler (MPC) and I am using scipy.optimize.minimize function as the optimization algorithm.

solution_guess = minimize(objectiveFunction,
                                  U_guess,
                                  arg_guess,
                                  callback= None,
                                  method = "SLSQP")

where the objective function is a self made function where a simulation of my system is executed.
it looks some like this:

def objectiveFunction(x,*arg):
    U_test = x
    dt_test = arg[0]
    setpoint_test = arg[1]
    pred_horizion_length_test = arg[2]
    initStateValue_test = arg[3]
    # Defining Model Arrays
    NS_pred_horizion_test = int(pred_horizion_length_test/dt_test)+1
    pred_horizion_array_test = np.linspace(0, pred_horizion_length_test, NS_pred_horizion_test)
    SP_array_test = np.zeros(NS_pred_horizion_test) + setpoint_test
    Y_array_test = SP_array_test * 0

    # Defining parameters for the testing model
    timeDelay_test = 50
    initDelayValue_test = 0
    K_test = 4
    Tc1_test = 30
    Tc2_test = 60

    # Defining Model Object
    obj_model_test = model.secDegModel(dt = dt_test,
                                      K = K_test,
                                      Tc1 = Tc1_test,
                                      Tc2 = Tc2_test,
                                      timeDelay = timeDelay_test,
                                      initStateValue = initStateValue_test,
                                      initDelayValue = initDelayValue_test
                                      )

    ###########################################
    #|||||||||||||||||||||||||||||||||||||||||#
    #     Testing Values for U on Model       #
    #|||||||||||||||||||||||||||||||||||||||||#
    ###########################################

    # Running simulation of "real" model function
    for k in range(NS_pred_horizion_test):
        Y_array_test[k] = obj_model_test.run(u_k = U_test)

    error = np.sum(abs(SP_array_test-Y_array_test))
    return error

What i struggle with no is how to get back the Y_array_test array so I can plot it every time the optimization is done. I tryed using global variables but i did not get it to work nor do I think its good coding manner to use global variables. does any one know a nice way to solv my problem? maybe using callback function? (if callback is the way to go, I do not fully understand how this method works or how to implement it in a nice way)

Body:
Why don't you just do the following?

Modify your objectiveFunction as follows

from numpy import savez

def objectiveFunction(x,*arg):
.
.
.
.
.

# Running simulation of "real" model function
for k in range(NS_pred_horizion_test):
    Y_array_test[k] = obj_model_test.run(u_k = U_test)
# Just save Y_array_test in a file
# Add some call_no if you don't want to overwrite
# then filename would be 'Y_array_test_' + str(call_no)
# You could increment this call_no, every time by
# call_no = call_no + 1
savez(file_name, Y_array_test)
# Then you could plot it outside using matplotlib
error = np.sum(abs(SP_array_test-Y_array_test))
return error


问:
java 8 stream - how to get original object reference after map
Is at all possible to simply the below code using Java 8 stream?

Code:-

```<code>private double calculateBCMMatrixCostForAnalyte(Long startingMaterialId) {

    double bcmMatrixCost = 0;

    StartingMaterialMatrix smm = startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId);

    if (smm.getBlending1MatrixConcentration() != null) {
        bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending1Matrix().getId()) * smm.getBlending1MatrixConcentration()) / 1000000f;
    }

    if (smm.getBlending2MatrixConcentration() != null) {
        bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending2Matrix().getId() * smm.getBlending2MatrixConcentration())) / 1000000f;
    }

    return Precision.round(bcmMatrixCost, 4);
}
</code>```

I tried something like below

```<code>    Stream.of(startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId))
            .filter(smm -> smm.getBlending1MatrixConcentration() != null)
            .mapToDouble(smm ->  priceService.findNeatMaterialCostByStartingMaterialId(smm.getStartingMaterial().getId()) * smm.getBlending1MatrixConcentration() / 1000000f);
</code>```

But after this, I won't have any reference to the original 'smm' object to do further checks.

答:
Usage of Stream would be good if you change your StartingMaterialMatrix class.
Instead of have Blending1Matrix and Blending2Matrix you should have collection List<BlendingMatrix> or Set and BlendingMatrix should have concentration and id
And then it will looks like this:

```<code>smm.getBlendingMatrixes()
.stream()
.filter(blendingMatrix -> blendingMatrix.getConcentration() != null)
.mapToDouble(blendingMatrix -> (priceService.findNeatMaterialCostByStartingMaterialId(blendingMatrix .getId()) * blendingMatrix.getConcentration())) / 1000000f)
.sum();
</code>```

Body:
Is at all possible to simply the below code using Java 8 stream?

Code:-

private double calculateBCMMatrixCostForAnalyte(Long startingMaterialId) {

    double bcmMatrixCost = 0;

    StartingMaterialMatrix smm = startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId);

    if (smm.getBlending1MatrixConcentration() != null) {
        bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending1Matrix().getId()) * smm.getBlending1MatrixConcentration()) / 1000000f;
    }

    if (smm.getBlending2MatrixConcentration() != null) {
        bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending2Matrix().getId() * smm.getBlending2MatrixConcentration())) / 1000000f;
    }

    return Precision.round(bcmMatrixCost, 4);
}

I tried something like below

    Stream.of(startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId))
            .filter(smm -> smm.getBlending1MatrixConcentration() != null)
            .mapToDouble(smm ->  priceService.findNeatMaterialCostByStartingMaterialId(smm.getStartingMaterial().getId()) * smm.getBlending1MatrixConcentration() / 1000000f);

But after this, I won't have any reference to the original 'smm' object to do further checks.

Body:
Usage of Stream would be good if you change your StartingMaterialMatrix class.
Instead of have Blending1Matrix and Blending2Matrix you should have collection List<BlendingMatrix> or Set and BlendingMatrix should have concentration and id
And then it will looks like this:

smm.getBlendingMatrixes()
.stream()
.filter(blendingMatrix -> blendingMatrix.getConcentration() != null)
.mapToDouble(blendingMatrix -> (priceService.findNeatMaterialCostByStartingMaterialId(blendingMatrix .getId()) * blendingMatrix.getConcentration())) / 1000000f)
.sum();


问:
Template friendly string to numeric in C++
In C++ standard library there are functions to convert from string to numeric types:

```<code>stoi
stol
stoll
stoul
stoull
stof
stod
stold
</code>```

but I find it tedious to use them in template code. Why there are no template functions something like:

```<code>template<typename T>
T sto(...)
</code>```

to convert strings to numeric types?

I don't see any technical reason to not have them, but maybe I'm missing something. They can be specialised to call the underlying named functions and use enable_if/concepts to disable non numeric types.

Are there any template friendly alternatives in the standard library to convert string to numeric types and the other way around in an efficient way?

答:
Why there are no template functions something like:

C++17 has such generic string to number function, but named differently. They went with std::from_chars, which is overloaded for all numeric types.

As you can see, the first overload is taking any integer type as an output parameter and will assign the value to it if possible.

It can be used like this:

```<code>template<typename Numeric>
void stuff(std::string_view s) {
    auto value = Numeric{};

    auto [ptr, error] = std::from_chars(s.data(), s.data() + s.size(), value);

    if (error != std::errc{}) {
        // error with the conversion
    } else {
        // conversion successful, do stuff with value
    }
}
</code>```

As you can see, it can work in generic context.

Body:
In C++ standard library there are functions to convert from string to numeric types:

stoi
stol
stoll
stoul
stoull
stof
stod
stold

but I find it tedious to use them in template code. Why there are no template functions something like:

template<typename T>
T sto(...)

to convert strings to numeric types?

I don't see any technical reason to not have them, but maybe I'm missing something. They can be specialised to call the underlying named functions and use enable_if/concepts to disable non numeric types.

Are there any template friendly alternatives in the standard library to convert string to numeric types and the other way around in an efficient way?

Body:
Why there are no template functions something like:

C++17 has such generic string to number function, but named differently. They went with std::from_chars, which is overloaded for all numeric types.

As you can see, the first overload is taking any integer type as an output parameter and will assign the value to it if possible.

It can be used like this:

template<typename Numeric>
void stuff(std::string_view s) {
    auto value = Numeric{};

    auto [ptr, error] = std::from_chars(s.data(), s.data() + s.size(), value);

    if (error != std::errc{}) {
        // error with the conversion
    } else {
        // conversion successful, do stuff with value
    }
}

As you can see, it can work in generic context.


问:
SQLAlchemy: add a relationship using id instead of object?
Is it possible to add to a SQLAlchemy relationship using ids rather than objects?

For example, consider two declarative SQLAlchemy classes, Review and Artist, with a relationship between them:

```<code>class Review(Base):
    artist_id = Column(Integer, ForeignKey('artist.id'))
    artist = relationship(Artist, backref=backref('reviews', order_by=id))
    # etc.

class Artist(Base):
    # etc.
</code>```

With a list of review ids to add to an artist, I seem to need to look up the artist from the id, then add the artist object to the review, like this:

```<code>for review_id in review_ids:
    review = session.query(Review).filter(Review.id==review_id).first()
    artist.reviews.append(review)
</code>```

I'm sure it would be more efficient to skip the lookup and just add the ids, but is this possible?

答:
I think if you want to stick with the pure ORM solution, you'll have to live with the somewhat inefficient querying pattern.

@TokenMacGuy has provided a good alternative. You could integrate that approach by adding add_reviews() to the Artist() class. This would augment the 'standard' orm api, so you could use either depending on the situation.

```<code>from sqlalchemy.orm.session import object_session

class Artist(Base):
    def add_reviews(self, review_ids):
        sess = object_session(self)
        if isinstance(review_ids, int): review_ids = [review_ids]
        sess.execute(
            Review.__table__
            .update()
            .values(artist_id=self.artist_id)
            .where(Review.id.in_(review_ids))
        )
        sess.refresh(self)

review_ids = [123, 556, 998, 667, 111]
artist.add_reviews(review_ids)
review_id = 333
artist.add_reviews(review_id)
</code>```

Body:
Is it possible to add to a SQLAlchemy relationship using ids rather than objects?

For example, consider two declarative SQLAlchemy classes, Review and Artist, with a relationship between them:

class Review(Base):
    artist_id = Column(Integer, ForeignKey('artist.id'))
    artist = relationship(Artist, backref=backref('reviews', order_by=id))
    # etc.

class Artist(Base):
    # etc.

With a list of review ids to add to an artist, I seem to need to look up the artist from the id, then add the artist object to the review, like this:

for review_id in review_ids:
    review = session.query(Review).filter(Review.id==review_id).first()
    artist.reviews.append(review)

I'm sure it would be more efficient to skip the lookup and just add the ids, but is this possible?

Body:
I think if you want to stick with the pure ORM solution, you'll have to live with the somewhat inefficient querying pattern.

@TokenMacGuy has provided a good alternative. You could integrate that approach by adding add_reviews() to the Artist() class. This would augment the 'standard' orm api, so you could use either depending on the situation.

from sqlalchemy.orm.session import object_session

class Artist(Base):
    def add_reviews(self, review_ids):
        sess = object_session(self)
        if isinstance(review_ids, int): review_ids = [review_ids]
        sess.execute(
            Review.__table__
            .update()
            .values(artist_id=self.artist_id)
            .where(Review.id.in_(review_ids))
        )
        sess.refresh(self)

review_ids = [123, 556, 998, 667, 111]
artist.add_reviews(review_ids)
review_id = 333
artist.add_reviews(review_id)


问:
Ceiling date (Similar to R's ceiling_date) in Python
Suppose I have the following pandas dataframe,

```<code>import pandas as pd
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

df = pd.DataFrame([[201901, 'Value1'], [201902, 'Value2'], [201707, 'Value3], columns=['Col1', 'Col2'])
╔════════╦═════════╗
║  Col1  ║  Col2   ║
╠════════╬═════════╣
║ 201901 ║ Value 1 ║
║ 201902 ║ Value 2 ║
║ 201707 ║ Value 3 ║
╚════════╩═════════╝
</code>```

And I want the first column to be like this (I want the last day of every month):

```<code>╔════════════╦═════════╗
║    Col1    ║  Col2   ║
╠════════════╬═════════╣
║ 2019-01-31 ║ Value 1 ║
║ 2019-02-28 ║ Value 2 ║
║ 2017-07-31 ║ Value 3 ║
╚════════════╩═════════╝
</code>```

So, to acchieve that I've tried the following:

```<code>next_month = {'01':'02', '02':'03',
              '03':'04', '04':'05',
              '05':'06', '06':'07',
              '07':'08', '08':'09',
              '09':'10', '10':'11',
              '11':'12', '12':'01'}

df = df['Col1'].apply(lambda x: str(int(str(x)[:4])+1) + next_month[str(x)[-2:]
                      if str(x)[-2:] else str(x)[:4] + next_month[str(x)[-2:]])

df['Col1'] = pd.to_datetime(df['Col1'], format='%Y%m') - timedelta(days=1)
</code>```

In that last part of the code, I'm replacing the row month for the following month, and checking if it's december adding one a year.

Is there a way to acchieve this effiently? I've tried also this but it took SO MUCH time, even more than the previous code showed.

```<code>df['Col1'] = df['Col1'].apply(lambda x: (x + relativedelta(months=1)) - relativedelta(days=1))
</code>```

答:
Use same idea in numpy for improve performance:

```<code>s = pd.to_datetime(df['Col1'], format='%Y%m')

df['Col11'] = (s.to_numpy().astype('datetime64[M]') +
              np.array([1], dtype='timedelta64[M]') -
              np.array([1], dtype='timedelta64[D]'))
</code>```

Another idea is create dictionary and Series.map:

```<code>d = dict(zip(pd.date_range('1900', '2100', freq='MS')[:-1],
             pd.date_range('1900', '2100', freq='M')))

df['Col12'] = pd.to_datetime(df['Col1'], format='%Y%m').map(d)
print (df)
     Col1    Col2      Col11      Col12
0  201901  Value1 2019-01-31 2019-01-31
1  201902  Value2 2019-02-28 2019-02-28
2  201707  Value3 2017-07-31 2017-07-31
</code>```

Body:
Suppose I have the following pandas dataframe,

import pandas as pd
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

df = pd.DataFrame([[201901, 'Value1'], [201902, 'Value2'], [201707, 'Value3], columns=['Col1', 'Col2'])
╔════════╦═════════╗
║  Col1  ║  Col2   ║
╠════════╬═════════╣
║ 201901 ║ Value 1 ║
║ 201902 ║ Value 2 ║
║ 201707 ║ Value 3 ║
╚════════╩═════════╝

And I want the first column to be like this (I want the last day of every month):

╔════════════╦═════════╗
║    Col1    ║  Col2   ║
╠════════════╬═════════╣
║ 2019-01-31 ║ Value 1 ║
║ 2019-02-28 ║ Value 2 ║
║ 2017-07-31 ║ Value 3 ║
╚════════════╩═════════╝

So, to acchieve that I've tried the following:

next_month = {'01':'02', '02':'03',
              '03':'04', '04':'05',
              '05':'06', '06':'07',
              '07':'08', '08':'09',
              '09':'10', '10':'11',
              '11':'12', '12':'01'}

df = df['Col1'].apply(lambda x: str(int(str(x)[:4])+1) + next_month[str(x)[-2:]
                      if str(x)[-2:] else str(x)[:4] + next_month[str(x)[-2:]])

df['Col1'] = pd.to_datetime(df['Col1'], format='%Y%m') - timedelta(days=1)

In that last part of the code, I'm replacing the row month for the following month, and checking if it's december adding one a year.

Is there a way to acchieve this effiently? I've tried also this but it took SO MUCH time, even more than the previous code showed.

df['Col1'] = df['Col1'].apply(lambda x: (x + relativedelta(months=1)) - relativedelta(days=1))

Body:
Use same idea in numpy for improve performance:

s = pd.to_datetime(df['Col1'], format='%Y%m')

df['Col11'] = (s.to_numpy().astype('datetime64[M]') +
              np.array([1], dtype='timedelta64[M]') -
              np.array([1], dtype='timedelta64[D]'))

Another idea is create dictionary and Series.map:

d = dict(zip(pd.date_range('1900', '2100', freq='MS')[:-1],
             pd.date_range('1900', '2100', freq='M')))

df['Col12'] = pd.to_datetime(df['Col1'], format='%Y%m').map(d)
print (df)
     Col1    Col2      Col11      Col12
0  201901  Value1 2019-01-31 2019-01-31
1  201902  Value2 2019-02-28 2019-02-28
2  201707  Value3 2017-07-31 2017-07-31


问:
Kentico CMS - open URL in specific browser
I am new to Kentico CMS and expect that my question can be answered easily by somebody in the know!

Basically the default web browser we use at work is IE but we have a web app that only supports Chrome, we have linked the web page but I am not sure how to force it to open in Chrome.

Thanks for any assistance!

Chris

答:
There is nothing specific in Kentico in which you can force a user to open a URL in a specific browser.  BUT what you can do is create a URL shortcut on the desktop with the Chrome browser application which will allow the user to double click the Chrome icon and open the URL in Chrome.  </p>

<p>To do this, simply open the URL you want to make a shortcut to in the Chrome browser.  Click and drag the "I" or the padlock on to the desktop and your shortcut will be created.  </p>

Body:
There is nothing specific in Kentico in which you can force a user to open a URL in a specific browser.  BUT what you can do is create a URL shortcut on the desktop with the Chrome browser application which will allow the user to double click the Chrome icon and open the URL in Chrome.

To do this, simply open the URL you want to make a shortcut to in the Chrome browser.  Click and drag the "I" or the padlock on to the desktop and your shortcut will be created.


问:
How do I not commit a record on MS-Access?
I have a bound form in microsoft access that allows a user to add data to a table. I want to place a "cancel" button on the form, that if clicked, will stop the record commitment.

What is the command I need to cancel the record commitment?

答:
I have a similar situation where I want the user to confirm whether to save changes, and have used the form's BeforeUpdate event to ask the user if they want to save changes.  It seems to work pretty well, at least in my case.</p>

```<code>Private Sub Form_BeforeUpdate(Cancel As Integer)

    If MsgBox("Do you want to save changes?", vbYesNo, "Confirm change") = vbNo Then
        Cancel = True
    Else
        'Do Nothing
    End If

End Sub
</code>```

Body:
I have a similar situation where I want the user to confirm whether to save changes, and have used the form's BeforeUpdate event to ask the user if they want to save changes.  It seems to work pretty well, at least in my case.

Private Sub Form_BeforeUpdate(Cancel As Integer)

    If MsgBox("Do you want to save changes?", vbYesNo, "Confirm change") = vbNo Then
        Cancel = True
    Else
        'Do Nothing
    End If

End Sub


问:
Lambda can't find modules from outer folders when deployed with CDK
I am deploying some apis to API Gateway using cdk. My problem is the file that contains the lambda(index.ts) can't import any files or npm modules outside that folder(folder named get-users).

I tried copying node_modules folder and other files (which were outside the folder get-users) to the folder get-users and it worked perfectly.

Example error when importing lodash is as follows,

```<code>"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'lodash'",
"stack": [
    "Runtime.ImportModuleError: Error: Cannot find module 'lodash'",
</code>```

I am importing lodash as follows,

```<code>import * as _ from "lodash";
</code>```

I am importing shared files as follows,

```<code>import { validator } from "./shared/validators" // This one works

import { validator } from "../../shared/validators" // This one doesn't work
</code>```

答:
I found the answer after some research. Problem was CDK not deploying the node_modules folder and other folders which are outside the folder which contains the lambda source file.

When creating the lambda file root path has to be added to the 'code' attribute so that it will take all the folders/files inside it and deploy to the lambda.

```<code>    const pathToRoot = //absolute path to the root folder
    const pathToHandler = //path to handler from root folder
    const lambdaFunction: Function = new Function(construct, name, {
        functionName: name,
        code: Code.asset(pathToRoot),
        handler: `${pathToHandler}/index.handler`,
        runtime: Runtime.NODEJS_10_X
    });
</code>```

UPDATE

And after some more research found out the best way to handle this is with Lambda Layers. I have added my node modules folder as a layer.

Body:
I am deploying some apis to API Gateway using cdk. My problem is the file that contains the lambda(index.ts) can't import any files or npm modules outside that folder(folder named get-users).

I tried copying node_modules folder and other files (which were outside the folder get-users) to the folder get-users and it worked perfectly.

Example error when importing lodash is as follows,

"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'lodash'",
"stack": [
    "Runtime.ImportModuleError: Error: Cannot find module 'lodash'",

I am importing lodash as follows,

import * as _ from "lodash";

I am importing shared files as follows,

import { validator } from "./shared/validators" // This one works

import { validator } from "../../shared/validators" // This one doesn't work

Body:
I found the answer after some research. Problem was CDK not deploying the node_modules folder and other folders which are outside the folder which contains the lambda source file.

When creating the lambda file root path has to be added to the 'code' attribute so that it will take all the folders/files inside it and deploy to the lambda.

    const pathToRoot = //absolute path to the root folder
    const pathToHandler = //path to handler from root folder
    const lambdaFunction: Function = new Function(construct, name, {
        functionName: name,
        code: Code.asset(pathToRoot),
        handler: `${pathToHandler}/index.handler`,
        runtime: Runtime.NODEJS_10_X
    });

UPDATE

And after some more research found out the best way to handle this is with Lambda Layers. I have added my node modules folder as a layer.


问:
Window open function works but immediately closes the newly opened window
I have a blob that is returned by the server. What I want to do is open the contents of a blob in a new tab.

I am currently creating a new file-url using that blob. Then I open it using window.open().

The code seems to be working and opens the window for a split second on Chrome.  Then it closes immediately. (I have enabled popup for the domain I am working on).

This is my code.

```<code>this._documentService.download(document.DocumentId).subscribe((data:any) => {
  let fileURL = URL.createObjectURL(data);//data => blob
  window.open(fileURL, '_blank');
},
error => {
  console.log("Error downloading document", error);
});
</code>```

However if I visit the url manually(by copying it from the source and pasting it in the address bar), the tab does not close immediately. It stays put and that is what I want.

I don't know why this is happening. Thanks.

Edit: seems to be working fine in incognito mode.

答: Since you mentioned that it works fine in incognito mode, I assume the reason is browser extension(s), such as ad blockers etc. Try to disable them one by one and you'll find the culprit.</p>

Body:
I have a blob that is returned by the server. What I want to do is open the contents of a blob in a new tab.

I am currently creating a new file-url using that blob. Then I open it using window.open().

The code seems to be working and opens the window for a split second on Chrome.  Then it closes immediately. (I have enabled popup for the domain I am working on).

This is my code.

this._documentService.download(document.DocumentId).subscribe((data:any) => {
  let fileURL = URL.createObjectURL(data);//data => blob
  window.open(fileURL, '_blank');
},
error => {
  console.log("Error downloading document", error);
});

However if I visit the url manually(by copying it from the source and pasting it in the address bar), the tab does not close immediately. It stays put and that is what I want.

I don't know why this is happening. Thanks.

Edit: seems to be working fine in incognito mode.


问:
getting an error- listen EADDRINUSE :::3000 on windows machine
I've searched a lot and I understand there is some process or server running on port 3000, but how can I stop that and run a new express http server on port 3000. There are few answers which tell it for Unix environment..but how to release the port on windows environment using cmd terminal.
Closing the task using PID also didn't work for me.
Thanks in advance </p>

答:
If you're using VS Code in Windows, You would need to first KILL all the previous instances of your Node-App

Afterwards, Open the BASH terminal in VS Code and run below command

cmd "/C TASKKILL /IM node.exe /F"


问:
Display expanded row conditionally for antd tables
I have the following table:

```<code>  <Table
    bordered
    loading={false}
    columns={this.columns(currentUser, fields)}
    dataSource={selectedAssets}
    expandedRowRender={(rec) => <AssetsExtraInformationTable {...rec} />}
    rowKey={(record) => record.id}
    pagination={false}
  />
</code>```

but I'm willing to display the + button of expandedRowRender only when I have data to expand.

I couldn't find something in the API doc, neither in the React component Table API, that allows me to do that, so I wonder if there is any hacky way to do this possible.

答:
Starting Antd version 3.11.3 you can use the expandIcon prop
Example:

```<code>const CustomExpandIcon = props => {
  if (!props.record.subData) return null; //nothing to expand
  if (props.expanded) {
    return (
      <a onClick={e => props.onExpand(props.record, e)}>
        <Icon type="minus" />
      </a>
    );
  } else {
    return (
      <a onClick={e => props.onExpand(props.record, e)}>
        <Icon type="plus" />
      </a>
    );
  }
};
</code>```

and then:

```<code> <Table expandIcon={p => <CustomExpandIcon {...p} />} />
</code>```

Body:
I have the following table:

 <AssetsExtraInformationTable {...rec} />}
    rowKey={(record) => record.id}
    pagination={false}
  />

but I'm willing to display the + button of expandedRowRender only when I have data to expand.

I couldn't find something in the API doc, neither in the React component Table API, that allows me to do that, so I wonder if there is any hacky way to do this possible.

Body:
Starting Antd version 3.11.3 you can use the expandIcon prop
Example:

const CustomExpandIcon = props => {
  if (!props.record.subData) return null; //nothing to expand
  if (props.expanded) {
    return (
      <a onClick={e => props.onExpand(props.record, e)}>
        <Icon type="minus" />
      </a>
    );
  } else {
    return (
      <a onClick={e => props.onExpand(props.record, e)}>
        <Icon type="plus" />
      </a>
    );
  }
};

and then:

 <Table expandIcon={p => <CustomExpandIcon {...p} />} />


问:
Today in history elasticsearch
I want to capture the data in history today.
This Query returns empty. I want to ignore the years.</p>

```<code>"query": {
    "bool": {
      "filter": [
        {
          "range": {
            "created_at": {
              "gte": "02-15",
              "lte": "02-15",
              "format": "MM-dd"
            }
          }
        }
      ]
    }
  }
</code>```

答:
https://www.elastic.co/blog/an-introduction-to-elasticsearch-sql-with-practical-examples-part-1 I got help from article.

adapted it to myself here

```<code>{
  "query" : {
    "bool" : {
      "must" : [
        {
          "script" : {
            "script" : {
              "source" : "InternalSqlScriptUtils.nullSafeFilter(InternalSqlScriptUtils.eq(InternalSqlScriptUtils.dateTimeChrono(InternalSqlScriptUtils.docValue(doc,params.v0), params.v1, params.v2),params.v3))",
              "lang" : "painless",
              "params" : {
                "v0" : "created_at",
                "v1" : "Z",
                "v2" : "DAY_OF_MONTH",
                "v3" : 15
              }
            }
          }
        },
        {
          "script" : {
            "script" : {
              "source" : "InternalSqlScriptUtils.nullSafeFilter(InternalSqlScriptUtils.eq(InternalSqlScriptUtils.dateTimeChrono(InternalSqlScriptUtils.docValue(doc,params.v0), params.v1, params.v2),params.v3))",
              "lang" : "painless",
              "params" : {
                "v0" : "created_at",
                "v1" : "Z",
                "v2" : "MONTH_OF_YEAR",
                "v3" : 2
              }
            }
          }
        }
      ]
    }
  }
}
</code>```

this is how I solved the problem. maybe it will work for someone else.

Title: Today in history elasticsearch

Body:
I want to capture the data in history today.
This Query returns empty. I want to ignore the years.

"query": {
    "bool": {
      "filter": [
        {
          "range": {
            "created_at": {
              "gte": "02-15",
              "lte": "02-15",
              "format": "MM-dd"
            }
          }
        }
      ]
    }
  }

Body:
https://www.elastic.co/blog/an-introduction-to-elasticsearch-sql-with-practical-examples-part-1 I got help from article.

adapted it to myself here

{
  "query" : {
    "bool" : {
      "must" : [
        {
          "script" : {
            "script" : {
              "source" : "InternalSqlScriptUtils.nullSafeFilter(InternalSqlScriptUtils.eq(InternalSqlScriptUtils.dateTimeChrono(InternalSqlScriptUtils.docValue(doc,params.v0), params.v1, params.v2),params.v3))",
              "lang" : "painless",
              "params" : {
                "v0" : "created_at",
                "v1" : "Z",
                "v2" : "DAY_OF_MONTH",
                "v3" : 15
              }
            }
          }
        },
        {
          "script" : {
            "script" : {
              "source" : "InternalSqlScriptUtils.nullSafeFilter(InternalSqlScriptUtils.eq(InternalSqlScriptUtils.dateTimeChrono(InternalSqlScriptUtils.docValue(doc,params.v0), params.v1, params.v2),params.v3))",
              "lang" : "painless",
              "params" : {
                "v0" : "created_at",
                "v1" : "Z",
                "v2" : "MONTH_OF_YEAR",
                "v3" : 2
              }
            }
          }
        }
      ]
    }
  }
}

this is how I solved the problem. maybe it will work for someone else.


问:
How to fix ng build project in angular
How to fix the ng build project in angular without editing in angular.json

here's the error

```<code>Your global Angular CLI version (8.3.16) is greater than your local
version (8.1.3). The local Angular CLI version is used.

To disable this warning use "ng config -g cli.warnings.versionMismatch false".

chunk {0} runtime-es2015.52e4031f7f0d4c5547f5.js (runtime) 2.25 kB [entry] [rendered]
chunk {1} main-es2015.4e8665ff7ceef4e442ee.js (main) 4.62 MB [initial] [rendered]
chunk {2} polyfills-es2015.556027bb8b3cb9b5932e.js (polyfills) 173 kB [initial] [rendered]
chunk {3} styles.26e824d23ac01d2a1ba0.css (styles) 695 kB [initial] [rendered]
chunk {4} 4-es2015.823687dfc617d3f0d9c2.js () 3.43 kB  [rendered]
chunk {5} 5-es2015.f2106b47214935964e1d.js () 2.76 kB  [rendered]
Date: 2019-11-12T03:49:07.167Z - Hash: a28b3171138b993d899e - Time: 134373ms

WARNING in budgets, maximum exceeded for initial. Budget 2 MB was exceeded by 3.47 MB.

ERROR in budgets, maximum exceeded for initial. Budget 5 MB was exceeded by 483 kB.
</code>```

thanks in advance.

I got an error when it comes to 92% and the error is in the above.

答:
I wouldn't suggest changing the budget sizes as they are meant just for this - warn you your bundles are growing too big.

You may consider 2 thing:

Lazy loaded modules for parts of the application that are not visible in the initial screen. You may also combine this with some pre-loading strategy to avoid consequent delays in bundle fetching.

If you've already done the above then most probably the problem is in some (maybe new) import that's adding a lot of code. Some new library you may be importing in multiple places. I've seen this when we started using an external component and imported it in 3 different places. The solution was to put the component in a lazy-loaded module and import in the modules that needed it.

Hope this helps.

Title: How to fix ng build project in angular

Body:
How to fix the ng build project in angular without editing in angular.json

here's the error

Your global Angular CLI version (8.3.16) is greater than your local
version (8.1.3). The local Angular CLI version is used.

To disable this warning use "ng config -g cli.warnings.versionMismatch false".

chunk {0} runtime-es2015.52e4031f7f0d4c5547f5.js (runtime) 2.25 kB [entry] [rendered]
chunk {1} main-es2015.4e8665ff7ceef4e442ee.js (main) 4.62 MB [initial] [rendered]
chunk {2} polyfills-es2015.556027bb8b3cb9b5932e.js (polyfills) 173 kB [initial] [rendered]
chunk {3} styles.26e824d23ac01d2a1ba0.css (styles) 695 kB [initial] [rendered]
chunk {4} 4-es2015.823687dfc617d3f0d9c2.js () 3.43 kB  [rendered]
chunk {5} 5-es2015.f2106b47214935964e1d.js () 2.76 kB  [rendered]
Date: 2019-11-12T03:49:07.167Z - Hash: a28b3171138b993d899e - Time: 134373ms

WARNING in budgets, maximum exceeded for initial. Budget 2 MB was exceeded by 3.47 MB.

ERROR in budgets, maximum exceeded for initial. Budget 5 MB was exceeded by 483 kB.

thanks in advance.

I got an error when it comes to 92% and the error is in the above.


问:
Rails Joins Select Associated Columns not working
I am working on a Ruby on Rails application there,

AnalyticsPage has the below relations. Many to Many relations with the users.

```<code>class AnalyticsPage < ApplicationRecord
  belongs_to :graph_page_layout
  has_many :analytics_pages_users
  has_many :users, through: :analytics_pages_users
  has_many :graph_sections
end

##### query #####
I need to write query where I need to fetch the columns from both of the tables.
analytics_pages = AnalyticsPage.select('users.first_name, users.last_name, analytics_pages.title').joins([:users])
</code>```

The above query is not giving users first name and last name.The other point is that when I am running the SQL query it is running in mysql admin.

答:
Try this

```<code>analytics_pages = AnalyticsPage.joins(:users).pluck('users.first_name,users.last_name')
</code>```

Alternately if the fields first_name and last_name are unambiguous, i.e. there exist no fields by the same name in AnalyticsPage model, then the following should also work

```<code>analytics_pages = AnalyticsPage.joins(:users).pluck([:first_name, :last_name])
</code>```

Edit 1:

If you also need to fetch data from AnalyticsPages model as well, here is the way to go

```<code>analytics_pages = AnalyticsPage.joins(:users).pluck('users.first_name,users.last_name, analytics_pages.field1,analytics_pages.field2')
</code>```

again if the fields are unambiguous the following should work

```<code>AnalyticsPage.joins(:users).pluck(:user_field_1, :analytics_pages_field_1)
</code>```

The key is to think of ModelA.joins(:model_b) as a single table. in this table, the unambiguous fields are names as they were in original tables, and the ambiguous fields are named with a table_name. prefix.

Edit 2:

Even select will work in place of pluck, the difference is that while select returns an array of ActiveRecord objects, pluck returns an array of fields.

Body:
I am working on a Ruby on Rails application there,

AnalyticsPage has the below relations. Many to Many relations with the users.

class AnalyticsPage < ApplicationRecord
  belongs_to :graph_page_layout
  has_many :analytics_pages_users
  has_many :users, through: :analytics_pages_users
  has_many :graph_sections
end

##### query #####
I need to write query where I need to fetch the columns from both of the tables.
analytics_pages = AnalyticsPage.select('users.first_name, users.last_name, analytics_pages.title').joins([:users])

The above query is not giving users first name and last name.The other point is that when I am running the SQL query it is running in mysql admin.

Body:
Try this

analytics_pages = AnalyticsPage.joins(:users).pluck('users.first_name,users.last_name')

Alternately if the fields first_name and last_name are unambiguous, i.e. there exist no fields by the same name in AnalyticsPage model, then the following should also work

analytics_pages = AnalyticsPage.joins(:users).pluck([:first_name, :last_name])

Edit 1:

If you also need to fetch data from AnalyticsPages model as well, here is the way to go

analytics_pages = AnalyticsPage.joins(:users).pluck('users.first_name,users.last_name, analytics_pages.field1,analytics_pages.field2')

again if the fields are unambiguous the following should work

AnalyticsPage.joins(:users).pluck(:user_field_1, :analytics_pages_field_1)

The key is to think of ModelA.joins(:model_b) as a single table. in this table, the unambiguous fields are names as they were in original tables, and the ambiguous fields are named with a table_name. prefix.

Edit 2:

Even select will work in place of pluck, the difference is that while select returns an array of ActiveRecord objects, pluck returns an array of fields.


问:
How browser knows that he need to connect to stun/turn server?
For example I want to share media traphic with WEBRtc.
Obviously if I want to go through NAT.
I need to use STUN/TURN server.
And when WEBRtc starts to share ICE candidates - how the browser knows that STUN/TURN server exists and it should go there first?

Thank's.

答:
WebRTC in Browser begins to analyze the status of the network connection (in fact, the standard does not indicate when to do this, and for many browsers, WebRTC starts to study the network immediately after creating the corresponding objects, so as not to create unnecessary delays when connecting). When the developer in the first steps was creating WebRTC objects, he should at least pass the address of the STUN server. This is a server that, in response to the UDP packet “what is my IP”, transmits the IP address from which this packet was received. WebRTC uses the STUN server to get an “external” IP address, compare it with an “internal” one and see if there is NAT. And if so, which reverse ports does NAT use to route UDP packets?

From time to time, WebRTC on the browser will call the onicecandidate callback, transmitting the SIP packet with information for the second connection participant. This packet contains information about internal and external IP addresses, connection attempts, ports used by NAT, and so on. The developer uses signaling to transfer these packets between Browsers. The transmitted packet is sent to WebRTC using the addIceCandidate() method.
After a while, WebRTC will establish a peer-to-peer connection. Or will not be able if NAT will interfere. For such cases, the developer can transmit the address of the TURN server, which will be used as an external connecting element: both browsers will transmit UDP packets with voice or video through it.

You pass STUN/TURN servers configuration when initially create RTCPeerConnection.


问:
Images flowing out of a tablet layout inside a constraint layout
I'm facing troubles with a TableLayout here. My goal would be to make two columns with equal width, each one with one image that should adjust it's width so it fits inside the cell's available space, but it seems the images keep overflowing outside the available space in the cell/row. I have tested some properties without luck so far, so I could use some help here.

This is the current outcome in the design view:

I'd have expected the teddy bear to occupy only 50% of the row width at the left, and then the other image (which is an umbrella) to fit into the remaining 50% at the right of the bear. But you see that's not what's happening.

This is the layout code:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.DebugFragment">

    <TableLayout
        android:id="@+id/tableImages"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:stretchColumns="*"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TableRow
            android:layout_width="0dp"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="16dp"
                app:srcCompat="@drawable/teddy_bear" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="16dp"
                tools:srcCompat="@drawable/umbrella" />

        </TableRow>
    </TableLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

UPDATE: Following Jakob F advice of replacing stretchColumns with shrinkColumns solves the issue with the image overflowing the layout boundaries, but breaks the requirement of both columns being of same width. See image:

UPDATE: Keeping the stretchColumns="*" and setting the layout_width of each image to 0dp does the trick of keeping them inside the layout boundaries AND make both columns the same with. Now I just have to figure out how to keep them at the same height, but that's a different issue I think.

UPDATE: Adding android:scaleType="fitStart" to both images aligns both of them to the top as desired, but it keeps adding space under the images for no reason (I have changed the background color so the limits of the images are more obvious).

答: You need to use android:shrinkColumns="*" instead of android:strechColumns="*" to make all columns shrinkable, so that the width is automatically determined to fit the images on screen. Stretching them would only enable them to become larger.

Body:
I'm facing troubles with a TableLayout here. My goal would be to make two columns with equal width, each one with one image that should adjust it's width so it fits inside the cell's available space, but it seems the images keep overflowing outside the available space in the cell/row. I have tested some properties without luck so far, so I could use some help here.

This is the current outcome in the design view:

I'd have expected the teddy bear to occupy only 50% of the row width at the left, and then the other image (which is an umbrella) to fit into the remaining 50% at the right of the bear. But you see that's not what's happening.

This is the layout code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.DebugFragment">

    <TableLayout
        android:id="@+id/tableImages"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:stretchColumns="*"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TableRow
            android:layout_width="0dp"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="16dp"
                app:srcCompat="@drawable/teddy_bear" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="16dp"
                tools:srcCompat="@drawable/umbrella" />

        </TableRow>
    </TableLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

UPDATE: Following Jakob F advice of replacing stretchColumns with shrinkColumns solves the issue with the image overflowing the layout boundaries, but breaks the requirement of both columns being of same width. See image:

UPDATE: Keeping the stretchColumns="*" and setting the layout_width of each image to 0dp does the trick of keeping them inside the layout boundaries AND make both columns the same with. Now I just have to figure out how to keep them at the same height, but that's a different issue I think.

UPDATE: Adding android:scaleType="fitStart" to both images aligns both of them to the top as desired, but it keeps adding space under the images for no reason (I have changed the background color so the limits of the images are more obvious).


问:
Keras: fit_generator NotImplementedError
I am having problem with model.fit_generator, it throws me NotImplementedError  and I don't know where is the problem. Under the older Keras and TF it is working but after years I tried to update to new version and problem occured.

Whene I use:

```<code>model.fit_generator(generator=generator_train,
                        steps_per_epoch=generator_train.n / batch_size,
                        epochs=20,
                        verbose=1,
                        validation_data=generator_val,
                        validation_steps=math.ceil(generator_val.n / batch_size),
                        callbacks=[tb_callback, saver_callback],
                        use_multiprocessing=False,
                        initial_epoch=0
                        )
</code>```

I got this error

My Generator:

```<code>import cv2
import numpy as np
from keras.preprocessing.image import Iterator
from boxcars_image_transformations import alter_HSV, image_drop, unpack_3DBB, add_bb_noise_flip
import random

#%%

class BoxCarsDataGenerator(Iterator):
    def __init__(self, dataset, part, batch_size=8, training_mode=False, seed=None, generate_y = True, image_size = (224,224)):
        assert image_size == (224,224), "only images 224x224 are supported by unpack_3DBB for now, if necessary it can be changed"
        assert dataset.X[part] is not None, "load some classification split first"
        super().__init__(dataset.X[part].shape[0], batch_size, training_mode, seed)
        self.part = part
        self.generate_y = generate_y
        self.dataset = dataset
        self.image_size = image_size
        self.training_mode = training_mode
        if self.dataset.atlas is None:
            self.dataset.load_atlas()
        print("ANOOO TU SOM")

    #%%
    def __next__(self):
        with self.lock:
            index_array, current_index, current_batch_size = next(self.index_generator)
        x = np.empty([current_batch_size] + list(self.image_size) + [3], dtype=np.float32)
        for i, ind in enumerate(index_array):
            vehicle_id, instance_id = self.dataset.X[self.part][ind]
            vehicle, instance, bb3d = self.dataset.get_vehicle_instance_data(vehicle_id, instance_id)
            image = self.dataset.get_image(vehicle_id, instance_id)
            if self.training_mode:
                image = alter_HSV(image) # randomly alternate color
                image = image_drop(image) # randomly remove part of the image
                bb_noise = np.clip(np.random.randn(2) * 1.5, -5, 5) # generate random bounding box movement
                flip = bool(random.getrandbits(1)) # random flip
                image, bb3d = add_bb_noise_flip(image, bb3d, flip, bb_noise)

            image = unpack_3DBB(image, bb3d)
            image = (image.astype(np.float32) - 116)/128.
            x[i, ...] = image
        if not self.generate_y:
            return x
        y = self.dataset.Y[self.part][index_array]
        return x, y

</code>```

答:
EDIT 2: how to fix your issue:

You want to add :

```<code>def __getitem__(self, item):
    return self.__next__()
</code>```

In your BoxCarsDataGenerator

EDIT: after looking the problem in more detail, the problem comes from Keras' Iterator class ; when iterating over your BoxCarsDataGenerator, __getitem__ returns:

```<code>self._get_batches_of_transformed_samples(index_array)
</code>```

And _get_batches_of_transformed_samples is defined as:

```<code>def _get_batches_of_transformed_samples(self, index_array):
    """Gets a batch of transformed samples.

    # Arguments
        index_array: Array of sample indices to include in batch.

    # Returns
        A batch of transformed samples.
    """
    raise NotImplementedError
</code>```

In conclusion, you shouldn't use Keras' Iterator as it seems not to be implemented yet.

END OF EDIT

fit_generator is now deprecated as fit can handle generators too, you can take a look at this post: https://stackoverflow.com/a/59381897/12896974

Body:
I am having problem with model.fit_generator, it throws me NotImplementedError  and I don't know where is the problem. Under the older Keras and TF it is working but after years I tried to update to new version and problem occured.

Whene I use:

model.fit_generator(generator=generator_train,
                        steps_per_epoch=generator_train.n / batch_size,
                        epochs=20,
                        verbose=1,
                        validation_data=generator_val,
                        validation_steps=math.ceil(generator_val.n / batch_size),
                        callbacks=[tb_callback, saver_callback],
                        use_multiprocessing=False,
                        initial_epoch=0
                        )

I got this error

My Generator:

import cv2
import numpy as np
from keras.preprocessing.image import Iterator
from boxcars_image_transformations import alter_HSV, image_drop, unpack_3DBB, add_bb_noise_flip
import random

#%%

class BoxCarsDataGenerator(Iterator):
    def __init__(self, dataset, part, batch_size=8, training_mode=False, seed=None, generate_y = True, image_size = (224,224)):
        assert image_size == (224,224), "only images 224x224 are supported by unpack_3DBB for now, if necessary it can be changed"
        assert dataset.X[part] is not None, "load some classification split first"
        super().__init__(dataset.X[part].shape[0], batch_size, training_mode, seed)
        self.part = part
        self.generate_y = generate_y
        self.dataset = dataset
        self.image_size = image_size
        self.training_mode = training_mode
        if self.dataset.atlas is None:
            self.dataset.load_atlas()
        print("ANOOO TU SOM")

    #%%
    def __next__(self):
        with self.lock:
            index_array, current_index, current_batch_size = next(self.index_generator)
        x = np.empty([current_batch_size] + list(self.image_size) + [3], dtype=np.float32)
        for i, ind in enumerate(index_array):
            vehicle_id, instance_id = self.dataset.X[self.part][ind]
            vehicle, instance, bb3d = self.dataset.get_vehicle_instance_data(vehicle_id, instance_id)
            image = self.dataset.get_image(vehicle_id, instance_id)
            if self.training_mode:
                image = alter_HSV(image) # randomly alternate color
                image = image_drop(image) # randomly remove part of the image
                bb_noise = np.clip(np.random.randn(2) * 1.5, -5, 5) # generate random bounding box movement
                flip = bool(random.getrandbits(1)) # random flip
                image, bb3d = add_bb_noise_flip(image, bb3d, flip, bb_noise)

            image = unpack_3DBB(image, bb3d)
            image = (image.astype(np.float32) - 116)/128.
            x[i, ...] = image
        if not self.generate_y:
            return x
        y = self.dataset.Y[self.part][index_array]
        return x, y

Body:
EDIT 2: how to fix your issue:

You want to add :

def __getitem__(self, item):
    return self.__next__()

In your BoxCarsDataGenerator

EDIT: after looking the problem in more detail, the problem comes from Keras' Iterator class ; when iterating over your BoxCarsDataGenerator, __getitem__ returns:

self._get_batches_of_transformed_samples(index_array)

And _get_batches_of_transformed_samples is defined as:

def _get_batches_of_transformed_samples(self, index_array):
    """Gets a batch of transformed samples.

    # Arguments
        index_array: Array of sample indices to include in batch.

    # Returns
        A batch of transformed samples.
    """
    raise NotImplementedError

In conclusion, you shouldn't use Keras' Iterator as it seems not to be implemented yet.

END OF EDIT

fit_generator is now deprecated as fit can handle generators too, you can take a look at this post: https://stackoverflow.com/a/59381897/12896974


问:
save cv_results_['params'] from grid search as csv
I would like to save my scores and parameters used in my grid search as a csv file. The problem is, that the parameters are all saved in the same column. Here is an example:

```<code>param_grid=dict(batch_size=batch_size, epochs=epochs)

grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1, cv=3)
grid_result = grid.fit(x_train, y_train, validation_data=(x_test, y_test), callbacks=[es])

means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
param = grid_result.cv_results_['params']

exportfile='/Users/test.csv'
with open(exportfile, 'w', newline='') as file:
    writer = csv.writer(file)
    for mean, stdev, param in zip(means, stds, params):
        writer.writerow([mean, stdev, param])
</code>```

The output of the param is like this:

{'batch_size': 40, 'epochs': 1000}

but I want to reduce it to:

40, 1000

答:
If params = {'batch_size': 40, 'epochs': 1000}
then do

list(params.values()) and this will be [40, 1000].

If params is an array of hashes, i.e: [{'batch_size': 40, 'epochs': 1000}, {'batch_size': 30, 'epochs': 1100}] then you can do this:

list(map(lambda p: list(p.values()), params)) this will result in: [[40, 1000], [30, 1100]]

Body:
I would like to save my scores and parameters used in my grid search as a csv file. The problem is, that the parameters are all saved in the same column. Here is an example:

param_grid=dict(batch_size=batch_size, epochs=epochs)

grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1, cv=3)
grid_result = grid.fit(x_train, y_train, validation_data=(x_test, y_test), callbacks=[es])

means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
param = grid_result.cv_results_['params']

exportfile='/Users/test.csv'
with open(exportfile, 'w', newline='') as file:
    writer = csv.writer(file)
    for mean, stdev, param in zip(means, stds, params):
        writer.writerow([mean, stdev, param])

The output of the param is like this:

{'batch_size': 40, 'epochs': 1000}

but I want to reduce it to:

40, 1000


问:
Need Studies, Proof or Research That Show Image Copy Protection Is Not Worth It
I am trying to convince someone that image copy protection such as watermarks, javascript no right clicks, blank image overlays etc is not worth the effort since they are easily bypassed by even non-technical users.

I am also trying to convince them that these measures annoys customers as it impedes the user experience and does nothing to prevent image theft. At the end of the day if its on the internet, its public and people can take it if they want.

So what I'm looking for is a good study, proof, research, anything which has numbers to back up a fall in sales, user experience etc before and after these measures.

Any ideas?

答:
That might not be what you wanna hear, but a full-size Watermark (not just a overlay-graphic) is a solid protection for pictures.

The rest can be easily explained:

The user can deactivate JavaScript

Overlays of all sort are worthless, the user just need to look at his cache, use a browserplugin or in new browser use the debugging tools to get the origin image