问:
Angular 5 + Material - MatToolbar: Attempting to combine different toolbar modes
Upgraded my application from angular 4 to angular 5 and although i can run ng serve --watch with no errors. I get this error message when i try to load the page of my project.

MatToolbar: Attempting to combine different toolbar modes. Either
  specify multiple <mat-toolbar-row> elements explicitly or just place
  content inside of a <mat-toolbar> for a single row.

Its referring to the piece of code below, which i do quite frequently throughout my app on different page.

profile.component.html

```<code><div id="profile" class="body-1">

    <mat-toolbar color="primary">
        <span>Profile</span>
        <span class="example-spacer"></span>

        <div *ngIf="!isItMyProfile()">

            <button mat-icon-button (click)="message()" matTooltip="Message">
                <mat-icon>message</mat-icon>
        </button>
            <button mat-icon-button *ngIf="!isFollowing()" (click)="follow()" matTooltip="Follow">
                    <mat-icon>person_add</mat-icon>
            </button>
            <button mat-icon-button *ngIf="isFollowing()" (click)="unfollow()" matTooltip="Unfollow">
                    <mat-icon>remove</mat-icon>
            </button>
        </div>

        <button mat-icon-button matTooltip="Share" matTooltip="Share">
                <mat-icon>share</mat-icon>
        </button>
        <button mat-icon-button matTooltip="Search" matTooltip="Search">
                <mat-icon>search</mat-icon>
        </button>
        <button mat-icon-button matTooltip="Notifications">
                <mat-icon>notifications</mat-icon>
        </button>

        <button mat-icon-button [matMenuTriggerFor]="menu">
                <mat-icon>more_vert</mat-icon>
        </button>
        <mat-menu #menu="matMenu" yPosition="below" xPosition="after">
            <button mat-menu-item routerLink="edit">
                    <mat-icon>mode_edit</mat-icon>
                    <span>Edit Profile</span>
                </button>
        </mat-menu>
        <mat-toolbar-row class="profile-header" fxLayout="row" fxLayoutAlign="space-between center">

            <section fxLayout="row" fxLayoutAlign="space-between center" fxLayoutGap="20px">
                <div class="profile-picture">
                    <img src="http://via.placeholder.com/100x100" alt="" class="img-circle">
                </div>
                <div class="profile-user" fxLayout="column" fxLayoutAlign="center">
                    <span class="body-1">@{{user?.profile?.username}}</span>
                    <span class="body-1">{{user?.profile?.firstname}} {{ user?.profile?.lastname }}</span>
                </div>
            </section>

            <div class="profile-info" fxLayout="column" fxLayoutAlign="center start">

                <small class="profile-age">
                                <i class="fa fa-mars"></i>
                         [21]
                    </small>
                <small class="profile-location">
                        <mat-icon>location_on</mat-icon>
                        [Manchester, UK]
                    </small>

                <div fxLayout="row" fxLayoutAlign="center center">
                    <small *ngFor="let t of user?.profile?.languages.teach; let isLast=last">{{t.code}}{{isLast ? '' : ', '}} </small>
                    <mat-icon>keyboard_arrow_right</mat-icon>
                    <small *ngFor="let l of user?.profile?.languages.learn; let isLast=last">{{l.code}}{{isLast ? '' : ', '}} </small>
                </div>
            </div>

        </mat-toolbar-row>
        <mat-toolbar-row fxLayout="row" fxLayoutAlign="space-between end">

            <div class="profile-meta" fxLayout="row" fxFlex="25" fxLayoutAlign="center" fxLayoutGap="20px">

                <div fxLayout="column" fxFlex="33" fxLayoutGap="-10px">
                    <h4>0</h4>
                    <small>level</small>
                </div>
                <div fxLayout="column" fxFlex="33" fxLayoutGap="-10px">
                    <h4>{{user?.followers.length}}</h4>
                    <small (click)="openFollowers()">Followers</small>
                </div>
                <div fxLayout="column" fxFlex="33" fxLayoutGap="-10px">
                    <h4>{{user?.following.length}}</h4>
                    <small (click)="openFollowing()">Following</small>
                </div>
            </div>

            <nav mat-tab-nav-bar class="profile-navbar" backgroundColor="primary">
                <a mat-tab-link *ngFor="let link of navLinks" [routerLink]="link.path" routerLinkActive #rla="routerLinkActive" [active]="rla.isActive">
                    <mat-icon>{{link.icon}}</mat-icon>{{link.label}}
                </a>
            </nav>

        </mat-toolbar-row>
    </mat-toolbar>

    <div class="profile-content">
        <router-outlet></router-outlet>
    </div>

</div>
</code>```

I don't actually know what the problem is because i just extended the example that was given in the material documentation. https://material.angular.io/components/toolbar/examples

```<code>"@angular/material": "^5.0.0-rc0",
</code>```

答:
This was a breaking change in the latest update.

https://github.com/angular/material2/blob/master/CHANGELOG.md#breaking-changes

toolbar: in previous versions, any content of mat-toolbar not wrapped
  in a mat-toolbar-row would be rendered inside of an implicitly created
  mat-toolbar-row. As of rc0, this implicit row will no longer be
  created. This means that any custom application CSS that targeted this
  implicitly created mat-toolbar-row will no longer apply. Users can
  re-add the mat-toolbar-row in their own templates to match the
  original output structure. This resolves a longstanding issue where
  display: flex styles were difficult to use on mat-toolbar.

Basically any content within a mat-toolbar should be wrapped inside of a mat-toolbar-row

Body:
Upgraded my application from angular 4 to angular 5 and although i can run ng serve --watch with no errors. I get this error message when i try to load the page of my project.

MatToolbar: Attempting to combine different toolbar modes. Either
  specify multiple <mat-toolbar-row> elements explicitly or just place
  content inside of a <mat-toolbar> for a single row.

Its referring to the piece of code below, which i do quite frequently throughout my app on different page.

profile.component.html

    <mat-toolbar color="primary">
        Profile

            <button mat-icon-button (click)="message()" matTooltip="Message">
                <mat-icon>message</mat-icon>
        </button>
            <button mat-icon-button *ngIf="!isFollowing()" (click)="follow()" matTooltip="Follow">
                    <mat-icon>person_add</mat-icon>
            </button>
            <button mat-icon-button *ngIf="isFollowing()" (click)="unfollow()" matTooltip="Unfollow">
                    <mat-icon>remove</mat-icon>
            </button>

        <button mat-icon-button matTooltip="Share" matTooltip="Share">
                <mat-icon>share</mat-icon>
        </button>
        <button mat-icon-button matTooltip="Search" matTooltip="Search">
                <mat-icon>search</mat-icon>
        </button>
        <button mat-icon-button matTooltip="Notifications">
                <mat-icon>notifications</mat-icon>
        </button>

        <button mat-icon-button [matMenuTriggerFor]="menu">
                <mat-icon>more_vert</mat-icon>
        </button>
        <mat-menu #menu="matMenu" yPosition="below" xPosition="after">
            <button mat-menu-item routerLink="edit">
                    <mat-icon>mode_edit</mat-icon>
                    Edit Profile
                </button>
        </mat-menu>
        <mat-toolbar-row class="profile-header" fxLayout="row" fxLayoutAlign="space-between center">

                    @{{user?.profile?.username}}
                    {{user?.profile?.firstname}} {{ user?.profile?.lastname }}

                         [21]

                        <mat-icon>location_on</mat-icon>
                        [Manchester, UK]

                    {{t.code}}{{isLast ? '' : ', '}}
                    <mat-icon>keyboard_arrow_right</mat-icon>
                    {{l.code}}{{isLast ? '' : ', '}}

        </mat-toolbar-row>
        <mat-toolbar-row fxLayout="row" fxLayoutAlign="space-between end">

0

                    level

{{user?.followers.length}}

                    Followers

{{user?.following.length}}

                    Following

                    <mat-icon>{{link.icon}}</mat-icon>{{link.label}}

        </mat-toolbar-row>
    </mat-toolbar>

        <router-outlet></router-outlet>

I don't actually know what the problem is because i just extended the example that was given in the material documentation. https://material.angular.io/components/toolbar/examples

"@angular/material": "^5.0.0-rc0",


来源: stackexchange

问:
Posting Attachment Facebook Graph API
Right now I'm trying to figure out how to post an attachment using facebooks graph api.

Right now I'm using

```<code>            $attachment = array(
                'message' => $_POST['tt'],
                'text' => 'Download',
                'name' => 'name',
                'href' => 'http://www.url.com',
                'description' => '  description!',
                'media' => array(array(
                    'type' => 'mp3',
                    'src' => $url,
                    'href' => 'http://www.url.com/',
                    'title' => $title,
                    'artist'=> 'artist',
                    'album'=>  'the album')));

        $statusUpdate = $facebook->api('/me/feed', 'post', $attachment);
</code>```

Problem is it's only posting the message, nothing else, no attachment or anything.

Does anyone have any idea why?

Thanks

答:
You have to use the old php SDK until graph supports attachments... Graph only supports photoupload.
Im mixing Graph and old SDK without problems..</p>

ContentLicense: CC BY-SA 2.5

Title: Posting Attachment Facebook Graph API

Body:
Right now I'm trying to figure out how to post an attachment using facebooks graph api.

Right now I'm using

            $attachment = array(
                'message' => $_POST['tt'],
                'text' => 'Download',
                'name' => 'name',
                'href' => 'http://www.url.com',
                'description' => '  description!',
                'media' => array(array(
                    'type' => 'mp3',
                    'src' => $url,
                    'href' => 'http://www.url.com/',
                    'title' => $title,
                    'artist'=> 'artist',
                    'album'=>  'the album')));

        $statusUpdate = $facebook->api('/me/feed', 'post', $attachment);

Problem is it's only posting the message, nothing else, no attachment or anything.

Does anyone have any idea why?

Thanks


问:
Optimal approach for detecting leaf like shapes in opencv
I started to play around with OpenCV for a project I am working on.

For this project I am growing  plants in pots. Static pictures of different developmental stages are taken from above (see figure below).

The goal is to detect and ultimately measure (i.e. size) the leaves of the growing plants during different developmental stages.

I tried a naive approach of using Canny edge detecting, however it doesn't work that well (see figure below) because it also detects small edges in the soil (no matter what kind of threshold I used).

I think the better approach is to first segment the image by color and then use some edge detection algorithm to detect the leaves.

Is there a better way to do it?

The leaf structure is known beforehand. Could I use machine learning/classification algorithm to obtain even better results?

I also haven't thought about how to measure the size of the leaves? Are there any common patterns for measuring size and other descriptors? (maybe have a reference object with known size in the picture?).

Finally I also have to deal with occlusion to some extend. This is not visible in the pictures but in later development stages I might have to deal with overlapping leaves.
Are there any approaches to deal with that?

I can't bias the picture in my favor (i.e. blacking out the soil, etc) as there might be thousands of plants which have to be processed.

To summarize my questions:

What's the best approach to detect leafs in a soil (see figures) ?

Can Machine learning algorithm improve detection?

How can I measure the size of the leaves?

How to deal with occlusion/overlapping leaves?

I would be really thankful for some pointers or ideas.

Update (based on Jeff7 comments):

I first ran the mean shift color segmentation together with a floodfill algorithm and ended up with this picture:

When I now run the canny edge detection + findcontours on the that picture the results are much better:

答:
This is an active area of research.  I recommend the following papers:

Scharr et al. 2016: Leaf segmentation in plant phenotyping: a collation study (pdf)

Bell and Dee 2016: Watching plants grow–a position paper on computer vision and Arabidopsis thaliana. http://doi.org/10.1049/iet-cvi.2016.0127

PlantCV has some facilities for segmenting leaves with distance transforms and watersheds, and I would like to add more. See our preprint, a revised version of which will be published in PeerJ soon.

ContentLicense: CC BY-SA 3.0


问:
Chronicle Queue - Read from last read position and delete files if read by all consumers
I am using Chronicle 4.5.27 for writing and reading market data.
I have got a single writer but multiple readers. Development OS is Windows followed by Linux for Prod deployment.

How to implement following uses cases?

How to start reading queues form last read position ? e.g. if reader has read 15 records from a file which has 100 records and crashed/stopped how to start reading from 16th record from next restart? Is there an inbuilt durable support in CQ?

Delete files which are read by all consumers to save disk space.

For this I have implemented but seems the files are not deleted on windows due to some open issue. Is there any built support in CQ where files can be deleted only if proceeded by all interested consumers?

```<code>public static long readMarketData(String pathForMarketDataFile, long indexFrom) {
SingleChronicleQueue queue = SingleChronicleQueueBuilder.binary(pathForMarketDataFile).rollCycle(RollCycles.MINUTELY).storeFileListener(new StoreFileListener() {
    @Override
    public void onReleased(int i, File file) {
        System.out.println("File is not in use and is ready for deletion: " + file.getName());
        try {
            file.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ;
        System.out.println("File deleted:  " + file.getName() );
    }

    @Override
    public void onAcquired(int cycle, File file) {
        System.out.println("File is use for reading: " + file.getName());
    }
}).build();
</code>```

I have read few blogs and posts on this topic e.g.

https://vanilla-java.github.io/2016/03/29/Microservices-in-the-Chronicle-world-Part-4.html

https://groups.google.com/forum/#!topic/java-chronicle/0Nz5P-nvLgM

But still want to know if any one has implemented this use case.

答:
Tracking of the consumer high-water mark is performed using MessageHistory, however, this requires that your consumers are also writing output to a chronicle queue (essentially storing the consumer read-sequence in the output queue).

Alternatively, you would need to implement your own mechanism for recording the highest sequence (index) each consumer has seen.

In terms of deleting files, there may be other processes holding open file handles to the queue files. If reader-A is no longer using queue file 15.cq4, then your code will attempt to call file.delete(), but reader-B may still have a reference to that file, stopping it from being deleted.

A more robust policy would be to have some sort of event from each reader to another service/process that is responsible for deleting the files once all readers have finished processing them.

Body:
I am using Chronicle 4.5.27 for writing and reading market data.
I have got a single writer but multiple readers. Development OS is Windows followed by Linux for Prod deployment.

How to implement following uses cases?

How to start reading queues form last read position ? e.g. if reader has read 15 records from a file which has 100 records and crashed/stopped how to start reading from 16th record from next restart? Is there an inbuilt durable support in CQ?

Delete files which are read by all consumers to save disk space.

For this I have implemented but seems the files are not deleted on windows due to some open issue. Is there any built support in CQ where files can be deleted only if proceeded by all interested consumers?

public static long readMarketData(String pathForMarketDataFile, long indexFrom) {
SingleChronicleQueue queue = SingleChronicleQueueBuilder.binary(pathForMarketDataFile).rollCycle(RollCycles.MINUTELY).storeFileListener(new StoreFileListener() {
    @Override
    public void onReleased(int i, File file) {
        System.out.println("File is not in use and is ready for deletion: " + file.getName());
        try {
            file.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ;
        System.out.println("File deleted:  " + file.getName() );
    }

    @Override
    public void onAcquired(int cycle, File file) {
        System.out.println("File is use for reading: " + file.getName());
    }
}).build();

I have read few blogs and posts on this topic e.g.

https://vanilla-java.github.io/2016/03/29/Microservices-in-the-Chronicle-world-Part-4.html

https://groups.google.com/forum/#!topic/java-chronicle/0Nz5P-nvLgM

But still want to know if any one has implemented this use case.


问:
What is the state of the art approach for creating own rules for Google's Prettify?
What is the state of the art approach for creating own rules for Google's Prettify?

I am not talking about changing the colors of existing rules, furthermore, I want to create new rules:

e.g for shell/bash

maybe in an extrem case for a poem, in which I want show all appearances of the word "love" bold

Or I want to show a tree and mark all spec.ts files bold, like:

```
    ├── src
    │   ├── app
    │   │   ├── app-routing.module.ts
    │   │   ├── app.component.css
    │   │   ├── app.component.css.map
    │   │   ├── app.component.html
    │   │   ├── app.component.scss
    │   │   ├── <b>app.component.spec.ts</b>
    │   │   ├── app.component.ts
    │   │   ├── app.module.ts
    │   │   └── lesson
    │   │       ├── lesson.component.css
    │   │       ├── lesson.component.css.map
    │   │       ├── lesson.component.html
    │   │       ├── lesson.component.scss
    │   │       ├── <b>lesson.component.spec.ts</b>
    │   │       └── lesson.component.ts
```

答:
The easiest way is to work from an existing example.

If you look at that file, you can see that it has some boilerplate that surrounds two lists of tuples:

```<code>PR['registerLangHandler'](
    PR['createSimpleLexer'](
        [
          // Some tuples
        ],
        [
          // Some more tuples
        ],
        [/* Some file extensions without dot */]));
</code>```

If the file extension list contains "ext" and prettify is asked to prettify a code block with class="lang-ext ..." then this handler will be used.

The two sets of tuples have similar structure.
Here's some from the first set

```<code>['opn',             /^\(+/, null, '('],
['clo',             /^\)+/, null, ')'],
</code>```

and here's one from the second set.

```<code>[PR['PR_KEYWORD'],     /^(?:block|c[ad]+r|catch|con[ds]|def(?:ine|un)|do|eq|eql|...)\b/, null],
</code>```

The PR['PR_KEYWORD'] is a predefined token type and matches up with styles in the predefined stylesheet:

```<code>.kwd { color: #008 }  /* a keyword */
</code>```

What

```<code>['opn',             /^\(+/, null, '('],
</code>```

is saying is that when prettifying, if the beginning of the code starts with /^\(+/, then the input gets wrapped in ....  opn (LISP open parenthesis) is a string literal since there is no predefined constant for it.  If you define your own token type classes, you will probably have to define style rules for them in whatever page loads prettify.

The string at the right, '(', is treated as a list of characters such that this rule is the only one that applies when the input text starts with one of those characters.  This was an important optimization for IE 6 in years past.

The only difference between the two groups of tuples is that the ones in the first list have this extra exclusive character element.

IIRC, the null supported a feature that was found to be rarely if ever necessary and is no longer supported.  Any value you put in that position will be ignored.

The CSS handler has some documentation on all this, and demonstrates one other feature.

```<code>['lang-css-kw', /^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],
</code>```

If the token type starts with lang-, instead of generating a ..., prettify will look for a language handler for the file extension css-kw and apply that recursively to the content in group 1.  This feature is probably overkill here since modern JS engines consistently support lookahead, but it is necessary so that the HTML mode can recursively apply JS and CSS mode to the content of

Body:
What is the state of the art approach for creating own rules for Google's Prettify?

I am not talking about changing the colors of existing rules, furthermore, I want to create new rules:

e.g for shell/bash

maybe in an extrem case for a poem, in which I want show all appearances of the word "love" bold

Or I want to show a tree and mark all spec.ts files bold, like:

    ├── src
    │   ├── app
    │   │   ├── app-routing.module.ts
    │   │   ├── app.component.css
    │   │   ├── app.component.css.map
    │   │   ├── app.component.html
    │   │   ├── app.component.scss
    │   │   ├── app.component.spec.ts
    │   │   ├── app.component.ts
    │   │   ├── app.module.ts
    │   │   └── lesson
    │   │       ├── lesson.component.css
    │   │       ├── lesson.component.css.map
    │   │       ├── lesson.component.html
    │   │       ├── lesson.component.scss
    │   │       ├── lesson.component.spec.ts
    │   │       └── lesson.component.ts

Body:
The easiest way is to work from an existing example.

If you look at that file, you can see that it has some boilerplate that surrounds two lists of tuples:

PR['registerLangHandler'](
    PR['createSimpleLexer'](
        [
          // Some tuples
        ],
        [
          // Some more tuples
        ],
        [/* Some file extensions without dot */]));

If the file extension list contains "ext" and prettify is asked to prettify a code block with class="lang-ext ..." then this handler will be used.

The two sets of tuples have similar structure.
Here's some from the first set

['opn',             /^\(+/, null, '('],
['clo',             /^\)+/, null, ')'],

and here's one from the second set.

[PR['PR_KEYWORD'],     /^(?:block|c[ad]+r|catch|con[ds]|def(?:ine|un)|do|eq|eql|...)\b/, null],

The PR['PR_KEYWORD'] is a predefined token type and matches up with styles in the predefined stylesheet:

.kwd { color: #008 }  /* a keyword */

What

['opn',             /^\(+/, null, '('],

is saying is that when prettifying, if the beginning of the code starts with /^\(+/, then the input gets wrapped in <span class="opn">...</span>.  opn (LISP open parenthesis) is a string literal since there is no predefined constant for it.  If you define your own token type classes, you will probably have to define style rules for them in whatever page loads prettify.

The string at the right, '(', is treated as a list of characters such that this rule is the only one that applies when the input text starts with one of those characters.  This was an important optimization for IE 6 in years past.

The only difference between the two groups of tuples is that the ones in the first list have this extra exclusive character element.

IIRC, the null supported a feature that was found to be rarely if ever necessary and is no longer supported.  Any value you put in that position will be ignored.

The CSS handler has some documentation on all this, and demonstrates one other feature.

['lang-css-kw', /^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],

If the token type starts with lang-, instead of generating a <span class="lang-css-kw">...</span>, prettify will look for a language handler for the file extension css-kw and apply that recursively to the content in group 1.  This feature is probably overkill here since modern JS engines consistently support lookahead, but it is necessary so that the HTML mode can recursively apply JS and CSS mode to the content of <script> and <style> blocks.

Prettify can handle any transformation that relies only on a left to right pass over tokens.  It doesn't have a way to collect symbols in side-tables for disambiguation, so there's no way to distinguish these two C snippets:

typedef int t  // t is declared as a type
t* x;   // declare x as a pointer to a t. "t" should have class="typ"

from

int t = 1;  // t is declared as a variable, not a type
t* x;   // multiplication.  "t" should not have class="typ"

This limited approach seems more robust in the face of small fragments of code and malformed code that you see often on sites like stackoverflow.

It's reasonable to encode common language conventions like

type names start with capitals

identifiers that end in _t are types

in your rules.


问:
Firebase data persistence, updating troubles - Swift
In my firebase database I use persistence to cache the data, but this give me a problem, because some of my data needs to be loaded from the database when the app loads and not from tha cached data. I have a tableview where the data from the database is shown, it needs to update with the database and not look for the saved data in the tableview. Right now I am using

```<code> self.ref?.child(u.uid).observe(.value, with: { (snapshot) in
   print(offersnapshot)
})
</code>```

to get the data from the data from the server. But right now the app needs to restart, before the data are updated.

答:
From the info you provided i think the problem is you did not enable the syncing of firebase cache data with the firebse server database.
try this:</p>

```<code>let scoresRef = Database.database().reference(withPath: "rootNode")
scoresRef.keepSynced(true)
</code>```

Body:
In my firebase database I use persistence to cache the data, but this give me a problem, because some of my data needs to be loaded from the database when the app loads and not from tha cached data. I have a tableview where the data from the database is shown, it needs to update with the database and not look for the saved data in the tableview. Right now I am using

 self.ref?.child(u.uid).observe(.value, with: { (snapshot) in
   print(offersnapshot)
})

to get the data from the data from the server. But right now the app needs to restart, before the data are updated.

Body:
From the info you provided i think the problem is you did not enable the syncing of firebase cache data with the firebse server database.
try this:

let scoresRef = Database.database().reference(withPath: "rootNode")
scoresRef.keepSynced(true)


问:
Chrome Extension: Refused to load the script because it violates the following Content Security Policy directive: "script-src 'self'
I'm building a Chrome extension and using $.ajax (jsonp) to pull article titles and urls from a json array on a wordpress site.

If I GET from a https site, it works fine, however if I GET from a http site I get the following error.

```<code>Refused to load the script because it violates the following Content Security Policy directive: "script-src 'self'
</code>```

Unfortunately it's not possible in this instance to use HTTPS on this particular site, so how do I allow  a none http site in my Content Security Policy in my manifest.json or is it strictly https only?

答:
According to developer.chrome.com/extensions/contentSecurityPolicy, only HTTPS sites can be added to the CSP, not HTTP.

But you should not be doing JSONP from a Chrome extension, period. Can't do HTTP Request with my Chrome Extension

Body:
I'm building a Chrome extension and using $.ajax (jsonp) to pull article titles and urls from a json array on a wordpress site.

If I GET from a https site, it works fine, however if I GET from a http site I get the following error.

Refused to load the script because it violates the following Content Security Policy directive: "script-src 'self'

Unfortunately it's not possible in this instance to use HTTPS on this particular site, so how do I allow  a none http site in my Content Security Policy in my manifest.json or is it strictly https only?


问:
How to define the name for a nested stack in CloudFormation template?
When the nested stack is created within another stack, it obtains the name like:

```<code><name-of-the-parent-stack>-<resource-name>-<UUID>
</code>```

what doesn't look nice. Meantime I can not find any property of the "AWS::CloudFormation::Stack" type where I could specify the desired name. Is it possible to define its name or not?

答: Unfortunately, there isn't an alternative. </p>

Body:
When the nested stack is created within another stack, it obtains the name like:

<name-of-the-parent-stack>-<resource-name>-<UUID>

what doesn't look nice. Meantime I can not find any property of the "AWS::CloudFormation::Stack" type where I could specify the desired name. Is it possible to define its name or not?


问:
Unable to resolve dependancy
I am new to Android Studio, and I've installed Android Studio 3 (no previous installations), and have attempted to create a new project.

However, I am getting multiple 'unable to resolve dependency' errors being displayed

I've not sure what I need to do to resolve these issues, as I've tried invalidating the cache, but this makes no difference.

答:
add Google's Maven repository (i.e in app build.gradle)

```<code>repositories {
    google()

    // If you're using a version of Gradle lower than 4.1, you must instead use:
    // maven {
    //     url 'https://maven.google.com'
    // }
    // An alternative URL is 'https://dl.google.com/dl/android/maven2/'
}
</code>```

More info https://developer.android.com/studio/build/dependencies.html#google-maven

Title: Unable to resolve dependancy

Body:
add Google's Maven repository (i.e in app build.gradle)

repositories {
    google()

    // If you're using a version of Gradle lower than 4.1, you must instead use:
    // maven {
    //     url 'https://maven.google.com'
    // }
    // An alternative URL is 'https://dl.google.com/dl/android/maven2/'
}

More info https://developer.android.com/studio/build/dependencies.html#google-maven


问:
How do you compare user input to values inside an array?
I am wanting to create a very simple script that checks user's input to a pre-existing array. However, it doesn't seem to work and I'm not sure why. Please, keep in mind I'm new to this and trying to learn.</p>

```<code><script>
    var usernumber = prompt('What is your number?');
    var numbers = ['1', '2', '3'];
    if (usernumber == 'numbers') //If the user number matches one of preset numbers
    {
        alert('Match');
    } else {
        alert('No match found.');
    }
</script>
</code>```

答:
this will work fine for you</p>

```<code><script>
    var usernumber = prompt('What is your number?');
    var numbers = ['1', '2', '3'];
    for(i=0;i<=numbers.length;i++)
     {if (usernumber == numbers[i])

    {
        alert('Match');
         break;
    } }
     if(i==numbers.length) {
        alert('No match found.');
    }
</script>
</code>```

Body:
this will work fine for you

<script>
    var usernumber = prompt('What is your number?');
    var numbers = ['1', '2', '3'];
    for(i=0;i<=numbers.length;i++)
     {if (usernumber == numbers[i])

    {
        alert('Match');
         break;
    } }
     if(i==numbers.length) {
        alert('No match found.');
    }
</script>


问:
Detect if user stop typing Angular 2
I'm trying to create something like isTyping or not, so I have to detect when user stop type more or less 3 seconds, so I can do my stuff, I allready detected when he's typing using this :

```<code>     ngOnChanges(searchValue: string) {
    if (!this.searchChangeObserver) {
      Observable.create(observer => {
        this.searchChangeObserver = observer;
      }).debounceTime(3000)
        .subscribe((data) => {
          if (data) {
            typingStuff();
          }
          else {
            notTypingStuff();
          }
        });
      this.searchChangeObserver.next(searchValue);
    }
  }
}
</code>```

So now I have to detect when user stops typing to do the notTypingStuff();

Is there a simple way to do it?

EDIT

I'm also using this :

```<code>constructor(){
    this.modelChanged
      .debounceTime(300)
      .subscribe((data) => {
        if (data) {
          typingStuff();
        }
        else {
          notTypingStuff();
        }
      });
}
</code>```

But should know when user stops to type in 3 seconds to do the notTypingStuff() as well..

答:
For the not typing stuff you could create an observable from the input event and set the debaunce time:

HTML:

```<code><input #yourElement [(ngModel)]="yourVar"/>
</code>```

Component:

```<code>@ViewChild('yourElement') yourElement: ElementRef;

ngAfterViewInit() {
    Observable.fromEvent(this.yourElement.nativeElement, 'input')
        .map((event: Event) => (<HTMLInputElement>event.target).value)
        .debounceTime(3000)
        .distinctUntilChanged()
        .subscribe(data => notTypingStuff());
}
</code>```

This way your method will only be executed 3000 after the input is modified, or in other words after the user stops typing.

EDIT: Angular 9 w/ RxJS 6.5.4

```<code>ngAfterViewInit(): void {
    fromEvent(this.yourElement.nativeElement, 'input')
      .pipe(map((event: Event) => (event.target as HTMLInputElement).value))
      .pipe(debounceTime(3000))
      .pipe(distinctUntilChanged())
      .subscribe(data => notTypingStuff());
  }
</code>```

Title: Detect if user stop typing Angular 2

Body:
I'm trying to create something like isTyping or not, so I have to detect when user stop type more or less 3 seconds, so I can do my stuff, I allready detected when he's typing using this :

     ngOnChanges(searchValue: string) {
    if (!this.searchChangeObserver) {
      Observable.create(observer => {
        this.searchChangeObserver = observer;
      }).debounceTime(3000)
        .subscribe((data) => {
          if (data) {
            typingStuff();
          }
          else {
            notTypingStuff();
          }
        });
      this.searchChangeObserver.next(searchValue);
    }
  }
}

So now I have to detect when user stops typing to do the notTypingStuff();

Is there a simple way to do it?

EDIT

I'm also using this :

constructor(){
    this.modelChanged
      .debounceTime(300)
      .subscribe((data) => {
        if (data) {
          typingStuff();
        }
        else {
          notTypingStuff();
        }
      });
}

But should know when user stops to type in 3 seconds to do the notTypingStuff() as well..

Body:
For the not typing stuff you could create an observable from the input event and set the debaunce time:

HTML:

<input #yourElement [(ngModel)]="yourVar"/>

Component:

@ViewChild('yourElement') yourElement: ElementRef;

ngAfterViewInit() {
    Observable.fromEvent(this.yourElement.nativeElement, 'input')
        .map((event: Event) => (<HTMLInputElement>event.target).value)
        .debounceTime(3000)
        .distinctUntilChanged()
        .subscribe(data => notTypingStuff());
}

This way your method will only be executed 3000 after the input is modified, or in other words after the user stops typing.

EDIT: Angular 9 w/ RxJS 6.5.4

ngAfterViewInit(): void {
    fromEvent(this.yourElement.nativeElement, 'input')
      .pipe(map((event: Event) => (event.target as HTMLInputElement).value))
      .pipe(debounceTime(3000))
      .pipe(distinctUntilChanged())
      .subscribe(data => notTypingStuff());
  }

ContentLicense: CC BY-SA 4.0


问:
Raw literal strings in Julia
In Python one can write r"a\nb" in order to prevent the \n from being interpreted as an escape sequence for newline.

Is there something similar in Julia? And what about string interpolation like "$variable", is there a way to prevent it?

I know one can simply write "a\\nb" and "\$variable" in Julia, but I would like to write a lot of LaTeX strings without having to care to proper escape every backslash \ and dollar $ characters...

(In Julia, r"..." creates a regular expression.)

答: From Julia 0.6 we have raw"\a$variable"

Title: Raw literal strings in Julia

Body: From Julia 0.6 we have raw"\a$variable"


问:
Loading XML into a browser with jQuery
Does anyone know why the following code does not work in FireFox but does in IE (on the server) and the other way around locally?</p>

```<code>function load_xml(msg) {   //this function will load xml even used in IE or any other browser
            if ( typeof msg == 'string') {
                data = new ActiveXObject( 'Microsoft.XMLDOM');
                data.async = false;
                data.loadXML( msg);
                } else {
                    data = msg;
                }
                return data;
        }

        function getTitle(letter) {
            $('#wordle').html('');
    jQuery.ajax({
        type: "POST",
        url: "wordle-list.dat",
        dataType: ($.browser.msie) ? "text/xml" : "xml",
        success: function(xml) {
                    var xml2 = load_xml(xml);
            var i=0;
            $(xml2).find('wordle').each(function(){
                        $(xml2).find('w').each(function(){ //can change to w:lt(50)
                            var tmpHold = $(this).text();
                            if (tmpHold.substring(0, 1) == letter) {
                                $('#wordle').append('<li class="w">'+$(this).text()+'</li>');
                            }
                        });
                    });
        }
    });
}
</code>```

答:
Try this:</p>

```<code> function load_xml(msg) {
         if ( typeof msg == 'string') {
            if (window.DOMParser)//Firefox
              {
                parser=new DOMParser();
                data=parser.parseFromString(msg,"text/xml");
            }else{ // Internet Explorer
               data=new ActiveXObject("Microsoft.XMLDOM");
               data.async="false";
               data.loadXML(msg);
           }
         } else {
            data = msg;
         }
            return data;
    }
</code>```

Title: Loading XML into a browser with jQuery

Body:
Does anyone know why the following code does not work in FireFox but does in IE (on the server) and the other way around locally?

function load_xml(msg) {   //this function will load xml even used in IE or any other browser
            if ( typeof msg == 'string') {
                data = new ActiveXObject( 'Microsoft.XMLDOM');
                data.async = false;
                data.loadXML( msg);
                } else {
                    data = msg;
                }
                return data;
        }

        function getTitle(letter) {
            $('#wordle').html('');
    jQuery.ajax({
        type: "POST",
        url: "wordle-list.dat",
        dataType: ($.browser.msie) ? "text/xml" : "xml",
        success: function(xml) {
                    var xml2 = load_xml(xml);
            var i=0;
            $(xml2).find('wordle').each(function(){
                        $(xml2).find('w').each(function(){ //can change to w:lt(50)
                            var tmpHold = $(this).text();
                            if (tmpHold.substring(0, 1) == letter) {
                                $('#wordle').append('
'+$(this).text()+'
');
                            }
                        });
                    });
        }
    });
}

Body:
Try this:

 function load_xml(msg) {
         if ( typeof msg == 'string') {
            if (window.DOMParser)//Firefox
              {
                parser=new DOMParser();
                data=parser.parseFromString(msg,"text/xml");
            }else{ // Internet Explorer
               data=new ActiveXObject("Microsoft.XMLDOM");
               data.async="false";
               data.loadXML(msg);
           }
         } else {
            data = msg;
         }
            return data;
    }


问:
save image in xampp and show it in web php
The HTML upload form:

```<code><form action="InformationData.php" method="post" enctype="multipart/form-data">
    <label >Barangay Certification</label>
    <input name="BarangayCertification" type="file" id="exampleInputFile1">
    <button type="Submit" name="Submit" value="Upload">Submit</button>
</form>
</code>```

The InformationData.php:

```<code><?php
$conn = mysqli_connect("localhost", "root", "", "registration");

if($_POST['BarangayCertification']){
    $BarangayCertification =   $_POST['BarangayCertification'];
} else {
    $BarangayCertification =  "";
}

$sql = "INSERT INTO stakeholdersform (BarangayCertification) VALUES ($BarangayCertification);
?>
</code>```

Code to show the image:

```<code><?php
$conn = mysqli_connect("localhost", "root", "", "registration");
$informations = "SELECT * FROM stakeholderinformations";
$result = $conn->query($informations);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $BarangayCertification = $row['BarangayCertification'];
        echo $BarangayCertification;
    }
}
?>
</code>```

I tried to echo it but nothing happens, but I can see the image in the database.

答:
From PHP documentation

echo — Output one or more strings

So, no, you can not echo image.
What you could do is

echo ''

Although there's an upper limit about the size of $BarangayCertification and I do not recommend storing image in your database.

Body:
The HTML upload form:

<form action="InformationData.php" method="post" enctype="multipart/form-data">
    Barangay Certification
    <input name="BarangayCertification" type="file" id="exampleInputFile1">
    <button type="Submit" name="Submit" value="Upload">Submit</button>
</form>

The InformationData.php:

<?php
$conn = mysqli_connect("localhost", "root", "", "registration");

if($_POST['BarangayCertification']){
    $BarangayCertification =   $_POST['BarangayCertification'];
} else {
    $BarangayCertification =  "";
}

$sql = "INSERT INTO stakeholdersform (BarangayCertification) VALUES ($BarangayCertification);
?>

Code to show the image:

<?php
$conn = mysqli_connect("localhost", "root", "", "registration");
$informations = "SELECT * FROM stakeholderinformations";
$result = $conn->query($informations);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $BarangayCertification = $row['BarangayCertification'];
        echo $BarangayCertification;
    }
}
?>

I tried to echo it but nothing happens, but I can see the image in the database.

Body:
From PHP documentation

echo — Output one or more strings

So, no, you can not echo image.
What you could do is

echo '<img src="data:image/jpeg;base64,' . $BarangayCertification . '">'

Although there's an upper limit about the size of $BarangayCertification and I do not recommend storing image in your database.


问:
How can I associate a specific calendar to an EKEventEditViewController instance
I'm trying to use the generic EKEventEditViewController instead of rolling my own. But I'm running into a problem with the calendar selection. In the controller instance, I see a choice of calendars, and I'd prefer not to see that choice -- I want all events to link to an app-specific calendar.

Is there a way to do this?

Right now, I'm calling EKEventEditViewController as follows:

```<code>@IBAction func addEventTapped(_ sender: UIButton) {

    // create an instance of EKEventEditViewController()
    let eventViewController: EKEventEditViewController = EKEventEditViewController()

    let calendars = eventStore.calendars(for: EKEntityType.event)

    for calendar in calendars {
        if calendar.title == "MyAppCalendar" {

            print("calendar is identified")
            eventViewController.eventStore = self.eventStore
            eventViewController.eventStore.calendar(withIdentifier: calendar.title)
        }
    }

    eventViewController.editViewDelegate = self
    self.present(eventViewController, animated: false, completion: nil)

}
</code>```

Thanks!

答:
I solved this by subclassing EKEventEditViewController

The code was lifted from Andrew Bancroft and from SpaceOTechnologies

I created an AddEventController and the code is:

```<code>import UIKit
import EventKit
import EventKitUI

class AddEventViewController: UIViewController, UITextFieldDelegate{

    var calendar: EKCalendar!

    @IBOutlet weak var eventNameTextField: UITextField!
    @IBOutlet weak var eventStartDatePicker: UIDatePicker!
    @IBOutlet weak var eventEndDatePicker: UIDatePicker!

    var delegate: EventAddedDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.eventStartDatePicker.setDate(initialDatePickerValue(), animated: false)
        self.eventEndDatePicker.setDate(initialDatePickerValue(), animated: false)

    }

    func initialDatePickerValue() -> Date {

        eventNameTextField.resignFirstResponder()

        let calendarUnitFlags: NSCalendar.Unit = [.year, .month, .day, .hour, .minute, .second]

        var dateComponents = (Calendar.current as NSCalendar).components(calendarUnitFlags, from: Date())

        dateComponents.hour = 0
        dateComponents.minute = 0
        dateComponents.second = 0

        if eventStartDatePicker.isFirstResponder == true {
            eventStartDatePicker.resignFirstResponder()
        }

        if eventEndDatePicker.isFirstResponder == true {
            eventEndDatePicker.resignFirstResponder()
        }
        return Calendar.current.date(from: dateComponents)!
    }

    @IBAction func cancelButtonTapped(_ sender: UIBarButtonItem) {
        self.dismiss(animated: true, completion: nil)
    }

    @IBAction func addEventButtonTapped(_ sender: UIBarButtonItem) {
        // Create an Event Store instance
        let eventStore = EKEventStore()

        let calendars = eventStore.calendars(for: EKEntityType.event)
        for calendar in calendars {
            if calendar.title == "PhotoBase" {
                let newEvent = EKEvent(eventStore: eventStore)

                newEvent.calendar = calendar
                newEvent.title = self.eventNameTextField.text ?? "Some Event Name"
                newEvent.startDate = self.eventStartDatePicker.date
                newEvent.endDate = self.eventEndDatePicker.date
                // Save the event using the Event Store instance
                do {
                    try eventStore.save(newEvent, span: .thisEvent, commit: true)
                    delegate?.eventDidAdd()

                    self.dismiss(animated: true, completion: nil)
                } catch {
                    let alert = UIAlertController(title: "Event could not save", message: (error as NSError).localizedDescription, preferredStyle: .alert)
                    let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                    alert.addAction(OKAction)

                    self.present(alert, animated: true, completion: nil)
                }
            }
        }
    }

    func textFieldDidEndEditing(_ textField: UITextField)  {
        eventNameTextField.resignFirstResponder()
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print(#file, #function)
        textField.resignFirstResponder();
        return true;
    }
</code>```

I'm open to improvements!

Body:
I'm trying to use the generic EKEventEditViewController instead of rolling my own. But I'm running into a problem with the calendar selection. In the controller instance, I see a choice of calendars, and I'd prefer not to see that choice -- I want all events to link to an app-specific calendar.

Is there a way to do this?

Right now, I'm calling EKEventEditViewController as follows:

@IBAction func addEventTapped(_ sender: UIButton) {

    // create an instance of EKEventEditViewController()
    let eventViewController: EKEventEditViewController = EKEventEditViewController()

    let calendars = eventStore.calendars(for: EKEntityType.event)

    for calendar in calendars {
        if calendar.title == "MyAppCalendar" {

            print("calendar is identified")
            eventViewController.eventStore = self.eventStore
            eventViewController.eventStore.calendar(withIdentifier: calendar.title)
        }
    }

    eventViewController.editViewDelegate = self
    self.present(eventViewController, animated: false, completion: nil)

}

Thanks!

Body:
I solved this by subclassing EKEventEditViewController

The code was lifted from Andrew Bancroft and from SpaceOTechnologies

I created an AddEventController and the code is:

import UIKit
import EventKit
import EventKitUI

class AddEventViewController: UIViewController, UITextFieldDelegate{

    var calendar: EKCalendar!

    @IBOutlet weak var eventNameTextField: UITextField!
    @IBOutlet weak var eventStartDatePicker: UIDatePicker!
    @IBOutlet weak var eventEndDatePicker: UIDatePicker!

    var delegate: EventAddedDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.eventStartDatePicker.setDate(initialDatePickerValue(), animated: false)
        self.eventEndDatePicker.setDate(initialDatePickerValue(), animated: false)

    }

    func initialDatePickerValue() -> Date {

        eventNameTextField.resignFirstResponder()

        let calendarUnitFlags: NSCalendar.Unit = [.year, .month, .day, .hour, .minute, .second]

        var dateComponents = (Calendar.current as NSCalendar).components(calendarUnitFlags, from: Date())

        dateComponents.hour = 0
        dateComponents.minute = 0
        dateComponents.second = 0

        if eventStartDatePicker.isFirstResponder == true {
            eventStartDatePicker.resignFirstResponder()
        }

        if eventEndDatePicker.isFirstResponder == true {
            eventEndDatePicker.resignFirstResponder()
        }
        return Calendar.current.date(from: dateComponents)!
    }

    @IBAction func cancelButtonTapped(_ sender: UIBarButtonItem) {
        self.dismiss(animated: true, completion: nil)
    }

    @IBAction func addEventButtonTapped(_ sender: UIBarButtonItem) {
        // Create an Event Store instance
        let eventStore = EKEventStore()

        let calendars = eventStore.calendars(for: EKEntityType.event)
        for calendar in calendars {
            if calendar.title == "PhotoBase" {
                let newEvent = EKEvent(eventStore: eventStore)

                newEvent.calendar = calendar
                newEvent.title = self.eventNameTextField.text ?? "Some Event Name"
                newEvent.startDate = self.eventStartDatePicker.date
                newEvent.endDate = self.eventEndDatePicker.date
                // Save the event using the Event Store instance
                do {
                    try eventStore.save(newEvent, span: .thisEvent, commit: true)
                    delegate?.eventDidAdd()

                    self.dismiss(animated: true, completion: nil)
                } catch {
                    let alert = UIAlertController(title: "Event could not save", message: (error as NSError).localizedDescription, preferredStyle: .alert)
                    let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                    alert.addAction(OKAction)

                    self.present(alert, animated: true, completion: nil)
                }
            }
        }
    }

    func textFieldDidEndEditing(_ textField: UITextField)  {
        eventNameTextField.resignFirstResponder()
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print(#file, #function)
        textField.resignFirstResponder();
        return true;
    }

I'm open to improvements!


问:
How do I remove unnecessary values from list view?
I am unable to remove these top two value, I am reading mp3 files from res folder and showing it here. last three files are the name of songs but the top two are not needed.Help me on how to remove them. This is my code as I am reading values from res and showing to ListView and then playing that audio:

```<code>public class MainActivity extends AppCompatActivity {

    ArrayList<String> songNames;
    MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = (ListView) findViewById(R.id.Mylistview);
        songNames = new ArrayList<String>();

        final ArrayList<String> list = new ArrayList<String>();

        Field[] fields = R.raw.class.getFields();
        list.clear();
        for(Field f : fields)
            try {

                list.add(f.getName());
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }

                //     songNames.add(getResources().getClass(R.raw.song1));
                //  songNames.add(getResources().getResourceEntryName(R.raw.song2));
                // songNames.add(getResources().getResourceEntryName(R.raw.song3));

                final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);

                listView.setAdapter(arrayAdapter);

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        Uri mp3 = Uri.parse("android.resource://"
                                + getApplicationContext().getPackageName() + "/raw/"
                                + list.get(position));
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        try {
                            mediaPlayer.setDataSource(getApplicationContext(),mp3);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        try {
                            mediaPlayer.prepare(); // might take long! (for buffering, etc)
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        mediaPlayer.start();
                        mediaPlayer.setOnCompletionListener(onCompletionListener);

                    }
                });

            }

    private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            // TODO Auto-generated method stub
            mediaPlayer.release();
            mediaPlayer = null;
        }
    };

}
</code>```

答:
Instead of for (Field f : fields), just write:

```<code>for (int i = 2; i < fields.length; i++) {
    Field f = fields[i];
</code>```

And add a closing curly bracket } after the try-catch block.

Body:
I am unable to remove these top two value, I am reading mp3 files from res folder and showing it here. last three files are the name of songs but the top two are not needed.Help me on how to remove them. This is my code as I am reading values from res and showing to ListView and then playing that audio:

public class MainActivity extends AppCompatActivity {

    ArrayList<String> songNames;
    MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = (ListView) findViewById(R.id.Mylistview);
        songNames = new ArrayList<String>();

        final ArrayList<String> list = new ArrayList<String>();

        Field[] fields = R.raw.class.getFields();
        list.clear();
        for(Field f : fields)
            try {

                list.add(f.getName());
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }

                //     songNames.add(getResources().getClass(R.raw.song1));
                //  songNames.add(getResources().getResourceEntryName(R.raw.song2));
                // songNames.add(getResources().getResourceEntryName(R.raw.song3));

                final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);

                listView.setAdapter(arrayAdapter);

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        Uri mp3 = Uri.parse("android.resource://"
                                + getApplicationContext().getPackageName() + "/raw/"
                                + list.get(position));
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        try {
                            mediaPlayer.setDataSource(getApplicationContext(),mp3);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        try {
                            mediaPlayer.prepare(); // might take long! (for buffering, etc)
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        mediaPlayer.start();
                        mediaPlayer.setOnCompletionListener(onCompletionListener);

                    }
                });

            }

    private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            // TODO Auto-generated method stub
            mediaPlayer.release();
            mediaPlayer = null;
        }
    };

}

Body:
Instead of for (Field f : fields), just write:

for (int i = 2; i < fields.length; i++) {
    Field f = fields[i];

And add a closing curly bracket } after the try-catch block.


问:
Unfortunately app Stopped - While running in real device but working well in emulator
My Android App is running successfully in android studio emulator, but after installing the same apk file in my mobile it is installing and it is shows the following error

Unfortunately app stopped

while I try to open it.

how to fix? My android version is 6.0(both emulator and mobile).

答:
I suggest you check the permissions of your application. Since version 6 of Android, you must request the permissions on demand.

Look at this topic:
https://stackoverflow.com/a/34722591/3665983


答:
You can check the following code

    var usernumber = prompt('What is your number?');
    var numbers = ['1', '2', '3'];
    if (numbers.indexOf(usernumber) >=0 ) //If the user number matches one of preset numbers
    {
        alert('Match');
    } else {
        alert('No match found.');
    }```

Title: How do you compare user input to values inside an array?

Body: I am wanting to create a very simple script that checks user's input to a pre-existing array. However, it doesn't seem to work and I'm not sure why. Please, keep in mind I'm new to this and trying to learn.


问:
How to configure CORS in a Spring Boot + Spring Security application?
I use Spring Boot with Spring Security and Cors Support.

If I execute following code

```<code>url = 'http://localhost:5000/api/token'
xmlhttp = new XMLHttpRequest
xmlhttp.onreadystatechange = ->
    if xmlhttp.readyState is 4
        console.log xmlhttp.status
xmlhttp.open "GET", url, true
# xmlhttp.setRequestHeader "X-Requested-With", "XMLHttpRequest"
xmlhttp.setRequestHeader 'Authorization', 'Basic ' + btoa 'a:a'
do xmlhttp.send
</code>```

I get as a result

```<code>200
</code>```

If I test with wrong credentials like

```<code>url = 'http://localhost:5000/api/token'
xmlhttp = new XMLHttpRequest
xmlhttp.onreadystatechange = ->
    if xmlhttp.readyState is 4
        console.log xmlhttp.status
xmlhttp.open "GET", url, true
# xmlhttp.setRequestHeader "X-Requested-With", "XMLHttpRequest"
xmlhttp.setRequestHeader 'Authorization', 'Basic ' + btoa 'a:aa'
do xmlhttp.send
</code>```

instead of getting 401 (that is the standard code for wrong authentication in spring security) I get

```<code>0
</code>```

with following browser notification:

GET http://localhost:5000/api/token

XMLHttpRequest cannot load http://localhost:5000. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.

I'm developing front-end code that needs useful http status codes from server responses to handle the situation. I need something more useful than 0. Also the response body is empty. I dont know if my config is wrong, or it's a software bug and I also don't know where, if it's chromium (using arch linux) or spring security.

My Spring Config is:

```<code>@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@RestController
@RequestMapping("api")
public class Controller {
    @RequestMapping("token")
    @CrossOrigin
    Map<String, String> token(HttpSession session) {
        return Collections.singletonMap("token", session.getId());
    }
}

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("a").password("a").roles("USER");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .anyRequest().authenticated()
                .and().httpBasic();
    }
}
</code>```

If I test with curl everything works perfect, I think because no CORS support needed, but I tried to simulate the CORS with OPTION requests and the result was also ok.

```<code>$ curl -v localhost:5000/api/token -H "Authorization: Basic YTpha"
*   Trying ::1...
* Connected to localhost (::1) port 5000 (#0)
> GET /api/token HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.48.0
> Accept: */*
> Authorization: Basic YTpha
>
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Access-Control-Allow-Origin: http://localhost:3000
< Access-Control-Allow-Methods: POST,GET,OPTIONS,DELETE
< Access-Control-Max-Age: 3600
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Headers: Origin,Accept,X-Requested-    With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization
< x-auth-token: 58e4cca9-7719-46c8-9180-2fc16aec8dff
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Sun, 01 May 2016 16:15:44 GMT
<
* Connection #0 to host localhost left intact
{"token":"58e4cca9-7719-46c8-9180-2fc16aec8dff"}
</code>```

and with wrong credentials:

```<code>$ curl -v localhost:5000/api/token -H "Authorization: Basic YTp"
*   Trying ::1...
* Connected to localhost (::1) port 5000 (#0)
> GET /api/token HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.48.0
> Accept: */*
> Authorization: Basic YTp
>
< HTTP/1.1 401 Unauthorized
< Server: Apache-Coyote/1.1
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< WWW-Authenticate: Basic realm="Realm"
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Sun, 01 May 2016 16:16:15 GMT
<
* Connection #0 to host localhost left intact
{"timestamp":1462119375041,"status":401,"error":"Unauthorized","message":"Failed to decode basic authentication token","path":"/api/token"}
</code>```

Edit:
To avoid misunderstandings. I use 1.3.3 Spring Boot.
The Blog post writes:

CORS support will be available in the upcoming Spring Boot 1.3 release, and is already available in the 1.3.0.BUILD-SNAPSHOT builds.

Using controller method CORS configuration with @CrossOrigin annotations in your Spring Boot application does not require any specific configuration.

Global CORS configuration can be defined by registering a WebMvcConfigurer bean with a customized addCorsMappings(CorsRegistry) method:

I have added following code to enable global cors support. actually I have tried this before but it the result was the same. I tried it again recently and the result is the same.

```<code>@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}
</code>```

The idea, that the problem comes from a redirect between the authorization process is an interesting though. how can i change the redirect to any resources to avoid this conflict?

EDIT:

I guess I am closer to a solution. I have tested with my nodejs server that supports cors without problems by adding
Access-Control-Allow-Origin: *
to all requests.

Like Stefan Isele has already mentioned it seems that spring security redirects or doesn't add the CORS header so that's why the request seems to be broken. So while spring security is checking the authentification it has to add the proper header.

Does anyone know how to do so?

EDIT:

I found a workaround, that seems to be ugly. I have started a github issue for spring boot where I describe the workaround: https://github.com/spring-projects/spring-boot/issues/5834

答:
I had the same problem on a methood that returns the status of the server.
The application is deployed on multiple servers. So the easiest I found is to add

```<code>@CrossOrigin(origins = "*")
@RequestMapping(value="/schedulerActive")
public String isSchedulerActive(){
  //code goes here
}
</code>```

This method is not secure but you can add allowCredentials for that.

Body:
I use Spring Boot with Spring Security and Cors Support.

If I execute following code

url = 'http://localhost:5000/api/token'
xmlhttp = new XMLHttpRequest
xmlhttp.onreadystatechange = ->
    if xmlhttp.readyState is 4
        console.log xmlhttp.status
xmlhttp.open "GET", url, true
# xmlhttp.setRequestHeader "X-Requested-With", "XMLHttpRequest"
xmlhttp.setRequestHeader 'Authorization', 'Basic ' + btoa 'a:a'
do xmlhttp.send

I get as a result

200

If I test with wrong credentials like

url = 'http://localhost:5000/api/token'
xmlhttp = new XMLHttpRequest
xmlhttp.onreadystatechange = ->
    if xmlhttp.readyState is 4
        console.log xmlhttp.status
xmlhttp.open "GET", url, true
# xmlhttp.setRequestHeader "X-Requested-With", "XMLHttpRequest"
xmlhttp.setRequestHeader 'Authorization', 'Basic ' + btoa 'a:aa'
do xmlhttp.send

instead of getting 401 (that is the standard code for wrong authentication in spring security) I get

0

with following browser notification:

GET http://localhost:5000/api/token

XMLHttpRequest cannot load http://localhost:5000. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.

I'm developing front-end code that needs useful http status codes from server responses to handle the situation. I need something more useful than 0. Also the response body is empty. I dont know if my config is wrong, or it's a software bug and I also don't know where, if it's chromium (using arch linux) or spring security.

My Spring Config is:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@RestController
@RequestMapping("api")
public class Controller {
    @RequestMapping("token")
    @CrossOrigin
    Map<String, String> token(HttpSession session) {
        return Collections.singletonMap("token", session.getId());
    }
}

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("a").password("a").roles("USER");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .anyRequest().authenticated()
                .and().httpBasic();
    }
}

If I test with curl everything works perfect, I think because no CORS support needed, but I tried to simulate the CORS with OPTION requests and the result was also ok.

$ curl -v localhost:5000/api/token -H "Authorization: Basic YTpha"
*   Trying ::1...
* Connected to localhost (::1) port 5000 (#0)
> GET /api/token HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.48.0
> Accept: */*
> Authorization: Basic YTpha
>
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Access-Control-Allow-Origin: http://localhost:3000
< Access-Control-Allow-Methods: POST,GET,OPTIONS,DELETE
< Access-Control-Max-Age: 3600
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Headers: Origin,Accept,X-Requested-    With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization
< x-auth-token: 58e4cca9-7719-46c8-9180-2fc16aec8dff
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Sun, 01 May 2016 16:15:44 GMT
<
* Connection #0 to host localhost left intact
{"token":"58e4cca9-7719-46c8-9180-2fc16aec8dff"}

and with wrong credentials:

$ curl -v localhost:5000/api/token -H "Authorization: Basic YTp"
*   Trying ::1...
* Connected to localhost (::1) port 5000 (#0)
> GET /api/token HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.48.0
> Accept: */*
> Authorization: Basic YTp
>
< HTTP/1.1 401 Unauthorized
< Server: Apache-Coyote/1.1
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< WWW-Authenticate: Basic realm="Realm"
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Sun, 01 May 2016 16:16:15 GMT
<
* Connection #0 to host localhost left intact
{"timestamp":1462119375041,"status":401,"error":"Unauthorized","message":"Failed to decode basic authentication token","path":"/api/token"}

Edit:
To avoid misunderstandings. I use 1.3.3 Spring Boot.
The Blog post writes:

CORS support will be available in the upcoming Spring Boot 1.3 release, and is already available in the 1.3.0.BUILD-SNAPSHOT builds.

Using controller method CORS configuration with @CrossOrigin annotations in your Spring Boot application does not require any specific configuration.

Global CORS configuration can be defined by registering a WebMvcConfigurer bean with a customized addCorsMappings(CorsRegistry) method:

I have added following code to enable global cors support. actually I have tried this before but it the result was the same. I tried it again recently and the result is the same.

@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

The idea, that the problem comes from a redirect between the authorization process is an interesting though. how can i change the redirect to any resources to avoid this conflict?

EDIT:

I guess I am closer to a solution. I have tested with my nodejs server that supports cors without problems by adding
Access-Control-Allow-Origin: *
to all requests.

Like Stefan Isele has already mentioned it seems that spring security redirects or doesn't add the CORS header so that's why the request seems to be broken. So while spring security is checking the authentification it has to add the proper header.

Does anyone know how to do so?

EDIT:

I found a workaround, that seems to be ugly. I have started a github issue for spring boot where I describe the workaround: https://github.com/spring-projects/spring-boot/issues/5834

Body:
I had the same problem on a methood that returns the status of the server.
The application is deployed on multiple servers. So the easiest I found is to add

@CrossOrigin(origins = "*")
@RequestMapping(value="/schedulerActive")
public String isSchedulerActive(){
  //code goes here
}

This method is not secure but you can add allowCredentials for that.


问:
How do you create a list of Observables in RxJava?
I've a API which gives me a list of ids. I need to use these ids to make another network request to get their details of individual items. Once I get all the details I need to put them in a list.

So here is an example. Make a network request, get a list of ids say

1, 2, 3, 4, 5.

Now I need to make 5 separate requests for these 5 ids.

And then once I get the response of all, I need to create a list which is used to populate the RecyclerView.

Let me know if further information are needed. I'm new to Reactive programming.

答:
Let us say that you have an observable source:

```<code>Observable<Integer> source;
</code>```

You want to do a network request for each ID:

```<code>Long getLongFromIdViaNetwork(Integer id);
</code>```

You compose them like so:

```<code>source
  .flatMap( i -> Observable.fromCallable( id -> getLongFromIdViaNetwork( id ) ) )
  .toList()
  .subscribeOn( backgroundScheduler )
  .observeOn( foregroundScheduler )
  .subscribe( listOfLongs -> {} );
</code>```

where backgroundScheduler and foregroundScheduler are appropriate for our environment.

Body:
Let us say that you have an observable source:

Observable<Integer> source;

You want to do a network request for each ID:

Long getLongFromIdViaNetwork(Integer id);

You compose them like so:

source
  .flatMap( i -> Observable.fromCallable( id -> getLongFromIdViaNetwork( id ) ) )
  .toList()
  .subscribeOn( backgroundScheduler )
  .observeOn( foregroundScheduler )
  .subscribe( listOfLongs -> {} );

where backgroundScheduler and foregroundScheduler are appropriate for our environment.


问:
move UITextField up when keyboard present
I have recently started to develop my own app following the instructions on internet. I am just a beginner (with no knowledge of coding) and hence may be doing very stupid mistake that I am not able to catch.

In my app I am facing a situation where my email text field is hiding behind the keyboard whenever I try to type email address. I did some research (on stack overflow) and wrote a piece of code that suppose to move my text field up but it is not ... I believe overall structure of code is right (I may be wrong here though) but it may be just tiny mistake that making my code ineffective.

can anyone guide me on what I am doing wrong here?

below is the piece of code I wrote:
{

```<code>import UIKit
import WebKit
import CoreGraphics
import AVFoundation
import QuartzCore
import Foundation

class StudentSignUpViewController: UIViewController,UIScrollViewDelegate, UITextFieldDelegate {

@IBOutlet weak var yourEmail: UITextField!
@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()

    //setting portrait
    AppUtility.lockOrientation(.portrait)

    //hide keyboard when click outside
    self.hideKeyboardWhenTappedAround()

    //hide keyboard when click on return
    self.yourEmail.delegate = self
    self.scrollView.delegate = self

    //boarder line for yourEmail
    yourEmail.frame.size.height =  UIScreen.main.fixedCoordinateSpace.bounds.size.width * CGFloat(0.05)
    yourEmail.font = UIFont.italicSystemFont(ofSize: UIScreen.main.fixedCoordinateSpace.bounds.size.width * CGFloat(0.04))
    bottomBoader(BottomLine: "UrEmailTextBottomLine", length: 1.0, yourTextBox: yourEmail)
    yourEmail.applyCustomClearButton(yourTextBox: yourEmail)

    registerForKeyboardNotifications()
    deregisterFromKeyboardNotifications()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    AppUtility.lockOrientation(.portrait)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    AppUtility.lockOrientation(.all)
}

// ***************************************************  moving textfiles when keyborad present ***********************************************************

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

@objc func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.yourEmail {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
    //self.scrollView.contentInset = UIEdgeInsets.zero
}

func textFieldDidBeginEditing( textField: UITextField){
    yourEmail = textField
}

func textFieldDidEndEditing(textField: UITextField){
    yourEmail = nil
}
</code>```

答:
The problem is you are registerForKeyboardNotifications() and then immediately deregisterFromKeyboardNotifications() so you aren't getting keyboard notifications. You should move the deregister to the deinit:

```<code>deinit {
    deregisterFromKeyboardNotifications()
}
</code>```

Edit

As @matt pointed out you don't need to deregisterFromKeyboardNotifications so just delete that code (including my suggestion of deinit)

Body:
I have recently started to develop my own app following the instructions on internet. I am just a beginner (with no knowledge of coding) and hence may be doing very stupid mistake that I am not able to catch.

In my app I am facing a situation where my email text field is hiding behind the keyboard whenever I try to type email address. I did some research (on stack overflow) and wrote a piece of code that suppose to move my text field up but it is not ... I believe overall structure of code is right (I may be wrong here though) but it may be just tiny mistake that making my code ineffective.

can anyone guide me on what I am doing wrong here?

below is the piece of code I wrote:
{

import UIKit
import WebKit
import CoreGraphics
import AVFoundation
import QuartzCore
import Foundation

class StudentSignUpViewController: UIViewController,UIScrollViewDelegate, UITextFieldDelegate {

@IBOutlet weak var yourEmail: UITextField!
@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()

    //setting portrait
    AppUtility.lockOrientation(.portrait)

    //hide keyboard when click outside
    self.hideKeyboardWhenTappedAround()

    //hide keyboard when click on return
    self.yourEmail.delegate = self
    self.scrollView.delegate = self

    //boarder line for yourEmail
    yourEmail.frame.size.height =  UIScreen.main.fixedCoordinateSpace.bounds.size.width * CGFloat(0.05)
    yourEmail.font = UIFont.italicSystemFont(ofSize: UIScreen.main.fixedCoordinateSpace.bounds.size.width * CGFloat(0.04))
    bottomBoader(BottomLine: "UrEmailTextBottomLine", length: 1.0, yourTextBox: yourEmail)
    yourEmail.applyCustomClearButton(yourTextBox: yourEmail)

    registerForKeyboardNotifications()
    deregisterFromKeyboardNotifications()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    AppUtility.lockOrientation(.portrait)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    AppUtility.lockOrientation(.all)
}

// ***************************************************  moving textfiles when keyborad present ***********************************************************

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

@objc func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.yourEmail {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
    //self.scrollView.contentInset = UIEdgeInsets.zero
}

func textFieldDidBeginEditing( textField: UITextField){
    yourEmail = textField
}

func textFieldDidEndEditing(textField: UITextField){
    yourEmail = nil
}

Body:
The problem is you are registerForKeyboardNotifications() and then immediately deregisterFromKeyboardNotifications() so you aren't getting keyboard notifications. You should move the deregister to the deinit:

deinit {
    deregisterFromKeyboardNotifications()
}

Edit

As @matt pointed out you don't need to deregisterFromKeyboardNotifications so just delete that code (including my suggestion of deinit)


问:
Is there any quick way to switch between docker hub accounts in command line?
Tired of typing in login and password. So the registry is the same, but accounts are different. Should I just make a script that replaces ~/.docker/config.json?</p>

答:
Unfortunately, no. The config.json can only hold one credentials value for each remote registry. Moreover, there is an open issue to handle multiple logins to dockerhub.

However, you can easily solve the problem using bash aliases. Edit your ~/.bashrc file and add the following lines:

```<code>alias dl1='docker login -u <user1> -p <password1>'
alias dl2='docker login -u <user2> -p <password2>'
</code>```

Now you can do dl1 to login to account1 and dl2 to switch to account2

You can basically also do something similar if you are on MAC or Windows.

Body:
Unfortunately, no. The config.json can only hold one credentials value for each remote registry. Moreover, there is an open issue to handle multiple logins to dockerhub.

However, you can easily solve the problem using bash aliases. Edit your ~/.bashrc file and add the following lines:

alias dl1='docker login -u <user1> -p <password1>'
alias dl2='docker login -u <user2> -p <password2>'

Now you can do dl1 to login to account1 and dl2 to switch to account2

You can basically also do something similar if you are on MAC or Windows.


问:
Docker port 80:80 127.0.0.1
Im having a huge issue and I can't get round it

Basically i went through the Laravel installation and installed homestead 7 and im using virtual box... vagrant

Now before this I'm using docker to run other application through it... which worked and it looks like something i've done is using the same port so I now cant use docker on that port

Cannot start service website: driver failed programming external connectivity on endpoint distinctly_website_1 (edc81f653cb3ac8c2af9b7ce070d0a0ccbb3ec255af452338ff4677ce99b156a): Error starting userland proxy: Bind for 0.0.0.0:80: unexpected error (Failure EADDRINUSE)
  ERROR: Encountered errors while bringing up the project.

I just need some help with removing this conflict with the port so I can run my docker applications. I dont care about anything than docker

答:
netstat: option requires an argument -- p
Usage:  netstat [-AaLlnW] [-f address_family | -p protocol]</p>

```<code>netstat [-gilns] [-f address_family]
netstat -i | -I interface [-w wait] [-abdgRtS]
netstat -s [-s] [-f address_family | -p protocol] [-w wait]
netstat -i | -I interface -s [-f address_family | -p protocol]
netstat -m [-m]
netstat -r [-Aaln] [-f address_family]
netstat -rs [-s]
</code>```

Title: Docker port 80:80 127.0.0.1

Body:
netstat: option requires an argument -- p
Usage:  netstat [-AaLlnW] [-f address_family | -p protocol]

netstat [-gilns] [-f address_family]
netstat -i | -I interface [-w wait] [-abdgRtS]
netstat -s [-s] [-f address_family | -p protocol] [-w wait]
netstat -i | -I interface -s [-f address_family | -p protocol]
netstat -m [-m]
netstat -r [-Aaln] [-f address_family]
netstat -rs [-s]


问:
Rails: no block given (yield)
I'm getting in my rails app this error no block given (yield) and this is referred to this line in my file elements = Element.where(study_version_id: self.id).find_each I'm trying to export to an XML file some data which is generated in my app. When I try to export I have that error and I would like some help to resolve it.

The entire code related:

```<code>def to_xml
    # Build the document and the header elements
    odm_document = Odm.new("ODM-#{self.id}", "Assero", "Tourmalet", Version::VERSION)
    odm = odm_document.root
    study = odm.add_study("S-#{self.id}")
    global_variables = study.add_global_variables()
    global_variables.add_study_name("#{self.name}")
    global_variables.add_study_description("#{self.description}")
    global_variables.add_protocol_name("#{self.protocol_name}")
    metadata_version = study.add_metadata_version("MDV-#{self.id}", "Metadata for #{self.description}", "Study export.")
    protocol = metadata_version.add_protocol()
    # Get the set of visits, forms and elements.
    visits = Visit.where(study_version_id: self.id).order(ordinal: :asc)
    forms = Form.where(study_version_id: self.id).order(ordinal: :asc)
    elements = Element.where(study_version_id: self.id).find_each
    # Build the Protocol element.
    visits.each do |visit|
      protocol.add_study_event_ref("SE-#{visit.ordinal}", "#{visit.ordinal}", "Yes", "")
    end
    # Build the StudyEventDef elements
    visits.each do |visit|
      study_event_def = metadata_version.add_study_event_def("SE-#{visit.ordinal}", "#{visit.long_name}", "No", "Scheduled", "")
      elements = Element.where(study_version_id: self.id, visit_id: visit.id).find_each
      elements.each do |element|
        #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "Element=#{element.to_json}")
        form = Form.find(element.form_id)
        study_event_def.add_form_ref("#{form.form_id}", "#{form.ordinal}", "Yes", "")
      end
    end
    # Now the remainder of the metadata
    forms.each do |form|
      form_json = Mdr.form_to_hash(form.form_id, form.form_namespace)
      #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "JSON=#{form_json}")
      xml_node(form_json, metadata_version, nil)
    end
    return odm_document.to_xml
  end
</code>```

答:
Quick solvation is replace find_each with all. It will work if you have small database (I think it's your case)

find_each is used for optimization. It returns you not all records at once, but sets of records (1000 by default). If you have 1.000.000 record you will get our of memory exception in case trying to load it all at once.

You can rewrite your code with find_each usage as:

```<code>Element.where(study_version_id: self.id, visit_id: visit.id).find_each do |elements|
  elements.each do |element|
    #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "Element=#{element.to_json}")
    form = Form.find(element.form_id)
    study_event_def.add_form_ref("#{form.form_id}", "#{form.ordinal}", "Yes", "")
  end
end
</code>```

But I am 90% sure you should just go with:

```<code>elements = Element.where(study_version_id: self.id, visit_id: visit.id).all
elements.each do |element|
  #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "Element=#{element.to_json}")
  form = Form.find(element.form_id)
  study_event_def.add_form_ref("#{form.form_id}", "#{form.ordinal}", "Yes", "")
end
</code>```

Title: Rails: no block given (yield)

Body:
I'm getting in my rails app this error no block given (yield) and this is referred to this line in my file elements = Element.where(study_version_id: self.id).find_each I'm trying to export to an XML file some data which is generated in my app. When I try to export I have that error and I would like some help to resolve it.

The entire code related:

def to_xml
    # Build the document and the header elements
    odm_document = Odm.new("ODM-#{self.id}", "Assero", "Tourmalet", Version::VERSION)
    odm = odm_document.root
    study = odm.add_study("S-#{self.id}")
    global_variables = study.add_global_variables()
    global_variables.add_study_name("#{self.name}")
    global_variables.add_study_description("#{self.description}")
    global_variables.add_protocol_name("#{self.protocol_name}")
    metadata_version = study.add_metadata_version("MDV-#{self.id}", "Metadata for #{self.description}", "Study export.")
    protocol = metadata_version.add_protocol()
    # Get the set of visits, forms and elements.
    visits = Visit.where(study_version_id: self.id).order(ordinal: :asc)
    forms = Form.where(study_version_id: self.id).order(ordinal: :asc)
    elements = Element.where(study_version_id: self.id).find_each
    # Build the Protocol element.
    visits.each do |visit|
      protocol.add_study_event_ref("SE-#{visit.ordinal}", "#{visit.ordinal}", "Yes", "")
    end
    # Build the StudyEventDef elements
    visits.each do |visit|
      study_event_def = metadata_version.add_study_event_def("SE-#{visit.ordinal}", "#{visit.long_name}", "No", "Scheduled", "")
      elements = Element.where(study_version_id: self.id, visit_id: visit.id).find_each
      elements.each do |element|
        #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "Element=#{element.to_json}")
        form = Form.find(element.form_id)
        study_event_def.add_form_ref("#{form.form_id}", "#{form.ordinal}", "Yes", "")
      end
    end
    # Now the remainder of the metadata
    forms.each do |form|
      form_json = Mdr.form_to_hash(form.form_id, form.form_namespace)
      #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "JSON=#{form_json}")
      xml_node(form_json, metadata_version, nil)
    end
    return odm_document.to_xml
  end

Body:
Quick solvation is replace find_each with all. It will work if you have small database (I think it's your case)

find_each is used for optimization. It returns you not all records at once, but sets of records (1000 by default). If you have 1.000.000 record you will get our of memory exception in case trying to load it all at once.

You can rewrite your code with find_each usage as:

Element.where(study_version_id: self.id, visit_id: visit.id).find_each do |elements|
  elements.each do |element|
    #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "Element=#{element.to_json}")
    form = Form.find(element.form_id)
    study_event_def.add_form_ref("#{form.form_id}", "#{form.ordinal}", "Yes", "")
  end
end

But I am 90% sure you should just go with:

elements = Element.where(study_version_id: self.id, visit_id: visit.id).all
elements.each do |element|
  #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "Element=#{element.to_json}")
  form = Form.find(element.form_id)
  study_event_def.add_form_ref("#{form.form_id}", "#{form.ordinal}", "Yes", "")
end


答:
```<code> <script>
    var usernumber = prompt('What is your number?');
    var numbers = new Array();
    numbers['1'] = true;
    numbers['2'] = true;
    numbers['3'] = true;
    if (numbers[usernumber]) //If the user number matches one of preset numbers
    {
        alert('Match');
    } else {
        alert('No match found.');
    }
</script>
</code>```