问:
Using output from BeautifulSoup as input in a loop
I'm learning python to scrape data from this specific game website. With the help of this community, I got solutions for most of my questions.
I am trying to scrape data from an airline management game website which shows distance, runway length, passenger demand, etc... between airports. Here is my code

import requests
from bs4 import BeautifulSoup

data = {'lEmail': '<myEmailid>',
        'lPass': '<Password>',
        'fbSig': 'web'}

login_url = 'https://www.airline4.net/weblogin/login.php'
url = 'https://www.airline4.net/research_main.php?mode=search&rwy=1000&dist=19210&depId=600&arr=0&arrId=0&fbSig=false'

with requests.session() as s:
    s.post(login_url, data=data).text

    # now you are logged in, just print some information:
    distance = 19210
    departure_id = 600
    while distance != 'stop':
        url = 'https://www.airline4.net/research_main.php?mode=search&rwy=1000&dist=' + str(distance) + '&depId=' + str(departure_id) + '&arr=0&arrId=0&fbSig=false'
        soup = BeautifulSoup(s.get(url).content, 'html.parser')
        print(soup.get_text(strip=True, separator='\n'))

        distance = input()```
</div>
</div>
</p>

<p>Here, I am manually entering variable <code>distance</code> and using it in my url.
The output I get is:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>C:\Users\Administrator\PycharmProjects\Project1\venv\Scripts\python.exe C:/Users/Administrator/PycharmProjects/Project1/Airline3.py
Distance
Y class
J class
F class
Rwy
EHBK
-
NZCI
Netherlands, Maastricht
-
New Zealand, Waitangi
19,208 km
4,462ft rwy
Market:
71%
Y class
211
J class
94
F class
76
EHBK
-
NZDN
Netherlands, Maastricht
-
New Zealand, Dunedin
18,743 km
6,234ft rwy
Market:
38%
Y class
180
J class
122
F class
74
EHBK
-
NZOU
Netherlands, Maastricht
-
New Zealand, Oamaru
18,740 km
4,210ft rwy
Market:
39%
Y class
103
J class
137
F class
44
EHBK
-
NZCH
Netherlands, Maastricht
-
New Zealand, Christchurch
18,722 km
10,787ft rwy
Market:
81%
Y class
253
J class
62
F class
81
EHBK
-
NZTU
Netherlands, Maastricht
-
New Zealand, Timaru
18,704 km
4,200ft rwy
Market:
35%
Y class
289
J class
92
F class
29</code>```

In this result, Is there any way to use that 18,704 km as input(should be selected automatically, without my intervention) for my loop?

答:
You have to use the findAll function to get a list of all the balise div with the appropriate attribute (see code below). This way, you can loop through each airport.

This way, you can then look for the precise elements you are searching for, and then compute an exit of your choice.

The code needs to be customized, but it is a good starting point.

distance = 19210
departure_id = 600
table = soup.findAll('div', attrs={'class': 'row border opa sorter'})
for apt in table:
    apt_detail = apt.findAll('div')
    for elem in apt_detail:
        print(elem.text.split('\n'))
```

<p>output:</p>

```['', '', '', '     EHBK', '    ', '    -', '    ', '     NZCI', '    ', '', '', '    Netherlands, Maastricht', '   ', '   -', '   ', '    New Zealand, Waitangi', '   ', '', '']
['', '', '     EHBK', '    ', '    -', '    ', '     NZCI', '    ', '']
['', '', '', '     19,208 km', '    ', '', '    4,462ft rwy', '   ', '   Market:', '   ', '    71%', '   ', '']
['', '', '     19,208 km', '    ', '', '    4,462ft rwy', '   ']
...
```

Body:
I'm learning python to scrape data from this specific game website. With the help of this community, I got solutions for most of my questions.
I am trying to scrape data from an airline management game website which shows distance, runway length, passenger demand, etc... between airports. Here is my code

import requests
from bs4 import BeautifulSoup

data = {'lEmail': '<myEmailid>',
        'lPass': '<Password>',
        'fbSig': 'web'}

login_url = 'https://www.airline4.net/weblogin/login.php'
url = 'https://www.airline4.net/research_main.php?mode=search&rwy=1000&dist=19210&depId=600&arr=0&arrId=0&fbSig=false'

with requests.session() as s:
    s.post(login_url, data=data).text

    # now you are logged in, just print some information:
    distance = 19210
    departure_id = 600
    while distance != 'stop':
        url = 'https://www.airline4.net/research_main.php?mode=search&rwy=1000&dist=' + str(distance) + '&depId=' + str(departure_id) + '&arr=0&arrId=0&fbSig=false'
        soup = BeautifulSoup(s.get(url).content, 'html.parser')
        print(soup.get_text(strip=True, separator='\n'))

        distance = input()

Here, I am manually entering variable distance and using it in my url.
The output I get is:

C:\Users\Administrator\PycharmProjects\Project1\venv\Scripts\python.exe C:/Users/Administrator/PycharmProjects/Project1/Airline3.py
Distance
Y class
J class
F class
Rwy
EHBK
-
NZCI
Netherlands, Maastricht
-
New Zealand, Waitangi
19,208 km
4,462ft rwy
Market:
71%
Y class
211
J class
94
F class
76
EHBK
-
NZDN
Netherlands, Maastricht
-
New Zealand, Dunedin
18,743 km
6,234ft rwy
Market:
38%
Y class
180
J class
122
F class
74
EHBK
-
NZOU
Netherlands, Maastricht
-
New Zealand, Oamaru
18,740 km
4,210ft rwy
Market:
39%
Y class
103
J class
137
F class
44
EHBK
-
NZCH
Netherlands, Maastricht
-
New Zealand, Christchurch
18,722 km
10,787ft rwy
Market:
81%
Y class
253
J class
62
F class
81
EHBK
-
NZTU
Netherlands, Maastricht
-
New Zealand, Timaru
18,704 km
4,200ft rwy
Market:
35%
Y class
289
J class
92
F class
29

In this result, Is there any way to use that 18,704 km as input(should be selected automatically, without my intervention) for my loop?

Body:
You have to use the findAll function to get a list of all the balise div with the appropriate attribute (see code below). This way, you can loop through each airport.

This way, you can then look for the precise elements you are searching for, and then compute an exit of your choice.

The code needs to be customized, but it is a good starting point.

distance = 19210
departure_id = 600
table = soup.findAll('div', attrs={'class': 'row border opa sorter'})
for apt in table:
    apt_detail = apt.findAll('div')
    for elem in apt_detail:
        print(elem.text.split('\n'))

output:

['', '', '', '     EHBK', '    ', '    -', '    ', '     NZCI', '    ', '', '', '    Netherlands, Maastricht', '   ', '   -', '   ', '    New Zealand, Waitangi', '   ', '', '']
['', '', '     EHBK', '    ', '    -', '    ', '     NZCI', '    ', '']
['', '', '', '     19,208 km', '    ', '', '    4,462ft rwy', '   ', '   Market:', '   ', '    71%', '   ', '']
['', '', '     19,208 km', '    ', '', '    4,462ft rwy', '   ']
...


来源: stackexchange

问:
How do I read the Windows NTFS $Secure file (and/or the $SDS stream) programmatically in C#
The methods in the .NET platform's DirectorySecurity namespace (e.g. GetAccessRules()) are far too slow for my purposes.  Instead, I wish to directly query the NTFS $Secure metafile (or, alternatively, the $SDS stream) in order to retrieve a list of local accounts and their associated permissions for each file system object.

My plan is to first read the $MFT metafile (which I've already figured out how to do) - and then, for each entry therein, look up the appropriate security descriptor in the metafile (or stream).

The ideal code block would look something like this:

```<code>//I've already successfully written code for MFTReader:
var mftReader = new MFTReader(driveToAnalyze, RetrieveMode.All);
IEnumerable<INode> nodes = mftReader.GetNodes(driveToAnalyze.Name);

foreach (NodeWrapper node in nodes)
{
    //Now I wish to return security information for each file system object
    //WITHOUT needing to traverse the directory tree.
    //This is where I need help:
    var securityInfo = GetSecurityInfoFromMetafile(node.FullName, node.SecurityID);
    yield return Tuple.Create(node.FullName, securityInfo.PrincipalName, DecodeAccessMask(securityInfo.AccessMask));
}
</code>```

And I would like my output to look like this:

```<code>c:\Folder1\File1.txt    jane_smith  Read, Write, Execute
c:\Folder1\File1.txt    bill_jones  Read, Execute
c:\Folder1\File2.txt    john_brown  Full Control
etc.
</code>```

I am running .NET version 4.7.1 on the Windows 10.

答:
Are you using FSCTL_QUERY_FILE_LAYOUT? The only real source of how to use this function I have found is here:
https://wimlib.net/git/?p=wimlib;a=blob;f=src/win32_capture.c;h=d62f7d07ef20c08c9bec93f261131033e39b159b;hb=HEAD

It looks like he solves the problem with security descriptors like this:
He gets basically all information about files from the MFT, but not security descriptors. For those he gets the field SecurityId from the MFT and looks in a hash table whether he already has a mapping from this ID to the ACL. If he has, he just returns it, otherwise he uses NtQuerySecurityObject and caches it in the hash table. This should drastically reduce the amount of calls. It assumes that there are few security descriptors and that the SecurityID field correctly represents the single instancing of the descriptors

ContentLicense: CC BY-SA 4.0

Body:
The methods in the .NET platform's DirectorySecurity namespace (e.g. GetAccessRules()) are far too slow for my purposes.  Instead, I wish to directly query the NTFS $Secure metafile (or, alternatively, the $SDS stream) in order to retrieve a list of local accounts and their associated permissions for each file system object.

My plan is to first read the $MFT metafile (which I've already figured out how to do) - and then, for each entry therein, look up the appropriate security descriptor in the metafile (or stream).

The ideal code block would look something like this:

//I've already successfully written code for MFTReader:
var mftReader = new MFTReader(driveToAnalyze, RetrieveMode.All);
IEnumerable<INode> nodes = mftReader.GetNodes(driveToAnalyze.Name);

foreach (NodeWrapper node in nodes)
{
    //Now I wish to return security information for each file system object
    //WITHOUT needing to traverse the directory tree.
    //This is where I need help:
    var securityInfo = GetSecurityInfoFromMetafile(node.FullName, node.SecurityID);
    yield return Tuple.Create(node.FullName, securityInfo.PrincipalName, DecodeAccessMask(securityInfo.AccessMask));
}

And I would like my output to look like this:

c:\Folder1\File1.txt    jane_smith  Read, Write, Execute
c:\Folder1\File1.txt    bill_jones  Read, Execute
c:\Folder1\File2.txt    john_brown  Full Control
etc.

I am running .NET version 4.7.1 on the Windows 10.


问:
Javascript Object - Compress & Count in Svelte
Consider this code that is accessing the data of a javascript object.

```<code>animalData.animal[i].type

'animal' : [
  {'type':'dog', 'colour':'brown'},
  {'type':'dog', 'colour':'yellow'},
  {'type':'cat', 'colour':'grey'},
  {'type':'chicken', 'colour':'orange'},
  {'type':'frog', 'colour':'green'},
  {'type':'cat', 'colour':'pink'},
  {'type':'dog', 'colour':'yellow'},
  {'type':'cat', 'colour':'grey'},
  {'type':'chicken', 'colour':'black'},
  {'type':'dog', 'colour':'yellow'}
]
</code>```

Using modern JS how can I transform the above into another array of objects that looks like this. eg. shows a count of each and removes the duplicates?

```<code>[
  {'type':'dog', 'count':'4'},
  {'type':'cat', 'count':'3'},
  {'type':'chicken', 'count':'2'},
  {'type':'frog', 'count':'1'},
]
</code>```

答:
You can reduce it and take Object values:

var data=[ {'type':'dog', 'colour':'brown'}, {'type':'dog', 'colour':'yellow'}, {'type':'cat', 'colour':'grey'}, {'type':'chicken', 'colour':'orange'}, {'type':'frog', 'colour':'green'}, {'type':'cat', 'colour':'pink'}, {'type':'dog', 'colour':'yellow'}, {'type':'cat', 'colour':'grey'}, {'type':'chicken', 'colour':'black'}, {'type':'dog', 'colour':'yellow'}];

var result = Object.values(data.reduce((acc, {type})=>{
  acc[type] = acc[type] || { type, count:0 };
  acc[type].count += 1;
  return acc;
},{}));

console.log(result);```

Body:
Consider this code that is accessing the data of a javascript object.

animalData.animal[i].type

'animal' : [
  {'type':'dog', 'colour':'brown'},
  {'type':'dog', 'colour':'yellow'},
  {'type':'cat', 'colour':'grey'},
  {'type':'chicken', 'colour':'orange'},
  {'type':'frog', 'colour':'green'},
  {'type':'cat', 'colour':'pink'},
  {'type':'dog', 'colour':'yellow'},
  {'type':'cat', 'colour':'grey'},
  {'type':'chicken', 'colour':'black'},
  {'type':'dog', 'colour':'yellow'}
]

Using modern JS how can I transform the above into another array of objects that looks like this. eg. shows a count of each and removes the duplicates?

[
  {'type':'dog', 'count':'4'},
  {'type':'cat', 'count':'3'},
  {'type':'chicken', 'count':'2'},
  {'type':'frog', 'count':'1'},
]


问:
How do I make impulse noise image efficiently using numpy?
I've been trying to create noisy image using the following piece of code:

```<code>def toImpulse(img, coef=1.2): # img - > 3dim numpy array, returns impulse image
    bmp = np.zeros(shape=(img.shape[0], img.shape[1], 1), dtype=np.float)
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            bmp[i][j] = sum(img[i][j]) / 3
</code>```

Here I'm summing over the RGB channel and making the image single-channeled? I guess it can be written as numpy.sum()

```<code>    sum_ = 0
    max_ = np.amax(bmp)
    final = np.zeros(img.shape)
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            sum_ += bmp[i][j]
            if sum_ >= coef * max_:
                final[i][j] = 1
                sum_ -= coef * max_
            else:
                final[i][j] = 0

    return final
</code>```

But it occurred to be very slow in real-time video processing. How can I make it more efficient using NumPy? Here is the example of the function's work
The original image
Noisy image

答:
Your code takes 539ms on my machine. If I use Numpy to calculate the mean of the 3 colour channels and avoid writing zeroes to the output image because it is already initialised to zero like this:

```<code>def metoImpulse(img, coef=1.2):
    # Get mean of the 3 colour channels
    bmp = np.mean(img, axis=-1, dtype=np.float32)
    sum_ = 0
    max_ = np.amax(bmp)
    final = np.zeros_like(img[...,0])
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            sum_ += bmp[i][j]
            if sum_ >= coef * max_:
                final[i][j] = 1
                sum_ -= coef * max_
    return final
</code>```

The time goes down from 539ms to 257ms. If I then use Numba by adding a decorator before my function:

```<code>@jit(parallel=True)
def metoImpulse(img, coef=1.2):
   # Get mean of the 3 colour channels
   bmp = np.mean(img, axis=-1, dtype=np.float32)
   sum_ = 0
   max_ = np.amax(bmp)
   final = np.zeros_like(img[...,0])
   for i in range(img.shape[0]):
      for j in range(img.shape[1]):
         sum_ += bmp[i][j]
         if sum_ >= coef * max_:
            final[i][j] = 1
            sum_ -= coef * max_
   return final
</code>```

The time goes down from 257ms to 1.11ms.

Input image:

Output image:

Body:
I've been trying to create noisy image using the following piece of code:

def toImpulse(img, coef=1.2): # img - > 3dim numpy array, returns impulse image
    bmp = np.zeros(shape=(img.shape[0], img.shape[1], 1), dtype=np.float)
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            bmp[i][j] = sum(img[i][j]) / 3

Here I'm summing over the RGB channel and making the image single-channeled? I guess it can be written as numpy.sum()

    sum_ = 0
    max_ = np.amax(bmp)
    final = np.zeros(img.shape)
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            sum_ += bmp[i][j]
            if sum_ >= coef * max_:
                final[i][j] = 1
                sum_ -= coef * max_
            else:
                final[i][j] = 0

    return final

But it occurred to be very slow in real-time video processing. How can I make it more efficient using NumPy? Here is the example of the function's work
The original image
Noisy image

Body:
Your code takes 539ms on my machine. If I use Numpy to calculate the mean of the 3 colour channels and avoid writing zeroes to the output image because it is already initialised to zero like this:

def metoImpulse(img, coef=1.2):
    # Get mean of the 3 colour channels
    bmp = np.mean(img, axis=-1, dtype=np.float32)
    sum_ = 0
    max_ = np.amax(bmp)
    final = np.zeros_like(img[...,0])
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            sum_ += bmp[i][j]
            if sum_ >= coef * max_:
                final[i][j] = 1
                sum_ -= coef * max_
    return final

The time goes down from 539ms to 257ms. If I then use Numba by adding a decorator before my function:

@jit(parallel=True)
def metoImpulse(img, coef=1.2):
   # Get mean of the 3 colour channels
   bmp = np.mean(img, axis=-1, dtype=np.float32)
   sum_ = 0
   max_ = np.amax(bmp)
   final = np.zeros_like(img[...,0])
   for i in range(img.shape[0]):
      for j in range(img.shape[1]):
         sum_ += bmp[i][j]
         if sum_ >= coef * max_:
            final[i][j] = 1
            sum_ -= coef * max_
   return final

The time goes down from 257ms to 1.11ms.

Input image:

Output image:


答:
First outer join two tables, then following

```<code>with join_table as (
select coleasce(t1.date, t2.date) as date, t2.id, t2.amount
  from table1 as t1
  outer join table2 as t2
    on t1.date = t2.date
)
, rank_table as (
select *, SUM(id) OVER (ORDER BY d_day ROWS BETWEEN unbounded preceding and CURRENT ROW) as id_rnk,
SUM(amount) OVER (ORDER BY d_day ROWS BETWEEN unbounded preceding and CURRENT ROW) as amount_rnk
  from join_table
)
select *, max(id) over (partition by id_rnk), max(amount) over (partition by amount_rnk)
  from rank_table
</code>```

Check this answer for more details.

Title: Repeat previous values by date in hive

Body:
I have 2 tables - Dates and Data with data as follows:
Table: Dates

Date
1/02/2020
2/02/2020
3/02/2020
4/02/2020
5/02/2020
6/02/2020
7/02/2020
8/02/2020
9/02/2020
10/02/2020

Table: Data

Date    Id  Amount
1/02/2020   1   10
3/02/2020   1   30
10/02/2020  1   50
2/02/2020   2   5
6/02/2020   2   10
9/02/2020   2   20

Expected results:

Date    Id  Amount
1/02/2020   1   10
2/02/2020   1   10
3/02/2020   1   30
4/02/2020   1   30
5/02/2020   1   30
6/02/2020   1   30
7/02/2020   1   30
8/02/2020   1   30
9/02/2020   1   30
10/02/2020  1   50
2/02/2020   2   5
3/02/2020   2   5
4/02/2020   2   5
5/02/2020   2   5
6/02/2020   2   10
7/02/2020   2   10
8/02/2020   2   10
9/02/2020   2   20

I have tried using PARTITION OVER but getting duplicate vales and not all dates from Dates table, therefore not getting desired results. Really appreciate if you can help with the code in Hive SQL.

Body:
First outer join two tables, then following

with join_table as (
select coleasce(t1.date, t2.date) as date, t2.id, t2.amount
  from table1 as t1
  outer join table2 as t2
    on t1.date = t2.date
)
, rank_table as (
select *, SUM(id) OVER (ORDER BY d_day ROWS BETWEEN unbounded preceding and CURRENT ROW) as id_rnk,
SUM(amount) OVER (ORDER BY d_day ROWS BETWEEN unbounded preceding and CURRENT ROW) as amount_rnk
  from join_table
)
select *, max(id) over (partition by id_rnk), max(amount) over (partition by amount_rnk)
  from rank_table

Check this answer for more details.


问:
Angular component (with a directive) testing
I have a component I want to test. The test fails with message

AdminPanelComponent > should create

TypeError: Cannot read property 'role' of undefined

error properties: Object({ ngDebugContext: DebugContext_({ view:
  Object({ def: Object({ factory: Function, nodeFlags: 50577443,
  rootNodeFlags: 1, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({
  nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0,
  outputIndex: 0, checkIndex: 0, flags: 1, childFlags: 50577443,
  directChildFlags: 1, childMatchedQueries: 0, matchedQueries: Object({
  }), matchedQueryIds: 0, references: Object({  }), ngContentIndex:
  null, childCount: 11, bindings: [  ], bindingFlags: 0, outputs: [  ],
  element: Object({ ns: '', name: 'div', attrs: [ Array ], template:
  null, componentProvider: null, componentView: null,
  componentRendererType: null, publicProviders: null({  }),
  allProviders: null({  }), handleEvent: Function }), provider: null,
  text: null, query: null, ngContent: null }), Object({ nodeIndex: 1,
  parent: Object({ nodeIndex: 0, parent: null, renderParent: null,
  bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 1, childFlags:
  50577443, directChildFlags: 1, chi ...
      at
      at HasRoleDirective.ngOnInit (http://localhost:9876/_karma_webpack_/src/app/_directives/hasRole.directive.ts:16:53)
      at checkAndUpdateDirectiveInline (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:26276:1)
      at checkAndUpdateNodeInline (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:37133:1)
      at checkAndUpdateNode (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:37072:1)
      at debugCheckAndUpdateNode (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:38094:36)
      at debugCheckDirectivesFn (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:38037:1)
      at Object.eval [as updateDirectives] (ng:///DynamicTestModule/AdminPanelComponent.ngfactory.js:62:5)
      at Object.debugUpdateDirectives [as updateDirectives] (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:38025:1)
      at checkAndUpdateView (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:37037:1)
      at callViewAction (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:37403:1)

admin-panel.component.ts

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-admin-panel',
  templateUrl: './admin-panel.component.html',
  styleUrls: ['./admin-panel.component.css']
})
export class AdminPanelComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

</code>```

admin-panel.component.html

```<code><div class="container mt-5">
  <h2>Admin panel</h2>
  <div class="tab-panel">
    <tabset class="member-tabset">
      <tab heading="User Management" *appHasRole="['Admin']">
        <div class="container">
            <app-user-management></app-user-management>
        </div>
      </tab>
      <tab heading="Photo management" *appHasRole="['Admin', 'Moderator']">
        <app-photo-management></app-photo-management>
      </tab>
    </tabset>
  </div>
</div>
</code>```

hasRole.directive.ts

```<code>import { Directive, Input, ViewContainerRef, TemplateRef, OnInit } from '@angular/core';
import { AuthService } from '../_services/auth.service';

@Directive({
  selector: '[appHasRole]'
})
export class HasRoleDirective implements OnInit {
  @Input() appHasRole: string[];
  isVisible = false;

  constructor(private viewContainerRef: ViewContainerRef,
              private templateRef: TemplateRef<any>,
              private authService: AuthService) { }

  ngOnInit() {
    const userRoles = this.authService.decodedToken.role as Array<string>;
    // if no roles clear the viewContainerRef
    if (!userRoles) {
      this.viewContainerRef.clear();
    }

    // if user has role need to render the element
    if (this.authService.roleMatch(this.appHasRole)) {
      if (!this.isVisible) {
        this.isVisible = true;
        this.viewContainerRef.createEmbeddedView(this.templateRef);
      } else {
        this.isVisible = false;
        this.viewContainerRef.clear();
      }
    }
  }
}
</code>```

The code part that is failing to work is

const userRoles = this.authService.decodedToken.role as Array<string>;

How do I test this component?

答:
The best way to test an angular app is to mock everything except the component you want to test.

The easiest way to do it is to use a lib like ng-mocks.

Nevertheless you need to stub the AuthService like that

TestBed.configureTestingModule({
  declarations: [HasRoleDirective, AdminPanelComponent],
  provides: [
    {
      provide: AuthService,
      useValue: {
        decodedToken: {
          role: [], // <- you can put here values for the test
        },
        roleMatch: () => false, // <- or to use a spy here.
      },
    },
  ],
})
```

in this case AuthService will be a stub with fake methods that don't do anything.

Body:
I have a component I want to test. The test fails with message

AdminPanelComponent > should create

TypeError: Cannot read property 'role' of undefined

error properties: Object({ ngDebugContext: DebugContext_({ view:
  Object({ def: Object({ factory: Function, nodeFlags: 50577443,
  rootNodeFlags: 1, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({
  nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0,
  outputIndex: 0, checkIndex: 0, flags: 1, childFlags: 50577443,
  directChildFlags: 1, childMatchedQueries: 0, matchedQueries: Object({
  }), matchedQueryIds: 0, references: Object({  }), ngContentIndex:
  null, childCount: 11, bindings: [  ], bindingFlags: 0, outputs: [  ],
  element: Object({ ns: '', name: 'div', attrs: [ Array ], template:
  null, componentProvider: null, componentView: null,
  componentRendererType: null, publicProviders: null({  }),
  allProviders: null({  }), handleEvent: Function }), provider: null,
  text: null, query: null, ngContent: null }), Object({ nodeIndex: 1,
  parent: Object({ nodeIndex: 0, parent: null, renderParent: null,
  bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 1, childFlags:
  50577443, directChildFlags: 1, chi ...
      at
      at HasRoleDirective.ngOnInit (http://localhost:9876/_karma_webpack_/src/app/_directives/hasRole.directive.ts:16:53)
      at checkAndUpdateDirectiveInline (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:26276:1)
      at checkAndUpdateNodeInline (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:37133:1)
      at checkAndUpdateNode (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:37072:1)
      at debugCheckAndUpdateNode (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:38094:36)
      at debugCheckDirectivesFn (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:38037:1)
      at Object.eval [as updateDirectives] (ng:///DynamicTestModule/AdminPanelComponent.ngfactory.js:62:5)
      at Object.debugUpdateDirectives [as updateDirectives] (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:38025:1)
      at checkAndUpdateView (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:37037:1)
      at callViewAction (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:37403:1)

admin-panel.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-admin-panel',
  templateUrl: './admin-panel.component.html',
  styleUrls: ['./admin-panel.component.css']
})
export class AdminPanelComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

admin-panel.component.html

Admin panel

    <tabset class="member-tabset">
      <tab heading="User Management" *appHasRole="['Admin']">

            <app-user-management></app-user-management>

      </tab>
      <tab heading="Photo management" *appHasRole="['Admin', 'Moderator']">
        <app-photo-management></app-photo-management>
      </tab>
    </tabset>

hasRole.directive.ts

import { Directive, Input, ViewContainerRef, TemplateRef, OnInit } from '@angular/core';
import { AuthService } from '../_services/auth.service';

@Directive({
  selector: '[appHasRole]'
})
export class HasRoleDirective implements OnInit {
  @Input() appHasRole: string[];
  isVisible = false;

  constructor(private viewContainerRef: ViewContainerRef,
              private templateRef: TemplateRef<any>,
              private authService: AuthService) { }

  ngOnInit() {
    const userRoles = this.authService.decodedToken.role as Array<string>;
    // if no roles clear the viewContainerRef
    if (!userRoles) {
      this.viewContainerRef.clear();
    }

    // if user has role need to render the element
    if (this.authService.roleMatch(this.appHasRole)) {
      if (!this.isVisible) {
        this.isVisible = true;
        this.viewContainerRef.createEmbeddedView(this.templateRef);
      } else {
        this.isVisible = false;
        this.viewContainerRef.clear();
      }
    }
  }
}

The code part that is failing to work is

const userRoles = this.authService.decodedToken.role as Array<string>;

How do I test this component?

Body:
The best way to test an angular app is to mock everything except the component you want to test.

The easiest way to do it is to use a lib like ng-mocks.

Nevertheless you need to stub the AuthService like that

TestBed.configureTestingModule({
  declarations: [HasRoleDirective, AdminPanelComponent],
  provides: [
    {
      provide: AuthService,
      useValue: {
        decodedToken: {
          role: [], // <- you can put here values for the test
        },
        roleMatch: () => false, // <- or to use a spy here.
      },
    },
  ],
})

in this case AuthService will be a stub with fake methods that don't do anything.


问:
What make an image to be displayed only in IOS
As the title say

What make an image to be displayed only in IOS

in Android , it display a blank white image

the source fetched from a remote url

```<code>import { Image } from 'react-native';

image = {uri : "correct_image_url"}

<Image style={{width : 100 , zIndex : 999 , height : 100}} source={image} />
</code>```

I use Expo , if this can help

答:
You can use Platform from react-native to check if OS is ios or android

```<code>import { Image, Platform, View } from 'react-native';

image = {uri : "correct_image_url"}

{
  Platform.OS === 'ios' ? (
    <Image style={{width : 100 , zIndex : 999 , height : 100}} source={image} />
  ) : (<View style={{ backgroundColor: 'white', height: 100, width: 100 }} />)
}
</code>```

Body:
As the title say

What make an image to be displayed only in IOS

in Android , it display a blank white image

the source fetched from a remote url

import { Image } from 'react-native';

image = {uri : "correct_image_url"}

<Image style={{width : 100 , zIndex : 999 , height : 100}} source={image} />

I use Expo , if this can help

Body:
You can use Platform from react-native to check if OS is ios or android

import { Image, Platform, View } from 'react-native';

image = {uri : "correct_image_url"}

{
  Platform.OS === 'ios' ? (
    <Image style={{width : 100 , zIndex : 999 , height : 100}} source={image} />
  ) : (<View style={{ backgroundColor: 'white', height: 100, width: 100 }} />)
}


问:
facing issue DataSourceId parameter in the CreateDataSource method in quickSight in JAVA sdk
So I am using quick sight java SDK for integrating s3 with quicksight, and for that, I am using CreateDataSource.so while using this method, I have to pass one parameter in this method DataSourceId. The description of this parameter in the AWS documentation is like "An ID for the data source. This ID is unique per AWS Region for each AWS account," and I do not know how to get this.i to have to get this parameter programmatically. Type of this parameter is String

```<code>getClient().createDataSource(new CreateDataSourceRequest().withDataSourceId("DataSourceID").withAwsAccountId("AWS ACCOUNT").withName("display name of data soure").withType(DataSourceType.S3));
</code>```

getClient is a client for using quicksight API

and yeah for the integration of s3 and quicksight I can not do this through AWS console I have to do this programmatically

答:
I do not know how to get this.i to have to get this parameter programmatically

This is something that you set yourself, for example:

```<code>DataSourceId = "my-first-test-data-source-id"
</code>```

Body:
So I am using quick sight java SDK for integrating s3 with quicksight, and for that, I am using CreateDataSource.so while using this method, I have to pass one parameter in this method DataSourceId. The description of this parameter in the AWS documentation is like "An ID for the data source. This ID is unique per AWS Region for each AWS account," and I do not know how to get this.i to have to get this parameter programmatically. Type of this parameter is String

getClient().createDataSource(new CreateDataSourceRequest().withDataSourceId("DataSourceID").withAwsAccountId("AWS ACCOUNT").withName("display name of data soure").withType(DataSourceType.S3));

getClient is a client for using quicksight API

and yeah for the integration of s3 and quicksight I can not do this through AWS console I have to do this programmatically

Body:
I do not know how to get this.i to have to get this parameter programmatically

This is something that you set yourself, for example:

DataSourceId = "my-first-test-data-source-id"


问:
React: 2 way binding props
How can I do a 2 way binding of a variable from the parent component (Form.js), such that changes occurred in the child component (InputText.js) will be updated in the parent component?

Expected result: typing values in the input in InputText.js will update the state of Form.js

In Form.js

```<code>render() {
    return (
      <div>
        <InputText
          title="Email"
          data={this.state.formInputs.email}
        />

        <div>
          Value: {this.state.formInputs.email} // <-- this no change
        </div>

      </div>
    )
  }
</code>```

In InputText.js

```<code>export default class InputText extends React.Component {

  constructor(props) {
    super(props);
    this.state = props;
    this.handleKeyChange = this.keyUpHandler.bind(this);
  }

  keyUpHandler(e) {
    this.setState({
      data: e.target.value
    });
  }

  render() {
    return (
      <div>
        <label className="label">{this.state.title}</label>
        <input type="text" value={this.state.data} onChange={this.handleKeyChange} /> // <-- type something here
        value: ({this.state.data}) // <-- this changed
      </div>
    )
  }
}
</code>```

答:
You would need to lift state up to the parent

parent class would look something like

onChangeHandler(e) {
   this.setState({
      inputValue: e.target.value // you receive the value from the child to the parent here
   })
}
render() {
    return (

        <InputText
          title="Email"
          onChange={this.onChangeHandler}
          value={this.state.inputValue}
        />

          Value: {this.state.inputValue}

    )
  }
```

<p>children class would look something like</p>

<pre class="lang-js prettyprint-override"><code>export default class InputText extends React.Component {

  constructor(props) {
    super(props);
    this.state = props;
  }

  render() {
    return (
      <div>
        <label className="label">{this.state.title}</label>
        <input type="text" value={this.state.value} onChange={this.props.onChange} />
        value: ({this.state.value})
      </div>
    )
  }
}
</code>```

Title: React: 2 way binding props

Body:
How can I do a 2 way binding of a variable from the parent component (Form.js), such that changes occurred in the child component (InputText.js) will be updated in the parent component?

Expected result: typing values in the input in InputText.js will update the state of Form.js

In Form.js

render() {
    return (

        <InputText
          title="Email"
          data={this.state.formInputs.email}
        />

          Value: {this.state.formInputs.email} // <-- this no change

    )
  }

In InputText.js

export default class InputText extends React.Component {

  constructor(props) {
    super(props);
    this.state = props;
    this.handleKeyChange = this.keyUpHandler.bind(this);
  }

  keyUpHandler(e) {
    this.setState({
      data: e.target.value
    });
  }

  render() {
    return (

        {this.state.title}
        <input type="text" value={this.state.data} onChange={this.handleKeyChange} /> // <-- type something here
        value: ({this.state.data}) // <-- this changed

    )
  }
}

Body:
You would need to lift state up to the parent

parent class would look something like

onChangeHandler(e) {
   this.setState({
      inputValue: e.target.value // you receive the value from the child to the parent here
   })
}
render() {
    return (
      <div>
        <InputText
          title="Email"
          onChange={this.onChangeHandler}
          value={this.state.inputValue}
        />

        <div>
          Value: {this.state.inputValue}
        </div>

      </div>
    )
  }

children class would look something like

export default class InputText extends React.Component {

  constructor(props) {
    super(props);
    this.state = props;
  }

  render() {
    return (
      <div>
        <label className="label">{this.state.title}</label>
        <input type="text" value={this.state.value} onChange={this.props.onChange} />
        value: ({this.state.value})
      </div>
    )
  }
}


问:
python pyomo: declaration of discrete variable
I am using pyomo for optimization modeling, including multiple continuous and discrete variables, but I am not clear how to define a discrete variable.The value of discrete variable is either 0 or 100.
my question is : how to define a discrete variable which value is either 0 or 100

thans all!

答:
You would have to declare a binary variable, e.g. y, in addition to your discrete variable, e.g. myvar.

Then, you need a constraint that says: myvar = 100 * y

If y=0, then myvar will necessarily be 0 too. If y=1, then myvar will be equal to 100.

I assume you would be able to express these in Pyomo syntax.


问:
Function is not working when called inside "addEventListener"
I am trying to make a slideshow in a webpage.

I created the next and previous button for changing images in different way. The next button is working but the previous button in not working. The display property of the images is set to none by default.

var nextbutton = document.querySelector(".next");
var prevbutton = document.querySelector(".prev");
var slide = document.querySelectorAll('.slideshow');
var slideindex = 1 ;

var show = function(n){
  var i;
  if (n > slide.length) { slideindex = 1};
  if (n < 1) {slideindex = slide.length};
  for (i = 0; i < slide.length; i++) {
    slide[i].style.display = "none";
  };
  slide[slideindex-1].style.display = "block";

};

var cl = function(p) {
  show(slideindex += p);
};

/* next button is working */
nextbutton.addEventListener("click", function(){
  show(slideindex += 1 );
} );

/* previous button is not working */
prevbutton.addEventListener("click" , cl(-1));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slideshow {
  width:100%;
  height: 500px !important ;
  border-radius: 7px;
  display: none;
 }</code>```

            ❮
            ❯

```

答:
You could also do:

```<code>prevbutton.addEventListener("click", cl.bind(null, -1));
</code>```

Why didn't your one work?

```<code>prevbutton.addEventListener("click", cl(-1));
</code>```

is equivalent to:

```<code>let theReturnValue = cl(-1);
prevbutton.addEventListener("click", theReturnValue);
</code>```

JavaScript calls cl(-1) and passes the return value to addEventListener

Why does this solution work

The solutuon used Function.prototype.bind which you can look up but it is equivalent to:

```<code>prevbutton.addEventListener("click", function(...args) {
  cl.call(null, -1, ...args);
});
</code>```

Bind in detail

Arguments: fn.bind(thisArg[, ...args])

fn

The function.

thisArg

What the value of this will be in the function fn (or cl in this case)

...args

Optional. Predefined arguments for the function. All other arguments given in invocation will be put after these arguments.

Body:
I am trying to make a slideshow in a webpage.

I created the next and previous button for changing images in different way. The next button is working but the previous button in not working. The display property of the images is set to none by default.

var nextbutton = document.querySelector(".next");
var prevbutton = document.querySelector(".prev");
var slide = document.querySelectorAll('.slideshow');
var slideindex = 1 ;

var show = function(n){
  var i;
  if (n > slide.length) { slideindex = 1};
  if (n < 1) {slideindex = slide.length};
  for (i = 0; i < slide.length; i++) {
    slide[i].style.display = "none";
  };
  slide[slideindex-1].style.display = "block";

};

var cl = function(p) {
  show(slideindex += p);
};

/* next button is working */
nextbutton.addEventListener("click", function(){
  show(slideindex += 1 );
} );

/* previous button is not working */
prevbutton.addEventListener("click" , cl(-1));

.slideshow {
  width:100%;
  height: 500px !important ;
  border-radius: 7px;
  display: none;
 }

            ❮
            ❯

Body:
You could also do:

prevbutton.addEventListener("click", cl.bind(null, -1));

Why didn't your one work?

prevbutton.addEventListener("click", cl(-1));

is equivalent to:

let theReturnValue = cl(-1);
prevbutton.addEventListener("click", theReturnValue);

JavaScript calls cl(-1) and passes the return value to addEventListener

Why does this solution work

The solutuon used Function.prototype.bind which you can look up but it is equivalent to:

prevbutton.addEventListener("click", function(...args) {
  cl.call(null, -1, ...args);
});

Bind in detail

Arguments: fn.bind(thisArg[, ...args])

fn

The function.

thisArg

What the value of this will be in the function fn (or cl in this case)

...args

Optional. Predefined arguments for the function. All other arguments given in invocation will be put after these arguments.


问:
How to specify mailbox I want in outlook command line?
for example, if I have two mailboxs in my outlook, one named "mailbox - first, sur", which is default one, the second one is named "mailbox - first2, sur"

How can I popup the outlook window for "first2. sur"? Right now, I only know of the command line outlook.exe /select "outlook:inbox" to popup my default inbox.

How can I popup the "first2. sur" inbox?

答:
After try in command line again and again, it found the answer by myself. :)
for example, if you want to popup the window for

inbox\error

```<code>outlook /select "outlook:\\mailbox - first2, sur\inbox\error"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
After try in command line again and again, it found the answer by myself. :)
for example, if you want to popup the window for

inbox\error

outlook /select "outlook:\\mailbox - first2, sur\inbox\error"


问:
InvalidValueError: not an Array
I am trying to get the google maps polygon function to work. The map is showing but I am having this error: InvalidValueError: not an Array. Any suggestions? Please help thank you!

Here are my codes:

Homepage.ts

```<code>import { Component, OnInit } from '@angular/core';
import { ViewChild, ElementRef } from '@angular/core';

declare var google: any;

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})

export class HomePage implements OnInit {

  map: any;
  @ViewChild('map', { read: ElementRef, static: false }) mapRef: ElementRef;

  polygon: any = [];
  triangleCoords: any = [
    { lat: 25.774, lng: -80.190 },
    { lat: 18.466, lng: -66.118 },
    { lat: 32.321, lng: -64.757 },
    { lat: 25.774, lng: -80.190 }
  ];

  constructor() {
  }

  ionViewDidEnter() {
    this.showMap();
  }

  addPolygon(triangleCoords) {
    for (let triangleCoord of triangleCoords) {
      let bermudaTriangle = new google.maps.Polygon({
        paths: triangleCoord,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35
      });
      bermudaTriangle.setMap(this.map);
    }
  }

  showMap() {
    const location = new google.maps.LatLng(24.886, -70.268);
    const options = {
      center: location,
      zoom: 5,
      disabledDefaultUI: true
    }
    this.map = new google.maps.Map(this.mapRef.nativeElement, options);
    this.addPolygon(this.triangleCoords);
  }

  ngOnInit() {
  }
}

</code>```

homepage.html

```<code><ion-header>
  <ion-toolbar>
    <ion-title>Home</ion-title>
    <ion-buttons slot="start">
      <ion-menu-button menu="main-menu"></ion-menu-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true" class="ion-padding">
  <div #map id="map"></div>
</ion-content>
</code>```

The error says its an array but im not sure what to add and remove.

答:
triangleCoords is a property of your class, to access it your need to add this:

```<code>let bermudaTriangle = new google.maps.Polygon({
    paths: this.triangleCoord, // <<<<<<<<<<<<<<<<<<<< Fix
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
});
</code>```

As it is in your code, triangleCoord was undefined in the context of the addPolygon method, which explains the error message.

Title: InvalidValueError: not an Array

Body:
I am trying to get the google maps polygon function to work. The map is showing but I am having this error: InvalidValueError: not an Array. Any suggestions? Please help thank you!

Here are my codes:

Homepage.ts

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

declare var google: any;

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})

export class HomePage implements OnInit {

  map: any;
  @ViewChild('map', { read: ElementRef, static: false }) mapRef: ElementRef;

  polygon: any = [];
  triangleCoords: any = [
    { lat: 25.774, lng: -80.190 },
    { lat: 18.466, lng: -66.118 },
    { lat: 32.321, lng: -64.757 },
    { lat: 25.774, lng: -80.190 }
  ];

  constructor() {
  }

  ionViewDidEnter() {
    this.showMap();
  }

  addPolygon(triangleCoords) {
    for (let triangleCoord of triangleCoords) {
      let bermudaTriangle = new google.maps.Polygon({
        paths: triangleCoord,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35
      });
      bermudaTriangle.setMap(this.map);
    }
  }

  showMap() {
    const location = new google.maps.LatLng(24.886, -70.268);
    const options = {
      center: location,
      zoom: 5,
      disabledDefaultUI: true
    }
    this.map = new google.maps.Map(this.mapRef.nativeElement, options);
    this.addPolygon(this.triangleCoords);
  }

  ngOnInit() {
  }
}

homepage.html

<ion-header>
  <ion-toolbar>
    <ion-title>Home</ion-title>
    <ion-buttons slot="start">
      <ion-menu-button menu="main-menu"></ion-menu-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true" class="ion-padding">

</ion-content>

The error says its an array but im not sure what to add and remove.

Body:
triangleCoords is a property of your class, to access it your need to add this:

let bermudaTriangle = new google.maps.Polygon({
    paths: this.triangleCoord, // <<<<<<<<<<<<<<<<<<<< Fix
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
});

As it is in your code, triangleCoord was undefined in the context of the addPolygon method, which explains the error message.


问:
Angular Material MatMomentDateModule imports all Moment locales
I'm using MatMomentDateModule for Angular Material's matDatePicker component.
But this imports all locales for Moment.js even though I need only one:

main bundle module's sizes

Is there a way to tell it to only import the locales I need?

In my module I import it like:

```<code>import { MatDatepickerModule } from '@angular/material';
import { MatMomentDateModule } from '@angular/material-moment-adapter';

@NgModule({
  declarations: [],
  imports: [
    ...
    MatDatepickerModule,
    MatMomentDateModule,
    ...
  ],
  exports: [
    ...
    MatDatepickerModule,
    MatMomentDateModule,
    ...
  ]
})
export class MaterialModule {}
</code>```

答:
You can try specify it in your Providers array of app.module.ts?

```<code>@NgModule({
  providers: [
    {provide: MAT_DATE_LOCALE, useValue: 'en-GB'},
  ],
})
export class MyApp {}
</code>```

See link: https://material.angular.io/components/datepicker/overview#setting-the-locale-code

Body:
I'm using MatMomentDateModule for Angular Material's matDatePicker component.
But this imports all locales for Moment.js even though I need only one:

main bundle module's sizes

Is there a way to tell it to only import the locales I need?

In my module I import it like:

import { MatDatepickerModule } from '@angular/material';
import { MatMomentDateModule } from '@angular/material-moment-adapter';

@NgModule({
  declarations: [],
  imports: [
    ...
    MatDatepickerModule,
    MatMomentDateModule,
    ...
  ],
  exports: [
    ...
    MatDatepickerModule,
    MatMomentDateModule,
    ...
  ]
})
export class MaterialModule {}

Body:
You can try specify it in your Providers array of app.module.ts?

@NgModule({
  providers: [
    {provide: MAT_DATE_LOCALE, useValue: 'en-GB'},
  ],
})
export class MyApp {}

See link: https://material.angular.io/components/datepicker/overview#setting-the-locale-code


问:
How to sync ExoPlayer library in Android?
My app crashed when it comes to sync ExoPlayer library. At first, it crashes when I had Android Studio 3.6 and for no reason it gave me following errors:
enter image description here

enter image description here

but recently I updated Android Studio to 4.0 so I can sync ExoPlayer libraries and no problem when running app

```<code>implementation 'com.google.android.exoplayer:exoplayer-core:2.11.4'
implementation 'com.google.android.exoplayer:exoplayer-dash:2.11.4'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.11.4'
</code>```

but when I add XML code as you see in the following

```<code><com.google.android.exoplayer2.ui.SimpleExoPlayerView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</code>```

and run my app it crashes and gives me the following error:

```<code>2020-05-30 12:39:59.271 18182-18182/? E/Zygote: isWhitelistProcess - Process
is Whitelisted
2020-05-30 12:39:59.271 18182-18182/? E/libpersona: scanKnoxPersonas
2020-05-30 12:39:59.271 18182-18182/? E/libpersona: Couldn't open the File -
/data/system/users/0/personalist.xml - No such file or directory
2020-05-30 12:40:00.364 18182-18182/com.example.myapplication A/libc: Fatal
signal 11 (SIGSEGV), code
1, fault addr 0xb5a9f98 in tid 18182 (e.myapplication), pid 18182
(e.myapplication)
</code>```

答:
Make Sure you are implemented all below steps :

1- Add repositories:

you should add add these repos exactly with writted order. (buld.gradle:project)

```<code>repositories {
    google()
    mavenCentral()
}
</code>```

2- Add ExoPlayer full module dependency

```<code>    implementation 'com.google.android.exoplayer:exoplayer:2.11.4'
</code>```

3- Turn on Java 8 support (buld.gradle - module:app)

```<code>  android{
     ...
    compileOptions {
      targetCompatibility JavaVersion.VERSION_1_8
    }
 }
</code>```

Body:
My app crashed when it comes to sync ExoPlayer library. At first, it crashes when I had Android Studio 3.6 and for no reason it gave me following errors:
enter image description here

enter image description here

but recently I updated Android Studio to 4.0 so I can sync ExoPlayer libraries and no problem when running app

implementation 'com.google.android.exoplayer:exoplayer-core:2.11.4'
implementation 'com.google.android.exoplayer:exoplayer-dash:2.11.4'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.11.4'

but when I add XML code as you see in the following

<com.google.android.exoplayer2.ui.SimpleExoPlayerView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

and run my app it crashes and gives me the following error:

2020-05-30 12:39:59.271 18182-18182/? E/Zygote: isWhitelistProcess - Process
is Whitelisted
2020-05-30 12:39:59.271 18182-18182/? E/libpersona: scanKnoxPersonas
2020-05-30 12:39:59.271 18182-18182/? E/libpersona: Couldn't open the File -
/data/system/users/0/personalist.xml - No such file or directory
2020-05-30 12:40:00.364 18182-18182/com.example.myapplication A/libc: Fatal
signal 11 (SIGSEGV), code
1, fault addr 0xb5a9f98 in tid 18182 (e.myapplication), pid 18182
(e.myapplication)

Body:
Make Sure you are implemented all below steps :

1- Add repositories:

you should add add these repos exactly with writted order. (buld.gradle:project)

repositories {
    google()
    mavenCentral()
}

2- Add ExoPlayer full module dependency

    implementation 'com.google.android.exoplayer:exoplayer:2.11.4'

3- Turn on Java 8 support (buld.gradle - module:app)

  android{
     ...
    compileOptions {
      targetCompatibility JavaVersion.VERSION_1_8
    }
 }


问:
Get file size of an URL without download
To get the file size of an URL without download, I wrote:

```<code>public static long getFileSizeWithoutDownload(String url) {
        ConnectionRequest cr = new GZConnectionRequest();
        cr.setUrl(url);
        cr.setPost(false);
        NetworkManager.getInstance().addProgressListener((NetworkEvent evt) -> {
            if (cr == evt.getConnectionRequest() && evt.getLength() > 0) {
                cr.kill();
            }
        });
        NetworkManager.getInstance().addToQueueAndWait(cr);
        return cr.getContentLength();
    }
</code>```

It seems to work on Simulator, Android and iOS with a testing URL of my Spring Boot server.

Anyway, I consider this code as a workaround, as I couldn't find an API that directly gives me the file size without starting the download first. Starting the download and then killing it works, but maybe there may be a better way to get the same result. By the way, the condition && evt.getLength() > 0 may never be satisfied in some cases (depending on the headers received), so it would be better to read only the headers, in which "Content-Length" may be present or absent.

So, my question is if, with Codename One, there is a way to download only the response headers, without starting the download. Thank you.

答:
Thank you Shai, your answer https://stackoverflow.com/a/62124902/1277576 led me in the right direction. cr.setHttpMethod("HEAD"); simplifies the code and prevents the download from starting:

```<code>public static long getFileSizeWithoutDownload(String url) {
        ConnectionRequest cr = new GZConnectionRequest();
        cr.setUrl(url);
        cr.setHttpMethod("HEAD");
        cr.setPost(false);
        NetworkManager.getInstance().addToQueueAndWait(cr);
        return cr.getContentLength();
    }
</code>```

However, as you wrote, I can override ConnectionRequest for a more precise control of the headers. This other method performs the same function as the previous one, but it also guarantees me that the server supports partial downloads. In fact, if the server does not support partial downloads, the information about the content length would be useless for my purposes:

```<code>    /**
     * Returns -2 if the server doesn't accept partial downloads, -1 if the
     * content length is unknow, a value greater than 0 if the Content-Length is
     * known
     *
     * @param url
     * @return must be interpreted as a boolean value: if greater than zero than
     * partial downloads are supported (the returned value is the Content-Length),
     * otherwise they are not supported.
     */
    public static long getFileSizeWithoutDownload(String url) {
        // documentation about the headers: https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests
        Wrapper<Long> result = new Wrapper<>(0l);
        ConnectionRequest cr = new GZConnectionRequest() {
            @Override
            protected void readHeaders(Object connection) throws IOException {
                String acceptRanges = getHeader(connection, "Accept-Ranges");
                if (acceptRanges == null || !acceptRanges.equals("bytes")) {
                    Log.p("The partial downloads of " + url + " are not supported.", Log.WARNING);
                    result.set(-2l);
                } else {
                    String contentLength = getHeader(connection, "Content-Length");
                    if (contentLength != null) {
                        result.set(Long.parseLong(contentLength));
                    } else {
                        Log.p("The Content-Length of " + url + " is unknown.", Log.WARNING);
                        result.set(-1l);
                    }
                }
            }
        };
        cr.setUrl(url);
        cr.setHttpMethod("HEAD");
        cr.setPost(false);
        NetworkManager.getInstance().addToQueueAndWait(cr);
        return result.get();
    }
</code>```

The readHeaders and getHeader methods are implementation dependent. I have verified that they work as desired on Simulator, Android and iOS.

Lastly, the Wrapper class is so implemented:

```<code>/**
 * Generic object wrapper, as workaround for the issue "Local variables
 * referenced from a lambda expression must be final or effectively final".
 */
public class Wrapper<T> {

    private T object;

    public Wrapper(T obj) {
        this.object = obj;
    }

    public T get() {
        return object;
    }

    public void set(T obj) {
        this.object = obj;
    }

}
</code>```

I hope this detailed answer will help those who need to read HTTP headers with Codename One.

Body:
To get the file size of an URL without download, I wrote:

public static long getFileSizeWithoutDownload(String url) {
        ConnectionRequest cr = new GZConnectionRequest();
        cr.setUrl(url);
        cr.setPost(false);
        NetworkManager.getInstance().addProgressListener((NetworkEvent evt) -> {
            if (cr == evt.getConnectionRequest() && evt.getLength() > 0) {
                cr.kill();
            }
        });
        NetworkManager.getInstance().addToQueueAndWait(cr);
        return cr.getContentLength();
    }

It seems to work on Simulator, Android and iOS with a testing URL of my Spring Boot server.

Anyway, I consider this code as a workaround, as I couldn't find an API that directly gives me the file size without starting the download first. Starting the download and then killing it works, but maybe there may be a better way to get the same result. By the way, the condition && evt.getLength() > 0 may never be satisfied in some cases (depending on the headers received), so it would be better to read only the headers, in which "Content-Length" may be present or absent.

So, my question is if, with Codename One, there is a way to download only the response headers, without starting the download. Thank you.

Body:
Thank you Shai, your answer https://stackoverflow.com/a/62124902/1277576 led me in the right direction. cr.setHttpMethod("HEAD"); simplifies the code and prevents the download from starting:

public static long getFileSizeWithoutDownload(String url) {
        ConnectionRequest cr = new GZConnectionRequest();
        cr.setUrl(url);
        cr.setHttpMethod("HEAD");
        cr.setPost(false);
        NetworkManager.getInstance().addToQueueAndWait(cr);
        return cr.getContentLength();
    }

However, as you wrote, I can override ConnectionRequest for a more precise control of the headers. This other method performs the same function as the previous one, but it also guarantees me that the server supports partial downloads. In fact, if the server does not support partial downloads, the information about the content length would be useless for my purposes:

    /**
     * Returns -2 if the server doesn't accept partial downloads, -1 if the
     * content length is unknow, a value greater than 0 if the Content-Length is
     * known
     *
     * @param url
     * @return must be interpreted as a boolean value: if greater than zero than
     * partial downloads are supported (the returned value is the Content-Length),
     * otherwise they are not supported.
     */
    public static long getFileSizeWithoutDownload(String url) {
        // documentation about the headers: https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests
        Wrapper<Long> result = new Wrapper<>(0l);
        ConnectionRequest cr = new GZConnectionRequest() {
            @Override
            protected void readHeaders(Object connection) throws IOException {
                String acceptRanges = getHeader(connection, "Accept-Ranges");
                if (acceptRanges == null || !acceptRanges.equals("bytes")) {
                    Log.p("The partial downloads of " + url + " are not supported.", Log.WARNING);
                    result.set(-2l);
                } else {
                    String contentLength = getHeader(connection, "Content-Length");
                    if (contentLength != null) {
                        result.set(Long.parseLong(contentLength));
                    } else {
                        Log.p("The Content-Length of " + url + " is unknown.", Log.WARNING);
                        result.set(-1l);
                    }
                }
            }
        };
        cr.setUrl(url);
        cr.setHttpMethod("HEAD");
        cr.setPost(false);
        NetworkManager.getInstance().addToQueueAndWait(cr);
        return result.get();
    }

The readHeaders and getHeader methods are implementation dependent. I have verified that they work as desired on Simulator, Android and iOS.

Lastly, the Wrapper class is so implemented:

/**
 * Generic object wrapper, as workaround for the issue "Local variables
 * referenced from a lambda expression must be final or effectively final".
 */
public class Wrapper<T> {

    private T object;

    public Wrapper(T obj) {
        this.object = obj;
    }

    public T get() {
        return object;
    }

    public void set(T obj) {
        this.object = obj;
    }

}

I hope this detailed answer will help those who need to read HTTP headers with Codename One.


问:
How to make this with a for-loop?
Trying to make a batteship game and want to make the code more smooth...

```<code>#Board:
A = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"]
B = ["B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9"]
C = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
D = ["D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9"]
E = ["E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9"]
F = ["F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9"]
G = ["G0", "G1", "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G9"]
H = ["H0", "H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9"]
I = ["I0", "I1", "I2", "I3", "I4", "I5", "I6", "I7", "I8", "I9"]
J = ["J0", "J1", "J2", "J3", "J4", "J5", "J6", "J7", "J8", "J9"]
print("\n",A,"\n",B,"\n",C,"\n",D,"\n",E,"\n",F,"\n",G,"\n",H,"\n",I,"\n",J)

#Variables
A_set = set(A)
B_set = set(B)
C_set = set(C)
D_set = set(D)
E_set = set(E)
F_set = set(F)
G_set = set(G)
H_set = set(H)
I_set = set(I)
J_set = set(J)
</code>```

When i check if the placed codinate are within the board I use this code:

```<code>def user_ship1():
    global nr1_user_ship
    nr1_user_ship = []
    print("Hide a ship within the board.")
    user_ship1 = input("")

    user_ship1 = user_ship1.capitalize()

    battlefield_check = set(user_ship1.split())

    within_battlefield0 = battlefield_check.intersection(A_set)
    within_battlefield1 = battlefield_check.intersection(B_set)
    within_battlefield2 = battlefield_check.intersection(C_set)
    within_battlefield3 = battlefield_check.intersection(D_set)
    within_battlefield4 = battlefield_check.intersection(E_set)
    within_battlefield5 = battlefield_check.intersection(F_set)
    within_battlefield6 = battlefield_check.intersection(G_set)
    within_battlefield7 = battlefield_check.intersection(H_set)
    within_battlefield8 = battlefield_check.intersection(I_set)
    within_battlefield9 = battlefield_check.intersection(J_set)

    if((within_battlefield0 == set()) and (within_battlefield1 == set()) and (within_battlefield2 == set()) and (within_battlefield3 == set()) and (within_battlefield4 == set()) and (within_battlefield5 == set()) and (within_battlefield6 == set()) and (within_battlefield7 == set()) and (within_battlefield8 == set()) and (within_battlefield9 == set())):
        print("Ship needs to be within the board.")
        exit()
    else:
        print("Great! Place another ship.")
    nr1_user_ship.append(user_ship1)
</code>```

So how can I use this in a forloop instead and how do I change the code so I don't use the "global" variable

答:
You can pack your sets in a list, and then take advantage of the built-in all function to minimize your if condition and avoid the 10 within_battlefieldx variables:

sets = [A_set, B_set, C_set, D_set, E_set, F_set, G_set, H_set, I_set, J_set]

if all(len(battlefield_check.intersection(s)) == 0 for s in sets):
    print("Ship needs to be within the board.")
```

<hr>

<p>You can actually avoid the 10 <code>X_set</code> variables as well by simply doing:</p>

<pre class="lang-py prettyprint-override"><code>rows = [A, B, C, D, E, F, G, H, I, J]
sets = [set(row) for row in rows]
</code>```

And you can then take one more step to eliminate the row variables by doing:

board = {'A': ["A0", "A1", "A2", ..., "A6", "A7", "A8", "A9"],
         'B': [...],
         ...}
```

<p>And the above will change to:</p>

<pre class="lang-py prettyprint-override"><code>sets = [set(row) for row in board.values()]
</code>```

You can alternatively make the board a list of lists and use for row in board, but it seems you want to keep the rows indexed with letters so I used a dict instead.

Title: How to make this with a for-loop?

Body:
Trying to make a batteship game and want to make the code more smooth...

#Board:
A = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"]
B = ["B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9"]
C = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
D = ["D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9"]
E = ["E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9"]
F = ["F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9"]
G = ["G0", "G1", "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G9"]
H = ["H0", "H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9"]
I = ["I0", "I1", "I2", "I3", "I4", "I5", "I6", "I7", "I8", "I9"]
J = ["J0", "J1", "J2", "J3", "J4", "J5", "J6", "J7", "J8", "J9"]
print("\n",A,"\n",B,"\n",C,"\n",D,"\n",E,"\n",F,"\n",G,"\n",H,"\n",I,"\n",J)

#Variables
A_set = set(A)
B_set = set(B)
C_set = set(C)
D_set = set(D)
E_set = set(E)
F_set = set(F)
G_set = set(G)
H_set = set(H)
I_set = set(I)
J_set = set(J)

When i check if the placed codinate are within the board I use this code:

def user_ship1():
    global nr1_user_ship
    nr1_user_ship = []
    print("Hide a ship within the board.")
    user_ship1 = input("")

    user_ship1 = user_ship1.capitalize()

    battlefield_check = set(user_ship1.split())

    within_battlefield0 = battlefield_check.intersection(A_set)
    within_battlefield1 = battlefield_check.intersection(B_set)
    within_battlefield2 = battlefield_check.intersection(C_set)
    within_battlefield3 = battlefield_check.intersection(D_set)
    within_battlefield4 = battlefield_check.intersection(E_set)
    within_battlefield5 = battlefield_check.intersection(F_set)
    within_battlefield6 = battlefield_check.intersection(G_set)
    within_battlefield7 = battlefield_check.intersection(H_set)
    within_battlefield8 = battlefield_check.intersection(I_set)
    within_battlefield9 = battlefield_check.intersection(J_set)

    if((within_battlefield0 == set()) and (within_battlefield1 == set()) and (within_battlefield2 == set()) and (within_battlefield3 == set()) and (within_battlefield4 == set()) and (within_battlefield5 == set()) and (within_battlefield6 == set()) and (within_battlefield7 == set()) and (within_battlefield8 == set()) and (within_battlefield9 == set())):
        print("Ship needs to be within the board.")
        exit()
    else:
        print("Great! Place another ship.")
    nr1_user_ship.append(user_ship1)

So how can I use this in a forloop instead and how do I change the code so I don't use the "global" variable

Body:
You can pack your sets in a list, and then take advantage of the built-in all function to minimize your if condition and avoid the 10 within_battlefieldx variables:

sets = [A_set, B_set, C_set, D_set, E_set, F_set, G_set, H_set, I_set, J_set]

if all(len(battlefield_check.intersection(s)) == 0 for s in sets):
    print("Ship needs to be within the board.")

You can actually avoid the 10 X_set variables as well by simply doing:

rows = [A, B, C, D, E, F, G, H, I, J]
sets = [set(row) for row in rows]

And you can then take one more step to eliminate the row variables by doing:

board = {'A': ["A0", "A1", "A2", ..., "A6", "A7", "A8", "A9"],
         'B': [...],
         ...}

And the above will change to:

sets = [set(row) for row in board.values()]

You can alternatively make the board a list of lists and use for row in board, but it seems you want to keep the rows indexed with letters so I used a dict instead.


问:
Using regextract and importrange together make a "duplicate" formula
I have a spreadsheet where I look if the data (website) already exist on the master sheet.

```<code>=if(countif(importrange("Spreadsheet Key","Leads!N:N"),K2)>0,"COMPANY EXISTS!","")
</code>```

But the above formula is not dynamic enough. If there are companies with co.uk and on the master sheet if it's registered under .com, it won't show "COMPANY EXISTS!"

So I changed to the formula to look for works after before and after "." on a website.

```<code>=ARRAYFORMULA(REGEXEXTRACT(UNIQUE(SUBSTITUTE(importrange("Spreadsheet Key","Leads!N:N"),"www.","")), "([0-9A-Za-z-]+)\."))
</code>```

But it's not working if I try to incorporate with if and countif.

```<code>=if(COUNTIF(ARRAYFORMULA(REGEXEXTRACT(SUBSTITUTE(importrange("Spreadsheet Key","Leads!N:N"),"www.",""), "([0-9A-Za-z-]+)\."),L2:L)>0,"Company Exist!",""))
</code>```

It shows 'Wrong number of arguments to IF. Expected between 2 and 3 arguments, but got 1 arguments'

Can anyone help me out on where I am making the mistake?

Spreadsheet link- https://docs.google.com/spreadsheets/d/1La3oOWiM5KpzRY0MLLEUQC25LzDuQlqTjgFp-VlS8Bo/edit#gid=0

Edited: Made a mistake beforehand, didn't specify on that cell its looking against

答:
Your formula had a typo. You are not closing the Arrayformula and the Countif correctly (the array formula closing parenthesis should go before the , of the count if). So change this:

```<code>=if(COUNTIF(ARRAYFORMULA(REGEXEXTRACT(SUBSTITUTE(importrange("Spreadsheet Key","Leads!N:N"),"www.",""), "([0-9A-Za-z-]+)\."),L2:L)>0,"Company Exist!",""))

</code>```

To this:

```<code>=if(COUNTIF(ARRAYFORMULA(REGEXEXTRACT(SUBSTITUTE(IMPORTRANGE("Spreadsheet Key","Leads!N:N"),"www.",""), "([0-9A-Za-z-]+)\.")),L3:L)>0,"Company Exist!","")
</code>```

I hope this has helped you. Let me know if you need anything else or if you did not understood something. :)

Body:
I have a spreadsheet where I look if the data (website) already exist on the master sheet.

=if(countif(importrange("Spreadsheet Key","Leads!N:N"),K2)>0,"COMPANY EXISTS!","")

But the above formula is not dynamic enough. If there are companies with co.uk and on the master sheet if it's registered under .com, it won't show "COMPANY EXISTS!"

So I changed to the formula to look for works after before and after "." on a website.

=ARRAYFORMULA(REGEXEXTRACT(UNIQUE(SUBSTITUTE(importrange("Spreadsheet Key","Leads!N:N"),"www.","")), "([0-9A-Za-z-]+)\."))

But it's not working if I try to incorporate with if and countif.

=if(COUNTIF(ARRAYFORMULA(REGEXEXTRACT(SUBSTITUTE(importrange("Spreadsheet Key","Leads!N:N"),"www.",""), "([0-9A-Za-z-]+)\."),L2:L)>0,"Company Exist!",""))

It shows 'Wrong number of arguments to IF. Expected between 2 and 3 arguments, but got 1 arguments'

Can anyone help me out on where I am making the mistake?

Spreadsheet link- https://docs.google.com/spreadsheets/d/1La3oOWiM5KpzRY0MLLEUQC25LzDuQlqTjgFp-VlS8Bo/edit#gid=0

Edited: Made a mistake beforehand, didn't specify on that cell its looking against

Body:
Your formula had a typo. You are not closing the Arrayformula and the Countif correctly (the array formula closing parenthesis should go before the , of the count if). So change this:

=if(COUNTIF(ARRAYFORMULA(REGEXEXTRACT(SUBSTITUTE(importrange("Spreadsheet Key","Leads!N:N"),"www.",""), "([0-9A-Za-z-]+)\."),L2:L)>0,"Company Exist!",""))

To this:

=if(COUNTIF(ARRAYFORMULA(REGEXEXTRACT(SUBSTITUTE(IMPORTRANGE("Spreadsheet Key","Leads!N:N"),"www.",""), "([0-9A-Za-z-]+)\.")),L3:L)>0,"Company Exist!","")

I hope this has helped you. Let me know if you need anything else or if you did not understood something. :)


问:
Printing with excel and java or others
at the moment I am using Desktop.print() to print excel sheets. This looks quite stupid when you want to print one file 10 times. Excel opens up, prints, shutsdown and that 10 times.

I don't care about multiplatform stuff, so a call the exec(excel.exe print-this 10-times); would be perfectly okay.

How can this be done? Maybe displaying the excel print dialog?

答:
Try a simple macro like this one, just make sure you change the parameters to what you want it as though!

sub printThis()

Sheets("Sheet1").Activate         '// Activate the sheet you want to print
With ActiveSheet.PageSetup        '// Change the page setup parameters
    .Orientation = xlLandscape    '// xlLandscape or xlPortrait
    .Draft = False                '// If true then any graphics aren't printed
    .PaperSize = xlPaperA4        '// Paper size
    .FitToPagesWide = 2           '// How wide you want it to be
    .FitToPagesTall = 1           '// How tall you want it to be
End With

'// Now print the selected page however many times you like!
ActiveWindow.SelectedSheets.PrintOut Copies:=10, Collate:=True

End sub

Here's an old reference to it on the MSDN library if you want to see all of the different parameters.
http://msdn.microsoft.com/en-us/library/aa174261(v=office.11).aspx

Title: Printing with excel and java or others


问:
Node + react js increse upload file size in post request
how can i increse upload file size in Node + react

i am successfully uploading csv file for 100k counts (14 mb)

but for 500K or 1000K . application crashes ..

i saw similar post , but that using express js to limit filesize

I am using fetch

```<code>fetch(url, {
        method: 'post',
        credentials: "same-origin",
        headers: {
            'user_token': sessionStorage.getItem('token'),
            'Accept': 'application/json',
            'Content-Type':'application/json',
        },
        body: JSON.stringify({
        'uploadedData': this.state.uploadedData,
        }),
    })
    .then(response => response.json())
    .then(json => {

    })
}
</code>```

i have tried to remove

```<code>'Accept': 'application/json',
'Content-Type':'application/json',
</code>```

or use

```<code>'Content-Type':'multipart/form-data',
</code>```

But that doesnot work

I am using laravel server , I also increase upload file size limit on php.ini .. still not result

is there any way to increase file size ??

答:
Try this in expressjs to increase limit of size</p>

```<code>app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
</code>```

Body:
how can i increse upload file size in Node + react

i am successfully uploading csv file for 100k counts (14 mb)

but for 500K or 1000K . application crashes ..

i saw similar post , but that using express js to limit filesize

I am using fetch

fetch(url, {
        method: 'post',
        credentials: "same-origin",
        headers: {
            'user_token': sessionStorage.getItem('token'),
            'Accept': 'application/json',
            'Content-Type':'application/json',
        },
        body: JSON.stringify({
        'uploadedData': this.state.uploadedData,
        }),
    })
    .then(response => response.json())
    .then(json => {

    })
}

i have tried to remove

'Accept': 'application/json',
'Content-Type':'application/json',

or use

'Content-Type':'multipart/form-data',

But that doesnot work

I am using laravel server , I also increase upload file size limit on php.ini .. still not result

is there any way to increase file size ??

Body:
Try this in expressjs to increase limit of size

app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));


问:
Wildcard search in Elasticsearch - Python
My code :

```<code>search_parm ={
    "query": {
        "match" : { "message" : "*error*" }
    }
res = es.search(index='indice_1', body=search_parm)
result = res['hits']['hits']
print(result)
</code>```

I am trying to get the messages which has the text 'error' in it.
The search parameter fetches the below result:

```<code>'message': 'Error handling attributes invalid syntax (<unknown>, line 1)'
</code>```

But, the below value is not fetched :

```<code>'message': 'Sent message on queue: documentprocessing_error'
</code>```

Mapping of message field :

```<code>  "message" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
</code>```

Please let me know how I have to edit the search parameter. Thanks.

答:
Modified my search parameter to

```<code>search_parm1 = {"query": {"wildcard": {"message": { "value": "*error*","boost": 1.0,"rewrite": "constant_score"}}}}
</code>```

Working as expected. Thanks.

Body:
My code :

search_parm ={
    "query": {
        "match" : { "message" : "*error*" }
    }
res = es.search(index='indice_1', body=search_parm)
result = res['hits']['hits']
print(result)

I am trying to get the messages which has the text 'error' in it.
The search parameter fetches the below result:

'message': 'Error handling attributes invalid syntax (<unknown>, line 1)'

But, the below value is not fetched :

'message': 'Sent message on queue: documentprocessing_error'

Mapping of message field :

  "message" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }

Please let me know how I have to edit the search parameter. Thanks.

Body:
Modified my search parameter to

search_parm1 = {"query": {"wildcard": {"message": { "value": "*error*","boost": 1.0,"rewrite": "constant_score"}}}}

Working as expected. Thanks.


问:
jquery todo list append li element to existing list
I am working on programming a todo list application with jquery, but there are some issuses/bugs I am facing. The first element is purposed to be set via HTML code and working like expected. My next step is to append another list element with a checkbox, input textfield, and a dropdown button if a user is clicking the "Neu" button. Like seen in the following picture.

The jquery code I am using to realise this is:

$('ul.todo-list').append('
' +
            '<input type="checkbox"/>' +
            '' +
            '<input [type="text"] placeholder="Insert your new task here"/>' +
            '' +
            '

' +
            '
');```
</div>
</div>
</p>

<p>After a user entered a random text and is clicking the enter button the new text is appearing under the first li element.</p>

<p><img src="https://i.stack.imgur.com/PogHu.png" alt="enter image description here"></p>

<p>Here's the code snipped for this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('input').keypress(function (event) {
            if (((event.which || event.keyCode) == 13) && ($(this).val() != '')) {   //Werte bei keypress: ENTER und nicht leerem Textfeld abfragen und setzen
                var todoText = $(this).val();            //Werte aus <input type="text"/> Textfeld abfangen und in einer
                //neuen Variablen abspeichern

                // append new listelement, drop-down button, edit-duplicate-remove button
                $('ul.todo-list').append('<li>' +
                    '<input type="checkbox">' +
                    '<label>' +
                    '<span></span>' +
                    '<input type="text" id="inputValue" readonly/>' +
                    '</label>' +
                    '<div class="arrow-btn"></div>' +
                    '<ul class="item-menu-bar">' +
                    '<li class="edit-btn">Editieren</li>' +
                    '<li class="duplicate-btn">Duplizieren</li>' +
                    '<li class="remove-btn">Löschen</li>' +
                    '</ul>' +
                    '</li>');

                $('#inputValue').val(todoText);</code>```

Here starts my problem if a previews Item is being added to a list and a user wants to add another list item or element by clicking the "Neu" button my new todo list is looking like this. The value in picture number two "new item inserted" on list position two is being overwritten with a new value which normaly should be on list position 3 and the third list position is empty.

答:
Id must be unique .. That means remove id="inputValue" because it keep repeating on every append .. And use the inline value="'+todoText+'" directly

Try this

$('input').keypress(function (event) {
  if (((event.which || event.keyCode) == 13) && ($(this).val().trim() !== '')) {   //Werte bei keypress: ENTER und nicht leerem Textfeld abfragen und setzen
      var todoText = $(this).val();            //Werte aus <input type="text"/> Textfeld abfangen und in einer
      //neuen Variablen abspeichern

      // append new listelement, drop-down button, edit-duplicate-remove button
      $('ul.todo-list').append('
' +
          '<input type="checkbox">' +
          '' +
          '' +
          '<input type="text" value="'+todoText+'" readonly/>' +
          '' +
          '

' +
          '
' +
          '
Editieren
' +
          '
Duplizieren
' +
          '
Löschen
' +
          '
' +
          '
');
  }
});```

Additional: Use $(this).val().trim() !== '' trim to avoid white-spaces

Body:
I am working on programming a todo list application with jquery, but there are some issuses/bugs I am facing. The first element is purposed to be set via HTML code and working like expected. My next step is to append another list element with a checkbox, input textfield, and a dropdown button if a user is clicking the "Neu" button. Like seen in the following picture.

The jquery code I am using to realise this is:

$('ul.todo-list').append('
' +
            '<input type="checkbox"/>' +
            '' +
            '<input [type="text"] placeholder="Insert your new task here"/>' +
            '' +
            '

' +
            '
');

After a user entered a random text and is clicking the enter button the new text is appearing under the first li element.

Here's the code snipped for this

$('input').keypress(function (event) {
            if (((event.which || event.keyCode) == 13) && ($(this).val() != '')) {   //Werte bei keypress: ENTER und nicht leerem Textfeld abfragen und setzen
                var todoText = $(this).val();            //Werte aus <input type="text"/> Textfeld abfangen und in einer
                //neuen Variablen abspeichern

                // append new listelement, drop-down button, edit-duplicate-remove button
                $('ul.todo-list').append('
' +
                    '<input type="checkbox">' +
                    '' +
                    '' +
                    '<input type="text" id="inputValue" readonly/>' +
                    '' +
                    '

' +
                    '
' +
                    '
Editieren
' +
                    '
Duplizieren
' +
                    '
Löschen
' +
                    '
' +
                    '
');

                $('#inputValue').val(todoText);

Here starts my problem if a previews Item is being added to a list and a user wants to add another list item or element by clicking the "Neu" button my new todo list is looking like this. The value in picture number two "new item inserted" on list position two is being overwritten with a new value which normaly should be on list position 3 and the third list position is empty.

Body:
Id must be unique .. That means remove id="inputValue" because it keep repeating on every append .. And use the inline value="'+todoText+'" directly

Try this

$('input').keypress(function (event) {
  if (((event.which || event.keyCode) == 13) && ($(this).val().trim() !== '')) {   //Werte bei keypress: ENTER und nicht leerem Textfeld abfragen und setzen
      var todoText = $(this).val();            //Werte aus <input type="text"/> Textfeld abfangen und in einer
      //neuen Variablen abspeichern

      // append new listelement, drop-down button, edit-duplicate-remove button
      $('ul.todo-list').append('<li>' +
          '<input type="checkbox">' +
          '<label>' +
          '<span></span>' +
          '<input type="text" value="'+todoText+'" readonly/>' +
          '</label>' +
          '<div class="arrow-btn"></div>' +
          '<ul class="item-menu-bar">' +
          '<li class="edit-btn">Editieren</li>' +
          '<li class="duplicate-btn">Duplizieren</li>' +
          '<li class="remove-btn">L&ouml;schen</li>' +
          '</ul>' +
          '</li>');
  }
});

Additional: Use $(this).val().trim() !== '' trim to avoid white-spaces


问:
PHP 2 actions from a single Button
I am wondering how to get 2 actions in PHP from a single Button.
Attached here is an screenshot of the page:

I have the following code:
For the Submit button

```<code><form method='POST'>
   <div class="form-group">
   <input type="text" name="s_amount" style='width:20%;' required>
   <input type="submit"  class="btn btn-primary" name="submit" value="Submit" />
    </div>
</form>
<?php
 $s_amount = $_POST['s_amount'];
 echo $s_amount;
?>

</code>```

AND for the Submit Code button

```<code>    <button id="submitcode"type="button" class="btn btn-default">Submit Code</button>
    ```.../...```

</code>```

When the Submit code is pressed, this executes the following script

```<code><script>
    $(document).ready(function(){
        $("#submitcode").on("click", function(){
            ocpu.seturl("https://public.opencpu.org/ocpu/library/base/R")
            //arguments
            var mysnippet = new ocpu.Snippet("V_CT="+$('[name="CT"]:radio:checked').val()+"\r V_TP="+$('[name="LENGTH"]:radio:checked').val()+$('#input2').val());
            //perform the request
            var req = ocpu.call("identity", {
                "x" : mysnippet
            }, function(session){
                session.getObject(function(data) {
                //data is the object returned by the R function
                $("#output").text(data);
            });
            });
        })
        });
    </script>
</code>```

What I would like to have is a single button, which not only gets the value next to the first submit button (here 12, see attached pciture) but also executes the script.

Many thanks !

答:
try giving id to form tag and on click on submitcode button call the form using its id.
for ex.

<form method='POST'>```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function(session){
                session.getObject(function(data) {
                //data is the object returned by the R function
                $("#output").text(data);
                // using form id call the form
                $("#formdata").submit(); // it will simply submit the form.
            });
            });</code>```

<form method="post" id="formdata">
</form>```

Title: PHP 2 actions from a single Button

Body:
I am wondering how to get 2 actions in PHP from a single Button.
Attached here is an screenshot of the page:

I have the following code:
For the Submit button

<form method='POST'>

   <input type="text" name="s_amount" style='width:20%;' required>
   <input type="submit"  class="btn btn-primary" name="submit" value="Submit" />

</form>
<?php
 $s_amount = $_POST['s_amount'];
 echo $s_amount;
?>

AND for the Submit Code button

    <button id="submitcode"type="button" class="btn btn-default">Submit Code</button>

.../...

When the Submit code is pressed, this executes the following script

What I would like to have is a single button, which not only gets the value next to the first submit button (here 12, see attached pciture) but also executes the script.

Many thanks !

Body:
try giving id to form tag and on click on submitcode button call the form using its id.
for ex.

<form method='POST'>

function(session){
                session.getObject(function(data) {
                //data is the object returned by the R function
                $("#output").text(data);
                // using form id call the form
                $("#formdata").submit(); // it will simply submit the form.
            });
            });

<form method="post" id="formdata"> <!--assign id to form tag-->
</form>


问:
Using placeholder but having an error 'NoneType' object has no attribute 'type'
I'm trying to obtain new image while combing two different ones, for style transfer. I have two images (one is the target and the other is the style). And I want to get new one from the two of them.

```<code>target_image = K.constant(preprocess_image(target_image_path))
style_reference_image = K.constant(preprocess_image(style_image_path))
combination_image = K.placeholder((1, img_height, img_width, 3))
</code>```

When I want to use the combinatin_image in this function:

```<code>grads = K.gradients(loss, combination_image)[0]
fetch_loss_and_grads = K.function([combination_image], [loss, grads])

class Evaluator(object):

    def __init__(self):
        self.loss_value = None
        self.grads_values = None

    def loss(self, x):
        assert self.loss_value is None
        x = x.reshape((1, img_height, img_width, 3))
        outs = fetch_loss_and_grads([x])
        loss_value = outs[0]
        grad_values = outs[1].flatten().astype('float64')
        self.loss_value = loss_value
        self.grad_values = grad_values
        return self.loss_value

    def grads(self, x):
        assert self.loss_value is not None
        grad_values = np.copy(self.grad_values)
        self.loss_value = None
        self.grad_values = None
        return grad_values

evaluator = Evaluator()

x = preprocess_image(target_image_path)
x = x.flatten()
for i in range(iterations):
    x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x,
                                     fprime=evaluator.grads, maxfun=20)
</code>```

I'm dealing with an error 'NoneType' object has no attribute 'type'.

I tried changing the combinatin_image (combination_image = preprocess_image(new_image_path)) but thet I have a new error:

```<code>---->5 fetch_loss_and_grads = K.function([combination_image], [loss, grads])

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/backend.py in __init__(self, inputs, outputs, updates, name)
   3681                        'of elements from multiple graphs.')
   3682
-> 3683     source_graph = graphs.pop()
   3684     global_graph = get_graph()
   3685

KeyError: 'pop from an empty set'
</code>```

答: combination_image must be None then. If you want a complete answer, please provide more details about your code and the error python returns. See minimal reproducible example and how to ask.

Body:
I'm trying to obtain new image while combing two different ones, for style transfer. I have two images (one is the target and the other is the style). And I want to get new one from the two of them.

target_image = K.constant(preprocess_image(target_image_path))
style_reference_image = K.constant(preprocess_image(style_image_path))
combination_image = K.placeholder((1, img_height, img_width, 3))

When I want to use the combinatin_image in this function:

grads = K.gradients(loss, combination_image)[0]
fetch_loss_and_grads = K.function([combination_image], [loss, grads])

class Evaluator(object):

    def __init__(self):
        self.loss_value = None
        self.grads_values = None

    def loss(self, x):
        assert self.loss_value is None
        x = x.reshape((1, img_height, img_width, 3))
        outs = fetch_loss_and_grads([x])
        loss_value = outs[0]
        grad_values = outs[1].flatten().astype('float64')
        self.loss_value = loss_value
        self.grad_values = grad_values
        return self.loss_value

    def grads(self, x):
        assert self.loss_value is not None
        grad_values = np.copy(self.grad_values)
        self.loss_value = None
        self.grad_values = None
        return grad_values

evaluator = Evaluator()

x = preprocess_image(target_image_path)
x = x.flatten()
for i in range(iterations):
    x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x,
                                     fprime=evaluator.grads, maxfun=20)

I'm dealing with an error 'NoneType' object has no attribute 'type'.

I tried changing the combinatin_image (combination_image = preprocess_image(new_image_path)) but thet I have a new error:

---->5 fetch_loss_and_grads = K.function([combination_image], [loss, grads])

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/backend.py in __init__(self, inputs, outputs, updates, name)
   3681                        'of elements from multiple graphs.')
   3682
-> 3683     source_graph = graphs.pop()
   3684     global_graph = get_graph()
   3685

KeyError: 'pop from an empty set'