问:
What is the recommended way to fanout in SQS lambda environment?
I would like to send a push notification to users in my database in a lambda environment via SQS / messaging queue architecture, in order to do that

I would first need to query all users in my database with push notifications enabled.

loop over all of them them

send a SQS event/message for each user.

let my sqs triggered lambda handle/send the push notification

Is there a better way to implement this to avoid querying a big number of users and/or looping over all the results to send a SQS message for each?

答:
I would take a slightly different approach here, but similar.

Query the database for the users

Loop over the users

Send one messages to SQS for a batch of records to send, and use the SendMessageBatch operation of SQS to send them. So batches of batches. Each batch of messages would have several "users" to send to, not just one. This will should increase your performance because a batch will require fewer lambda invocations.

Lambda handles SQS messages (probably more than one), and each SQS message results in sending many push notifications. In the case of Firebase I believe there is a way to send batches, which is even better. Even without that you can send several messages at once using a Promise.all type logic.

With this structure you can send a very large number of messages really quickly, and probably a lot cheaper. Imagine you need to send to 1M users. If you send batches of 100, in batches of 25 to SQS, then you have 2,500 messages per call to SQS. That would mean 400 calls to SQS, far better than even the 40K you'd have to make if you sent single messages in batches of 25.

On the receiving side, even if you throttled the SQS integration to 1 message per invocation you'd have 10,000 lambda invocations. If you assume even 1s per invocation, and 1000 concurrent invocations, it would take 10 seconds (likely less). If you send one message per user you'd have to make 1M lambda invocations. If you assume each invocation takes 100ms then you can send 10/second, so with 1000 concurrent executions it would take 100 seconds. In reality the numbers are probably even better than that for the batch version, especially if you don't limit it to 1 message at a time.

Edit
Based on the comments the question seemed to be a bit more about the first part of the process. With that in mind I'd suggest the following options.

If you find yourself needing to address the same large groups repeatedly most messaging services (Firebase and SNS for sure) support some sort of topic subscription model. Given that these are push notifications you can subscribe a device to the topic in code. What this ultimately leads to is one messages sent from your code to the messaging service. The service handles the rest. This is probably the preferred solution for anything that has mass recipients, especially if you can know the recipients up front. This even works for dynamic topics. For example, consider a situation where a person comments on a post. Any new comment on that post should send a message to everyone who has commented on that post. You can create a topic on the fly when the post is created, and add recipients to the topic as they comment. If a user wishes to stop receiving messages you can remove the user from the topic.

If you don't know the recipients up front the above solution is a solid solution. However, if you are concerned with Lambda timeouts on the first two steps I'd modify slightly. I would take advantage of AWS Step Functions and page the data in the lambda. Lambda will tell you, via the context object supplied in the invocation, how much time is remaining. You can check that periodically to determine if you should exit the lambda and pass to the step function the current paging information. The step function can pass that paging information back into the lambda, which should be coded to accept the paging information as part of the request, and continue from that point if supplied.


来源: stackexchange

问:
Downloading mp3 file with RN-FETCH-BLOB
I am trying to download an mp3 file with rn-fetch-blob in ios from a link
https://www.myinstants.com/media/sounds/anime-wow-sound-effect-mp3cut.mp3. Than I will share this file with react-native-share but I am not able to retrieve correct file like it is not mp3 file. It is file which whatsapp can not open.

```<code>RNFetchBlob
  .config({
    fileCache: true,
    appendExt : 'mp3'
  })
  .fetch('GET', url, {
    //some headers ..
  })
  .then((res) => {
    // the temp file path
    console.log('The file saved to ', res.path())
    const shareOptions = {
      title: 'Share via',
      message: 'Do not miss to share meme sounds',
      url: 'file://' + res.path(),
    };
    Share.share(shareOptions)
      .then((res) => console.log(res))
      .catch((err) => err && console.log(err))
  })
</code>```

File downloaded returns a path like this /var/mobile/Containers/Data/Application/BC8BC14B-FE8B-4E2C-ACA4-799270D8972B/Documents/RNFetchBlob_tmp/RNFetchBlobTmp_m6vz8itit4jxuxpb8tabrm

If I add appendExt: 'mp3' it returns something like this /var/mobile/Containers/Data/Application/BC8BC14B-FE8B-4E2C-ACA4-799270D8972B/Documents/RNFetchBlob_tmp/RNFetchBlobTmp_m6vz8itit4jxuxpb8tabrm.mp3

Than if I share it on whatapp I got these file like things. This is not mp3 file. This is not even a file I can not open it. Question is do I download the mp3 file in a correct way in ios. If I do why do not I see a path which ends with .mp3 extension? Or am I just using Share library in a wrong way please someone just enlighten me.

答:
I solved the problem. RN-Fetch-Blob paths are not really good with iOS. It is better specifying the path like this.

let path = RNFetchBlob.fs.dirs.DocumentDir

and pass the file you want to download at the end of the path in RNFetchBlob.config like this.

```<code> RNFetchBlob
  .config({
    fileCache: true,
    path: path + '/sound.mp3',

  })
</code>```

Than if you want to share file to random apps. Use react-native-share library's url parameter like this.

```<code>const shareOptions = {
      subject: 'Music',
      title: '',
      message: 'Do not miss to share meme sounds',
      url:  res.path(),
    };
</code>```

Both url: 'file:// + res.path() and url: res.path() will work correctly in Android. But in my case declaring url without file:// was working.

ContentLicense: CC BY-SA 4.0

Title: Downloading mp3 file with RN-FETCH-BLOB

Body:
I am trying to download an mp3 file with rn-fetch-blob in ios from a link
https://www.myinstants.com/media/sounds/anime-wow-sound-effect-mp3cut.mp3. Than I will share this file with react-native-share but I am not able to retrieve correct file like it is not mp3 file. It is file which whatsapp can not open.

RNFetchBlob
  .config({
    fileCache: true,
    appendExt : 'mp3'
  })
  .fetch('GET', url, {
    //some headers ..
  })
  .then((res) => {
    // the temp file path
    console.log('The file saved to ', res.path())
    const shareOptions = {
      title: 'Share via',
      message: 'Do not miss to share meme sounds',
      url: 'file://' + res.path(),
    };
    Share.share(shareOptions)
      .then((res) => console.log(res))
      .catch((err) => err && console.log(err))
  })

File downloaded returns a path like this /var/mobile/Containers/Data/Application/BC8BC14B-FE8B-4E2C-ACA4-799270D8972B/Documents/RNFetchBlob_tmp/RNFetchBlobTmp_m6vz8itit4jxuxpb8tabrm

If I add appendExt: 'mp3' it returns something like this /var/mobile/Containers/Data/Application/BC8BC14B-FE8B-4E2C-ACA4-799270D8972B/Documents/RNFetchBlob_tmp/RNFetchBlobTmp_m6vz8itit4jxuxpb8tabrm.mp3

Than if I share it on whatapp I got these file like things. This is not mp3 file. This is not even a file I can not open it. Question is do I download the mp3 file in a correct way in ios. If I do why do not I see a path which ends with .mp3 extension? Or am I just using Share library in a wrong way please someone just enlighten me.

Body:
I solved the problem. RN-Fetch-Blob paths are not really good with iOS. It is better specifying the path like this.

let path = RNFetchBlob.fs.dirs.DocumentDir

and pass the file you want to download at the end of the path in RNFetchBlob.config like this.

 RNFetchBlob
  .config({
    fileCache: true,
    path: path + '/sound.mp3',

  })

Than if you want to share file to random apps. Use react-native-share library's url parameter like this.

const shareOptions = {
      subject: 'Music',
      title: '',
      message: 'Do not miss to share meme sounds',
      url:  res.path(),
    };

Both url: 'file:// + res.path() and url: res.path() will work correctly in Android. But in my case declaring url without file:// was working.


问:
Struct contents reference from a non-struct array object
I want to create a loop to delete file within specific file size and I have these problems.

```<code>selpath = uigetdir(files)
for ii = 1:length(files)
    if files(ii).bytes<500000   % 500kb
        delete(fullfile(files(ii).folder, files(ii).name))
    end
end
</code>```

and I always got this message

```<code>>> cobayginibro

selpath =

    'D:\Proyekan Tes'

Struct contents reference from a non-struct array object.

Error in cobayginibro (line 3)
    if files(ii).bytes<500000   % 500kb
</code>```

Any idea how to solve this?
Also I want to fprint how many files i've deleted
Thanks before

答:
You just need to set files after getting selpath.

selpath = uigetdir()
files = dir(selpath)
for ii = 1:length(files)
    if ~files(ii).isdir && files(ii).bytes<500000   % 500kb
        delete(fullfile(files(ii).folder, files(ii).name))
    end
end
```

Body:
I want to create a loop to delete file within specific file size and I have these problems.

selpath = uigetdir(files)
for ii = 1:length(files)
    if files(ii).bytes<500000   % 500kb
        delete(fullfile(files(ii).folder, files(ii).name))
    end
end

and I always got this message

>> cobayginibro

selpath =

    'D:\Proyekan Tes'

Struct contents reference from a non-struct array object.

Error in cobayginibro (line 3)
    if files(ii).bytes<500000   % 500kb

Any idea how to solve this?
Also I want to fprint how many files i've deleted
Thanks before


问:
COM on 64 Bit Platform
I'm using a 3rd party COM Library with C#, all works fine on 32 bit XP. I use tlbimp to create the wrapper, add a reference all works. However, when porting to our Server environment which is 64 bit Windows Server 2008, I've run into a road block.

The code below only runs properly when I right click and test it, ie run within the VS environment. The code does not work when compiled to a Console App, nor does the code work in an Assembly whether in test or called from a console App. In an attempt to get it working I'm running as Administrator and in a 32bit command window - still nothing grouper is always null, and no exception is thrown, indicating that GrpSvr.GrpCall is a valid Com Library name.

```<code>    string sMessage = "no grouper";
    GrpSvr.GrpCall grouper = Activator.CreateInstance(
        Type.GetTypeFromProgID("GrpSvr.GrpCall")) as GrpSvr.GrpCall;
    if (grouper != null)
        sMessage = grouper.GroupInit(@"C:\CmdGrp.txt", true, true);

    Console.WriteLine(sMessage);
</code>```

答: It sounds like the 3rd party COM DLL is 32 bits only.  You have to configure your app to run as 32 bits only, instead of any cpu.</p>

ContentLicense: CC BY-SA 3.0

Title: COM on 64 Bit Platform

Body:
I'm using a 3rd party COM Library with C#, all works fine on 32 bit XP. I use tlbimp to create the wrapper, add a reference all works. However, when porting to our Server environment which is 64 bit Windows Server 2008, I've run into a road block.

The code below only runs properly when I right click and test it, ie run within the VS environment. The code does not work when compiled to a Console App, nor does the code work in an Assembly whether in test or called from a console App. In an attempt to get it working I'm running as Administrator and in a 32bit command window - still nothing grouper is always null, and no exception is thrown, indicating that GrpSvr.GrpCall is a valid Com Library name.

    string sMessage = "no grouper";
    GrpSvr.GrpCall grouper = Activator.CreateInstance(
        Type.GetTypeFromProgID("GrpSvr.GrpCall")) as GrpSvr.GrpCall;
    if (grouper != null)
        sMessage = grouper.GroupInit(@"C:\CmdGrp.txt", true, true);

    Console.WriteLine(sMessage);


问:
Is destructuring this possible?
I am new to destructuring and need help finding the best solution. I have a pretty complicated object coming back as a response and would like to clean it up. Without doing anything, it looks like this:

```<code>
const homeTeam = {

totalPlaysFor: res.data.stats.home.teamStats[0].miscellaneous.offensePlays,

totalPlaysAgainst: res.data.stats.away.teamStats[0].miscellaneous.offensePlays

}

</code>```

I know I can do something like:

```<code>
const { offensePlays } = res.data.stats.home.teamStats[0].miscellaneous;

</code>```

but that only solves my problem for one of them and would leave the other still long and tough to read.

答:
While you can destructure this directly, via something like

const {
  data: {
    stats: {
      home: {
        teamStats: [{
          miscellaneous: {
            offensePlays: totalPlaysFor
          }
        }]
      },
      away: {
        teamStats: [{
          miscellaneous: {
            offensePlays: totalPlaysAgainst
          }
        }]
      }
    }
  }
} = res

const homeTeam = {totalPlaysFor, totalPlaysAgainst}
```

<p>that feels pretty ugly.</p>

<p>Regardless whether you think your code is ugly, I can see a much more important problem with it: it doesn't work when any of those properties doesn't exist. To solve that, you might want a feature not yet ubiquitous in the language, one of Optional Chaining that would avoid throwing errors for a nested path such as <code>'data?.stats?.home?.teamStats?.0?.miscellaneous?.offensePlays'</code>, simply returning <code>undefined</code> if one of the nodes mentioned does not exist.</p>

<p>An equivalent feature is available as a function in many libraries.  Underscore's <code>property</code>, lodash's <code>property</code>, and Ramda's <code>path</code> offer slightly different versions of this.  (Disclaimer: I'm a Ramda author.)  However it's easy enough to write our own:</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>const getPath = (pathStr) => (obj) =>
  pathStr .split ('.')
    .reduce ((o, p) => (o || {}) [p], obj)

const res = {data: {stats: {home: {teamStats: [{miscellaneous: {offensePlays: "foo"}}]}, away: {teamStats: [{miscellaneous: {offensePlays: "bar"}}]}}}}

const homeTeam = {
  totalPlaysFor: getPath ('data.stats.home.teamStats.0.miscellaneous.offensePlays') (res),
  totalPlaysAgainst: getPath ('data.stats.away.teamStats.0.miscellaneous.offensePlays') (res)
}

console .log (homeTeam)</code>```

Note that the array is not delineated in this simple version as [0] but just as .0.  Obviously we could make this more sophisticated if necessary.

Title: Is destructuring this possible?

Body:
I am new to destructuring and need help finding the best solution. I have a pretty complicated object coming back as a response and would like to clean it up. Without doing anything, it looks like this:

const homeTeam = {

totalPlaysFor: res.data.stats.home.teamStats[0].miscellaneous.offensePlays,

totalPlaysAgainst: res.data.stats.away.teamStats[0].miscellaneous.offensePlays

}

I know I can do something like:

const { offensePlays } = res.data.stats.home.teamStats[0].miscellaneous;

but that only solves my problem for one of them and would leave the other still long and tough to read.

Body:
While you can destructure this directly, via something like

const {
  data: {
    stats: {
      home: {
        teamStats: [{
          miscellaneous: {
            offensePlays: totalPlaysFor
          }
        }]
      },
      away: {
        teamStats: [{
          miscellaneous: {
            offensePlays: totalPlaysAgainst
          }
        }]
      }
    }
  }
} = res

const homeTeam = {totalPlaysFor, totalPlaysAgainst}

that feels pretty ugly.

Regardless whether you think your code is ugly, I can see a much more important problem with it: it doesn't work when any of those properties doesn't exist. To solve that, you might want a feature not yet ubiquitous in the language, one of Optional Chaining that would avoid throwing errors for a nested path such as 'data?.stats?.home?.teamStats?.0?.miscellaneous?.offensePlays', simply returning undefined if one of the nodes mentioned does not exist.

An equivalent feature is available as a function in many libraries.  Underscore's property, lodash's property, and Ramda's path offer slightly different versions of this.  (Disclaimer: I'm a Ramda author.)  However it's easy enough to write our own:

const getPath = (pathStr) => (obj) =>
  pathStr .split ('.')
    .reduce ((o, p) => (o || {}) [p], obj)

const res = {data: {stats: {home: {teamStats: [{miscellaneous: {offensePlays: "foo"}}]}, away: {teamStats: [{miscellaneous: {offensePlays: "bar"}}]}}}}

const homeTeam = {
  totalPlaysFor: getPath ('data.stats.home.teamStats.0.miscellaneous.offensePlays') (res),
  totalPlaysAgainst: getPath ('data.stats.away.teamStats.0.miscellaneous.offensePlays') (res)
}

console .log (homeTeam)

Note that the array is not delineated in this simple version as [0] but just as .0.  Obviously we could make this more sophisticated if necessary.


问:
How Can I Detect Gaps and Consecutive Periods In A Time Series In Pandas
I have a pandas Dataframe that is indexed by Date.  I would like to select all consecutive gaps by period and all consecutive days by Period.    How can I do this?

Example of Dataframe with No Columns but a Date Index:

```<code>In [29]: import pandas as pd

In [30]: dates = pd.to_datetime(['2016-09-19 10:23:03', '2016-08-03 10:53:39','2016-09-05 11:11:30', '2016-09-05 11:10:46','2016-09-05 10:53:39'])

In [31]: ts = pd.DataFrame(index=dates)
</code>```

As you can see there is a gap from 2016-08-03 and 2016-09-19.  How do I detect these so I can create descriptive statistics, i.e.  40 gaps, with median gap duration of "x", etc.  Also, I can see that 2016-09-05 and 2016-09-06 is a two day range.  How I can detect these and also print descriptive stats?

Ideally the result would be returned as another Dataframe in each case since I want use other columns in the Dataframe to groupby.

答:
Pandas version 1.0.1 has a built-in method DataFrame.diff() which you can use to accomplish this. One benefit is you can use pandas series functions like mean() to quickly compute summary statistics on the gaps series object

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

# Construct dummy dataframe
dates = pd.to_datetime([
    '2016-08-03',
    '2016-08-04',
    '2016-08-05',
    '2016-08-17',
    '2016-09-05',
    '2016-09-06',
    '2016-09-07',
    '2016-09-19'])
df = pd.DataFrame(dates, columns=['date'])

# Take the diff of the first column (drop 1st row since it's undefined)
deltas = df['date'].diff()[1:]

# Filter diffs (here days > 1, but could be seconds, hours, etc)
gaps = deltas[deltas > timedelta(days=1)]

# Print results
print(f'{len(gaps)} gaps with average gap duration: {gaps.mean()}')
for i, g in gaps.iteritems():
    gap_start = df['date'][i - 1]
    print(f'Start: {datetime.strftime(gap_start, "%Y-%m-%d")} | '
          f'Duration: {str(g.to_pytimedelta())}')
</code>```

Body:
I have a pandas Dataframe that is indexed by Date.  I would like to select all consecutive gaps by period and all consecutive days by Period.    How can I do this?

Example of Dataframe with No Columns but a Date Index:

In [29]: import pandas as pd

In [30]: dates = pd.to_datetime(['2016-09-19 10:23:03', '2016-08-03 10:53:39','2016-09-05 11:11:30', '2016-09-05 11:10:46','2016-09-05 10:53:39'])

In [31]: ts = pd.DataFrame(index=dates)

As you can see there is a gap from 2016-08-03 and 2016-09-19.  How do I detect these so I can create descriptive statistics, i.e.  40 gaps, with median gap duration of "x", etc.  Also, I can see that 2016-09-05 and 2016-09-06 is a two day range.  How I can detect these and also print descriptive stats?

Ideally the result would be returned as another Dataframe in each case since I want use other columns in the Dataframe to groupby.

Body:
Pandas version 1.0.1 has a built-in method DataFrame.diff() which you can use to accomplish this. One benefit is you can use pandas series functions like mean() to quickly compute summary statistics on the gaps series object

from datetime import datetime, timedelta
import pandas as pd

# Construct dummy dataframe
dates = pd.to_datetime([
    '2016-08-03',
    '2016-08-04',
    '2016-08-05',
    '2016-08-17',
    '2016-09-05',
    '2016-09-06',
    '2016-09-07',
    '2016-09-19'])
df = pd.DataFrame(dates, columns=['date'])

# Take the diff of the first column (drop 1st row since it's undefined)
deltas = df['date'].diff()[1:]

# Filter diffs (here days > 1, but could be seconds, hours, etc)
gaps = deltas[deltas > timedelta(days=1)]

# Print results
print(f'{len(gaps)} gaps with average gap duration: {gaps.mean()}')
for i, g in gaps.iteritems():
    gap_start = df['date'][i - 1]
    print(f'Start: {datetime.strftime(gap_start, "%Y-%m-%d")} | '
          f'Duration: {str(g.to_pytimedelta())}')


问:
Some projects' dependencies contain unexplained code analyzers
I have a couple of projects where under Dependencies there are one or two branches of code analyzers like this:

I tried the right mouse click on every branch as explaind here but there is no option to configure them and I also searched for *.ruleset files insinde the solution, I also check the packages as shown in the docs but there is nothing like that anywhere.

There is also nothing suspicious in the .csproj files, just some nuget packages that I've installed but nothing analyzer related.

How do I get rid of them? They give me warnings when I reference such projects in other solutions and nuget restore doesn't fix it either:

I have no idea where they come from. Some projects have them and others don't. However, they seem to somehow be related to ASP.NET Core or MVC packages that are installed in those projects.

答:
There is a bug in Visual Studio and it is supposed to be fixed soon.
When Visual Studio loads all projects for the solution and tries to resolve all dependencies to display in Solution Explorer, some dependencies may fail and display as warnings with the path of the likely file for the dependency.

Workaround:

Right click the project with the warnings, and select Unload Project on the menu. Then right click it again and select Reload Project. Because Visual Studio is less busy with background processes than it was when it was loading everything for the entire solution, it is likely to resolve the dependency. It seems to always work for me.


问:
How to label every nth row of a pandas dataframe by an incremental value
I have a simple problem (hopefully!). and i am overly complicating it. Maybe there is a one liner out there; I have a dataframe that contains lets say 10 rows and I want to label rows in such a way it looks like col B. Every 4th row has an different label.

```<code>Row B
1   1
2   1
3   1
4   1
5   2
6   2
7   2
8   2
9   3
10  3
</code>```

I tried iterating by dataframe position and ended up complicating it.

```<code>num =4
id=1
    def label_id(x,num,id):
        if x > num:
          id=id+1
          label=id
          num=num*id
        else:
            label = id
            id=id
        return label
    id=1
    for i in range(len(df)):
        df.iat[i,1] = df.apply(label_id(df.iat[i,0],num,id),axis=1)
</code>```

i get an error TypeError: ("'int' object is not callable", 'occurred at index 0'). I am sure i am overthinking this. Any help?

答:
You can use expanding:</p>

```<code>df.Row.expanding().apply(lambda x: (len(x)+3)//4, raw=True).astype(int)
</code>```

Body:
I have a simple problem (hopefully!). and i am overly complicating it. Maybe there is a one liner out there; I have a dataframe that contains lets say 10 rows and I want to label rows in such a way it looks like col B. Every 4th row has an different label.

Row B
1   1
2   1
3   1
4   1
5   2
6   2
7   2
8   2
9   3
10  3

I tried iterating by dataframe position and ended up complicating it.

num =4
id=1
    def label_id(x,num,id):
        if x > num:
          id=id+1
          label=id
          num=num*id
        else:
            label = id
            id=id
        return label
    id=1
    for i in range(len(df)):
        df.iat[i,1] = df.apply(label_id(df.iat[i,0],num,id),axis=1)

i get an error TypeError: ("'int' object is not callable", 'occurred at index 0'). I am sure i am overthinking this. Any help?

Body:
You can use expanding:

df.Row.expanding().apply(lambda x: (len(x)+3)//4, raw=True).astype(int)


问:
Connect Adobe Flex To Arcgis Service?
I'm trying to connect my flex app to my Arcgis webservices. I tried using the connect to webservice interface. But I keep getting this error.

There was an error during service
  introspection. WSDLException:
  faultCode=PARSER_ERROR: Problem
  parsing
  'http://localhost/ArcGIS/rest/services/geodata/MapServer'.:
  org.xml.sax.SAXParseException: The
  element type "link" must be terminated
  by the matching end-tag "/link".

My web service looks like this

ArcGIS Services Directory Home >
  geodata (MapServer)   Help | API
  Reference geodata (MapServer) View In:
  ArcMap   ArcGIS Explorer   ArcGIS
  JavaScript   Google Earth   ArcGIS.com
  Map

View Footprint In:   Google Earth

Service Description:

Map Name: Layers

Legend

All Layers and Tables

Layers:

```<code>Geocoding_Result layer (0)
</code>```

Tables:

Description:

Copyright Text:

Spatial Reference: 4326

Single Fused Map Cache: false

Intial Extent:

```<code>XMin: -95.901360470612
YMin: 29.4513469530748
XMax: -95.1472749640384
YMax: 30.045474927951
Spatial Reference: 4326
</code>```

Full Extent:

```<code>XMin: -100.3273442
YMin: 29.451583
XMax: -94.8230278
YMax: 31.250677
Spatial Reference: 4326
</code>```

Units: esriDecimalDegrees

Supported Image Format Types:
  PNG24,PNG,JPG,DIB,TIFF,EMF,PS,PDF,GIF,SVG,SVGZ,AI,BMP

Document Info:

```<code>Title:
Author:
Comments:
Subject:
Category:
Keywords:
Credits:
</code>```

Supported Interfaces:   REST   SOAP

Supported Operations:   Export Map

  Identify   Find

答: Maybe you already know... but if you are trying to connect to an ArcGIS Server using Flex you might be interested in the ArcGIS API for Flex - http://links.esri.com/flex - it will take care of most of that for you.  </p>

Title: Connect Adobe Flex To Arcgis Service?

Body:
I'm trying to connect my flex app to my Arcgis webservices. I tried using the connect to webservice interface. But I keep getting this error.

There was an error during service
  introspection. WSDLException:
  faultCode=PARSER_ERROR: Problem
  parsing
  'http://localhost/ArcGIS/rest/services/geodata/MapServer'.:
  org.xml.sax.SAXParseException: The
  element type "link" must be terminated
  by the matching end-tag "/link".

My web service looks like this

ArcGIS Services Directory Home >
  geodata (MapServer)   Help | API
  Reference geodata (MapServer) View In:
  ArcMap   ArcGIS Explorer   ArcGIS
  JavaScript   Google Earth   ArcGIS.com
  Map

View Footprint In:   Google Earth

Service Description:

Map Name: Layers

Legend

All Layers and Tables

Layers:

Geocoding_Result layer (0)

Tables:

Description:

Copyright Text:

Spatial Reference: 4326

Single Fused Map Cache: false

Intial Extent:

XMin: -95.901360470612
YMin: 29.4513469530748
XMax: -95.1472749640384
YMax: 30.045474927951
Spatial Reference: 4326

Full Extent:

XMin: -100.3273442
YMin: 29.451583
XMax: -94.8230278
YMax: 31.250677
Spatial Reference: 4326

Units: esriDecimalDegrees

Supported Image Format Types:
  PNG24,PNG,JPG,DIB,TIFF,EMF,PS,PDF,GIF,SVG,SVGZ,AI,BMP

Document Info:

Title:
Author:
Comments:
Subject:
Category:
Keywords:
Credits:

Supported Interfaces:   REST   SOAP

Supported Operations:   Export Map

  Identify   Find


问:
Flatten JUnit tests in static member classes
For one of my projects I'm using JUnit 5 to test reflection code, which requires a large number of classes for test cases. Throwing them all in one scope and trying to name them intelligently is nearly impossible, so I'm hoping to put both the test methods and the types being tested inside a static member class. Doing this would allow me to reuse names such as X or Y in each test, and would keep the types being tested near the code that tests them. (The member classes have to be static so I can add interfaces)

If I just add static classes the tests run fine out of the box, but in the final report I end up with all the member classes listed separately, so I'd like to be able to "flatten" them all into the single class in the report.

Here's an example of what I would like to achieve: (I'm actually writing the tests in Kotlin, but this is the equivalent Java code)

class MethodTests {
    static class WhateverName {
        interface X {}
        class Y implements X {}

        @Test
        void something_withInterfaceSupertype_shouldReturnThing() {
            // ...
        }

        @Test
        void other_withInterfaceSupertype_shouldReturnThing() {
            // ...
        }
    }
    static class WhateverOtherName {
        interface X {
            void m();
        }
        class Y implements X {
            void m() {}
        }

        @Test
        void something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing() {
            // ...
        }
    }

    // This might actually be even better, since I wouldn't need `WhateverName`
    @Test // not valid, but maybe I could annotate the class instead of the method?
    static class something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo {
        interface X {}
        class Y implements X {}

        @Test
        void runTest() {
            // ...
        }
    }

}
```

<p>At the moment the test report in IDEA ends up being structured like this:</p>

```- MethodTests
  - someRoot_testHere
- MethodTests$WhateverName
  - something_withInterfaceSupertype_shouldReturnThing
  - other_withInterfaceSupertype_shouldReturnThing
- MethodTests$WhateverOtherName
  - something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing
- MethodTests$something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo
  - runTest
```

<p>But I'd like the test report to be structured like this:</p>

```- MethodTests
  - someRoot_testHere
  - something_withInterfaceSupertype_shouldReturnThing
  - other_withInterfaceSupertype_shouldReturnThing
  - something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing
  - something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo
```

I tried using @DisplayName on the member classes but it just resulted in a duplicate name in the report. So far I think I might want to use an extension, but after doing a bit of research I haven't found any way to change the class a test is listed under in the report using them.

答:
After more digging I was able to achieve almost exactly what I wanted using dynamic tests:

```<code>class MethodsTest {

    @TestFactory
    Iterator<DynamicTest> flat() {
        return FlatTestScanner.scan(this);
    }

    @Test
    void rootTest() {
    }

    @FlatTest
    static class singleTestClass implements TestClass {
        void run() {
            // ...
        }
    }

    static class Whatever {
        @FlatTest
        void multiTestClass_1() {
            // ...
        }

        @FlatTest
        void multiTestClass_2() {
            // ...
        }
    }
}
</code>```

The final report structure isn't quite perfect, but it's pretty close to what I was going for:

```<code>- MethodsTest
  - flat()
    - singleTestClass
    - multiTestClass_1
    - multiTestClass_2
  - rootTest
</code>```

Here's the code that makes this happen. It works by scanning all the declared classes for annotated methods and grabbing any that are annotated themselves, then creating dynamic tests for them, making sure to specify their source URIs. It's in Kotlin, but with a bit of work could be translated to Java:

```<code>import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.DynamicTest
import java.net.URI

/**
 * Useful for having separate class scopes for tests without having fragmented reports.
 *
 * @see FlatTestScanner.scan
 */
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class FlatTest

object FlatTestScanner {
    /**
     * Returns dynamic tests to run all the flat tests declared in the passed class. This currently only works with
     * static inner classes.
     *
     * - Annotated functions in inner classes will be run
     * - Annotated inner classes will have their `run()` methods run
     *
     * To use this create a method in the outer class annotated with [@TestFactory][org.junit.jupiter.api.TestFactory]
     * and return the result of passing `this` to this method. This will return matches from superclasses as well.
     *
     * ```java
     * @TestFactory
     * Iterator<DynamicTest> flat() {
     *     return FlatTestScanner.scan(this)
     * }
     * ```
     */
    @JvmStatic
    fun scan(obj: Any): Iterator<DynamicTest> {
        val classes = generateSequence<Class<*>>(obj.javaClass) { it.superclass }
            .flatMap { it.declaredClasses.asSequence() }
            .toList()
        val testMethods = classes.asSequence()
            .map { clazz ->
                clazz to clazz.declaredMethods.filter { m -> m.isAnnotationPresent(FlatTest::class.java) }
            }
            .filter { (_, methods) -> methods.isNotEmpty() }
            .flatMap { (clazz, methods) ->
                val instance = clazz.newInstance()
                methods.asSequence().map { m ->
                    val name = m.getAnnotation(DisplayName::class.java)?.value ?: m.name

                    m.isAccessible = true
                    DynamicTest.dynamicTest(name, URI("method:${clazz.canonicalName}#${m.name}")) {
                        try {
                            m.invoke(instance)
                        } catch(e: InvocationTargetException) {
                            e.cause?.also { throw it } // unwrap assertion failures
                        }
                    }
                }
            }

        val testClasses = classes.asSequence()
            .filter { it.isAnnotationPresent(FlatTest::class.java) }
            .map {
                val name = it.getAnnotation(DisplayName::class.java)?.value ?: it.simpleName

                val instance = it.newInstance()
                val method = it.getDeclaredMethod("run")
                method.isAccessible = true
                DynamicTest.dynamicTest(name, URI("method:${it.canonicalName}#run")) {
                    try {
                        method.invoke(instance)
                    } catch(e: InvocationTargetException) {
                        e.cause?.also { throw it } // unwrap assertion failures
                    }
                }
            }
        return (testMethods + testClasses).iterator()
    }
}
</code>```

Body:
For one of my projects I'm using JUnit 5 to test reflection code, which requires a large number of classes for test cases. Throwing them all in one scope and trying to name them intelligently is nearly impossible, so I'm hoping to put both the test methods and the types being tested inside a static member class. Doing this would allow me to reuse names such as X or Y in each test, and would keep the types being tested near the code that tests them. (The member classes have to be static so I can add interfaces)

If I just add static classes the tests run fine out of the box, but in the final report I end up with all the member classes listed separately, so I'd like to be able to "flatten" them all into the single class in the report.

Here's an example of what I would like to achieve: (I'm actually writing the tests in Kotlin, but this is the equivalent Java code)

class MethodTests {
    static class WhateverName {
        interface X {}
        class Y implements X {}

        @Test
        void something_withInterfaceSupertype_shouldReturnThing() {
            // ...
        }

        @Test
        void other_withInterfaceSupertype_shouldReturnThing() {
            // ...
        }
    }
    static class WhateverOtherName {
        interface X {
            void m();
        }
        class Y implements X {
            void m() {}
        }

        @Test
        void something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing() {
            // ...
        }
    }

    // This might actually be even better, since I wouldn't need `WhateverName`
    @Test // not valid, but maybe I could annotate the class instead of the method?
    static class something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo {
        interface X {}
        class Y implements X {}

        @Test
        void runTest() {
            // ...
        }
    }

}

At the moment the test report in IDEA ends up being structured like this:

- MethodTests
  - someRoot_testHere
- MethodTests$WhateverName
  - something_withInterfaceSupertype_shouldReturnThing
  - other_withInterfaceSupertype_shouldReturnThing
- MethodTests$WhateverOtherName
  - something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing
- MethodTests$something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo
  - runTest

But I'd like the test report to be structured like this:

- MethodTests
  - someRoot_testHere
  - something_withInterfaceSupertype_shouldReturnThing
  - other_withInterfaceSupertype_shouldReturnThing
  - something_withInterfaceSupertype_andMethodImpl_shouldReturnOtherThing
  - something_withInterfaceSupertype_shouldReturnThing_2ElectricBoogaloo

I tried using @DisplayName on the member classes but it just resulted in a duplicate name in the report. So far I think I might want to use an extension, but after doing a bit of research I haven't found any way to change the class a test is listed under in the report using them.

Body:
After more digging I was able to achieve almost exactly what I wanted using dynamic tests:

class MethodsTest {

    @TestFactory
    Iterator<DynamicTest> flat() {
        return FlatTestScanner.scan(this);
    }

    @Test
    void rootTest() {
    }

    @FlatTest
    static class singleTestClass implements TestClass {
        void run() {
            // ...
        }
    }

    static class Whatever {
        @FlatTest
        void multiTestClass_1() {
            // ...
        }

        @FlatTest
        void multiTestClass_2() {
            // ...
        }
    }
}

The final report structure isn't quite perfect, but it's pretty close to what I was going for:

- MethodsTest
  - flat()
    - singleTestClass
    - multiTestClass_1
    - multiTestClass_2
  - rootTest

Here's the code that makes this happen. It works by scanning all the declared classes for annotated methods and grabbing any that are annotated themselves, then creating dynamic tests for them, making sure to specify their source URIs. It's in Kotlin, but with a bit of work could be translated to Java:

import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.DynamicTest
import java.net.URI

/**
 * Useful for having separate class scopes for tests without having fragmented reports.
 *
 * @see FlatTestScanner.scan
 */
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class FlatTest

object FlatTestScanner {
    /**
     * Returns dynamic tests to run all the flat tests declared in the passed class. This currently only works with
     * static inner classes.
     *
     * - Annotated functions in inner classes will be run
     * - Annotated inner classes will have their `run()` methods run
     *
     * To use this create a method in the outer class annotated with [@TestFactory][org.junit.jupiter.api.TestFactory]
     * and return the result of passing `this` to this method. This will return matches from superclasses as well.
     *
     * ```java
     * @TestFactory
     * Iterator<DynamicTest> flat() {
     *     return FlatTestScanner.scan(this)
     * }
     * ```
     */
    @JvmStatic
    fun scan(obj: Any): Iterator<DynamicTest> {
        val classes = generateSequence<Class<*>>(obj.javaClass) { it.superclass }
            .flatMap { it.declaredClasses.asSequence() }
            .toList()
        val testMethods = classes.asSequence()
            .map { clazz ->
                clazz to clazz.declaredMethods.filter { m -> m.isAnnotationPresent(FlatTest::class.java) }
            }
            .filter { (_, methods) -> methods.isNotEmpty() }
            .flatMap { (clazz, methods) ->
                val instance = clazz.newInstance()
                methods.asSequence().map { m ->
                    val name = m.getAnnotation(DisplayName::class.java)?.value ?: m.name

                    m.isAccessible = true
                    DynamicTest.dynamicTest(name, URI("method:${clazz.canonicalName}#${m.name}")) {
                        try {
                            m.invoke(instance)
                        } catch(e: InvocationTargetException) {
                            e.cause?.also { throw it } // unwrap assertion failures
                        }
                    }
                }
            }

        val testClasses = classes.asSequence()
            .filter { it.isAnnotationPresent(FlatTest::class.java) }
            .map {
                val name = it.getAnnotation(DisplayName::class.java)?.value ?: it.simpleName

                val instance = it.newInstance()
                val method = it.getDeclaredMethod("run")
                method.isAccessible = true
                DynamicTest.dynamicTest(name, URI("method:${it.canonicalName}#run")) {
                    try {
                        method.invoke(instance)
                    } catch(e: InvocationTargetException) {
                        e.cause?.also { throw it } // unwrap assertion failures
                    }
                }
            }
        return (testMethods + testClasses).iterator()
    }
}


问:
How to execute code if the difference in the value of a variable is over 20
I'm trying to see if var1 is not equal to var2, but has top be greater than it by 20 or more to execute the code.

I currently have:

```<code>if (var1 != var2) {
    // need to put what happens if var2 is 20 or more greater than var1
}
else {

}
</code>```

答:
add condition this on loop</p>

```<code>if (var1 != var2) {

// need to put what happens if var2 is 20 or more greater than var1
if(var1 - var2 >= 20){

}else{

}
}else{

}

</code>```

Body:
I'm trying to see if var1 is not equal to var2, but has top be greater than it by 20 or more to execute the code.

I currently have:

if (var1 != var2) {
    // need to put what happens if var2 is 20 or more greater than var1
}
else {

}

Body:
add condition this on loop

if (var1 != var2) {

// need to put what happens if var2 is 20 or more greater than var1
if(var1 - var2 >= 20){

}else{

}
}else{

}


问:
I am getting a 'Cannot set property 'variable' of undefined' in the following component
The component will render a list of values fetched from an API. I am getting the following component initialization issue:

```<code>Cannot set property 'hits' of undefined
</code>```

display-recipes.component.ts:

```<code>import { Component, OnInit, Input} from '@angular/core';
import { SearchRecipeService } from '../search-recipe.service';
import { RecipeGlobal } from '../pojos/RecipeGlobal';

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

  @Input() calories: String;
  @Input() recipe: String;
  recipeResult: RecipeGlobal;
  constructor(private searchRecipeService: SearchRecipeService) { }

  ngOnInit() {
     this.recipeResult.hits = [];
  }

  ngOnChanges(){
    this.getRecipeInfo();
  }

  getRecipeInfo(){
     this.searchRecipeService.getRecipeInfo().
     subscribe(recipeResult => this.recipeResult = recipeResult);
  }

}
</code>```

display-recipes.component.html

```<code><p>display-recipes works!</p>
<div id='display_recipe'  *ngFor="let recipe of recipeResult.hits">
    {{recipe.label}}
</div>
</code>```

RecipeGlobal.ts

```<code>export class RecipeGlobal{
    q: String;
    hits: Recipe[];
}

export class Recipe{
    image: String;
    calories: String;
    label: String
}
</code>```

I am failing to understand how objects are initialized in typescript. If I declare a non primitive inside the object, do I have to initialize it?. If so, in this case how should I initialize the array?.

答:
Your error is occuring because of this line of code

```<code> ngOnInit() {
 this.recipeResult.hits = [];
  }
</code>```

Since recipeResult variable is not defined yet.

The ngOnInit lifecycle hook would get called before the data is fetched from the api.

Now you'll have to define the recipeResult variable before hand, e.g. where it was declared, change that line to this

```<code>recipeResult: RecipeGlobal = new RecipeGlobal();
</code>```

Thanks.

Body:
The component will render a list of values fetched from an API. I am getting the following component initialization issue:

Cannot set property 'hits' of undefined

display-recipes.component.ts:

import { Component, OnInit, Input} from '@angular/core';
import { SearchRecipeService } from '../search-recipe.service';
import { RecipeGlobal } from '../pojos/RecipeGlobal';

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

  @Input() calories: String;
  @Input() recipe: String;
  recipeResult: RecipeGlobal;
  constructor(private searchRecipeService: SearchRecipeService) { }

  ngOnInit() {
     this.recipeResult.hits = [];
  }

  ngOnChanges(){
    this.getRecipeInfo();
  }

  getRecipeInfo(){
     this.searchRecipeService.getRecipeInfo().
     subscribe(recipeResult => this.recipeResult = recipeResult);
  }

}

display-recipes.component.html

display-recipes works!

    {{recipe.label}}

RecipeGlobal.ts

export class RecipeGlobal{
    q: String;
    hits: Recipe[];
}

export class Recipe{
    image: String;
    calories: String;
    label: String
}

I am failing to understand how objects are initialized in typescript. If I declare a non primitive inside the object, do I have to initialize it?. If so, in this case how should I initialize the array?.

Body:
Your error is occuring because of this line of code

 ngOnInit() {
 this.recipeResult.hits = [];
  }

Since recipeResult variable is not defined yet.

The ngOnInit lifecycle hook would get called before the data is fetched from the api.

Now you'll have to define the recipeResult variable before hand, e.g. where it was declared, change that line to this

recipeResult: RecipeGlobal = new RecipeGlobal();

Thanks.


问:
Angular material not working in angular version 9
I'm updated the angular version 8 to angular 9 and also updated angular material to version 9 but it's not working and not showing any error. how to fix it.

here is code
material module

```<code>import { NgModule } from '@angular/core';
import {MatButtonModule} from '@angular/material/button';

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

app-component.html

```<code><h3>Stroked Buttons</h3>
 <div class="example-button-row">
  <button mat-stroked-button>Basic</button>
  <button mat-stroked-button color="primary">Primary</button>
  <button mat-stroked-button color="accent">Accent</button>
  <button mat-stroked-button color="warn">Warn</button>
  <button mat-stroked-button disabled>Disabled</button>
  <a mat-stroked-button routerLink=".">Link</a>
 </div>
</code>```

app.module

```<code> import { BrowserModule } from '@angular/platform-browser';
 import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
 import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform browser/animations';
 import { MaterialModule } from './angular-material/material/material.module';
  import { MatButtonModule } from '@angular/material/button';

@NgModule({
 declarations: [
  AppComponent
 ],
 imports: [
   BrowserModule,
   AppRoutingModule,
   BrowserAnimationsModule,
    MaterialModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
 })
 export class AppModule { }
</code>```

答:
You may need to also add any material modules to the exports like so:

```<code>import { NgModule } from '@angular/core';

import {MatButtonModule} from '@angular/material/button';

@NgModule({
   declarations: [],
   imports: [ MatButtonModule ],
   exports: [ MatButtonModule ]
})

export class MaterialModule { }
</code>```

This is an example from a material.module I am using in a project:

```<code>import { NgModule } from '@angular/core';

import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatToolbarModule } from '@angular/material/toolbar';

const mat = [
  MatButtonModule,
  MatIconModule,
  MatMenuModule,
  MatSidenavModule,
  MatSlideToggleModule,
  MatToolbarModule,
];

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

This way everything that is added to the array will be imported and exported to other modules.

Body:
I'm updated the angular version 8 to angular 9 and also updated angular material to version 9 but it's not working and not showing any error. how to fix it.

here is code
material module

import { NgModule } from '@angular/core';
import {MatButtonModule} from '@angular/material/button';

 @NgModule({
  declarations: [],
  imports: [
    MatButtonModule
  ]
})
export class MaterialModule { }

app-component.html

Stroked Buttons

  <button mat-stroked-button>Basic</button>
  <button mat-stroked-button color="primary">Primary</button>
  <button mat-stroked-button color="accent">Accent</button>
  <button mat-stroked-button color="warn">Warn</button>
  <button mat-stroked-button disabled>Disabled</button>
  Link

app.module

 import { BrowserModule } from '@angular/platform-browser';
 import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
 import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform browser/animations';
 import { MaterialModule } from './angular-material/material/material.module';
  import { MatButtonModule } from '@angular/material/button';

@NgModule({
 declarations: [
  AppComponent
 ],
 imports: [
   BrowserModule,
   AppRoutingModule,
   BrowserAnimationsModule,
    MaterialModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
 })
 export class AppModule { }

Body:
You may need to also add any material modules to the exports like so:

import { NgModule } from '@angular/core';

import {MatButtonModule} from '@angular/material/button';

@NgModule({
   declarations: [],
   imports: [ MatButtonModule ],
   exports: [ MatButtonModule ]
})

export class MaterialModule { }

This is an example from a material.module I am using in a project:

import { NgModule } from '@angular/core';

import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatToolbarModule } from '@angular/material/toolbar';

const mat = [
  MatButtonModule,
  MatIconModule,
  MatMenuModule,
  MatSidenavModule,
  MatSlideToggleModule,
  MatToolbarModule,
];

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

This way everything that is added to the array will be imported and exported to other modules.


问:
Override existing properties with Groovy DSL delegate getter
In the example below I want to override all properties with my own delegate's logic. But I can only do that for inexistent properties, the ones known at the compile time remains the same.

Is it possible to process them all?

```<code>def dsl(Closure action) {
    action.delegate = new Object() {
        Object getProperty(String name) {
            println "overriding property [$name] => Ross"
            return "Ross"
        }
    }
    action()
}

dsl {
    def existingSymbol = "Joe"
    println "existingSymbol: $existingSymbol"
    println "inexistentSymbol: $inexistentSymbol"
}
</code>```

Output:

```<code>existingSymbol: Joe     <--- expecting "Ross" here
overriding property [inexistentSymbol] => Ross
inexistentSymbol: Ross
</code>```

答:
the problem in def existingSymbol = "Joe"

by using def you are declaring a new local variable that has maximum priority.

check the following code:

```<code>def dsl(Closure action) {
    def delegate = new Object() {
        Object getProperty(String name) {
            return "Ross"
        }
    }
    action=action.rehydrate(delegate,delegate,delegate)
    action.call()
}

dsl {
    def existingSymbol = "Joe"
    println "1 existingSymbol: ${existingSymbol}"
    println "2 existingSymbol: ${this.existingSymbol}"
}
dsl {
    existingSymbol = "Joe"
    println "3 existingSymbol: ${existingSymbol}"
    println "4 existingSymbol: ${this.existingSymbol}"
}
</code>```

output:

```<code>1 existingSymbol: Joe
2 existingSymbol: Ross
3 existingSymbol: Ross
4 existingSymbol: Ross
</code>```

Body:
In the example below I want to override all properties with my own delegate's logic. But I can only do that for inexistent properties, the ones known at the compile time remains the same.

Is it possible to process them all?

def dsl(Closure action) {
    action.delegate = new Object() {
        Object getProperty(String name) {
            println "overriding property [$name] => Ross"
            return "Ross"
        }
    }
    action()
}

dsl {
    def existingSymbol = "Joe"
    println "existingSymbol: $existingSymbol"
    println "inexistentSymbol: $inexistentSymbol"
}

Output:

existingSymbol: Joe     <--- expecting "Ross" here
overriding property [inexistentSymbol] => Ross
inexistentSymbol: Ross

Body:
the problem in def existingSymbol = "Joe"

by using def you are declaring a new local variable that has maximum priority.

check the following code:

def dsl(Closure action) {
    def delegate = new Object() {
        Object getProperty(String name) {
            return "Ross"
        }
    }
    action=action.rehydrate(delegate,delegate,delegate)
    action.call()
}

dsl {
    def existingSymbol = "Joe"
    println "1 existingSymbol: ${existingSymbol}"
    println "2 existingSymbol: ${this.existingSymbol}"
}
dsl {
    existingSymbol = "Joe"
    println "3 existingSymbol: ${existingSymbol}"
    println "4 existingSymbol: ${this.existingSymbol}"
}

output:

1 existingSymbol: Joe
2 existingSymbol: Ross
3 existingSymbol: Ross
4 existingSymbol: Ross


问:
Code is working fine locally, but not execute after hosting
I am using dot net core 2.1.
when I execute local code Process.Start("C:/Windows/notepad.exe"); it is working fine.
But when I hosted my code on IIS it is not working.
I already give all the permission.

答:
If you want to open the client machine's notepad, it's impossible. The process start will just open the server's nodepad.

Since the client side browser will just get the server's reponse which is the html codes and show it. The process start is running on the server-side not client side.

The reason why you could open the nodepad is the client and server is the same machine.


问:
How do I delete an sql database in Azure?
I have used the following powershell script to delete a database:

```<code>Remove-AzureRmSqlDatabase -ServerName $server -ResourceGroupName $rgname -DatabaseName $dbname
</code>```

(first setting the variables)

and have tried using the Azure Portal

The port indicates a success in deletion, as does the activity logs, however

the resource is not being deleted?

Screenshot of activity log:

The deletes (on a number of occasions after the db comes back) show successful, however there is an audit policy that seems to be doing something.
There are no Locks on the resrouce group.

UPDATE:

I have deleted from SSMS, and is not showing there or in the portal anymore..
(will wait to see if it comes back, as it did when deleting via portal and powershell)

UPDATE 2:
Database is now back, so this is the database having been deleted 3 ways, portal, powershell and via SSMS.

答:
Do you happen to have a rogue policy somewhere? It seems something is running  a Policy Effect: deployIfNotExist on the resource. Without access to your environment, there's not much I could recommend.

Check the documentation here: https://learn.microsoft.com/en-us/azure/governance/policy/concepts/effects#audit

Body:
I have used the following powershell script to delete a database:

Remove-AzureRmSqlDatabase -ServerName $server -ResourceGroupName $rgname -DatabaseName $dbname

(first setting the variables)

and have tried using the Azure Portal

The port indicates a success in deletion, as does the activity logs, however

the resource is not being deleted?

Screenshot of activity log:

The deletes (on a number of occasions after the db comes back) show successful, however there is an audit policy that seems to be doing something.
There are no Locks on the resrouce group.

UPDATE:

I have deleted from SSMS, and is not showing there or in the portal anymore..
(will wait to see if it comes back, as it did when deleting via portal and powershell)

UPDATE 2:
Database is now back, so this is the database having been deleted 3 ways, portal, powershell and via SSMS.


问:
Is there a way get documents and the associated facets in one query with MongoDb?
I want to run some query, get first X documents and the facet data on the full data set.

Is it possible in one query or I must do two queries for that? (one for documents and one for facet data)

For example, unifying the following two, to one query:

```<code>db.mycollection.find({tenant:"tenant1", class: "myclass"}).limit(20)
db.mycollection.aggregate( [ {$match: {tenant:"tenant1", class: "myclass"}},
                             {$facet: { "typeFacet": [{$sortByCount: "$type"}]}])
</code>```

答:
The following aggregation will get the first 20 (as specified by the $limit) documents as the"xDocs" facet result, for the the documents that match filter in the $match stage. The "typeFacet" facet will apply the $sortByCount.

The $facet pipeline stage allows run multiple facet queries in parallel on the same set of documents (in this case all the documents in the collection).

```<code>db.collection.aggregate( [
{ $facet: {
       xDocs: [
           { $match: { tenant: "tenant1", class: "myclass" } },
           { $limit: 20 }
       ],
       typeFacet: [
           { $sortByCount: "$type" }
       ]
} }
] )
</code>```

Body:
I want to run some query, get first X documents and the facet data on the full data set.

Is it possible in one query or I must do two queries for that? (one for documents and one for facet data)

For example, unifying the following two, to one query:

db.mycollection.find({tenant:"tenant1", class: "myclass"}).limit(20)
db.mycollection.aggregate( [ {$match: {tenant:"tenant1", class: "myclass"}},
                             {$facet: { "typeFacet": [{$sortByCount: "$type"}]}])

Body:
The following aggregation will get the first 20 (as specified by the $limit) documents as the"xDocs" facet result, for the the documents that match filter in the $match stage. The "typeFacet" facet will apply the $sortByCount.

The $facet pipeline stage allows run multiple facet queries in parallel on the same set of documents (in this case all the documents in the collection).

db.collection.aggregate( [
{ $facet: {
       xDocs: [
           { $match: { tenant: "tenant1", class: "myclass" } },
           { $limit: 20 }
       ],
       typeFacet: [
           { $sortByCount: "$type" }
       ]
} }
] )


问:
Access EC2 instance from internet?
I have an EC2 instance running Apex Oracle.

On the virtual machine I can access Apex by typing : localhost:8080/apex

I'm trying to access the same URL but from internet.

I use : ec2-xx-xx-xx-xx.us-east-2.compute.amazonaws.com:8080/apex but it's not working.

In my security attributes I have the following inbound rule :

Customized TCP Rule

Protocol : TCP

Ports : 8080

Source : MyIP address

My virtual machine's firewall doesn't block any connexion on this port.

What am I doing wrong ?

Thanks.
Cheers,

答:
you should use elastic IP instead of EC2 public DNS.
Besides, you need check your VPC network, routing, NACLs. It's better if you can showing your logs error.</p>

Title: Access EC2 instance from internet?


问:
How can I draw a line in my form from another class?
I have 3 classes in my program:

Arrow (it contains the logic for drawing arrow, and all required information about it, like: starting point, ending point, etc.)

Form1 (that contains the drawing area(basically panel), where this arrow will be located in the future)

UserControl, is located in Form1 (I did Form1.Controls.Add(UserControl)). It has a Form1 as a parent. In this UserControl, I have a button, when I click it, an arrow should be drawn on the Form1's drawing area.

And I'm so confused with the logic that this program should have. I tried to create Arrow class object in the UserControl.Button_Click(), and call all the Arrow's methods from there, but I can't access to Form1's controls. I also thought maybe I can create object of Arrow in the Form1. So I tried to subscribe event UserControl.Button_Click() with some Form1's delegate, but I don't know how to do it. In this case, does delegate and the method that this delegate have as a reference should be Static?

So this is how my code looks like.
(I little bit simplified and shortened my classes)
Arrow:

```<code>public class Arrow
{
    public Point PointBeginning { get => pointBeginning; set => pointBeginning = value; }
    public Point PointEnding { get => pointEnding; set => pointEnding = value; }
    public int ArrowClickCounter { get => arrowClickCounter; set => arrowClickCounter = value; }

    public void Draw(object sender, MouseEventArgs e)
    {
        //code for drawing
    }
}
</code>```

Form1:

```<code>public class Form1
{
    public delegate void DrawArrowDelegate(object sender, MouseEventArgs e);
    DrawArrowDelegate drawArrowDelegate = DrawArrow;
    /* .. */

    private void DrawArrow(object sender, MouseEventArgs e)
    {
        Arrow arrow = new Arrow();
        arrow.PointBegining = //some point
        arrow.PointEnding = //some another point
        arrow.Draw(sender, e);
    }
}
</code>```

UserControl:

```<code>public class UserControl
{
    /*...*/

    private void button_MouseClick(object sender, MouseEventArgs e)
    {
        //And here i somehow want to call delegate. But don't know how :(
    }
}
</code>```

Sorry for such confused code :(

Can you please recommend me something?

答:
Arrow class:

```<code>    public class Arrow
    {
        public Point PointBeginning { get; set; }
        public Point PointEnding { get; set; }
        public int ArrowClickCounter { get; set; }

        public void Draw()
        {
            //code for drawing
        }
    }
</code>```

UserControl.cs:

```<code>    public delegate void CreateArrowEventArgs(Arrow arrow);
    public event CreateArrowEventArgs OnCreateArrow;
    private void button1_Click(object sender, EventArgs e)
    {
        if(this.OnCreateArrow!=null)
        {
            // Create Arrow object which you will have access to in your Form
            Arrow arrowToDraw = new Arrow();

            // Fire The Event
            this.OnCreateArrow.Invoke(arrowToDraw);
        }
    }
</code>```

Form codebehind :

```<code>    private void Form1_Load(object sender, EventArgs e)
    {
        // Create User Control
        var UserCtrl = new UserControl1();

        // Register Event
        UserCtrl.OnCreateArrow += UserCtrl_OnCreateArrow;

        //Add Control to Form
        this.Controls.Add(UserCtrl);
    }

    // You get the Arrow object for use here
    private void UserCtrl_OnCreateArrow(Arrow arrow)
    {
        arrow.Draw();
    }
</code>```

Body:
I have 3 classes in my program:

Arrow (it contains the logic for drawing arrow, and all required information about it, like: starting point, ending point, etc.)

Form1 (that contains the drawing area(basically panel), where this arrow will be located in the future)

UserControl, is located in Form1 (I did Form1.Controls.Add(UserControl)). It has a Form1 as a parent. In this UserControl, I have a button, when I click it, an arrow should be drawn on the Form1's drawing area.

And I'm so confused with the logic that this program should have. I tried to create Arrow class object in the UserControl.Button_Click(), and call all the Arrow's methods from there, but I can't access to Form1's controls. I also thought maybe I can create object of Arrow in the Form1. So I tried to subscribe event UserControl.Button_Click() with some Form1's delegate, but I don't know how to do it. In this case, does delegate and the method that this delegate have as a reference should be Static?

So this is how my code looks like.
(I little bit simplified and shortened my classes)
Arrow:

public class Arrow
{
    public Point PointBeginning { get => pointBeginning; set => pointBeginning = value; }
    public Point PointEnding { get => pointEnding; set => pointEnding = value; }
    public int ArrowClickCounter { get => arrowClickCounter; set => arrowClickCounter = value; }

    public void Draw(object sender, MouseEventArgs e)
    {
        //code for drawing
    }
}

Form1:

public class Form1
{
    public delegate void DrawArrowDelegate(object sender, MouseEventArgs e);
    DrawArrowDelegate drawArrowDelegate = DrawArrow;
    /* .. */

    private void DrawArrow(object sender, MouseEventArgs e)
    {
        Arrow arrow = new Arrow();
        arrow.PointBegining = //some point
        arrow.PointEnding = //some another point
        arrow.Draw(sender, e);
    }
}

UserControl:

public class UserControl
{
    /*...*/

    private void button_MouseClick(object sender, MouseEventArgs e)
    {
        //And here i somehow want to call delegate. But don't know how :(
    }
}

Sorry for such confused code :(

Can you please recommend me something?

Body:
Arrow class:

    public class Arrow
    {
        public Point PointBeginning { get; set; }
        public Point PointEnding { get; set; }
        public int ArrowClickCounter { get; set; }

        public void Draw()
        {
            //code for drawing
        }
    }

UserControl.cs:

    public delegate void CreateArrowEventArgs(Arrow arrow);
    public event CreateArrowEventArgs OnCreateArrow;
    private void button1_Click(object sender, EventArgs e)
    {
        if(this.OnCreateArrow!=null)
        {
            // Create Arrow object which you will have access to in your Form
            Arrow arrowToDraw = new Arrow();

            // Fire The Event
            this.OnCreateArrow.Invoke(arrowToDraw);
        }
    }

Form codebehind :

    private void Form1_Load(object sender, EventArgs e)
    {
        // Create User Control
        var UserCtrl = new UserControl1();

        // Register Event
        UserCtrl.OnCreateArrow += UserCtrl_OnCreateArrow;

        //Add Control to Form
        this.Controls.Add(UserCtrl);
    }

    // You get the Arrow object for use here
    private void UserCtrl_OnCreateArrow(Arrow arrow)
    {
        arrow.Draw();
    }


问:
How can I have a single goroutine function that waits for values from multiple others?
I've created a Go playground sample that illustrates what I'm talking about.

In the example, I create one goroutine, func2, which I would simply like to wait for inputs through its channel and print the value once it arrives.

```<code>func func2(ch chan int) {
    fmt.Println("func2")
    v:=<-ch
    fmt.Println(v)
}
</code>```

Then, in a loop, I create goroutines for another function, and these are part of a WaitGroup.

```<code>func func1(ch chan int, wg *sync.WaitGroup) {
    fmt.Println("func1")
    ch <- 11032
    wg.Done()
}
</code>```

And in main, I wait for the WaitGroup. I'm running into a deadlock and I'm not sure how to fix it. Just so it's clear what I'm trying to achieve, I want func2 to stay open as a thread once I call it, to process n values, where n is the number of goroutines I call for func1. I considered using a WaitGroup Wait inside of func2, but I don't want it blocking, as it needs to process new data from func1 as it's sent.

答:
I think you're getting a deadlock because your func2 is consuming only 1 value from ch and then finishing. Then the other func1 goroutines are stuck waiting for ch to be available to write into, which they cannot do because there is no other goroutine to read from ch on the other end.

Since you want func2 to continually consume values from ch until ch is closed, you need to create a loop in func2 like so:

```<code>func func2(ch chan int) {
    fmt.Println("func2")
    for v := range ch {
        fmt.Println(v)
    }
}
</code>```

This will keep func2 "alive" and reading from ch until you do close(ch) somewhere else. The appropriate place to close ch in your example would likely be in main after wg.Wait().

If you want to be sure to see the results from all Println statements before the program finishes, you should also use some synchronization mechanism to wait for func2 to finish. Otherwise main will end immediately after close(ch) which may or may not be before func2 has printed every value it received.

A common technique for this is a "done" channel. For example:

```<code>func func2(ch chan int, done chan bool) {
    fmt.Println("func2")
    for v := range ch {
        fmt.Println(v)
    }
    done <- true
}
</code>```

and in main:

```<code>done := make(chan bool)
go func2(ch, done)
...
wg.Wait()
close(ch)
<-done
</code>```

Using chan struct{} (empty struct) is also very common since empty struct requires no memory.

Body:
I've created a Go playground sample that illustrates what I'm talking about.

In the example, I create one goroutine, func2, which I would simply like to wait for inputs through its channel and print the value once it arrives.

func func2(ch chan int) {
    fmt.Println("func2")
    v:=<-ch
    fmt.Println(v)
}

Then, in a loop, I create goroutines for another function, and these are part of a WaitGroup.

func func1(ch chan int, wg *sync.WaitGroup) {
    fmt.Println("func1")
    ch <- 11032
    wg.Done()
}

And in main, I wait for the WaitGroup. I'm running into a deadlock and I'm not sure how to fix it. Just so it's clear what I'm trying to achieve, I want func2 to stay open as a thread once I call it, to process n values, where n is the number of goroutines I call for func1. I considered using a WaitGroup Wait inside of func2, but I don't want it blocking, as it needs to process new data from func1 as it's sent.

Body:
I think you're getting a deadlock because your func2 is consuming only 1 value from ch and then finishing. Then the other func1 goroutines are stuck waiting for ch to be available to write into, which they cannot do because there is no other goroutine to read from ch on the other end.

Since you want func2 to continually consume values from ch until ch is closed, you need to create a loop in func2 like so:

func func2(ch chan int) {
    fmt.Println("func2")
    for v := range ch {
        fmt.Println(v)
    }
}

This will keep func2 "alive" and reading from ch until you do close(ch) somewhere else. The appropriate place to close ch in your example would likely be in main after wg.Wait().

If you want to be sure to see the results from all Println statements before the program finishes, you should also use some synchronization mechanism to wait for func2 to finish. Otherwise main will end immediately after close(ch) which may or may not be before func2 has printed every value it received.

A common technique for this is a "done" channel. For example:

func func2(ch chan int, done chan bool) {
    fmt.Println("func2")
    for v := range ch {
        fmt.Println(v)
    }
    done <- true
}

and in main:

done := make(chan bool)
go func2(ch, done)
...
wg.Wait()
close(ch)
<-done

Using chan struct{} (empty struct) is also very common since empty struct requires no memory.


问:
Display different fab depending on active View of TabBarView
If PageA is selected, fabA should be displayed. If PageB is selected, fabB respectively.
Whats the best way to achieve this?

```<code>var fabA = FloatingActionButton();
var fabB = FloatingActionButton();
</code>```

...

```<code>Scaffold(
        body: TabBarView(children: [
          PageA(),
          PageB(),
        ]),
        floatingActionButton: fabA,
      )
</code>```

答:
You can copy paste run full code below

You can declare a List<FloatingActionButton> and return based on tabController.index

code snippet

```<code>_tabController = TabController(vsync: this, length: choices.length)
          ..addListener(() {
            if (_tabController.indexIsChanging) {
              print(
                  "tab is animating. from active (getting the index) to inactive(getting the index) ");
            } else {
              setState(() {});
...
floatingActionButton: floatButton[_tabController.index],
...
List<FloatingActionButton> floatButton = [
      FloatingActionButton(
        onPressed: () {
          // Add your onPressed code here!
        },
        child: Icon(Icons.navigation),
        backgroundColor: Colors.green,
      ),
      FloatingActionButton(
        onPressed: () {
          // Add your onPressed code here!
        },
        child: Icon(Icons.share),
        backgroundColor: Colors.green,
      ),
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';

class AppBarBottomSample extends StatefulWidget {
  @override
  _AppBarBottomSampleState createState() => _AppBarBottomSampleState();
}

class _AppBarBottomSampleState extends State<AppBarBottomSample>
    with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: choices.length)
      ..addListener(() {
        if (_tabController.indexIsChanging) {
          print(
              "tab is animating. from active (getting the index) to inactive(getting the index) ");
        } else {
          //tab is finished animating you get the current index
          //here you can get your index or run some method once.
          print(_tabController.index);
          setState(() {});
        }
      });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  void _nextPage(int delta) {
    final int newIndex = _tabController.index + delta;
    if (newIndex < 0 || newIndex >= _tabController.length) return;
    _tabController.animateTo(newIndex);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('AppBar Bottom Widget'),
          leading: IconButton(
            tooltip: 'Previous choice',
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              _nextPage(-1);
            },
          ),
          actions: <Widget>[
            IconButton(
              icon: const Icon(Icons.arrow_forward),
              tooltip: 'Next choice',
              onPressed: () {
                _nextPage(1);
              },
            ),
          ],
          bottom: PreferredSize(
            preferredSize: const Size.fromHeight(48.0),
            child: Theme(
              data: Theme.of(context).copyWith(accentColor: Colors.white),
              child: Container(
                height: 48.0,
                alignment: Alignment.center,
                child: TabPageSelector(controller: _tabController),
              ),
            ),
          ),
        ),
        body: TabBarView(
          controller: _tabController,
          children: choices.map((Choice choice) {
            return Padding(
              padding: const EdgeInsets.all(16.0),
              child: ChoiceCard(choice: choice),
            );
          }).toList(),
        ),
        floatingActionButton: floatButton[_tabController.index],
      ),
    );
  }
}

List<FloatingActionButton> floatButton = [
  FloatingActionButton(
    onPressed: () {
      // Add your onPressed code here!
    },
    child: Icon(Icons.navigation),
    backgroundColor: Colors.green,
  ),
  FloatingActionButton(
    onPressed: () {
      // Add your onPressed code here!
    },
    child: Icon(Icons.share),
    backgroundColor: Colors.green,
  ),
  FloatingActionButton(
    onPressed: () {
      // Add your onPressed code here!
    },
    child: Icon(Icons.create),
    backgroundColor: Colors.green,
  ),
  FloatingActionButton(
    onPressed: () {
      // Add your onPressed code here!
    },
    child: Icon(Icons.repeat),
    backgroundColor: Colors.green,
  ),
  FloatingActionButton(
    onPressed: () {
      // Add your onPressed code here!
    },
    child: Icon(Icons.forward),
    backgroundColor: Colors.green,
  ),
  FloatingActionButton(
    onPressed: () {
      // Add your onPressed code here!
    },
    child: Icon(Icons.link),
    backgroundColor: Colors.green,
  )
];

class Choice {
  const Choice({this.title, this.icon});

  final String title;
  final IconData icon;
}

const List<Choice> choices = const <Choice>[
  const Choice(title: 'CAR', icon: Icons.directions_car),
  const Choice(title: 'BICYCLE', icon: Icons.directions_bike),
  const Choice(title: 'BOAT', icon: Icons.directions_boat),
  const Choice(title: 'BUS', icon: Icons.directions_bus),
  const Choice(title: 'TRAIN', icon: Icons.directions_railway),
  const Choice(title: 'WALK', icon: Icons.directions_walk),
];

class ChoiceCard extends StatelessWidget {
  const ChoiceCard({Key key, this.choice}) : super(key: key);

  final Choice choice;

  @override
  Widget build(BuildContext context) {
    final TextStyle textStyle = Theme.of(context).textTheme.display1;
    return Card(
      color: Colors.white,
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Icon(choice.icon, size: 128.0, color: textStyle.color),
            Text(choice.title, style: textStyle),
          ],
        ),
      ),
    );
  }
}

void main() {
  runApp(AppBarBottomSample());
}
</code>```

Body:
If PageA is selected, fabA should be displayed. If PageB is selected, fabB respectively.
Whats the best way to achieve this?

var fabA = FloatingActionButton();
var fabB = FloatingActionButton();

...

Scaffold(
        body: TabBarView(children: [
          PageA(),
          PageB(),
        ]),
        floatingActionButton: fabA,
      )

Body:
You can copy paste run full code below

You can declare a List<FloatingActionButton> and return based on tabController.index

code snippet

_tabController = TabController(vsync: this, length: choices.length)
          ..addListener(() {
            if (_tabController.indexIsChanging) {
              print(
                  "tab is animating. from active (getting the index) to inactive(getting the index) ");
            } else {
              setState(() {});
...
floatingActionButton: floatButton[_tabController.index],
...
List<FloatingActionButton> floatButton = [
      FloatingActionButton(
        onPressed: () {
          // Add your onPressed code here!
        },
        child: Icon(Icons.navigation),
        backgroundColor: Colors.green,
      ),
      FloatingActionButton(
        onPressed: () {
          // Add your onPressed code here!
        },
        child: Icon(Icons.share),
        backgroundColor: Colors.green,
      ),

working demo

full code

import 'package:flutter/material.dart';

class AppBarBottomSample extends StatefulWidget {
  @override
  _AppBarBottomSampleState createState() => _AppBarBottomSampleState();
}

class _AppBarBottomSampleState extends State<AppBarBottomSample>
    with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: choices.length)
      ..addListener(() {
        if (_tabController.indexIsChanging) {
          print(
              "tab is animating. from active (getting the index) to inactive(getting the index) ");
        } else {
          //tab is finished animating you get the current index
          //here you can get your index or run some method once.
          print(_tabController.index);
          setState(() {});
        }
      });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  void _nextPage(int delta) {
    final int newIndex = _tabController.index + delta;
    if (newIndex < 0 || newIndex >= _tabController.length) return;
    _tabController.animateTo(newIndex);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('AppBar Bottom Widget'),
          leading: IconButton(
            tooltip: 'Previous choice',
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              _nextPage(-1);
            },
          ),
          actions: <Widget>[
            IconButton(
              icon: const Icon(Icons.arrow_forward),
              tooltip: 'Next choice',
              onPressed: () {
                _nextPage(1);
              },
            ),
          ],
          bottom: PreferredSize(
            preferredSize: const Size.fromHeight(48.0),
            child: Theme(
              data: Theme.of(context).copyWith(accentColor: Colors.white),
              child: Container(
                height: 48.0,
                alignment: Alignment.center,
                child: TabPageSelector(controller: _tabController),
              ),
            ),
          ),
        ),
        body: TabBarView(
          controller: _tabController,
          children: choices.map((Choice choice) {
            return Padding(
              padding: const EdgeInsets.all(16.0),
              child: ChoiceCard(choice: choice),
            );
          }).toList(),
        ),
        floatingActionButton: floatButton[_tabController.index],
      ),
    );
  }
}

List<FloatingActionButton> floatButton = [
  FloatingActionButton(
    onPressed: () {
      // Add your onPressed code here!
    },
    child: Icon(Icons.navigation),
    backgroundColor: Colors.green,
  ),
  FloatingActionButton(
    onPressed: () {
      // Add your onPressed code here!
    },
    child: Icon(Icons.share),
    backgroundColor: Colors.green,
  ),
  FloatingActionButton(
    onPressed: () {
      // Add your onPressed code here!
    },
    child: Icon(Icons.create),
    backgroundColor: Colors.green,
  ),
  FloatingActionButton(
    onPressed: () {
      // Add your onPressed code here!
    },
    child: Icon(Icons.repeat),
    backgroundColor: Colors.green,
  ),
  FloatingActionButton(
    onPressed: () {
      // Add your onPressed code here!
    },
    child: Icon(Icons.forward),
    backgroundColor: Colors.green,
  ),
  FloatingActionButton(
    onPressed: () {
      // Add your onPressed code here!
    },
    child: Icon(Icons.link),
    backgroundColor: Colors.green,
  )
];

class Choice {
  const Choice({this.title, this.icon});

  final String title;
  final IconData icon;
}

const List<Choice> choices = const <Choice>[
  const Choice(title: 'CAR', icon: Icons.directions_car),
  const Choice(title: 'BICYCLE', icon: Icons.directions_bike),
  const Choice(title: 'BOAT', icon: Icons.directions_boat),
  const Choice(title: 'BUS', icon: Icons.directions_bus),
  const Choice(title: 'TRAIN', icon: Icons.directions_railway),
  const Choice(title: 'WALK', icon: Icons.directions_walk),
];

class ChoiceCard extends StatelessWidget {
  const ChoiceCard({Key key, this.choice}) : super(key: key);

  final Choice choice;

  @override
  Widget build(BuildContext context) {
    final TextStyle textStyle = Theme.of(context).textTheme.display1;
    return Card(
      color: Colors.white,
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Icon(choice.icon, size: 128.0, color: textStyle.color),
            Text(choice.title, style: textStyle),
          ],
        ),
      ),
    );
  }
}

void main() {
  runApp(AppBarBottomSample());
}


问:
Is there a generic, recursive flask template?
As a way to rapidly prototype an html ui, I am looking for a generic jinja2 template, that will display an object's or dictionary name/value pairs recursively, including drilling into sub objects recursively.

So say I had this dictionary:

```<code>a_dict = {'name1': 'value1', 'name2': 'value2'}
a_dict['other'] = {'name3': 'value3', 'name4': 'value4'}
</code>```

It would display something like this:

```<code>name1: value1
name2: value2
other:
    name3: value3
    name4: value4
</code>```

答:
```<code>{% macro show_node(node) %}
   {% for key, value in node.__dict__.items() %}
        <span>{{key}}: </span>
        {% if value is mapping %} <-- not sure what to do here
            {{ show_node(value) }}

        {%else%}
            <span>Value: {{value}}</span>
        {% endif %}
   {% endfor %}
{% endmacro %}
</code>```

there you go

Body:
As a way to rapidly prototype an html ui, I am looking for a generic jinja2 template, that will display an object's or dictionary name/value pairs recursively, including drilling into sub objects recursively.

So say I had this dictionary:

a_dict = {'name1': 'value1', 'name2': 'value2'}
a_dict['other'] = {'name3': 'value3', 'name4': 'value4'}

It would display something like this:

name1: value1
name2: value2
other:
    name3: value3
    name4: value4

Body:
{% macro show_node(node) %}
   {% for key, value in node.__dict__.items() %}
        <span>{{key}}: </span>
        {% if value is mapping %} <-- not sure what to do here
            {{ show_node(value) }}

        {%else%}
            <span>Value: {{value}}</span>
        {% endif %}
   {% endfor %}
{% endmacro %}

there you go


问:
How can I find my site in the first 5 search results and follow the link
I tried the below code, but it's not correct exactly. How can I find my site in the first 5 search results and follow the link?</p>

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
# driver.maximize_window()

driver.get("http://google.com")
search = driver.find_element_by_name('q')
search.click()

search.send_keys('python')
search.send_keys(Keys.ENTER)

first_five = driver.find_elements_by_xpath(".//*[@id='rso']//div//h3/a")[:5]
link = first_five[:5].find_element_by_xpath('//*[@id="rso"]/div[4]/div/div[1]/div/div/div[1]/a/div/cite')
link.click()

#driver.quit()
</code>```

答:
This is a little confusing, but hopefully, I can help.

In your example, it looks like you are trying to:

open google and search

collect top 5 results and click on 1 of the links => I believe this is what you are trying to do by using this code:

```<code>first_five = driver.find_elements_by_xpath(".//*[@id='rso']//div//h3/a")[:5]
link = first_five[:5].find_element_by_xpath('//*[@id="rso"]/div[4]/div/div[1]/div/div/div[1]/a/div/cite')
link.click()
</code>```

So there are 2 issues I see here: first_five already collects all links and takes top five, because you have [:5] at the end of this like.
And then, when setting link, it looks like you are trying to take the top 5 elements again because you are doing link = first_five[:5] and using [:5] again.

Also, it is not clear to me why you use this:

```<code>.find_element_by_xpath('//*[@id="rso"]/div[4]/div/div[1]/div/div/div[1]/a/div/cite')
</code>```

You have already found all the elements of the list, why need to search again?

The solution I'd suggest is this:

```<code># Search
search.send_keys('habr.com python')
search.send_keys(Keys.ENTER)

# Store first 5 results
first_five = driver.find_elements_by_xpath("//div[@class='r']//a[.//h3]")[:5]

# Click the result you need by index: if your link in first, use [0]
link = first_five[0].click()
</code>```

Note, my locator in first_five is different from yours, bc I see a different google page when searching, you may want to use the one that works for you.

Hope this helped. Good luck.

Edited:

If you need to search for a link to a certain web site from top 5 links, use a for loop and simply search for your url in href attribute of the element, if the url matches - it'll click:

```<code>first_five = driver.find_elements_by_xpath("//div[@class='r']//a[.//h3]")[:5]

for link in first_five:
    if 'https://habr.com/ru/hub/python' in link.get_attribute('href'):
        link.click()
        break
</code>```

Body:
I tried the below code, but it's not correct exactly. How can I find my site in the first 5 search results and follow the link?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
# driver.maximize_window()

driver.get("http://google.com")
search = driver.find_element_by_name('q')
search.click()

search.send_keys('python')
search.send_keys(Keys.ENTER)

first_five = driver.find_elements_by_xpath(".//*[@id='rso']//div//h3/a")[:5]
link = first_five[:5].find_element_by_xpath('//*[@id="rso"]/div[4]/div/div[1]/div/div/div[1]/a/div/cite')
link.click()

#driver.quit()

Body:
This is a little confusing, but hopefully, I can help.

In your example, it looks like you are trying to:

open google and search

collect top 5 results and click on 1 of the links => I believe this is what you are trying to do by using this code:

first_five = driver.find_elements_by_xpath(".//*[@id='rso']//div//h3/a")[:5]
link = first_five[:5].find_element_by_xpath('//*[@id="rso"]/div[4]/div/div[1]/div/div/div[1]/a/div/cite')
link.click()

So there are 2 issues I see here: first_five already collects all links and takes top five, because you have [:5] at the end of this like.
And then, when setting link, it looks like you are trying to take the top 5 elements again because you are doing link = first_five[:5] and using [:5] again.

Also, it is not clear to me why you use this:

.find_element_by_xpath('//*[@id="rso"]/div[4]/div/div[1]/div/div/div[1]/a/div/cite')

You have already found all the elements of the list, why need to search again?

The solution I'd suggest is this:

# Search
search.send_keys('habr.com python')
search.send_keys(Keys.ENTER)

# Store first 5 results
first_five = driver.find_elements_by_xpath("//div[@class='r']//a[.//h3]")[:5]

# Click the result you need by index: if your link in first, use [0]
link = first_five[0].click()

Note, my locator in first_five is different from yours, bc I see a different google page when searching, you may want to use the one that works for you.

Hope this helped. Good luck.

Edited:

If you need to search for a link to a certain web site from top 5 links, use a for loop and simply search for your url in href attribute of the element, if the url matches - it'll click:

first_five = driver.find_elements_by_xpath("//div[@class='r']//a[.//h3]")[:5]

for link in first_five:
    if 'https://habr.com/ru/hub/python' in link.get_attribute('href'):
        link.click()
        break


问:
Phaxio API Create Fax and using the dreaded multipart/form-data encoding type
I'm slowing building out a Swift interface to the Phaxio set of API's.  I have figured out some of the basic GET functions but the hard one is the create fax function.  It's my first attempt at creating a multipart/form-data POST and uploading a binary file to the fax server.  I think I'm close.  I'm struggling with correctly passing my credentials, and fax number while also including the file in a multipart format.  Just now, I was able to work through the "bad Message" response I was getting back from the server for the file upload.  Now I'm stuck on the error below.  Any help would be appreciated.</p>

```<code>import Cocoa

// This program uses the phaxio API to send a fax (at least thats the intent). Shout out to Ignacio Nieto Carvajal's very helpful Networking in Swift: The Complete Guide on www.digialleaves.com to help me piece this together. //

// handy function to create unique identifier to define the multi-part boundaries
func generateBoundaryString() -> String {
   return "Boundary-\(UUID().uuidString)"
}

var body = Data()
var parameter = ""

// Open file, read contents into buffer - This works great, so easy in SWIFT!
let fileMgr = FileManager.default
var sourceFile = "/tmp/test.pdf"
let databuffer = fileMgr.contents(atPath: sourceFile)

// post the user, pass and faxnumber
let boundary = generateBoundaryString()

parameter.append("--\(boundary)\r\n")
parameter.append(contentsOf: "Content-Disposition: form-data; name=\"api_key\"; value=\"cn577fcvrcrjuj9v8\"\r\n")

parameter.append("--\(boundary)\r\n")
parameter.append(contentsOf: "Content-Disposition: form-data; name=\"api_secret\"; value=\"ciwx0sc7owqv4gzg\"\r\n")

parameter.append("--\(boundary)\r\n")
parameter.append(contentsOf: "Content-Disposition: form-data; name=\"to\"; value=\"5555555555\"\r\n")

parameter.append("--\(boundary)\r\n")
parameter.append(contentsOf: "Content-Disposition: form-data; name=\"file\"; filename=\"\(sourceFile)\"\r\n")
parameter.append(contentsOf: "Content-Type: application/PDF\r\n\r\n")

// Create boundary around file contents
body.append(contentsOf: parameter.utf8)

// Add binary contents of file
body.append((databuffer ?? nil)!)

body.append(contentsOf: "\r\n".utf8)
body.append(contentsOf: "--\(boundary)--\r\n".utf8)

// Initialize our URL & Request
let baseURL = "https://api.phaxio.com/v2/faxes"
let session = URLSession.shared
let url = URL(string: baseURL)!
var request = URLRequest(url: url)

//Define request method & set header values
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")

// Initialize HTTP Request Body
request.httpBody = body

URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let error = error {
        print("error took Place\(error)")
        return
    }

    if let data = data, let dataString = String(data: data, encoding: .utf8) {
        print("response data string: \(dataString)")

    }

}.resume()

This is the Response I'm getting from the Server:

{"success":false, "message": "You must provide API credentials for this operation (HTTP auth or api_key and api_secret)."}

</code>```

答: Solved! Believe it or not, by appending the credentials API_KEY, API_SECRET and the phone number to the URL string, Phaxio accepted the message and queued the fax for sending.</p>

Body:
I'm slowing building out a Swift interface to the Phaxio set of API's.  I have figured out some of the basic GET functions but the hard one is the create fax function.  It's my first attempt at creating a multipart/form-data POST and uploading a binary file to the fax server.  I think I'm close.  I'm struggling with correctly passing my credentials, and fax number while also including the file in a multipart format.  Just now, I was able to work through the "bad Message" response I was getting back from the server for the file upload.  Now I'm stuck on the error below.  Any help would be appreciated.

import Cocoa

// This program uses the phaxio API to send a fax (at least thats the intent). Shout out to Ignacio Nieto Carvajal's very helpful Networking in Swift: The Complete Guide on www.digialleaves.com to help me piece this together. //

// handy function to create unique identifier to define the multi-part boundaries
func generateBoundaryString() -> String {
   return "Boundary-\(UUID().uuidString)"
}

var body = Data()
var parameter = ""

// Open file, read contents into buffer - This works great, so easy in SWIFT!
let fileMgr = FileManager.default
var sourceFile = "/tmp/test.pdf"
let databuffer = fileMgr.contents(atPath: sourceFile)

// post the user, pass and faxnumber
let boundary = generateBoundaryString()

parameter.append("--\(boundary)\r\n")
parameter.append(contentsOf: "Content-Disposition: form-data; name=\"api_key\"; value=\"cn577fcvrcrjuj9v8\"\r\n")

parameter.append("--\(boundary)\r\n")
parameter.append(contentsOf: "Content-Disposition: form-data; name=\"api_secret\"; value=\"ciwx0sc7owqv4gzg\"\r\n")

parameter.append("--\(boundary)\r\n")
parameter.append(contentsOf: "Content-Disposition: form-data; name=\"to\"; value=\"5555555555\"\r\n")

parameter.append("--\(boundary)\r\n")
parameter.append(contentsOf: "Content-Disposition: form-data; name=\"file\"; filename=\"\(sourceFile)\"\r\n")
parameter.append(contentsOf: "Content-Type: application/PDF\r\n\r\n")

// Create boundary around file contents
body.append(contentsOf: parameter.utf8)

// Add binary contents of file
body.append((databuffer ?? nil)!)

body.append(contentsOf: "\r\n".utf8)
body.append(contentsOf: "--\(boundary)--\r\n".utf8)

// Initialize our URL & Request
let baseURL = "https://api.phaxio.com/v2/faxes"
let session = URLSession.shared
let url = URL(string: baseURL)!
var request = URLRequest(url: url)

//Define request method & set header values
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")

// Initialize HTTP Request Body
request.httpBody = body

URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let error = error {
        print("error took Place\(error)")
        return
    }

    if let data = data, let dataString = String(data: data, encoding: .utf8) {
        print("response data string: \(dataString)")

    }

}.resume()

This is the Response I'm getting from the Server:

{"success":false, "message": "You must provide API credentials for this operation (HTTP auth or api_key and api_secret)."}