问:
Volley get request doesn't hit server
I am around this issue it already past like 2 hours, basicly i am trying to get some data from my server and the volley callback never get executed.

Basicly i have an interface defined to handle the volley request, so for the getRequest i have something like this:

```<code>public void getDataObjectVolley(final String requestType, String url, final String token){
        try {
            RequestQueue queue = Volley.newRequestQueue(mContext);

            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    if(mResultCallback != null)
                        mResultCallback.notifySuccess(requestType, response);
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {

                @Override
                public Map<String, String> getHeaders(){
                    Map<String, String> headers = new HashMap<>();
                    Log.d("tokenXX",token);
                    headers.put("x-access-token", token);
                    return headers;
                }
            };

            jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(jsonObjectRequest);

        }catch(Exception e){

        }
    }
</code>```

then on my activity i intialize the callback and pass the functions to him:

```<code>IResult mResultCallbackGET = null;
</code>```

onCreate i call the loadPhotos

```<code> loadPhotoDetails();
</code>```

then the method is like this:

```<code> private void loadPhotoDetails() {
        final String urlDetails = connectionTxt + "/fotos/" + fotoId;
        loadPhotoInfo();
        mVolleyService = new VolleyService(mResultCallbackGET,this);
        mVolleyService.getDataObjectVolley(GETREQUEST,urlDetails,token);
    }
</code>```

the loadPhotoInfo

```<code>void loadPhotoInfo(){
        Log.d("HELLOWORLD","HELLOWOLD");
        mResultCallbackGET = new IResult() {
            @Override
            public void notifySuccess(String requestType, JSONObject response) {
                /*Log.d("HELLOWOLRD","HELLOWOLD1");
                Log.d("resposta123",response.toString());
                String path = null;
                Double lat = null;
                Double lon = null;
                Double alt = null;
                Boolean hasFlower = null;
                Boolean hasLeaf = null;
                Boolean hasThorn = null;
                Boolean hasFruit = null;
                String flowerColor = null;
                String time = null;

                try {
                    path = response.getString("image");
                    lat = response.getDouble("lat");
                    lon = response.getDouble("lon");
                    alt = response.getDouble("altitude");
                    hasFlower = response.getBoolean("hasFlower");
                    hasLeaf = response.getBoolean("hasLeaf");
                    hasThorn = response.getBoolean("hasThorn");
                    hasFruit = response.getBoolean("hasFruit");
                    flowerColor = response.getString("flowerColor");
                    time = response.getString("date");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                photoDetails = new Photo(path,lat,lon,alt,time,hasFlower,hasLeaf,hasThorn,hasFruit,flowerColor);
                Log.d("fruit12",String.valueOf(hasFlower));
                Log.d("fruit12",String.valueOf(hasLeaf));
                Log.d("fruit12",String.valueOf(hasThorn));

                if(hasFruit){
                    hasFruitTxt.setText("Sim");
                }
                else{
                    Log.d("fruit","false");
                    hasFruitTxt.setText("Não");
                }

                if(photoDetails.getHasFlower()){
                    hasFlowerTxt.setText("Sim");
                }
                else{
                    hasFlowerTxt.setText("Não");
                }

                if(photoDetails.getHasThorns()){
                    hasThornsTxt.setText("Sim");
                }
                else{
                    hasThornsTxt.setText("Não");
                }

                if(photoDetails.getHasLeaf()){
                    hasLeafTxt.setText("Sim");
                }
                else{
                    hasLeafTxt.setText("Não");
                }*/
                Log.d("HELLOWOLRD","HELLOWOLD1");
            }

            @Override
            public void notifySuccess(String requestType, JSONArray response) {
                Log.d("HELLOWOLRD","HELLOWOLD2");
            }

            @Override
            public void notifyError(String requestType, VolleyError error) {
                Log.d("HELLOWOLRD","HELLOWOLD3");
            }
        };
    }
</code>```

you guys can see that i have 4 hello worlds log, it just enters the first, it never hits the server, any help with this?

thanks a lot

答:
My suggestion is handle all your HTTP requests in the loadPhotoDetails() method. Code will be shorter. You can create a CONSTANTS file to handle connectionTxt and other constants. (Refer to example below)

//--------------------------------------------------------

private void loadPhotoDetails()(String fotoId) {

```<code>    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
            connectionTxt + "/fotos/" + fotoId, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try{
                if (response.has("Ratings")) {
                    JSONArray ratings = response.getJSONArray("Ratings");

                    String source = null;
                    String value = null;
                    if (ratings.length() > 0) {

                        JSONObject mRatings = ratings.getJSONObject(ratings.length() - 1);
                        source = mRatings.getString("Source");
                        value = mRatings.getString("Value");
                        rating.setText(source + " : " + value);

                    }else {
                        rating.setText("Ratings: N/A");
                    }

                    path.setText(response.getString("image"));
                    lat.setText(response.getString("lat"));
                    lon.setText(response.getString("lon"));
                    alt.setText(response.getString("altitude"));
                    hasFlower.setText(response.getBoolean("hasFlower"));
                    hasLeaf.setText(response.getBoolean("hasLeaf"));
                    hasThorn.setText(response.getBoolean("hasThorn"));
                    hasFruit.setText(response.getBoolean("hasFruit"));
                    flowerColor.setText(response.getString("flowerColor"));
                    time.setText(response.getString("date"));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("Error:", error.getMessage());
        }
    });

    queue.add(jsonObjectRequest);

}
</code>```

//-----------------------------------------

Title: Volley get request doesn't hit server

Body:
I am around this issue it already past like 2 hours, basicly i am trying to get some data from my server and the volley callback never get executed.

Basicly i have an interface defined to handle the volley request, so for the getRequest i have something like this:

public void getDataObjectVolley(final String requestType, String url, final String token){
        try {
            RequestQueue queue = Volley.newRequestQueue(mContext);

            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    if(mResultCallback != null)
                        mResultCallback.notifySuccess(requestType, response);
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {

                @Override
                public Map<String, String> getHeaders(){
                    Map<String, String> headers = new HashMap<>();
                    Log.d("tokenXX",token);
                    headers.put("x-access-token", token);
                    return headers;
                }
            };

            jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(jsonObjectRequest);

        }catch(Exception e){

        }
    }

then on my activity i intialize the callback and pass the functions to him:

IResult mResultCallbackGET = null;

onCreate i call the loadPhotos

 loadPhotoDetails();

then the method is like this:

 private void loadPhotoDetails() {
        final String urlDetails = connectionTxt + "/fotos/" + fotoId;
        loadPhotoInfo();
        mVolleyService = new VolleyService(mResultCallbackGET,this);
        mVolleyService.getDataObjectVolley(GETREQUEST,urlDetails,token);
    }

the loadPhotoInfo

void loadPhotoInfo(){
        Log.d("HELLOWORLD","HELLOWOLD");
        mResultCallbackGET = new IResult() {
            @Override
            public void notifySuccess(String requestType, JSONObject response) {
                /*Log.d("HELLOWOLRD","HELLOWOLD1");
                Log.d("resposta123",response.toString());
                String path = null;
                Double lat = null;
                Double lon = null;
                Double alt = null;
                Boolean hasFlower = null;
                Boolean hasLeaf = null;
                Boolean hasThorn = null;
                Boolean hasFruit = null;
                String flowerColor = null;
                String time = null;

                try {
                    path = response.getString("image");
                    lat = response.getDouble("lat");
                    lon = response.getDouble("lon");
                    alt = response.getDouble("altitude");
                    hasFlower = response.getBoolean("hasFlower");
                    hasLeaf = response.getBoolean("hasLeaf");
                    hasThorn = response.getBoolean("hasThorn");
                    hasFruit = response.getBoolean("hasFruit");
                    flowerColor = response.getString("flowerColor");
                    time = response.getString("date");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                photoDetails = new Photo(path,lat,lon,alt,time,hasFlower,hasLeaf,hasThorn,hasFruit,flowerColor);
                Log.d("fruit12",String.valueOf(hasFlower));
                Log.d("fruit12",String.valueOf(hasLeaf));
                Log.d("fruit12",String.valueOf(hasThorn));

                if(hasFruit){
                    hasFruitTxt.setText("Sim");
                }
                else{
                    Log.d("fruit","false");
                    hasFruitTxt.setText("Não");
                }

                if(photoDetails.getHasFlower()){
                    hasFlowerTxt.setText("Sim");
                }
                else{
                    hasFlowerTxt.setText("Não");
                }

                if(photoDetails.getHasThorns()){
                    hasThornsTxt.setText("Sim");
                }
                else{
                    hasThornsTxt.setText("Não");
                }

                if(photoDetails.getHasLeaf()){
                    hasLeafTxt.setText("Sim");
                }
                else{
                    hasLeafTxt.setText("Não");
                }*/
                Log.d("HELLOWOLRD","HELLOWOLD1");
            }

            @Override
            public void notifySuccess(String requestType, JSONArray response) {
                Log.d("HELLOWOLRD","HELLOWOLD2");
            }

            @Override
            public void notifyError(String requestType, VolleyError error) {
                Log.d("HELLOWOLRD","HELLOWOLD3");
            }
        };
    }

you guys can see that i have 4 hello worlds log, it just enters the first, it never hits the server, any help with this?

thanks a lot

Body:
My suggestion is handle all your HTTP requests in the loadPhotoDetails() method. Code will be shorter. You can create a CONSTANTS file to handle connectionTxt and other constants. (Refer to example below)

//--------------------------------------------------------

private void loadPhotoDetails()(String fotoId) {

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
            connectionTxt + "/fotos/" + fotoId, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try{
                if (response.has("Ratings")) {
                    JSONArray ratings = response.getJSONArray("Ratings");

                    String source = null;
                    String value = null;
                    if (ratings.length() > 0) {

                        JSONObject mRatings = ratings.getJSONObject(ratings.length() - 1);
                        source = mRatings.getString("Source");
                        value = mRatings.getString("Value");
                        rating.setText(source + " : " + value);

                    }else {
                        rating.setText("Ratings: N/A");
                    }

                    path.setText(response.getString("image"));
                    lat.setText(response.getString("lat"));
                    lon.setText(response.getString("lon"));
                    alt.setText(response.getString("altitude"));
                    hasFlower.setText(response.getBoolean("hasFlower"));
                    hasLeaf.setText(response.getBoolean("hasLeaf"));
                    hasThorn.setText(response.getBoolean("hasThorn"));
                    hasFruit.setText(response.getBoolean("hasFruit"));
                    flowerColor.setText(response.getString("flowerColor"));
                    time.setText(response.getString("date"));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("Error:", error.getMessage());
        }
    });

    queue.add(jsonObjectRequest);

}

//-----------------------------------------


来源: stackexchange

问:
Why compare a flag with the result of bitwise AND of a bitmask and the flag?
As a follow-up to "How to use bitmask": When I want to test if a certain flag is set in a given bitmask, I would usually do so solely through the usage of a bitwise AND:

```<code>if(bitmask & flag) { …
</code>```

Yet I frequently see something like this:

```<code>if((bitmask & flag) == flag) { …
</code>```

This is something I observed on both, strongly and weakly typed languages, which is ruling out some sort of prevention for type-casting disasters. The only scenario I can come up with in which the two tests were not equivalent were if flag happens to have actually more than one bit set and all of those are required to be set in bitmask for the condition to pass. Is that all or am I missing something here?

Bonus: Do compilers have means to recognize a flag that will have at most one bit set during runtime and optimize the (possibly bogus) comparison away?

答:
As you point out, the two conditions aren't equivalent. The check (bitmask & flag)1 is checking if any bit set in flag is set in bitmask, while the (bitmask & flag) == flag check checks if all bits in flag are set.

In cases where there will only ever be one bit set, you might also see the second form rather than the first in languages like Java that don't have an implicit conversion from integral types to boolean. The exact equivalent of the first check in those languages is (bitmask & flag) != 0 and that form is probably also more canonical even for checking a single flag.

In terms of actual generated code it's mostly all academic.

For known-at-compile-time2 flags where the compiler can see that the flag only has one bit, both forms will generally be compiled to identical code - see the fixedA and fixedB functions in that link.

For functions with unknown flags, the forms aren't equivalent, as mentioned, so the code is different (see the unknownA and B functions) but the performance difference is very minor.

1 Or, equivalently, (bitmask & flag) != 0 in languages that don't have an implicit conversion from integer types to boolean.

2 Importantly, this includes functions that accept variable flags but where the caller is using a constant flag and the function is inlined.

ContentLicense: CC BY-SA 3.0

Body:
As a follow-up to "How to use bitmask": When I want to test if a certain flag is set in a given bitmask, I would usually do so solely through the usage of a bitwise AND:

if(bitmask & flag) { …

Yet I frequently see something like this:

if((bitmask & flag) == flag) { …

This is something I observed on both, strongly and weakly typed languages, which is ruling out some sort of prevention for type-casting disasters. The only scenario I can come up with in which the two tests were not equivalent were if flag happens to have actually more than one bit set and all of those are required to be set in bitmask for the condition to pass. Is that all or am I missing something here?

Bonus: Do compilers have means to recognize a flag that will have at most one bit set during runtime and optimize the (possibly bogus) comparison away?


问:
google-container access the ui panel
I'm following a course where the teacher connects to google container ui panel by accessing https://ip-of-container/ui he is then asked for password and username.

In my case what I see is :

```<code>User "system:anonymous" cannot get  at the cluster scope.: "No policy matched.\nUnknown user \"system:anonymous\""
</code>```

This issue on github says this:

A better way to access the UI via the API is to run kubectl proxy and
  access http://localhost:8001/ui

I don't understand what he is trying to say. Is localhost a placeholder for the machine endpoint ip ? How could it connect to my localhost since I have no server running ?

I did run kubectl proxy then,

try to access http(s)://container-endpoint-ip:8001/ui

literally http://localhost:8001/ui

None of those work.

答: I was running the command on the website's console. That's why it made no sens to me that it said to connect to localhost. Tbh it's ambiguous, I only used the console on the website so far and forgot I could do things directly on my local machine..

Title: google-container access the ui panel

Body:
I'm following a course where the teacher connects to google container ui panel by accessing https://ip-of-container/ui he is then asked for password and username.

In my case what I see is :

User "system:anonymous" cannot get  at the cluster scope.: "No policy matched.\nUnknown user \"system:anonymous\""

This issue on github says this:

A better way to access the UI via the API is to run kubectl proxy and
  access http://localhost:8001/ui

I don't understand what he is trying to say. Is localhost a placeholder for the machine endpoint ip ? How could it connect to my localhost since I have no server running ?

I did run kubectl proxy then,

try to access http(s)://container-endpoint-ip:8001/ui

literally http://localhost:8001/ui

None of those work.


问:
Node.js file to run a local server with access-control-allow-origin
I have an html file that has resources in it's directory

(example file tree)

```<code>index.html
imgs
  >img1.jpg
  >img2.jpg
  >img3.jpg
js
  >js1.js
  >js2.js
</code>```

How do I run a node.js server that will allow me to view the HTML file, as well as allow me to access certain websites with the access-control-allow-origin *

I am unfamiliar with node, so the simpler, the better!

Extra: does not necessarily have to be node, just a server that will allow access control

答:
Since You're learning and starting from scratch so it's preferred to learn how it's done than installing supper-pupper swiss knife toolset that will hide the logic from You and make You boring lazy developer.

If You just want to achieve quick result and don't want to learn - You may use serve package that will do what You need.

But if You're learning nodejs from zero to hero so read my answer.

It's better to do simple things.

Let's go (:

Create some folder and inside of it do following commands in terminal (or cmd in windows os):

1) Init app:

```<code>npm init
</code>```

2) Install express module:

```<code>npm i --save express
</code>```

3) Install cors module/middleware:

```<code>npm i --save cors
</code>```

4) Create public folder and put Your html files there

5) Create app.js file in sibling folder with public:

```<code>"use strict";

const
  express = require('express'),
  app = express(),
  cors = require('cors');

app.use(cors()); // attach cors middleware (must be set before of most route handlers to populate appropriate headers to response context)
app.use('/', express.static('public'));
app.listen(8080, () => console.log('APP STARTED'));
</code>```

6) Run it: node app.js

7) Open in browser: http://127.0.0.1:8080

for more stuff search in YouTube for nodejs express tutorials, nodejs mean stack tutorials and etc. (:

Body:
I have an html file that has resources in it's directory

(example file tree)

index.html
imgs
  >img1.jpg
  >img2.jpg
  >img3.jpg
js
  >js1.js
  >js2.js

How do I run a node.js server that will allow me to view the HTML file, as well as allow me to access certain websites with the access-control-allow-origin *

I am unfamiliar with node, so the simpler, the better!

Extra: does not necessarily have to be node, just a server that will allow access control

Body:
Since You're learning and starting from scratch so it's preferred to learn how it's done than installing supper-pupper swiss knife toolset that will hide the logic from You and make You boring lazy developer.

If You just want to achieve quick result and don't want to learn - You may use serve package that will do what You need.

But if You're learning nodejs from zero to hero so read my answer.

It's better to do simple things.

Let's go (:

Create some folder and inside of it do following commands in terminal (or cmd in windows os):

1) Init app:

npm init

2) Install express module:

npm i --save express

3) Install cors module/middleware:

npm i --save cors

4) Create public folder and put Your html files there

5) Create app.js file in sibling folder with public:

"use strict";

const
  express = require('express'),
  app = express(),
  cors = require('cors');

app.use(cors()); // attach cors middleware (must be set before of most route handlers to populate appropriate headers to response context)
app.use('/', express.static('public'));
app.listen(8080, () => console.log('APP STARTED'));

6) Run it: node app.js

7) Open in browser: http://127.0.0.1:8080

for more stuff search in YouTube for nodejs express tutorials, nodejs mean stack tutorials and etc. (:


问:
Can Math.Round in C# be used for whole integer values?
I have integer 363 for example.

Any method to make it 360 or 365?

答:
This is a hack, but it works:</p>

```<code>var rounded = Math.Round(363 / 5f) * 5;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This is a hack, but it works:

var rounded = Math.Round(363 / 5f) * 5;


问:
Angular 2: Smart component passing in data to Presentation component
I have set up where I have a smart component that ngOnInit uses a service to call out to a Rest API to fetch an object of data.

That data is passed into the presentation (child) component through an @Input() property.

In the presentation component, I need to repack the data into a bit of a different model so that it fits into the 3rd party component I am using for presentation.

I am not 100% how to deal with that fact that in the ngOnInit of the presentatioin component, the passed in @Input property is still undefined. Since the actual data is a Rest API call, the parent (smart) component will only get it in the subscribe's observer, i.e., asynchronously.

How do I hook this up together such that I am not trying to manipulate an undefined object, but wait until it's actually there in the presentation component?

I guess, I can always link the presentation component to the smart parent component through @ViewChild and then introduce a public method on the presentation component like showData(data), but I am wondering what the best practice is here.

答:
There is actually quite some answers online for this already. Have a look at https://scotch.io/tutorials/3-ways-to-pass-async-data-to-angular-2-child-components

I reviewed your case and although it's hard to understand without knowing exactly what you do. I solved this by initializing my variable in the Smart Component:

```<code>private apiData: Array = [];
</code>```

Using *ngIf in my template, and then repacking the data in the child if I have the data:

```<code>@Input('apiData') apiData: <any>;

ngOnInit(): void {
    this.repack();
}

repack(): void {
    // here is the part that prevents errors
    if(! this.apiData) return;

    // repack logic here
}
</code>```

However @ThinkingMedia answer is likely the more correct one in your case.

Body:
There is actually quite some answers online for this already. Have a look at https://scotch.io/tutorials/3-ways-to-pass-async-data-to-angular-2-child-components

I reviewed your case and although it's hard to understand without knowing exactly what you do. I solved this by initializing my variable in the Smart Component:

private apiData: Array = [];

Using *ngIf in my template, and then repacking the data in the child if I have the data:

@Input('apiData') apiData: <any>;

ngOnInit(): void {
    this.repack();
}

repack(): void {
    // here is the part that prevents errors
    if(! this.apiData) return;

    // repack logic here
}

However @ThinkingMedia answer is likely the more correct one in your case.


问:
Visual Studio 2015 Xamarin iOS menu disabled
I loaded Visual Studio Professional 2015
Version 14.0.25123.00 Update 2
Xamarin   4.0.3.214 (0dd817c)
Xamarin.Android   6.0.3.5 (a94a03b)
Xamarin.iOS   9.6.1.8 (3a25bf1)

However, when I bring up Visual Studio, the Tools/iOS menus items are disabled.  The Android menu items ARE enabled.

答:
I got the same issue. When I installed Visual Studio 2017, first thing I did was to download an existing Xamarin project. When I checked the 'iOS' menu item in Tools it was all disabled.

After a restart of the system, I tried to create a new Cross Platform App (Xamarin). Once the solution is created, I got the following message and the iOS menu has Mac Agent option enabled.


问:
session data for mvc login with angular 2 app
We have an MVC login site that loads an angular 4 app once successfully logged in.  We are using mvc controllers, which have a session manager that holds user data.  What's the best way for my angular 2 app to get and hold this data?  Currently I have a global service with UserId and UserStatus.  The UserStatus is needed to control access to parts of the site, which includes hiding or showing some of the navigation menu links.

The problem is that the calls are not completed before the page renders, so the menu doesn't get updated and the site's home page shows all controls.  If I click to another page then come back the site's home page is correctly hiding parts based on the user's status.  I created a simple plnkr that seems to simulate it.  https://plnkr.co/edit/NHgoMi?p=preview

I added a setTimeout variable to to simulate the delay of getting data from the server.  Notice that the one with the setTimeout has not completed before the page loads, so it displays the wrong value.

Is there a way to delay the app loading or the home component from rendering till the permissions are retrieved from the server?

here are the plnkr files:

main.ts:

```<code>    import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
    import {AppModule} from './app';

    import { SessionService } from './session.service';

    platformBrowserDynamic().bootstrapModule(AppModule, [SessionService])
</code>```

app.ts

```<code>    import {Component, NgModule, VERSION} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'

    import {SessionService } from './session.service';

    import { LayoutModule } from './layout.module';

    @Component({
      selector: 'my-app',
      template: `
        <div>
          <h2>Hello {{name}}</h2>
          <layout></layout>
        </div>
      `,
      providers:[
        SessionService
      ]
    })
    export class App {
      name:string;
      constructor() {
        this.name = `Angular! v${VERSION.full}`
      }
    }

    @NgModule({
      imports: [
        BrowserModule,
        LayoutModule
        ],
      declarations: [ App ],
      bootstrap: [ App ]
    })
    export class AppModule {}
</code>```

home.componenet.ts

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

    import { SessionService } from './session.service';

    @Component({
        selector: 'home',
        template: '<p>userStatus: {{userStatus}}</p><p>userStatusWithTimeout: {{userStatusWithTimeout}}</p>'
    })

    export class HomeComponent implements OnInit {

        userStatus: boolean;
        userStatusWithTimeout: boolean;

        constructor(private _sessionService: SessionService) {
        }

        ngOnInit(): void {
            this.userStatus = this._sessionService.getUserStatus();

            this.userStatusWithTimeout = this._sessionService.getUserStatusWithTimeout();
        }
    }
</code>```

layout.componenet.ts

```<code>    import { Component } from '@angular/core';
    import { NgControl } from '@angular/forms';

    @Component({
        selector: 'layout',
        template: '<home></home>'
    })

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

layout.module.ts

```<code>    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';

    //components
    import { HomeComponent } from './home.component';
    import { LayoutComponent } from './layout.component';

    @NgModule({
        imports: [
            BrowserModule
        ],
        declarations:
        [
            HomeComponent,
            LayoutComponent
        ],
        exports: [
            LayoutComponent,
            HomeComponent
        ],
        providers: [
        ]
    })

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

session.service.ts

```<code>    import { Injectable } from '@angular/core';
    import { Http, Response } from '@angular/http';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/Rx';

    @Injectable()
    export class SessionService { // extends ServiceAdapter {

        private _userStatus: boolean = false;
        private _userStatusWithTimeout: boolean = false;
        private _userID: number;
        private _getSessionUserID = 'Session/GetSessionUserID';
        private _getIsSessionUserStatus = 'Session/GetIsSessionUserStatus';

        constructor() {

            this.setSessionVariables();
        }

        setSessionVariables() {

            this.loadUserID()
                .do(data => console.log("loading id: ", data))
                .subscribe(result => this._userID = result);

            this.loadUserStatus()
                .do(data => console.log("loading status: ", data))
                .subscribe(result => this._userStatus = result);

            this.loadUserStatusWithTimeout()
                .do(data => console.log("loading status with timeout: ", data))
                .subscribe(result => this._userStatusWithTimeout = result);
        }

        loadUserID(): Observable<number> {
            return  Observable.of(setTimeout(() => { 1 }, 1000))  // this.getaction<number>(this._getSessionUserID);
        }

        loadUserStatus(): Observable<boolean> {
            return Observable.of(true)   //this.getaction<number>(this._getIsSessionUserStatus);
        }

        loadUserStatusWithTimeout(): Observable<boolean> {
          console.log("setting temp", this._userStatusWithTimeout);
          setTimeout(() => { this._userStatusWithTimeout = true }, 1000)
          console.log("temp is set", this._userStatusWithTimeout);

            return Observable.of(this._userStatusWithTimeout)   //this.getaction<number>(this._getIsSessionUserStatus);
        }

        getUserID(): number {
            return this._userID;
        }

        getUserStatus(): boolean {
            return this._userStatus;
        }

        getUserStatusWithTimeout(): boolean {
            return this._userStatusWithTimeout;
        }
    }
</code>```

答:
Rather than hiding the restricted UI once you fetch the session data, reveal the restricted UI once you can verify the user should see it. This will prevent controls that a user shouldn't see from flashing and disappearing. If this creates some jank when new elements appear, consider a loading state that designs around it.

The most basic implementation of a loading state in Angular is to set an isLoading flag to true on a component or service when the request starts, then false when it finishes. Then put an *ngIf='service.isLoading' on an element in your template and voila.
Here's a bare-bones example of one I made for a pagination service: service / template / result.

Also, if you are serving your Angular application with your MVC framework, it's possible to embed your permissions as a JavaScript object in the window of Angular's index page to make them immediately available to your app's permission/session service. This will avoid any loading delay while you fetch permissions, but will take additional configuration to get your server code working in the Angular launch page.

Body:
We have an MVC login site that loads an angular 4 app once successfully logged in.  We are using mvc controllers, which have a session manager that holds user data.  What's the best way for my angular 2 app to get and hold this data?  Currently I have a global service with UserId and UserStatus.  The UserStatus is needed to control access to parts of the site, which includes hiding or showing some of the navigation menu links.

The problem is that the calls are not completed before the page renders, so the menu doesn't get updated and the site's home page shows all controls.  If I click to another page then come back the site's home page is correctly hiding parts based on the user's status.  I created a simple plnkr that seems to simulate it.  https://plnkr.co/edit/NHgoMi?p=preview

I added a setTimeout variable to to simulate the delay of getting data from the server.  Notice that the one with the setTimeout has not completed before the page loads, so it displays the wrong value.

Is there a way to delay the app loading or the home component from rendering till the permissions are retrieved from the server?

here are the plnkr files:

main.ts:

    import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
    import {AppModule} from './app';

    import { SessionService } from './session.service';

    platformBrowserDynamic().bootstrapModule(AppModule, [SessionService])

app.ts

    import {Component, NgModule, VERSION} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'

    import {SessionService } from './session.service';

    import { LayoutModule } from './layout.module';

    @Component({
      selector: 'my-app',
      template: `

Hello {{name}}

          <layout></layout>

      `,
      providers:[
        SessionService
      ]
    })
    export class App {
      name:string;
      constructor() {
        this.name = `Angular! v${VERSION.full}`
      }
    }

    @NgModule({
      imports: [
        BrowserModule,
        LayoutModule
        ],
      declarations: [ App ],
      bootstrap: [ App ]
    })
    export class AppModule {}

home.componenet.ts

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

    import { SessionService } from './session.service';

    @Component({
        selector: 'home',
        template: '
userStatus: {{userStatus}}

userStatusWithTimeout: {{userStatusWithTimeout}}
'
    })

    export class HomeComponent implements OnInit {

        userStatus: boolean;
        userStatusWithTimeout: boolean;

        constructor(private _sessionService: SessionService) {
        }

        ngOnInit(): void {
            this.userStatus = this._sessionService.getUserStatus();

            this.userStatusWithTimeout = this._sessionService.getUserStatusWithTimeout();
        }
    }

layout.componenet.ts

    import { Component } from '@angular/core';
    import { NgControl } from '@angular/forms';

    @Component({
        selector: 'layout',
        template: '<home></home>'
    })

    export class LayoutComponent {}

layout.module.ts

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';

    //components
    import { HomeComponent } from './home.component';
    import { LayoutComponent } from './layout.component';

    @NgModule({
        imports: [
            BrowserModule
        ],
        declarations:
        [
            HomeComponent,
            LayoutComponent
        ],
        exports: [
            LayoutComponent,
            HomeComponent
        ],
        providers: [
        ]
    })

    export class LayoutModule {}

session.service.ts

    import { Injectable } from '@angular/core';
    import { Http, Response } from '@angular/http';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/Rx';

    @Injectable()
    export class SessionService { // extends ServiceAdapter {

        private _userStatus: boolean = false;
        private _userStatusWithTimeout: boolean = false;
        private _userID: number;
        private _getSessionUserID = 'Session/GetSessionUserID';
        private _getIsSessionUserStatus = 'Session/GetIsSessionUserStatus';

        constructor() {

            this.setSessionVariables();
        }

        setSessionVariables() {

            this.loadUserID()
                .do(data => console.log("loading id: ", data))
                .subscribe(result => this._userID = result);

            this.loadUserStatus()
                .do(data => console.log("loading status: ", data))
                .subscribe(result => this._userStatus = result);

            this.loadUserStatusWithTimeout()
                .do(data => console.log("loading status with timeout: ", data))
                .subscribe(result => this._userStatusWithTimeout = result);
        }

        loadUserID(): Observable<number> {
            return  Observable.of(setTimeout(() => { 1 }, 1000))  // this.getaction<number>(this._getSessionUserID);
        }

        loadUserStatus(): Observable<boolean> {
            return Observable.of(true)   //this.getaction<number>(this._getIsSessionUserStatus);
        }

        loadUserStatusWithTimeout(): Observable<boolean> {
          console.log("setting temp", this._userStatusWithTimeout);
          setTimeout(() => { this._userStatusWithTimeout = true }, 1000)
          console.log("temp is set", this._userStatusWithTimeout);

            return Observable.of(this._userStatusWithTimeout)   //this.getaction<number>(this._getIsSessionUserStatus);
        }

        getUserID(): number {
            return this._userID;
        }

        getUserStatus(): boolean {
            return this._userStatus;
        }

        getUserStatusWithTimeout(): boolean {
            return this._userStatusWithTimeout;
        }
    }


问:
app not installed error on android in kotlin gradle 3.0.0-alpha5
```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "//"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

and project level

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

actually before i'm using 2.3 gradle at that time there is no error now i changed to 3.0.0-alphs-5 app not installing error.  i do appreciate if u solve this error . is it  kotlin error or anything different i cant find the solution pls help me(this is happening only  while i'm sharing  not by debugging through studio)

答: check your manifest if your MainActivity is duplicated.</p>

Body:
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "//"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

and project level

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

actually before i'm using 2.3 gradle at that time there is no error now i changed to 3.0.0-alphs-5 app not installing error.  i do appreciate if u solve this error . is it  kotlin error or anything different i cant find the solution pls help me(this is happening only  while i'm sharing  not by debugging through studio)


问:
Unexpected caret reposition in Android Chrome
As I was reinventing the wheel for fun and profit, I isolated an interesting behavior that appears to only occur in Android Chrome.

I am formatting a text input as the user types, which means setting the input value, losing the caret position. No problem - just track the caret position, and set it back after you change the value (adjusting for added/removed characters) in the input event callback.

Works great! Except for Android Chrome (Android 7, Chrome 58.0.3029.83) - I set the caret position, observe the caret position where I expect - then on keyup event it is magically moved - after input event but before keyup event.

Tracking caret positions

You can see this for yourself in this (exceedingly simplified) fiddle. I even output the relevant data on screen so you don't have to hook up a debugger to see it.

Type "abcd" and get:

Numbers are caret positions from this.selectionStart

D = keyDown, I = Input, C = position Changed to, U = keyUp

```<code>D: 0 | I: 0 | C: 1 | U: 1
D: 1 | I: 1 | C: 2 | U: 2
D: 2 | I: 2 | C: 3 | U: 3
D: 3 | I: 3 | C: 5 | U: 4 //<- This 4 is the culprit
</code>```

Where every other browser tested (IE11, iOS Safari, Desktop Chrome) gives you:

```<code>D: 0 | I: 1 | C: 1 | U: 1
D: 1 | I: 2 | C: 2 | U: 2
D: 2 | I: 3 | C: 3 | U: 3
D: 3 | I: 4 | C: 5 | U: 5
</code>```

Is there an event in there I'm missing? It's not in the docs that I can find, though I know virtual keyboards get a little janky. I'd love to find out exactly where this is happening so I can nuke it.

Also tried

beforeinput, compositionstart, and compositionend events. The only one that is triggered is compositionstart, between the keydown and input events. It shows the caret position I would expect to see at that time.

Typing "abcd" then hitting backspace in Android Chrome gives you:

```<code>D: 4 | I: 3 | C: 5 | U: 5
</code>```

Seeming to indicate that whatever is moving the caret did not do so in this case.

Not looking for a workaround. The workaround is to set the caret again in the keyup event. I'm asking to see if anyone knows a less-wrong answer.

答:
As you can see, typing on soft keyboards in Android Chrome doesn't update the caret position in the input event as PC Chrome does. This is pretty typical of web development; there's always one case where it just doesn't work the same way.

D: 0 | I: 0 | C: 1 | U: 1
```

Based on my own testing, the caret position is updated in input when pasting, but when typing it's only updated in keyup. This means if you copy a single letter and paste that repeatedly, when you get to the fourth paste your textbox formatting code will work as expected (and as it does on PC).

This also means that if you want your code to work reliably you'll need to keep track of whether the caret is updated in input, but also preemptively update it in input since keyup won't fire if you're pasting. This could be difficult, however, because keydown also doesn't fire when pasting so you won't know the previous caret position.

You say you're not looking for a workaround, but based on the edit to your post I suspect you now need one. I'm not sure what a good workaround would be. Possibly tracking caret position changes and storing them manually (maybe in a data attribute on the textbox) would be your best bet. The real difficulty comes from the fact that when pasting, you could be pasting an arbitrary number of characters so you can't just assume that if input is fired when keydown isn't, use currentCaretPosition - 1.

After a bit of experimentation, this is the workaround I came up with:

https://jsfiddle.net/smfaenvb/10/

It's not perfect, but it does make it work on Android Chrome the same way your original test code worked on PC Chrome.

Body:
As I was reinventing the wheel for fun and profit, I isolated an interesting behavior that appears to only occur in Android Chrome.

I am formatting a text input as the user types, which means setting the input value, losing the caret position. No problem - just track the caret position, and set it back after you change the value (adjusting for added/removed characters) in the input event callback.

Works great! Except for Android Chrome (Android 7, Chrome 58.0.3029.83) - I set the caret position, observe the caret position where I expect - then on keyup event it is magically moved - after input event but before keyup event.

Tracking caret positions

You can see this for yourself in this (exceedingly simplified) fiddle. I even output the relevant data on screen so you don't have to hook up a debugger to see it.

Type "abcd" and get:

Numbers are caret positions from this.selectionStart

D = keyDown, I = Input, C = position Changed to, U = keyUp

D: 0 | I: 0 | C: 1 | U: 1
D: 1 | I: 1 | C: 2 | U: 2
D: 2 | I: 2 | C: 3 | U: 3
D: 3 | I: 3 | C: 5 | U: 4 //<- This 4 is the culprit

Where every other browser tested (IE11, iOS Safari, Desktop Chrome) gives you:

D: 0 | I: 1 | C: 1 | U: 1
D: 1 | I: 2 | C: 2 | U: 2
D: 2 | I: 3 | C: 3 | U: 3
D: 3 | I: 4 | C: 5 | U: 5

Is there an event in there I'm missing? It's not in the docs that I can find, though I know virtual keyboards get a little janky. I'd love to find out exactly where this is happening so I can nuke it.

Also tried

beforeinput, compositionstart, and compositionend events. The only one that is triggered is compositionstart, between the keydown and input events. It shows the caret position I would expect to see at that time.

Typing "abcd" then hitting backspace in Android Chrome gives you:

D: 4 | I: 3 | C: 5 | U: 5

Seeming to indicate that whatever is moving the caret did not do so in this case.

Not looking for a workaround. The workaround is to set the caret again in the keyup event. I'm asking to see if anyone knows a less-wrong answer.

Body:
As you can see, typing on soft keyboards in Android Chrome doesn't update the caret position in the input event as PC Chrome does. This is pretty typical of web development; there's always one case where it just doesn't work the same way.

D: 0 | I: 0 | C: 1 | U: 1

Based on my own testing, the caret position is updated in input when pasting, but when typing it's only updated in keyup. This means if you copy a single letter and paste that repeatedly, when you get to the fourth paste your textbox formatting code will work as expected (and as it does on PC).

This also means that if you want your code to work reliably you'll need to keep track of whether the caret is updated in input, but also preemptively update it in input since keyup won't fire if you're pasting. This could be difficult, however, because keydown also doesn't fire when pasting so you won't know the previous caret position.

You say you're not looking for a workaround, but based on the edit to your post I suspect you now need one. I'm not sure what a good workaround would be. Possibly tracking caret position changes and storing them manually (maybe in a data attribute on the textbox) would be your best bet. The real difficulty comes from the fact that when pasting, you could be pasting an arbitrary number of characters so you can't just assume that if input is fired when keydown isn't, use currentCaretPosition - 1.

After a bit of experimentation, this is the workaround I came up with:

https://jsfiddle.net/smfaenvb/10/

It's not perfect, but it does make it work on Android Chrome the same way your original test code worked on PC Chrome.


问:
How to have ZeroMQ to timeout messages that are outbound queued, but haven't been sent within a set time?
I have an application running on a server which takes requests from a phone app and then load balances the request across worker servers. I'm trying to add a timeout in the case that messages on the main server that have been in the outbound queue for the length of the timeout are removed from the queue. More specifically, the application on the main server is written in golang and implements the Paranoid Pirate Pattern of load balancing. The code I currently have is:

```<code>import (
    "fmt"
    zmq "github.com/pebbe/zmq4"
    "time"
)

const (
    HEARTBEAT_LIVENESS = 3
    HEARTBEAT_INTERVAL = 1500 * time.Millisecond

    MESSAGE_READY     = "\001"
    MESSAGE_HEARTBEAT = "\002"
)

var (
    client *zmq.Socket
    backend *zmq.Socket
    frontend *zmq.Socket
    workerPoller *zmq.Poller
    brokerPoller *zmq.Poller
    workerQueue []Worker
)

type Worker struct {
    Id string
    Expire time.Time
}

type RequestWrapper {
    RequestToSend Request

}

func NewWorker(id string) Worker {
    return Worker{
        Id: id,
        Expire: time.Now().Add(HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS),
    }
}

func AddReadyWorker(workers []Worker, worker Worker) []Worker {
    fmt.Println(worker.Id, " joined")
    for i, w := range workers {
        if worker.Id == w.Id {
            if i == 0 {
                workers = workers[1:]
            } else if i == len(workers)-1 {
                workers = workers[:i]
            } else {
                workers = append(workers[:i], workers[i+1:]...)
            }
            break
        }
    }
    return append(workers, worker)
}

func PurgeInactiveWorkers() {
    now := time.Now()
    for i, worker := range workerQueue {
        if now.Before(worker.Expire) {
            workerQueue = workerQueue[i:]
            return
        }
    }

    workerQueue = workerQueue[0:0]
}

func LoadBalance() {
// Loop:
    heartbeat := time.Tick(HEARTBEAT_INTERVAL)
    for {
        var sockets []zmq.Polled

        // If you have available workers, poll on the both front and backend
        // If not poll on backend with infinite timeout
        if len(workerQueue) > 0 {
            sockets, _ = brokerPoller.Poll(HEARTBEAT_INTERVAL)
        } else {
            sockets, _ = workerPoller.Poll(HEARTBEAT_INTERVAL)
        }

        for _, socket := range sockets {
            switch socket.Socket {
                // backend is a router
                case backend:
                    workerId, _ := backend.Recv(0)
                    workerQueue = AddReadyWorker(workerQueue, NewWorker(workerId))
                    clientId, _ := backend.Recv(0)
                    if clientId != MESSAGE_READY && clientId != MESSAGE_HEARTBEAT {
                        route, _ := backend.Recv(0)
                        message, _ := backend.RecvBytes(0)

                        fmt.Println("Received response")
                        RouteResponse(route, message)

                        // frontend.Send(clientId, zmq.SNDMORE)
                        // frontend.Send("", zmq.SNDMORE)
                        // frontend.SendBytes(message, 0)
                    }
                // frontend is a dealer
                case frontend:
                    clientId, _ := frontend.Recv(0)
                    route, _ := frontend.Recv(0)
                    message, _ := frontend.RecvBytes(0)

                    backend.Send(workerQueue[0].Id, zmq.SNDMORE)
                    backend.Send(clientId, zmq.SNDMORE)
                    backend.Send(route, zmq.SNDMORE)
                    backend.SendBytes(message, 0)

                    workerQueue = workerQueue[1:]
            }
        }

        select {
            case <-heartbeat:
                for _, worker := range workerQueue {
                    backend.Send(worker.Id, zmq.SNDMORE)
                    backend.Send(MESSAGE_HEARTBEAT, 0)
                }
                break
            default:
        }

        PurgeInactiveWorkers()
    }
}
</code>```

If the backend sends a message, but it is not actually sent to a worker in some period of time, I want it to expire and not ever be sent. Is there a socket option that can accomplish this? If not, what would I have to do to accomplish this?

Two ways I think I can do this without socket options are:

1) Have the backend wrap the message in a wrapper and send to a golang queue and not through zeromq. The wrapper contains the time that the message was "sent". The backend concurrently pulls from the front of the golang queue one at a time and checks if the message is expired. If so, don't send, if not, send the message. I could have the backend add the message to the golang queue first and then truly send it out after in the same block of code. That way, I don't need a lock.

2) Send the wrapper message through zeromq to a retriever and the retriever checks if its expired and returns early. I don't like this because it seems like its bad for performance.

答: In the end, the solution was to add an expires-at property like @colini and @bazza mentioned, and to drop timed out messages from the queue after each heartbeat. However, doing so and satisfying all requirements of my application was proving to be more difficult than first glance, so I ended up using RabbitMQ, whose ttl-expires argument provided the desired functionality.</p>

Body:
I have an application running on a server which takes requests from a phone app and then load balances the request across worker servers. I'm trying to add a timeout in the case that messages on the main server that have been in the outbound queue for the length of the timeout are removed from the queue. More specifically, the application on the main server is written in golang and implements the Paranoid Pirate Pattern of load balancing. The code I currently have is:

import (
    "fmt"
    zmq "github.com/pebbe/zmq4"
    "time"
)

const (
    HEARTBEAT_LIVENESS = 3
    HEARTBEAT_INTERVAL = 1500 * time.Millisecond

    MESSAGE_READY     = "\001"
    MESSAGE_HEARTBEAT = "\002"
)

var (
    client *zmq.Socket
    backend *zmq.Socket
    frontend *zmq.Socket
    workerPoller *zmq.Poller
    brokerPoller *zmq.Poller
    workerQueue []Worker
)

type Worker struct {
    Id string
    Expire time.Time
}

type RequestWrapper {
    RequestToSend Request

}

func NewWorker(id string) Worker {
    return Worker{
        Id: id,
        Expire: time.Now().Add(HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS),
    }
}

func AddReadyWorker(workers []Worker, worker Worker) []Worker {
    fmt.Println(worker.Id, " joined")
    for i, w := range workers {
        if worker.Id == w.Id {
            if i == 0 {
                workers = workers[1:]
            } else if i == len(workers)-1 {
                workers = workers[:i]
            } else {
                workers = append(workers[:i], workers[i+1:]...)
            }
            break
        }
    }
    return append(workers, worker)
}

func PurgeInactiveWorkers() {
    now := time.Now()
    for i, worker := range workerQueue {
        if now.Before(worker.Expire) {
            workerQueue = workerQueue[i:]
            return
        }
    }

    workerQueue = workerQueue[0:0]
}

func LoadBalance() {
// Loop:
    heartbeat := time.Tick(HEARTBEAT_INTERVAL)
    for {
        var sockets []zmq.Polled

        // If you have available workers, poll on the both front and backend
        // If not poll on backend with infinite timeout
        if len(workerQueue) > 0 {
            sockets, _ = brokerPoller.Poll(HEARTBEAT_INTERVAL)
        } else {
            sockets, _ = workerPoller.Poll(HEARTBEAT_INTERVAL)
        }

        for _, socket := range sockets {
            switch socket.Socket {
                // backend is a router
                case backend:
                    workerId, _ := backend.Recv(0)
                    workerQueue = AddReadyWorker(workerQueue, NewWorker(workerId))
                    clientId, _ := backend.Recv(0)
                    if clientId != MESSAGE_READY && clientId != MESSAGE_HEARTBEAT {
                        route, _ := backend.Recv(0)
                        message, _ := backend.RecvBytes(0)

                        fmt.Println("Received response")
                        RouteResponse(route, message)

                        // frontend.Send(clientId, zmq.SNDMORE)
                        // frontend.Send("", zmq.SNDMORE)
                        // frontend.SendBytes(message, 0)
                    }
                // frontend is a dealer
                case frontend:
                    clientId, _ := frontend.Recv(0)
                    route, _ := frontend.Recv(0)
                    message, _ := frontend.RecvBytes(0)

                    backend.Send(workerQueue[0].Id, zmq.SNDMORE)
                    backend.Send(clientId, zmq.SNDMORE)
                    backend.Send(route, zmq.SNDMORE)
                    backend.SendBytes(message, 0)

                    workerQueue = workerQueue[1:]
            }
        }

        select {
            case <-heartbeat:
                for _, worker := range workerQueue {
                    backend.Send(worker.Id, zmq.SNDMORE)
                    backend.Send(MESSAGE_HEARTBEAT, 0)
                }
                break
            default:
        }

        PurgeInactiveWorkers()
    }
}

If the backend sends a message, but it is not actually sent to a worker in some period of time, I want it to expire and not ever be sent. Is there a socket option that can accomplish this? If not, what would I have to do to accomplish this?

Two ways I think I can do this without socket options are:

1) Have the backend wrap the message in a wrapper and send to a golang queue and not through zeromq. The wrapper contains the time that the message was "sent". The backend concurrently pulls from the front of the golang queue one at a time and checks if the message is expired. If so, don't send, if not, send the message. I could have the backend add the message to the golang queue first and then truly send it out after in the same block of code. That way, I don't need a lock.

2) Send the wrapper message through zeromq to a retriever and the retriever checks if its expired and returns early. I don't like this because it seems like its bad for performance.


问:
Split a name field in Oracle into First and Last Name
I've got a table with names in it, which looks like this:

```<code>Emp_ID     Emp_Name
0001       Jack Skelly
0002       Susan Ryan
</code>```

I need to produce something that looks like this:

```<code>Emp_ID    Emp_F_Name    Emp_L_Name
0001      Jack          Skelly
0002      Susan         Ryan
</code>```

I've come up with this to split the name:

```<code>SubStr(d.Name, 0, InStr(d.Name, ' ')-1) as FName,
SubStr(d.Name, InStr(d.Name, ' ')+1) as LName
</code>```

I've seen people suggest INSTR, I've seen people suggest regexp_instr and I've seen them suggest regexp_substr.  I'm still new to Oracle and I don't really understand either, or which (if either) of them is more efficient for the split I need to do.  Can someone tell me the best way to go about splitting this field?  Is the method I've used the best/most efficient for what I want to do?

答:
substr and instr are almost always faster/more efficient than regular expression functions.

INSTR is used to find the position of the space in the input string. SUBSTR is used to extract a substring from the input string. Search (google) the Oracle documentation for these functions - you will find detailed explanations and examples.

The bigger issue you will have with your problem is the business requirement - what do you do with names like "John Clayton Stuart", "Ali Abu Ahmad", or single-word like "Belphegor"?

The query below shows how easily you can solve the problem if all the names have the format "Firstname Lastname".

```<code>with
     input_table ( emp_id, emp_name ) as (
       select '0001', 'Jack Skelly' from dual union all
       select '0002', 'Susan Ryan'  from dual
     )
-- End of simulated input data (not part of the solution).
-- SQL query begins BELOW THIS LINE.
select emp_id, emp_name,
       substr(emp_name, 1, instr(emp_name, ' ') - 1) as first_name,
       substr(emp_name, instr(emp_name, ' ') + 1)    as last_name
from   input_table
;

EMP_ID EMP_NAME    FIRST_NAME  LAST_NAME
----   ----------- ----------- -----------
0001   Jack Skelly Jack        Skelly
0002   Susan Ryan  Susan       Ryan
</code>```

Body:
I've got a table with names in it, which looks like this:

Emp_ID     Emp_Name
0001       Jack Skelly
0002       Susan Ryan

I need to produce something that looks like this:

Emp_ID    Emp_F_Name    Emp_L_Name
0001      Jack          Skelly
0002      Susan         Ryan

I've come up with this to split the name:

SubStr(d.Name, 0, InStr(d.Name, ' ')-1) as FName,
SubStr(d.Name, InStr(d.Name, ' ')+1) as LName

I've seen people suggest INSTR, I've seen people suggest regexp_instr and I've seen them suggest regexp_substr.  I'm still new to Oracle and I don't really understand either, or which (if either) of them is more efficient for the split I need to do.  Can someone tell me the best way to go about splitting this field?  Is the method I've used the best/most efficient for what I want to do?

Body:
substr and instr are almost always faster/more efficient than regular expression functions.

INSTR is used to find the position of the space in the input string. SUBSTR is used to extract a substring from the input string. Search (google) the Oracle documentation for these functions - you will find detailed explanations and examples.

The bigger issue you will have with your problem is the business requirement - what do you do with names like "John Clayton Stuart", "Ali Abu Ahmad", or single-word like "Belphegor"?

The query below shows how easily you can solve the problem if all the names have the format "Firstname Lastname".

with
     input_table ( emp_id, emp_name ) as (
       select '0001', 'Jack Skelly' from dual union all
       select '0002', 'Susan Ryan'  from dual
     )
-- End of simulated input data (not part of the solution).
-- SQL query begins BELOW THIS LINE.
select emp_id, emp_name,
       substr(emp_name, 1, instr(emp_name, ' ') - 1) as first_name,
       substr(emp_name, instr(emp_name, ' ') + 1)    as last_name
from   input_table
;

EMP_ID EMP_NAME    FIRST_NAME  LAST_NAME
----   ----------- ----------- -----------
0001   Jack Skelly Jack        Skelly
0002   Susan Ryan  Susan       Ryan


问:
Semantic UI Segments

How to code this segment in Semantic UI? I tried using grids too, but it unfortunately didn't work out.

```<code><div class="ui horizontal segments">

            <div class="ui segment">
                <div class="two column row">
                    <div class="column">

                    </div>
                    <div class="column">

                    </div>
                </div>
            </div>
            <div class="ui segment">

            </div>
</div>
</code>```

答:
I think this Plunkr fits with what you're looking for

```<code><div class="ui grid">
    <!-- left part -->
    <div class="eight wide column">
        <div class="row"></div>
        <div class="row"></div>
        <div class="row"></div>
    </div>
    <!-- right part -->
    <div class="eight wide column"></div>
</div>
</code>```

Grid separated on two wide equal columns. On the right column, three rows, on the left column, your content.

Title: Semantic UI Segments

Body:
I think this Plunkr fits with what you're looking for

<div class="ui grid">
    <!-- left part -->
    <div class="eight wide column">
        <div class="row"></div>
        <div class="row"></div>
        <div class="row"></div>
    </div>
    <!-- right part -->
    <div class="eight wide column"></div>
</div>

Grid separated on two wide equal columns. On the right column, three rows, on the left column, your content.


问:
Subsampling an .hdf5 file with multiple datasets
I am trying to extract some "rows" from a big .h5 file, to create a smaller, sample file.

In order to make sure my sample looks like the original file, I am extracting rows at random.

```<code>#Get length of files and prepare samples
 source_file = h5py.File(args.data_path, "r")
 dataset = source_file['X']
 indices = np.sort(np.random.choice(dataset.shape[0],args.nb_rows))

#checking we're extracting a subsample
if args.nb_rows > dataset.shape[0]:
    raise ValueError("Can't extract more rows than dataset contains. Dataset has %s rows" % dataset.shape[0] )

target_file =  h5py.File(target, "w")
for k in source_file.keys():
    dataset = source_file[k]
    dataset = dataset[indices,:,:,:]
    dest_dataset = target_file.create_dataset(k, shape=(dataset.shape), dtype=np.float32)
dest_dataset.write_direct(dataset)
target_file.close()
source_file.close()
</code>```

However when nb_rows is by (like 10,000) I'm getting TypeError("Indexing elements must be in increasing order"). The indexes are sorted, so I think I should not get this error. Am I misunderstanding something?

答:
I think you are getting duplicates.

Obviously you'll get duplicates in the args.nb_rows > dataset.shape[0] case:

```<code>In [499]: np.random.choice(10, 20)
Out[499]: array([2, 4, 1, 5, 2, 8, 4, 3, 7, 0, 2, 6, 6, 8, 9, 3, 8, 4, 2, 5])
In [500]: np.sort(np.random.choice(10, 20))
Out[500]: array([1, 1, 1, 2, 2, 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, 8, 8, 9])
</code>```

But you can still get duplicates when the number is smaller:

```<code>In [502]: np.sort(np.random.choice(10, 9))
Out[502]: array([0, 0, 1, 1, 1, 5, 5, 9, 9])
</code>```

Turn off replace:

```<code>In [504]: np.sort(np.random.choice(10, 9, replace=False))
Out[504]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])
</code>```

Body:
I am trying to extract some "rows" from a big .h5 file, to create a smaller, sample file.

In order to make sure my sample looks like the original file, I am extracting rows at random.

#Get length of files and prepare samples
 source_file = h5py.File(args.data_path, "r")
 dataset = source_file['X']
 indices = np.sort(np.random.choice(dataset.shape[0],args.nb_rows))

#checking we're extracting a subsample
if args.nb_rows > dataset.shape[0]:
    raise ValueError("Can't extract more rows than dataset contains. Dataset has %s rows" % dataset.shape[0] )

target_file =  h5py.File(target, "w")
for k in source_file.keys():
    dataset = source_file[k]
    dataset = dataset[indices,:,:,:]
    dest_dataset = target_file.create_dataset(k, shape=(dataset.shape), dtype=np.float32)
dest_dataset.write_direct(dataset)
target_file.close()
source_file.close()

However when nb_rows is by (like 10,000) I'm getting TypeError("Indexing elements must be in increasing order"). The indexes are sorted, so I think I should not get this error. Am I misunderstanding something?

Body:
I think you are getting duplicates.

Obviously you'll get duplicates in the args.nb_rows > dataset.shape[0] case:

In [499]: np.random.choice(10, 20)
Out[499]: array([2, 4, 1, 5, 2, 8, 4, 3, 7, 0, 2, 6, 6, 8, 9, 3, 8, 4, 2, 5])
In [500]: np.sort(np.random.choice(10, 20))
Out[500]: array([1, 1, 1, 2, 2, 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, 8, 8, 9])

But you can still get duplicates when the number is smaller:

In [502]: np.sort(np.random.choice(10, 9))
Out[502]: array([0, 0, 1, 1, 1, 5, 5, 9, 9])

Turn off replace:

In [504]: np.sort(np.random.choice(10, 9, replace=False))
Out[504]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])


问:
gradient background not working in Chrome with -webkit-gradient
Greetings all,

I'm using a gradient background with -webkit-gradient. It's not working on Chrome 8.0.552.224 on Windows 7, but I could swear it was recently working on Chrome-OS X.  It's Monday so perhaps I'm missing something obvious, but if so I can't figure it out.  I'd appreciate your taking a look.  The sample code here will work on Firefox but doesn't display a gradient in Chrome:

Thanks,
-Northk

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <title>Gradient test </title>
    <style>
        .main-header
        {
            padding-top: 50px;
            min-height: 50px;
            background: -webkit-gradient(linear, 0%, 0%, 0%, 100%, from(#fff), to(#000));
            background: -moz-linear-gradient(top, #fff, #000);
            border: 1px solid #000;
        }
    </style>
</head>
<body>
    <div class="main-header">
        THIS WORKS ON FIREFOX BUT DOESN'T WORK ON CHROME-WINDOWS 7!
    </div>
</body>
</html>
</code>```

答:
Seems I just got the syntax wrong.  Here's how it should be:</p>

```<code>   background: -webkit-gradient(linear, center top, center bottom, from(#fff), to(#000));
</code>```

Body:
Greetings all,

I'm using a gradient background with -webkit-gradient. It's not working on Chrome 8.0.552.224 on Windows 7, but I could swear it was recently working on Chrome-OS X.  It's Monday so perhaps I'm missing something obvious, but if so I can't figure it out.  I'd appreciate your taking a look.  The sample code here will work on Firefox but doesn't display a gradient in Chrome:

Thanks,
-Northk

<!DOCTYPE html>

    <title>Gradient test </title>

        THIS WORKS ON FIREFOX BUT DOESN'T WORK ON CHROME-WINDOWS 7!

Body:
Seems I just got the syntax wrong.  Here's how it should be:

   background: -webkit-gradient(linear, center top, center bottom, from(#fff), to(#000));


问:
C# string array from JSON
I'm currently using Newtonsoft's json library to deserialize json from a file.

JSON:

```<code>{
"name":"test",
"description":"test",
"tags":"Maps"
}
</code>```

C#:

```<code>public class RootObject
{
    public string name { get; set; }
    public string tag { get; set; }
    public string description { get; set; }
    public string[] tags { get; set; }
}
</code>```

The "tags" has to be an array as it is required for steam.

How can I retrieve the "tags" as an string array?
The console prints out this expection:

```<code>Newtonsoft.Json.JsonSerializationException: Error converting value "Maps" to type 'System.String[]'. Path 'tags', line 4, position 17
</code>```

答: Your json property "tags" doesn't contain an array, but just a string. Change "Maps" to ["Maps"].

Title: C# string array from JSON

Body:
I'm currently using Newtonsoft's json library to deserialize json from a file.

JSON:

{
"name":"test",
"description":"test",
"tags":"Maps"
}

C#:

public class RootObject
{
    public string name { get; set; }
    public string tag { get; set; }
    public string description { get; set; }
    public string[] tags { get; set; }
}

The "tags" has to be an array as it is required for steam.

How can I retrieve the "tags" as an string array?
The console prints out this expection:

Newtonsoft.Json.JsonSerializationException: Error converting value "Maps" to type 'System.String[]'. Path 'tags', line 4, position 17


问:
Realign buttons

JavaScript

```<code>$(function(){
  $('.select-another-button').each(function(){
    $(this).bind('click', function(e) {
      $(this).attr('disabled','true'); //disables the button
      $('#overlay').show(); //after disabling show the overlay for hover
      setTimeout(function(){
        $(this).attr('disabled','false'); //enables after 5mins
        $('#overlay').hide(); //hide the overlay
      }, 300000);
      e.preventDefault();
      fileBrowser(this);
      return false;
    });
  });
});

$("#overlay").hover(function(){
    $('#message').show();
},function(){
    $('#message').hide();
});
</code>```

HTML

```<code><div class="card-title">
    <div class="title-actions">

        <a href="#" id="id_select_request_document" title="Select file(s)" class="btn btn-icon select-button"
                data-turbolinks="false" data-save-label="Ok" data-close-label="Cancel" data-copy-to="9"
                data-reload="true" data-url="/documents/select/8/">
            <i class="material-icons">folder</i>
        </a>

        <a href="#" id="id_upload_request_document" title="Upload file(s)" class="btn btn-icon upload-button"
                data-turbolinks="false" data-url="/documents/upload/9/"
                data-complete-post="/requests/validate-requirements/2/" data-max-uploader-connections="1"
                style="position: relative; overflow: visible; direction: ltr;">
            <i class="material-icons">cloud_upload</i>
            <i style="overflow: hidden;display: block;position: absolute;top: 0;left: 0;width: 35px;height: 35px;"><input
                        multiple="multiple" type="file" name="file"
                        style="position: absolute; right: 0px; top: 0px; font-family: Arial; font-size: 118px; margin: 0px; padding: 0px; cursor: pointer; opacity: 0;"></i>
        </a>
        <div class="wrapper">
            <div id="overlay"></div>
            <a href="#" title="Send email - rejected file(s)" class="btn btn-icon select-another-button"
                    data-url="/messaging/send/2/">
                <i class="material-icons">assignment_late</i>
                <div class="alert alert-success" id="send-message" style="display: none;">
                    <p>
                        The message was sent to the client. Please wait 5 minutes <br> before sending the message again.
                    </p>
                </div>
            </a>
        </div>

        <a href="/admin/filer/folder/9/list/" class="btn-icon"><i class="material-icons">settings</i></a>

    </div>
    <h5>Request documents</h5>
</div>
</code>```

 CSS

```<code>.title-actions {
    float: right;
    height: 50px;
    margin-top: 13px;
}

.title-actions a {
    transition: background 0.3s ease;
}

.title-actions a.btn {
    padding: 2px 14px;
    line-height: 26px;
    max-height: 28px;
    position: relative;
    top: -1px;
    margin-left: 8px;
}

.title-actions a:hover {
    background: #4382B5;
}

.title-actions span {
    color: #444;
    background: #E6E6E6;
    padding: 6px 10px;
    border-radius: 3px;
    float: none;
    position: relative;
    margin-left: 6px;
}

.title-actions .btn {
    padding: 2px 14px;
    line-height: 26px;
    max-height: 28px;
    position: relative;
    top: -1px;
    margin-left: 8px;
}

.title-actions .btn-icon {
    background: transparent;
    position: relative;
    color: #3E5366;
    text-align: center;
    display: inline-block;
    padding: 0 !important;
    transition: color 0.3s ease;
    box-shadow: none !important;
    margin-top: -16px;
    margin-left: 6px;
}

.title-actions .btn-icon i {
    font-size: 35px;
    line-height: 20px;
    position: relative;
    top: 12px;
}

.title-actions .btn-icon:hover {
    color: #4382B5;
    background: transparent;
}

.title-actions .badge .material-icons {
    font-size: 1.2em;
    line-height: 0;
    position: relative;
    top: 4px;
}
</code>```

In the html block, I added the

```<code><div class="wrapper">
            <div id="overlay"></div>
            <a href="#"
               title="{% trans "Send email - rejected file(s)" %}"
               class="btn btn-icon select-another-button"
               data-url="{% url "messaging:send" request_id=object.pk %}">
                <i class="material-icons">assignment_late</i>
                <div class='alert alert-success' id='send-message' style="display: none;">
                    <p>
                    The message was sent to the client. Please wait 5 minutes <br> before sending the message again.
                    </p>
                </div>
            </a>
        </div>
</code>```

In fact, I didn't add everything. I just did add the first two div tags, and I got a little issue with the different button from this code. It changed the old line of  to the new line of , but I don't even know how to fix it. How could I modify my code to bring back two the old line of buttons? I think I could style with css, but I can't say how because I don't have a lot of experience with it.

答:
This may be a slightly odd answer to your question.  Assuming you wanted them into groups on the top rightith your 4 icons.  (Given i dont have full entirely experience with the mobile-html platform)  Here is a javascript you can use to eliminate odd issues:</p>

```<code>//this var is short and clean coded to help diagnose some issues
//for this example, you can store values as an array
//these arrays with your content will be used to make cloned sections
//with different icons
var
    icon = ["folder", "cloud", "case", "settings"],
    imgbg = ["folder.jpg", "cloud.jpg", "case.jpg", "setting.jpg"],
    frame = ""
;

for (i = 0; i < icon.length; i++) {
    frame += "<div class='" +
             icon[i] +
             "'style='background-image:url(assets/" +
             imgbg[i] +
             ");'></div>"
    ;
    //which creates the code below as cloning
    //"<div class="icon[i]" style="background-image:url(imgbg[i]);"></div>"
}

document.getElementById("demo").innerHTML = frame;
//this returns the clone code into a desired tml empty target like:
//<div id="demo"></div>
//then you can edit the css for float right as well as display top right
//to keep it at top right use this css
   .display-top-right{
       position:absolute;
       top:0;
       right:0;
       float:right;
       z-index:1;
   }
</code>```

Title: Realign buttons

Body:
JavaScript

$(function(){
  $('.select-another-button').each(function(){
    $(this).bind('click', function(e) {
      $(this).attr('disabled','true'); //disables the button
      $('#overlay').show(); //after disabling show the overlay for hover
      setTimeout(function(){
        $(this).attr('disabled','false'); //enables after 5mins
        $('#overlay').hide(); //hide the overlay
      }, 300000);
      e.preventDefault();
      fileBrowser(this);
      return false;
    });
  });
});

$("#overlay").hover(function(){
    $('#message').show();
},function(){
    $('#message').hide();
});

HTML

            folder

            cloud_upload
            <input
                        multiple="multiple" type="file" name="file"
                        style="position: absolute; right: 0px; top: 0px; font-family: Arial; font-size: 118px; margin: 0px; padding: 0px; cursor: pointer; opacity: 0;">

                assignment_late

                        The message was sent to the client. Please wait 5 minutes
 before sending the message again.

        settings

Request documents

 CSS

.title-actions {
    float: right;
    height: 50px;
    margin-top: 13px;
}

.title-actions a {
    transition: background 0.3s ease;
}

.title-actions a.btn {
    padding: 2px 14px;
    line-height: 26px;
    max-height: 28px;
    position: relative;
    top: -1px;
    margin-left: 8px;
}

.title-actions a:hover {
    background: #4382B5;
}

.title-actions span {
    color: #444;
    background: #E6E6E6;
    padding: 6px 10px;
    border-radius: 3px;
    float: none;
    position: relative;
    margin-left: 6px;
}

.title-actions .btn {
    padding: 2px 14px;
    line-height: 26px;
    max-height: 28px;
    position: relative;
    top: -1px;
    margin-left: 8px;
}

.title-actions .btn-icon {
    background: transparent;
    position: relative;
    color: #3E5366;
    text-align: center;
    display: inline-block;
    padding: 0 !important;
    transition: color 0.3s ease;
    box-shadow: none !important;
    margin-top: -16px;
    margin-left: 6px;
}

.title-actions .btn-icon i {
    font-size: 35px;
    line-height: 20px;
    position: relative;
    top: 12px;
}

.title-actions .btn-icon:hover {
    color: #4382B5;
    background: transparent;
}

.title-actions .badge .material-icons {
    font-size: 1.2em;
    line-height: 0;
    position: relative;
    top: 4px;
}

In the html block, I added the

                assignment_late

                    The message was sent to the client. Please wait 5 minutes
 before sending the message again.

In fact, I didn't add everything. I just did add the first two div tags, and I got a little issue with the different button from this code. It changed the old line of  to the new line of , but I don't even know how to fix it. How could I modify my code to bring back two the old line of buttons? I think I could style with css, but I can't say how because I don't have a lot of experience with it.

Body:
This may be a slightly odd answer to your question.  Assuming you wanted them into groups on the top rightith your 4 icons.  (Given i dont have full entirely experience with the mobile-html platform)  Here is a javascript you can use to eliminate odd issues:

//this var is short and clean coded to help diagnose some issues
//for this example, you can store values as an array
//these arrays with your content will be used to make cloned sections
//with different icons
var
    icon = ["folder", "cloud", "case", "settings"],
    imgbg = ["folder.jpg", "cloud.jpg", "case.jpg", "setting.jpg"],
    frame = ""
;

for (i = 0; i < icon.length; i++) {
    frame += "<div class='" +
             icon[i] +
             "'style='background-image:url(assets/" +
             imgbg[i] +
             ");'></div>"
    ;
    //which creates the code below as cloning
    //"<div class="icon[i]" style="background-image:url(imgbg[i]);"></div>"
}

document.getElementById("demo").innerHTML = frame;
//this returns the clone code into a desired tml empty target like:
//<div id="demo"></div>
//then you can edit the css for float right as well as display top right
//to keep it at top right use this css
   .display-top-right{
       position:absolute;
       top:0;
       right:0;
       float:right;
       z-index:1;
   }


问:
implicit value of Function2 is not the same as implicit[Function2]
I have the following two test cases:

TEST CASE 1：

```<code>  @Test
  def testImplicit1(): Unit = {
    class Person(val age: Int)
    val func: Person => Int = p => p.age
    implicit val x = func
    val y = implicitly((p: Person) => Int)
    println(func.hashCode())
    println(x.hashCode())
    println(y.hashCode())
  }
</code>```

x and func have the same hashcode, while y's hashcode is different with the other two.

TEST CASE 2:

```<code>  @Test
  def testImplicit2(): Unit = {
    class Person(val age: Int)
    implicit val p = new Person(10)
    val p2 = implicitly[Person]
    println(p.hashCode())
    println(p2.hashCode())

  }
</code>```

p and p2 have the same hash code

I would ask why y's hashcode is different with func and x's in TEST CASE 1

答:
implicitly is defined as:

```<code>def implicitly[T](implicit e: T): T = e
</code>```

What you are doing in test case 1 is explicitly passing in the value (not the type) for argument e as ((p: Person) => Int) which is a function that takes a Person as argument and returns the object Int. Then implicitly just returns that same value back to you.

What you want is:

```<code>val y = implicitly[Person => Int]
</code>```

Which will cause the scala compiler to fill in the argument value e with your implicit value x.

Body:
I have the following two test cases:

TEST CASE 1：

  @Test
  def testImplicit1(): Unit = {
    class Person(val age: Int)
    val func: Person => Int = p => p.age
    implicit val x = func
    val y = implicitly((p: Person) => Int)
    println(func.hashCode())
    println(x.hashCode())
    println(y.hashCode())
  }

x and func have the same hashcode, while y's hashcode is different with the other two.

TEST CASE 2:

  @Test
  def testImplicit2(): Unit = {
    class Person(val age: Int)
    implicit val p = new Person(10)
    val p2 = implicitly[Person]
    println(p.hashCode())
    println(p2.hashCode())

  }

p and p2 have the same hash code

I would ask why y's hashcode is different with func and x's in TEST CASE 1

Body:
implicitly is defined as:

def implicitly[T](implicit e: T): T = e

What you are doing in test case 1 is explicitly passing in the value (not the type) for argument e as ((p: Person) => Int) which is a function that takes a Person as argument and returns the object Int. Then implicitly just returns that same value back to you.

What you want is:

val y = implicitly[Person => Int]

Which will cause the scala compiler to fill in the argument value e with your implicit value x.


问:
Selecting array of strings with SwiftyJSON
I am parsing some JSON data using the Swift framework SwiftyJSON. Normally I can select an element such as domain from the sample JSON below by doing:

```<code>json["domain"].string!
</code>```

This works fine, however when selecting the gallery element, I am getting a response that it is nil when using json["gallery"].array

This appears to be an array of strings but perhaps there is something I am misunderstanding. How is it that I can select this element from the JSON sample?

```<code>{
    "id": 2450,
    "domain": "http://website.com",
    "gallery": [
        "image1",
        "image2",
        "image3"
    ],
}
</code>```

答:
You have to case your gallery as an array of String.</p>

```<code>let array = json["gallery"].arrayValue
dump(array)
</code>```

Body:
I am parsing some JSON data using the Swift framework SwiftyJSON. Normally I can select an element such as domain from the sample JSON below by doing:

json["domain"].string!

This works fine, however when selecting the gallery element, I am getting a response that it is nil when using json["gallery"].array

This appears to be an array of strings but perhaps there is something I am misunderstanding. How is it that I can select this element from the JSON sample?

{
    "id": 2450,
    "domain": "http://website.com",
    "gallery": [
        "image1",
        "image2",
        "image3"
    ],
}

Body:
You have to case your gallery as an array of String.

let array = json["gallery"].arrayValue
dump(array)


问:
How do stateless servers work?
I try to understand this.  Normally each time user login system, server side will create a session, while user client side there is cookie. When people talk about stateless serverside, stateful client side, what do they mean? server side no need use session keep track user? only use cookies on client side to check user? mean if I change server, user will not notice it and still can resume using the service?

How to configure spring-security to to do this?

答:
A stateless service is a service that does not store any data on the application server.  It reads or writes data to the database, returns a value (or not), and after that, any information on the task itself is forgotten.

A stateful service is used to perform transactions, that is a series of tasks that depend on the result of preceding tasks.  The easiest example is sending an order at a web store, where you gather your products in a shopping cart, and when you check out, you enter your account data on one page, store it, then enter your billing address, store it, then confirm your order and conclude the transaction.  Each step depends on the successful outcome of the preceding step, and data needs to be preserved until the last one of these steps is completed or the transaction is canceled, in which case there has to be a rollback to restore your account balance to the way it was before you checked out.

In most cases, you can implement transactions both ways, but if you were to use stateless services, your client application would have to take care of handling the proper order and completion of tasks, or you would have to find some other way to store the transaction information correctly and manage the rollbacks. That would be a stateful client-side, as you called it.

All of this is, however, quite general, and security and/or session handling would have to be considered in each of those cases.  You can very well use session information to authenticate stateless service calls - you will just have to authenticate each call individually, for example by attaching a session id or user id or some other security token to the business data.

Title: How do stateless servers work?


问:
element.select() doesn't work in Firefox
I have a test where I go to Google.com and run the following commands in the console:

```<code>test = document.querySelector('#lst-ib') //#lst-ib is the ID of Google's search bar
test.value = 'abcd'
test.select()
window.getSelection().toString() //expected return value of 'abcd'
</code>```

If I run this test in Chrome or Safari, I get the expected return value of 'abcd' - meaning the text in the input has been selected.

In FireFox, I get an empty string.

Does anyone have an explanation? I get the same behavior when I run this code on my own page from a script - not the console.

I'm testing on Firefox 54.01 and Chrome 59.0.3071.115

答:
This is a known bug for Firefox. 16 years and counting.

https://bugzilla.mozilla.org/show_bug.cgi?id=85686

Body:
I have a test where I go to Google.com and run the following commands in the console:

test = document.querySelector('#lst-ib') //#lst-ib is the ID of Google's search bar
test.value = 'abcd'
test.select()
window.getSelection().toString() //expected return value of 'abcd'

If I run this test in Chrome or Safari, I get the expected return value of 'abcd' - meaning the text in the input has been selected.

In FireFox, I get an empty string.

Does anyone have an explanation? I get the same behavior when I run this code on my own page from a script - not the console.

I'm testing on Firefox 54.01 and Chrome 59.0.3071.115


问:
c - passing argument 1 from incompatible pointer type
I have this code, very simple and it gives me the error on function max(), when I call it from the latest printf:

```<code>#include <stdio.h>

float max(float v[], int n){
  float maxim = v[0];
  for(int i = 0; i < n; i++){
    if(maxim < v[i]){
      maxim = v[i];
    }
  }
  return maxim;
}

void main(){
  int v[10], n;
  float x;

  for(int i = 0; i < 10; i++){
    printf("Introduza %d de 10 números: ", i+1);
    scanf(" %f", &x);
    v[i] = x;
  }

  printf("Indique o número de elementos que pretende avaliar: ");
  scanf(" %d", &n);

  printf("O maior valor introduzido entre os %d primeiros números foi %f", n, max(v,n));
}
</code>```

Text is in Portuguese, but that doesn't matter.
The error:

```<code>warning: passing argument 1 of ‘max’ from incompatible pointer type [-Wincompatible-pointer-types]
</code>```

I saw a few threads but I think this is different. Can somebody help me?

答:
Change this:

```<code>void main(){
  int v[10], n;
  float x;
</code>```

To:

```<code>void main(){
  float v[10];
  int n;
  float x;
</code>```

Body:
I have this code, very simple and it gives me the error on function max(), when I call it from the latest printf:

#include <stdio.h>

float max(float v[], int n){
  float maxim = v[0];
  for(int i = 0; i < n; i++){
    if(maxim < v[i]){
      maxim = v[i];
    }
  }
  return maxim;
}

void main(){
  int v[10], n;
  float x;

  for(int i = 0; i < 10; i++){
    printf("Introduza %d de 10 números: ", i+1);
    scanf(" %f", &x);
    v[i] = x;
  }

  printf("Indique o número de elementos que pretende avaliar: ");
  scanf(" %d", &n);

  printf("O maior valor introduzido entre os %d primeiros números foi %f", n, max(v,n));
}

Text is in Portuguese, but that doesn't matter.
The error:

warning: passing argument 1 of ‘max’ from incompatible pointer type [-Wincompatible-pointer-types]

I saw a few threads but I think this is different. Can somebody help me?

Body:
Change this:

void main(){
  int v[10], n;
  float x;

To:

void main(){
  float v[10];
  int n;
  float x;


问:
Changing App from Ionic to Native
Okay so 2 years ago I was just a web developer with no real knowledge about mobile app development so I decided to go with ionic when I was asked to develop the app.  2 years later I can now code in java and I've been asked to build a native version of the same app which I have done successfully.

Now this is my problem, it is time for my app to be released on the play store but I am unable to add a new update because the current version was signed with a different certificate than what I used with ionic 2 years ago.

Now I managed to locate my old ionic project with the .keystore file however I am unable to use it to sign my android app because I do not remember the alias neither do I remember the password.

So this is my question now, what do I do? Is there a way of recovering or changing the old alias and password? Is there a way for me to publish this new release as an update to the old one even though it is signed with a different certificate?

答: Unfortunately, no. Each Android app has an unique signing key, and when you publish the first APK to Google Play, the key hash is registered as a security mechanism: even if someone hacks your Google Play Developer Account and posts a new hacked APK, this APK won't be accepted unless it was signed with the same key as the first one published. Google Play refuses new APKs signed with different Keys.</p>

Title: Changing App from Ionic to Native


问:
Angular4 - How to detect if a response is JSON or plain text with observable
I'm wondering if there is a way to detect the format of a response in an observable, when using a generic api service to call a variety of endpoints. Some send back JSON, others plain text.</p>

```<code>this.http.get(endpoint).map(response => {
    // if JSON
    return response.json();
    // else if plain text
    return response.text();
})...
</code>```

答:
A ResponseContentType exists in the angular doc but I never found this enum in the response object so I use a "trick" :

```<code>this.http.get(endpoint).map(response => {
    const contentType = res.headers.get('Content-type');
   if (contentType == 'application/json') {
    return response.json();
   } else if (contentType == 'application/text') {
    return response.text();
   }
})...
</code>```

if someone know where we can find the ResponseContentType enum please told us !

Body:
I'm wondering if there is a way to detect the format of a response in an observable, when using a generic api service to call a variety of endpoints. Some send back JSON, others plain text.

this.http.get(endpoint).map(response => {
    // if JSON
    return response.json();
    // else if plain text
    return response.text();
})...

Body:
A ResponseContentType exists in the angular doc but I never found this enum in the response object so I use a "trick" :

this.http.get(endpoint).map(response => {
    const contentType = res.headers.get('Content-type');
   if (contentType == 'application/json') {
    return response.json();
   } else if (contentType == 'application/text') {
    return response.text();
   }
})...

if someone know where we can find the ResponseContentType enum please told us !