问:
Observable withLatestFrom value
I Implemented a pseudo-operator called "FilterByLatestFrom" as an extension function for kotlin.

I wrote the next code using this operator:

```<code>    fun testFilterByLatestFromOperator(){
    val observableA : Observable<Int> = Observable.fromArray(1,2,3,4,5,6,7,8,9,10)
    val observableC : PublishSubject<Int> = PublishSubject.create()
    val observableB : Observable<Int> = Observable.just(2).mergeWith(observableC)

    observableB.subscribe { println("observableB onNext: $it") }

    observableA
            .subscribe({ println("Original : $it")})

    observableA.filterByLatestFrom(observableB, BiFunction { aVal, bVal -> aVal%bVal==0 })
            .subscribe({ println("Result A : $it") })

    observableC.onNext(3)

    observableA.filterByLatestFrom(observableB, BiFunction { aVal, bVal -> aVal%bVal==0 })
            .subscribe({ println("Result AC : $it") })
}
</code>```

the output is :

```<code>observableB onNext: 2
Original : 1
Original : 2
Original : 3
Original : 4
Original : 5
Original : 6
Original : 7
Original : 8
Original : 9
Original : 10
Result A : 2
Result A : 4
Result A : 6
Result A : 8
Result A : 10
observableB onNext: 3
Result AC : 2
Result AC : 4
Result AC : 6
Result AC : 8
Result AC : 10
</code>```

I want the filter operator will filter obsA according last value of observable B.
It works for the first block but when i add On-next with new value it doesn't change the result (use same last value from the original observable).

this is the FilterByLatestFrom impl (it was design to be used from Java also (with compose):

```<code>class FilterByLatestFrom<T,U>(private val observable: Observable<T>, private val biFunction: BiFunction<U, T, Boolean>){
fun filter() : ObservableTransformer<U,U> = ObservableTransformer {
    it
            .withLatestFrom(
                    observable,
                    BiFunction<U,T,Pair<U,Boolean>> {
                        u, t -> Pair(u,biFunction.apply(u,t))
                    })
            .filter { it.second }
            .map { it.first }
    }
}
fun <T,U> Observable<U>.filterByLatestFrom(observable: Observable<T>, biFunction: BiFunction<U, T, Boolean>) : Observable<U> =
        this.compose(FilterByLatestFrom(observable,biFunction).filter())
</code>```

What am I missing?

EDIT : I think I found the problem : the PublishSubject should be BehaviorSubject instead. and merge function should be conacat to promise obsC will emit after obsB.

答:
Your pseudo-operator filterByLatestFrom is just fine, the problem lies within the testing, PublishSubject will emit just the subsequent items, so when in your last subscription ('result AC'), observableB will emit only 2, as observableC already emitted 3 and will not replay it to  observableB (using the merge).

Just move the observableC.onNext(3) to after the last subscription (last line) and you should see the expected behavior.

EDIT:
also changing to PublishSubject like you did solve the same issue (the subject will replay the last value to the new subscription)

Title: Observable withLatestFrom value

Body:
I Implemented a pseudo-operator called "FilterByLatestFrom" as an extension function for kotlin.

I wrote the next code using this operator:

    fun testFilterByLatestFromOperator(){
    val observableA : Observable<Int> = Observable.fromArray(1,2,3,4,5,6,7,8,9,10)
    val observableC : PublishSubject<Int> = PublishSubject.create()
    val observableB : Observable<Int> = Observable.just(2).mergeWith(observableC)

    observableB.subscribe { println("observableB onNext: $it") }

    observableA
            .subscribe({ println("Original : $it")})

    observableA.filterByLatestFrom(observableB, BiFunction { aVal, bVal -> aVal%bVal==0 })
            .subscribe({ println("Result A : $it") })

    observableC.onNext(3)

    observableA.filterByLatestFrom(observableB, BiFunction { aVal, bVal -> aVal%bVal==0 })
            .subscribe({ println("Result AC : $it") })
}

the output is :

observableB onNext: 2
Original : 1
Original : 2
Original : 3
Original : 4
Original : 5
Original : 6
Original : 7
Original : 8
Original : 9
Original : 10
Result A : 2
Result A : 4
Result A : 6
Result A : 8
Result A : 10
observableB onNext: 3
Result AC : 2
Result AC : 4
Result AC : 6
Result AC : 8
Result AC : 10

I want the filter operator will filter obsA according last value of observable B.
It works for the first block but when i add On-next with new value it doesn't change the result (use same last value from the original observable).

this is the FilterByLatestFrom impl (it was design to be used from Java also (with compose):

class FilterByLatestFrom<T,U>(private val observable: Observable<T>, private val biFunction: BiFunction){
fun filter() : ObservableTransformer = ObservableTransformer {
    it
            .withLatestFrom(
                    observable,
                    BiFunction<U,T,Pair> {
                        u, t -> Pair(u,biFunction.apply(u,t))
                    })
            .filter { it.second }
            .map { it.first }
    }
}
fun <T,U> Observable.filterByLatestFrom(observable: Observable<T>, biFunction: BiFunction) : Observable =
        this.compose(FilterByLatestFrom(observable,biFunction).filter())

What am I missing?

EDIT : I think I found the problem : the PublishSubject should be BehaviorSubject instead. and merge function should be conacat to promise obsC will emit after obsB.


来源: stackexchange

问:
Provision certficate to LAMP EC2, which are autoscaled on AWS
I need to design a solution, where the AWS EC2 has LAMP installed . The EC2s are autoscalled . The EC2 should have HTTPS for LAMP . The certificate can be self signed , but the private key should be protected. That is the private key should not be hardcoded on EC2 instance ( which is not best practice) . Also the HTTPS  should originate from EC2 and not from ELB,CloudFront,ACM etc. </p>

<p>Can someone help me in suggesting best practices ? </p>

答:
You can store the Private key in an encrypted S3 bucket that only the IAM role of the EC2 instance has access too. In user data for the EC2 instance have it pull down the cert and place it in the proper directory. You can build an AMI that has a LAMP stack already installed.

EC2 user data

S3 server side encryption

EC2 instance profile

ContentLicense: CC BY-SA 3.0

Body:
I need to design a solution, where the AWS EC2 has LAMP installed . The EC2s are autoscalled . The EC2 should have HTTPS for LAMP . The certificate can be self signed , but the private key should be protected. That is the private key should not be hardcoded on EC2 instance ( which is not best practice) . Also the HTTPS  should originate from EC2 and not from ELB,CloudFront,ACM etc.

Can someone help me in suggesting best practices ?


问:
Save image from webview never save to local mobile phone
i already create a code to save image from webview. the code works but there are some problem, here is the code

```<code>public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

        final WebView.HitTestResult result = mWebView.getHitTestResult();
        if (result.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {

            //menu.setHeaderTitle(result.getExtra());
            menu.add(0, 1, 0, "Save Image")
                    .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {

                            String DownloadImageURL = result.getExtra();

                            if(URLUtil.isValidUrl(DownloadImageURL)){

                                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL));
                                request.allowScanningByMediaScanner();
                                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                DownloadManager downloadManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
                                downloadManager.enqueue(request);

                                Toast.makeText(getContext(),"Image save successfully.",Toast.LENGTH_SHORT).show();
                            }
                            else {
                                Toast.makeText(getContext(),"Error to save image.",Toast.LENGTH_SHORT).show();
                            }
                            return false;
                        }
                    });
        }
    }
</code>```

when i try to long click the image it will show dialog message to save the image, when i click on it, it will show toast message that says the image have been save succesfully and yes there a notification in my stat bar

the problem is, when i try to open my gallery and search for the image, i never find the image because it's not save to my local storage.

can you help me to fix the code?
thanks

答:
Try calling this method from your onMenuItemClick after String DownloadImageURL = result.getExtra();

```<code>public void saveImage(){
try {
  URL url = new URL(yourImageUrl);
  InputStream is = (InputStream) url.getContent();
  byte[] buffer = new byte[8192];
  int bytesRead;
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  while ((bytesRead = is.read(buffer)) != -1) {
    output.write(buffer, 0, bytesRead);
  }
  //return output.toByteArray();
  Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
} catch (MalformedURLException e) {
e.printStackTrace();
//return null;
} catch (IOException e) {
e.printStackTrace();
//return null;
}
FileOutputStream out = null;
try {
    out = new FileOutputStream(filename); //some String filename
    bm.compress(Bitmap.CompressFormat.PNG, 100, out); // bm is your Bitmap instance
    // PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (out != null) {
            out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}
</code>```

However the above method is not tested at all. I have googled a little just because it looks like you needed some more help. Hope this solves your problem.

Body:
i already create a code to save image from webview. the code works but there are some problem, here is the code

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

        final WebView.HitTestResult result = mWebView.getHitTestResult();
        if (result.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {

            //menu.setHeaderTitle(result.getExtra());
            menu.add(0, 1, 0, "Save Image")
                    .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {

                            String DownloadImageURL = result.getExtra();

                            if(URLUtil.isValidUrl(DownloadImageURL)){

                                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL));
                                request.allowScanningByMediaScanner();
                                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                DownloadManager downloadManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
                                downloadManager.enqueue(request);

                                Toast.makeText(getContext(),"Image save successfully.",Toast.LENGTH_SHORT).show();
                            }
                            else {
                                Toast.makeText(getContext(),"Error to save image.",Toast.LENGTH_SHORT).show();
                            }
                            return false;
                        }
                    });
        }
    }

when i try to long click the image it will show dialog message to save the image, when i click on it, it will show toast message that says the image have been save succesfully and yes there a notification in my stat bar

the problem is, when i try to open my gallery and search for the image, i never find the image because it's not save to my local storage.

can you help me to fix the code?
thanks

Body:
Try calling this method from your onMenuItemClick after String DownloadImageURL = result.getExtra();

public void saveImage(){
try {
  URL url = new URL(yourImageUrl);
  InputStream is = (InputStream) url.getContent();
  byte[] buffer = new byte[8192];
  int bytesRead;
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  while ((bytesRead = is.read(buffer)) != -1) {
    output.write(buffer, 0, bytesRead);
  }
  //return output.toByteArray();
  Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
} catch (MalformedURLException e) {
e.printStackTrace();
//return null;
} catch (IOException e) {
e.printStackTrace();
//return null;
}
FileOutputStream out = null;
try {
    out = new FileOutputStream(filename); //some String filename
    bm.compress(Bitmap.CompressFormat.PNG, 100, out); // bm is your Bitmap instance
    // PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (out != null) {
            out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

However the above method is not tested at all. I have googled a little just because it looks like you needed some more help. Hope this solves your problem.


问:
Getting Parsley 2.x working with Bootstrap 3 correctly
I am using Twitter Bootstrap 3.1.1 with Parsley v2.0.0-rc3. I made it mostly work apart from classHandler option.

I have HTML like this:

```<code><div class="form-group">
    <label class="control-label" for="username">User Name</label>
    <input class="form-control" id="username" name="username" required="" type="text" value="">
</div>
</code>```

And run Parsley like this:

```<code>$("#register_form").parsley({
    successClass: "has-success",
    errorClass: "has-error",
    classHandler: function(el) {
        return $(el).closest(".form-group");
    },
    errorsWrapper: "<span class='help-block'></span>",
    errorTemplate: "<span></span>"
});
</code>```

Everything works fine, but success / error classes are applied to wrong element. After the page is loaded, I get this:

```<code><div class="form-group">
    <label class="control-label" for="username">User Name</label>
    <input class="form-control" id="username" name="username" required="" type="text" value="" data-parsley-id="5043">
    <span class="help-block" id="parsley-id-5043"></span>
</div>
</code>```

And when validated, the result is this:

```<code><div class="form-group">
    <label class="control-label" for="username">User Name</label>
    <input class="form-control has-error" id="username" name="username" required="" type="text" value="" data-parsley-id="5043">
    <span class="help-block filled" id="parsley-id-5043">
        <span class="parsley-required">This value is required.</span>
    </span>
</div>
</code>```

However, I expect something different:

```<code><div class="form-group has-error">
    <label class="control-label" for="username">User Name</label>
    <input class="form-control" id="username" name="username" required="" type="text" value="" data-parsley-id="5043">
    <span class="help-block filled" id="parsley-id-5043">
        <span class="parsley-required">This value is required.</span>
    </span>
</div>
</code>```

I have verified using alert that the function runs. But I am new to jQuery and JavaScript, so I do not know how to debug it any further and fix it.

答:
Full code working:</p>

```<code>$("#register_form").parsley({
    successClass: "has-success",
    errorClass: "has-error",
    classHandler: function(e) {
        return e.$element.closest('.form-group');
    },
    errorsWrapper: "<span class='help-block'></span>",
    errorTemplate: "<span></span>"
});
</code>```

Body:
I am using Twitter Bootstrap 3.1.1 with Parsley v2.0.0-rc3. I made it mostly work apart from classHandler option.

I have HTML like this:

    User Name
    <input class="form-control" id="username" name="username" required="" type="text" value="">

And run Parsley like this:

$("#register_form").parsley({
    successClass: "has-success",
    errorClass: "has-error",
    classHandler: function(el) {
        return $(el).closest(".form-group");
    },
    errorsWrapper: "",
    errorTemplate: ""
});

Everything works fine, but success / error classes are applied to wrong element. After the page is loaded, I get this:

    User Name
    <input class="form-control" id="username" name="username" required="" type="text" value="" data-parsley-id="5043">

And when validated, the result is this:

    User Name
    <input class="form-control has-error" id="username" name="username" required="" type="text" value="" data-parsley-id="5043">

        This value is required.

However, I expect something different:

    User Name
    <input class="form-control" id="username" name="username" required="" type="text" value="" data-parsley-id="5043">

        This value is required.

I have verified using alert that the function runs. But I am new to jQuery and JavaScript, so I do not know how to debug it any further and fix it.

Body:
Full code working:

$("#register_form").parsley({
    successClass: "has-success",
    errorClass: "has-error",
    classHandler: function(e) {
        return e.$element.closest('.form-group');
    },
    errorsWrapper: "<span class='help-block'></span>",
    errorTemplate: "<span></span>"
});


问:
Why Spring Boot Application logs that it started twice after adding spring-cloud-bus dependency
This is simple code in my Spring boot application:

```<code>package com.maxxton.SpringBootHelloWorld;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootHelloWorldApplication {

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

And a ApplicationListener class to listen to ApplicationEvent:

```<code>package com.maxxton.SpringBootHelloWorld;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class Test implements ApplicationListener {

  @Override
  public void onApplicationEvent(ApplicationEvent event) {
    if (event.getClass().getSimpleName().equals("ApplicationReadyEvent")) {
      System.out.println("-------------------------------------");
      System.out.println(event.getClass().getSimpleName());
      System.out.println("-------------------------------------");
    }
  }
}
</code>```

build.gradle contains these dependencies:

```<code>dependencies {

    compile("org.springframework.boot:spring-boot-starter-amqp")
    compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")

    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter')
    compile("org.springframework.cloud:spring-cloud-starter")
    compile("org.springframework.cloud:spring-cloud-starter-security")
    compile("org.springframework.cloud:spring-cloud-starter-eureka")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}
</code>```

Now, when I run this spring boot application, I see this log printed twice:

```<code>[main] c.m.S.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in ... seconds (JVM running for ...)
</code>```

Usually, this log get printed only once, but it get printed twice if I add these dependencies:

```<code>compile("org.springframework.boot:spring-boot-starter-amqp")
compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")
</code>```

This is complete log:

```<code>2017-11-17 15:44:07.372  INFO 5976 --- [           main] o.s.c.support.GenericApplicationContext  : Refreshing org.springframework.context.support.GenericApplicationContext@31c7c281: startup date [Fri Nov 17 15:44:07 IST 2017]; root of context hierarchy
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:07.403  INFO 5976 --- [           main] c.m.S.SpringBootHelloWorldApplication    : Started SpringBootHelloWorldApplication in 1.19 seconds (JVM running for 10.231)
2017-11-17 15:44:09.483  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:09.492  INFO 5976 --- [           main] o.s.integration.channel.DirectChannel    : Channel 'a-bootiful-client.springCloudBusOutput' has 1 subscriber(s).
2017-11-17 15:44:09.493  INFO 5976 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.i.channel.PublishSubscribeChannel    : Channel 'a-bootiful-client.errorChannel' has 1 subscriber(s).
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started _org.springframework.integration.errorLogger
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147482647
2017-11-17 15:44:09.539  INFO 5976 --- [           main] c.s.b.r.p.RabbitExchangeQueueProvisioner : declaring queue for inbound: springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, bound to: springCloudBus
2017-11-17 15:44:11.562  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:13.587  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare queue: Queue [name=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, durable=false, autoDelete=true, exclusive=true, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:15.611  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare binding: Binding [destination=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, exchange=springCloudBus, routingKey=#], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:17.662  INFO 5976 --- [           main] o.s.i.a.i.AmqpInboundChannelAdapter      : started inbound.springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ
2017-11-17 15:44:17.662  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {message-handler:inbound.springCloudBus.default} as a subscriber to the 'bridge.springCloudBus' channel
2017-11-17 15:44:17.662  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started inbound.springCloudBus.default
2017-11-17 15:44:17.663  INFO 5976 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
2017-11-17 15:44:17.714  INFO 5976 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:17.717  INFO 5976 --- [           main] c.m.S.SpringBootHelloWorldApplication    : Started SpringBootHelloWorldApplication in 20.131 seconds (JVM running for 20.545)
</code>```

As you can see, ApplicationReadyEvent is happening twice.

Why is this happening?
Is there any way to avoid this?

答:
spring-cloud-bus uses spring-cloud-stream which puts the binder in a separate boot child application context.

You should make your event listener aware of the application context it is running in. You can also use generics to select the event type you are interested in...

```<code>@Component
public class Test implements ApplicationListener<ApplicationReadyEvent>,
                             ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (event.getApplicationContext().equals(this.applicationContext)) {
            System.out.println("-------------------------------------");
            System.out.println(event.getClass().getSimpleName());
            System.out.println("-------------------------------------");
        }
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is simple code in my Spring boot application:

package com.maxxton.SpringBootHelloWorld;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootHelloWorldApplication {

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

And a ApplicationListener class to listen to ApplicationEvent:

package com.maxxton.SpringBootHelloWorld;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class Test implements ApplicationListener {

  @Override
  public void onApplicationEvent(ApplicationEvent event) {
    if (event.getClass().getSimpleName().equals("ApplicationReadyEvent")) {
      System.out.println("-------------------------------------");
      System.out.println(event.getClass().getSimpleName());
      System.out.println("-------------------------------------");
    }
  }
}

build.gradle contains these dependencies:

dependencies {

    compile("org.springframework.boot:spring-boot-starter-amqp")
    compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")

    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter')
    compile("org.springframework.cloud:spring-cloud-starter")
    compile("org.springframework.cloud:spring-cloud-starter-security")
    compile("org.springframework.cloud:spring-cloud-starter-eureka")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Now, when I run this spring boot application, I see this log printed twice:

[main] c.m.S.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in ... seconds (JVM running for ...)

Usually, this log get printed only once, but it get printed twice if I add these dependencies:

compile("org.springframework.boot:spring-boot-starter-amqp")
compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")

This is complete log:

2017-11-17 15:44:07.372  INFO 5976 --- [           main] o.s.c.support.GenericApplicationContext  : Refreshing org.springframework.context.support.GenericApplicationContext@31c7c281: startup date [Fri Nov 17 15:44:07 IST 2017]; root of context hierarchy
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:07.403  INFO 5976 --- [           main] c.m.S.SpringBootHelloWorldApplication    : Started SpringBootHelloWorldApplication in 1.19 seconds (JVM running for 10.231)
2017-11-17 15:44:09.483  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:09.492  INFO 5976 --- [           main] o.s.integration.channel.DirectChannel    : Channel 'a-bootiful-client.springCloudBusOutput' has 1 subscriber(s).
2017-11-17 15:44:09.493  INFO 5976 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.i.channel.PublishSubscribeChannel    : Channel 'a-bootiful-client.errorChannel' has 1 subscriber(s).
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started _org.springframework.integration.errorLogger
2017-11-17 15:44:09.530  INFO 5976 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147482647
2017-11-17 15:44:09.539  INFO 5976 --- [           main] c.s.b.r.p.RabbitExchangeQueueProvisioner : declaring queue for inbound: springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, bound to: springCloudBus
2017-11-17 15:44:11.562  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:13.587  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare queue: Queue [name=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, durable=false, autoDelete=true, exclusive=true, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:15.611  WARN 5976 --- [           main] o.s.amqp.rabbit.core.RabbitAdmin         : Failed to declare binding: Binding [destination=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, exchange=springCloudBus, routingKey=#], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:17.662  INFO 5976 --- [           main] o.s.i.a.i.AmqpInboundChannelAdapter      : started inbound.springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ
2017-11-17 15:44:17.662  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {message-handler:inbound.springCloudBus.default} as a subscriber to the 'bridge.springCloudBus' channel
2017-11-17 15:44:17.662  INFO 5976 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started inbound.springCloudBus.default
2017-11-17 15:44:17.663  INFO 5976 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
2017-11-17 15:44:17.714  INFO 5976 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:17.717  INFO 5976 --- [           main] c.m.S.SpringBootHelloWorldApplication    : Started SpringBootHelloWorldApplication in 20.131 seconds (JVM running for 20.545)

As you can see, ApplicationReadyEvent is happening twice.

Why is this happening?
Is there any way to avoid this?

Body:
spring-cloud-bus uses spring-cloud-stream which puts the binder in a separate boot child application context.

You should make your event listener aware of the application context it is running in. You can also use generics to select the event type you are interested in...

@Component
public class Test implements ApplicationListener<ApplicationReadyEvent>,
                             ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (event.getApplicationContext().equals(this.applicationContext)) {
            System.out.println("-------------------------------------");
            System.out.println(event.getClass().getSimpleName());
            System.out.println("-------------------------------------");
        }
    }

}


问:
C structure assignment of same address valid?
If I have something like this in my code:

```<code>void f(struct foo *x, struct foo *y)
{
  *x = *y; // structure copy (memcpy?)
}
</code>```

If x and y point to the same address, what happens?

Is this valid code, and what if the compiler converts the assignment into a memcpy call with potentially-invalid operands (they aren't allowed to overlap)?

[Yes, I know I can use "restrict" in this case, but the actual code we found which made us consider this is automatically-generated by bison so we were wondering if it should always be valid and whether the compiler should use memmove or something else which allows overlap..]

答: Structure assignment is perfectly legal.  Therefore the compiler will generate the correct code (compiler bugs notwithstanding).</p>

ContentLicense: CC BY-SA 2.5

Body:
If I have something like this in my code:

void f(struct foo *x, struct foo *y)
{
  *x = *y; // structure copy (memcpy?)
}

If x and y point to the same address, what happens?

Is this valid code, and what if the compiler converts the assignment into a memcpy call with potentially-invalid operands (they aren't allowed to overlap)?

[Yes, I know I can use "restrict" in this case, but the actual code we found which made us consider this is automatically-generated by bison so we were wondering if it should always be valid and whether the compiler should use memmove or something else which allows overlap..]


问:
Can't get the data from a table: error while compiling
My app had to get some infos from the DataBase and display a table in a ListView.
So basicly, there is no Activity dedicated to the insert of the Data to the table.
And I'm doing it in the ModelHelper like that:
The user table contains: ID,Fname,Lname;
ID is PRIMARY KEY AUTOINCREMENT NOT NULL;

```<code>public void onCreate(SQLiteDatabase db) {
       db.execSQL(CREATE_TABLE_USER);
db.execSQL("INSERT INTO " + USER +" VALUES ('DOME','TRY')");
}
</code>```

I did a method that returns the Fnames of the users

```<code>public ArrayList getOnlyNames(){
        ArrayList lst = new ArrayList();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery("SELECT " +KEY_FNAME+ " from " +TABLE_QUESTION,null);
        if (c.moveToFirst()) {
            while(c.isAfterLast()==false){
                String t1 = c.getString(1);
                lst.add(t1);
                c.moveToNext();
            }
        }
        return lst;
    }
</code>```

In the Activity I declared the list:
ListView lst = (Listview) findViewById(R.id.list1);

and here's the used method:

```<code>public void showQuest(View view){

        ArrayList<String> lstQ = md.getOnlyNames();
        ArrayAdapter lstad = new ArrayAdapter(this, android.R.layout.simple_list_item_1,lstQ);
        lst.setAdapter(lstad);
    }
</code>```

and I added Onlick"showquest" in a button in the same activity.

The log error is:

```<code>FATAL EXCEPTION: main
                                                                                Process: com.example.root.myapplication, PID: 10225
                                                                                java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                                                at android.view.View.performClick(View.java:6294)
                                                                                at android.view.View$PerformClick.run(View.java:24770)
                                                                                at android.os.Handler.handleCallback(Handler.java:790)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                                                                                Caused by: java.lang.reflect.InvocationTargetException
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                                at android.view.View.performClick(View.java:6294)
                                                                                at android.view.View$PerformClick.run(View.java:24770)
                                                                                at android.os.Handler.handleCallback(Handler.java:790)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                                                                                Caused by: android.database.sqlite.SQLiteException: no such column: Question (code 1): , while compiling: SELECT Question from Question
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                                                                                at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
                                                                                at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1392)
                                                                                at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1331)
                                                                                at model.sqlite.data.ModelHelper.getOnlyQuestions(ModelHelper.java:253)
                                                                                at com.example.root.myapplication.kamiActivity.showQuest(kamiActivity.java:98)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                                at android.view.View.performClick(View.java:6294)
                                                                                at android.view.View$PerformClick.run(View.java:24770)
                                                                                at android.os.Handler.handleCallback(Handler.java:790)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
</code>```

The problem comes from the use of the method by the button, and I think the DB is empty, but I don't know why it can't take the column and it's already in the table.

答:
You have requested data for only one column. The column index would be 0 not 1.

```<code>while(c.isAfterLast()==false){
            String t1 = c.getString(0);
            lst.add(t1);
            c.moveToNext();
}
</code>```

The exception says it all.

```<code>Caused by: android.database.sqlite.SQLiteException: no such column: Question (code 1): , while compiling: SELECT Question from Question
</code>```

Safe method would be

```<code>c.getString(c.getColumnIndex(KEY_NAME));
</code>```

Body:
My app had to get some infos from the DataBase and display a table in a ListView.
So basicly, there is no Activity dedicated to the insert of the Data to the table.
And I'm doing it in the ModelHelper like that:
The user table contains: ID,Fname,Lname;
ID is PRIMARY KEY AUTOINCREMENT NOT NULL;

public void onCreate(SQLiteDatabase db) {
       db.execSQL(CREATE_TABLE_USER);
db.execSQL("INSERT INTO " + USER +" VALUES ('DOME','TRY')");
}

I did a method that returns the Fnames of the users

public ArrayList getOnlyNames(){
        ArrayList lst = new ArrayList();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery("SELECT " +KEY_FNAME+ " from " +TABLE_QUESTION,null);
        if (c.moveToFirst()) {
            while(c.isAfterLast()==false){
                String t1 = c.getString(1);
                lst.add(t1);
                c.moveToNext();
            }
        }
        return lst;
    }

In the Activity I declared the list:
ListView lst = (Listview) findViewById(R.id.list1);

and here's the used method:

public void showQuest(View view){

        ArrayList<String> lstQ = md.getOnlyNames();
        ArrayAdapter lstad = new ArrayAdapter(this, android.R.layout.simple_list_item_1,lstQ);
        lst.setAdapter(lstad);
    }

and I added Onlick"showquest" in a button in the same activity.

The log error is:

FATAL EXCEPTION: main
                                                                                Process: com.example.root.myapplication, PID: 10225
                                                                                java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                                                at android.view.View.performClick(View.java:6294)
                                                                                at android.view.View$PerformClick.run(View.java:24770)
                                                                                at android.os.Handler.handleCallback(Handler.java:790)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                                                                                Caused by: java.lang.reflect.InvocationTargetException
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                                at android.view.View.performClick(View.java:6294)
                                                                                at android.view.View$PerformClick.run(View.java:24770)
                                                                                at android.os.Handler.handleCallback(Handler.java:790)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                                                                                Caused by: android.database.sqlite.SQLiteException: no such column: Question (code 1): , while compiling: SELECT Question from Question
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                                                                                at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
                                                                                at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1392)
                                                                                at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1331)
                                                                                at model.sqlite.data.ModelHelper.getOnlyQuestions(ModelHelper.java:253)
                                                                                at com.example.root.myapplication.kamiActivity.showQuest(kamiActivity.java:98)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                                at android.view.View.performClick(View.java:6294)
                                                                                at android.view.View$PerformClick.run(View.java:24770)
                                                                                at android.os.Handler.handleCallback(Handler.java:790)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)

The problem comes from the use of the method by the button, and I think the DB is empty, but I don't know why it can't take the column and it's already in the table.

Body:
You have requested data for only one column. The column index would be 0 not 1.

while(c.isAfterLast()==false){
            String t1 = c.getString(0);
            lst.add(t1);
            c.moveToNext();
}

The exception says it all.

Caused by: android.database.sqlite.SQLiteException: no such column: Question (code 1): , while compiling: SELECT Question from Question

Safe method would be

c.getString(c.getColumnIndex(KEY_NAME));


问:
Is there a way to Fix a Google Maps Marker to the Center of its Map always?
To be more precise, what I try to accomplish is that while I Drag a Google Map there's a Google Maps Marker that stays fixed at the center of the map at all times.
This will improve User experience in my opinion, This is how I'm doing it now:

```<code>var map, marker, options;

options = {
  center: new google.maps.LatLng(latitude, longitude),
  zoom: 15,
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  mapTypeControl: false,
  overviewMapControl: false,
  zoomControl: true,
  draggable: true
};

map = new google.maps.Map(mapContainer, options);

marker = new google.maps.Marker({
  position: new google.maps.LatLng(latitude, longitude),
  map: map,
  animation: google.maps.Animation.DROP
});

//This line is what makes the Marker stick to the center of the map
marker.bindTo('position', map, 'center');
</code>```

The problem I have with the code above is that.. When I drag the map underneath the Marker it's not smooth enough, ie. the Marker makes a wierd jump from the 'last' center to the 'new' center when dragging ends. (this is more noticeable on mobile devices), Therefore what I need is that the Marker is Really permanently fixed to the Center of its Map.

Is there a way to get this done? (I think I've seen this in a web-site once)

Let me know If you guys can help me.

Thank you.

答:
If this can help, what I did is :</p>

```<code>const myLatLng = {lat: 42, lng: 42};

map = new google.maps.Map(document.getElementById('map'), {
  center: myLatLng,
  zoom: 14,
});

marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
});

map.addListener('center_changed', () => {
  marker.setPosition(map.getCenter())
})
</code>```

Body:
To be more precise, what I try to accomplish is that while I Drag a Google Map there's a Google Maps Marker that stays fixed at the center of the map at all times.
This will improve User experience in my opinion, This is how I'm doing it now:

var map, marker, options;

options = {
  center: new google.maps.LatLng(latitude, longitude),
  zoom: 15,
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  mapTypeControl: false,
  overviewMapControl: false,
  zoomControl: true,
  draggable: true
};

map = new google.maps.Map(mapContainer, options);

marker = new google.maps.Marker({
  position: new google.maps.LatLng(latitude, longitude),
  map: map,
  animation: google.maps.Animation.DROP
});

//This line is what makes the Marker stick to the center of the map
marker.bindTo('position', map, 'center');

The problem I have with the code above is that.. When I drag the map underneath the Marker it's not smooth enough, ie. the Marker makes a wierd jump from the 'last' center to the 'new' center when dragging ends. (this is more noticeable on mobile devices), Therefore what I need is that the Marker is Really permanently fixed to the Center of its Map.

Is there a way to get this done? (I think I've seen this in a web-site once)

Let me know If you guys can help me.

Thank you.

Body:
If this can help, what I did is :

const myLatLng = {lat: 42, lng: 42};

map = new google.maps.Map(document.getElementById('map'), {
  center: myLatLng,
  zoom: 14,
});

marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
});

map.addListener('center_changed', () => {
  marker.setPosition(map.getCenter())
})


问:
How to pass url value in django to views
My url.py is as below,

```<code>from myapp import views
urlpatterns = [
   url(r'^myapp/get_requests/$', views.get_requests),
]
</code>```

Now my views.py is as below,

```<code>@api_view(['GET'])
def get_request(request):
   #How can I get request ID (base url here)?
   return HttpResponse('test')
</code>```

In the above if I do request in my browser with url as below it reaches my get_request method,

```<code>http://localhost:8080/myapp/get_requests/
</code>```

But the same gives error 404 when I try with some ID in the end as below,

```<code>http://localhost:8080/myapp/get_requests/40
</code>```

Now How can I get this ID number 40 in my views.py method?

答:
There is a typo in the view function name in your above code. So, it would be get_requests not get_request.

Now coming to your question, it throws you 404 - Not Found because there is no actual route that you've defined that should expect the id after the url.

To start accepting id, add another route for it in your urls.py which has a digit regext like:

```<code>from myapp import views
urlpatterns = [
   url(r'^myapp/get_requests/$', views.get_requests),
   url(r'^myapp/get_requests/(?P<id>\d+)$', views.get_requests_with_id),
]
</code>```

and in your views.py, define the view function to accept id parameter something like this:

```<code>@api_view(['GET'])
def get_requests_with_id(request, id):
   # Now use id for whatever you want
   return HttpResponse('test')
</code>```

You can read about it form the official documentation here: https://docs.djangoproject.com/en/1.11/topics/http/urls/#named-groups

Body:
My url.py is as below,

from myapp import views
urlpatterns = [
   url(r'^myapp/get_requests/$', views.get_requests),
]

Now my views.py is as below,

@api_view(['GET'])
def get_request(request):
   #How can I get request ID (base url here)?
   return HttpResponse('test')

In the above if I do request in my browser with url as below it reaches my get_request method,

http://localhost:8080/myapp/get_requests/

But the same gives error 404 when I try with some ID in the end as below,

http://localhost:8080/myapp/get_requests/40

Now How can I get this ID number 40 in my views.py method?

Body:
There is a typo in the view function name in your above code. So, it would be get_requests not get_request.

Now coming to your question, it throws you 404 - Not Found because there is no actual route that you've defined that should expect the id after the url.

To start accepting id, add another route for it in your urls.py which has a digit regext like:

from myapp import views
urlpatterns = [
   url(r'^myapp/get_requests/$', views.get_requests),
   url(r'^myapp/get_requests/(?P<id>\d+)$', views.get_requests_with_id),
]

and in your views.py, define the view function to accept id parameter something like this:

@api_view(['GET'])
def get_requests_with_id(request, id):
   # Now use id for whatever you want
   return HttpResponse('test')

You can read about it form the official documentation here: https://docs.djangoproject.com/en/1.11/topics/http/urls/#named-groups


问:
Arity of methods
When classifying the arity of a method function, do you need to consider the use of this? For example:

```<code>// Unary
function double(num) {
    return num * 2;
}

// Binary
function add(num1, num2) {
    return num1 + num2;
}

class Calc {
    value;

    // Unary or binary?
    add(num1) {
        return this.value + num1;
    }

    // Nullary or unary?
    double() {
        return this.value * 2;
    }
}
</code>```

I've always thought of this as an implicit parameter.

(I'm assuming there is a language-agnostic answer to this, but it's JavaScript I'm most interested in the answer to)

答: The way I see it, this is not a parameter, but a context in which the method is executed, so the add method is unary and the double method is nullary.

Title: Arity of methods

Body:
When classifying the arity of a method function, do you need to consider the use of this? For example:

// Unary
function double(num) {
    return num * 2;
}

// Binary
function add(num1, num2) {
    return num1 + num2;
}

class Calc {
    value;

    // Unary or binary?
    add(num1) {
        return this.value + num1;
    }

    // Nullary or unary?
    double() {
        return this.value * 2;
    }
}

I've always thought of this as an implicit parameter.

(I'm assuming there is a language-agnostic answer to this, but it's JavaScript I'm most interested in the answer to)


问:
how can git identify repositories owner?
I wonder if someone can pretend as a real github repository owner and do some push in that repository.
Does github verify the repository owner by using user.name and user.email?</p>

答: Github will ask your username and password when you try to push for first time when using https and it will be cached on your computer until you change your credentials. Check this reference about caching of github credentials</p>


问:
when login from ionic app to dashboard the menu button showing as a back button

import { Component} from '@angular/core';
import { NavController } from 'ionic-angular';
import { HomePage } from '../../pages/dashboard/home';
import { Signup } from '../../commen/signup/signup';
import { Forgot } from '../../commen/forgot/forgot';
import { NgForm } from '@angular/forms';
import { AuthService } from '../../services/auth.service'
import { ToastController } from 'ionic-angular';

@Component({
  selector: 'page-Login',
  templateUrl: 'login.html',
  providers: [AuthService]
})
export class Login {
  forgot:any;

  spinnerLoad: boolean = false;
  msg:any;
  constructor(public navCtrl: NavController,private authservice: AuthService,public toastCtrl: ToastController) {
    this.forgot=Forgot;

  }

  Submitlogin(value: any) {

    if(value.email){
    this.spinnerLoad = true;

    let email = value.email;
    let pass = value.password;

    this.authservice.login(email, pass).subscribe((result) => {
      this.spinnerLoad = false;
      if (result)
        if (result.status) {
          localStorage.setItem('userData', JSON.stringify(result.data));
          this.navCtrl.push(HomePage);
        } else {
          const toast = this.toastCtrl.create({
            message: 'Invalid credentials',
            duration: 3000,
            position: 'bottom'
          });
          toast.present();

          this.spinnerLoad = false;

        }
    }, error => {
      this.spinnerLoad = true;

    });
  }

  }
  onSignup() {

    this.navCtrl.push(Signup);
  }
  facebookLogin(){
    // alert('hello')
    // window.location.href = 'http://d4v.nextfellow.com/login/facebook';
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form ngsubmit="formvalue()">
<ionic-input type="text"  placeholder="email example"></ionic-input>
<ionic-input type="text"  placeholder="password"></ionic-input>

      <ion-col>
        <button ion-button [disabled]="!loginForm.form.valid" type="submit"   block>Login</button>
      </ion-col>
      </form</code>```

html is my dummy code once i validate form and route to dashboard on the header side of the menu button showing as a back button but it should be menu right please give me the solution for this also i have dashboard component
am working on ionic 3 its ....................................................

答: I think you should use this.navCtrl.setRoot(HomePage); instead of this.navCtrl.push(HomePage);

Body:
import { Component} from '@angular/core';
import { NavController } from 'ionic-angular';
import { HomePage } from '../../pages/dashboard/home';
import { Signup } from '../../commen/signup/signup';
import { Forgot } from '../../commen/forgot/forgot';
import { NgForm } from '@angular/forms';
import { AuthService } from '../../services/auth.service'
import { ToastController } from 'ionic-angular';

@Component({
  selector: 'page-Login',
  templateUrl: 'login.html',
  providers: [AuthService]
})
export class Login {
  forgot:any;

  spinnerLoad: boolean = false;
  msg:any;
  constructor(public navCtrl: NavController,private authservice: AuthService,public toastCtrl: ToastController) {
    this.forgot=Forgot;

  }

  Submitlogin(value: any) {

    if(value.email){
    this.spinnerLoad = true;

    let email = value.email;
    let pass = value.password;

    this.authservice.login(email, pass).subscribe((result) => {
      this.spinnerLoad = false;
      if (result)
        if (result.status) {
          localStorage.setItem('userData', JSON.stringify(result.data));
          this.navCtrl.push(HomePage);
        } else {
          const toast = this.toastCtrl.create({
            message: 'Invalid credentials',
            duration: 3000,
            position: 'bottom'
          });
          toast.present();

          this.spinnerLoad = false;

        }
    }, error => {
      this.spinnerLoad = true;

    });
  }

  }
  onSignup() {

    this.navCtrl.push(Signup);
  }
  facebookLogin(){
    // alert('hello')
    // window.location.href = 'http://d4v.nextfellow.com/login/facebook';
  }
}

<form ngsubmit="formvalue()">
<ionic-input type="text"  placeholder="email example"></ionic-input>
<ionic-input type="text"  placeholder="password"></ionic-input>

      <ion-col>
        <button ion-button [disabled]="!loginForm.form.valid" type="submit"   block>Login</button>
      </ion-col>
      </form

html is my dummy code once i validate form and route to dashboard on the header side of the menu button showing as a back button but it should be menu right please give me the solution for this also i have dashboard component
am working on ionic 3 its ....................................................


问:
Go: **Type pointer
In tutorial is written:

The type *T is a pointer to a T value. The & operator generates
  a pointer to its operand.

I am just playing around with pointers in Go and have following:

```<code>example := 42

p:=&example
fmt.Println(reflect.TypeOf(&p)) // **int
fmt.Println(reflect.TypeOf(*p)) // int
</code>```

So if I got it correctly, &p is a pointer to a pointer to an int value.

What is use of **Type in the Go language?

答:
Yes, you got it correctly.

As to "what use", it's the same as everywhere else: you use a pointer in these cases:

A variable has to be changed in some other code —
typically another function, — and so you pass a pointer to the memory
occupied by that variable to that function so it's able to update
that memory via that address.

A value is too large to be passed around fast enough by copying it.

A pointer to a pointer is a bit of a pathological case for Go,
but still this can be used in the first case: when you want some function
to change the value of a pointer variable your code controls.

Title: Go: **Type pointer

Body:
In tutorial is written:

The type *T is a pointer to a T value. The & operator generates
  a pointer to its operand.

I am just playing around with pointers in Go and have following:

example := 42

p:=&example
fmt.Println(reflect.TypeOf(&p)) // **int
fmt.Println(reflect.TypeOf(*p)) // int

So if I got it correctly, &p is a pointer to a pointer to an int value.

What is use of **Type in the Go language?


问:
Disable "input assistance" for editText
I'm programming a vocable trainer for my son. It works fine.
He must input the vocables in an editTextfield.

When he enters the first letters of the translated word, the "input assistance"
upper the virtual keypad shows the best suggestions. I thinks this is the
default way of entering text in android.
Of course he should not see the suggestions. He should type in the word without help! Is there a way to hide the suggestions?

I hope you know what I mean.

I would be glad to get an answer!

Title: Disable "input assistance" for editText

Body: editText.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);


问:
get json response from neo4j using python
I want to convert the results of cypher queries in neo4j into a JSON format.

I am currently using the neo4j library to connect and query the graph. I can, but converting the results into JSON is cumbersome and hence this question.

Here is my current code:

```<code>from neo4j.v1 import GraphDatabase, basic_auth
from config import bolt_url,auth_id,auth_pass

driver = GraphDatabase.driver(bolt_url, auth=basic_auth(auth_id, auth_pass))
session = driver.session()

def get_some_data(limit=25) :
    query = 'MATCH (n:Person)--(m:Organization) \
            RETURN n,m LIMIT ' + str(limit)
    return session.run(query)

result_some_data = get_some_data(limit=1)
gen = result_some_data.records()

for record in gen :
    for k,v in record.items() :
        print('{',k,':',v,'}')
        print(v.get('name','meow'))

session.close
</code>```

I get the following output :

```<code>{ n : <Node id=44567 labels={'Person'} properties={'name': 'ABC'}> }
ABC
{ m : <Node id=34745 labels={'Organization'} properties={'name': 'XYZ'}> }
XYZ
</code>```

As you can see, the output is giving Node objects. I am able to get the
properties but not the labels or id. I may be able to get the id and labels, but it gets much complex and much cumbersome.

Now the JSON format I need is very specific and I don't expect to get the results in that specific format.

Let's say this is the basic JSON format I need:

```<code>{
    "results": [{
        "columns": ["n", "m"],
        "data": [{
            "graph": {
                "nodes": [{
                    "id": "44567",
                    "labels": ["Person"],
                    "properties": {
                        "name": "ABC"
                    }
                }, {
                    "id": "34745",
                    "labels": ["Organization"],
                    "properties": {
                        "name": "ABC"
                }],
                "relationships": [{
                    "id": "1",
                    "type": "WorksIn",
                    "startNode": "44567",
                    "endNode": "34745",
                    "properties": {
                        "title": "CEO"
                    }
                }]
            }
        }]
    }],
}
</code>```

The code here, is not the code I am going to use in the future, it is just a demo code I wrote to ask this question.

So basically what I am asking here is a way to get the JSON response from neo4j, after running the cypher queries, rather than parsing the result and then generating a JSON.

答:
Not sure what you mean with cumbersome to get the labels and the id ... I mean, if you have a Node object o then the id is o.id and the labels are o.labels, no ?

Anyway, the issue is that Cypher can return quite a few different things (a table of discrete values, nodes, relationships, paths, a subgraph, ...) and when accessing the database through a driver it is you that has to determine what to do with the result. So you are given a result-set (which from the point of view of the database could contain anything) and have to do the post-processing yourself (since only you know what you actually asked for).

If you really want a JSON-like result, you could query the database through the HTTP endpoint. It will still require heavy processing from your end though.

Hope this helps (or at least explains why things are the way they are).

Regards,
Tom

Body:
I want to convert the results of cypher queries in neo4j into a JSON format.

I am currently using the neo4j library to connect and query the graph. I can, but converting the results into JSON is cumbersome and hence this question.

Here is my current code:

from neo4j.v1 import GraphDatabase, basic_auth
from config import bolt_url,auth_id,auth_pass

driver = GraphDatabase.driver(bolt_url, auth=basic_auth(auth_id, auth_pass))
session = driver.session()

def get_some_data(limit=25) :
    query = 'MATCH (n:Person)--(m:Organization) \
            RETURN n,m LIMIT ' + str(limit)
    return session.run(query)

result_some_data = get_some_data(limit=1)
gen = result_some_data.records()

for record in gen :
    for k,v in record.items() :
        print('{',k,':',v,'}')
        print(v.get('name','meow'))

session.close

I get the following output :

{ n : <Node id=44567 labels={'Person'} properties={'name': 'ABC'}> }
ABC
{ m : <Node id=34745 labels={'Organization'} properties={'name': 'XYZ'}> }
XYZ

As you can see, the output is giving Node objects. I am able to get the
properties but not the labels or id. I may be able to get the id and labels, but it gets much complex and much cumbersome.

Now the JSON format I need is very specific and I don't expect to get the results in that specific format.

Let's say this is the basic JSON format I need:

{
    "results": [{
        "columns": ["n", "m"],
        "data": [{
            "graph": {
                "nodes": [{
                    "id": "44567",
                    "labels": ["Person"],
                    "properties": {
                        "name": "ABC"
                    }
                }, {
                    "id": "34745",
                    "labels": ["Organization"],
                    "properties": {
                        "name": "ABC"
                }],
                "relationships": [{
                    "id": "1",
                    "type": "WorksIn",
                    "startNode": "44567",
                    "endNode": "34745",
                    "properties": {
                        "title": "CEO"
                    }
                }]
            }
        }]
    }],
}

The code here, is not the code I am going to use in the future, it is just a demo code I wrote to ask this question.

So basically what I am asking here is a way to get the JSON response from neo4j, after running the cypher queries, rather than parsing the result and then generating a JSON.


问:
Unable to extract a data from Table using inner join on same table
Trying to extract the data from table called TB_Emloyee. There are 4 columns in table with C_ID, Name, Department, Count.

My table has following data

http://sqlfiddle.com/#!9/e74be

I would like to have following output.

```<code>C_ID   NAme    Department  Count
200    Max     IH          2
100    David   PR          1
101    Lex     PR          1
102    Alex    IT          2
103    Slava   IH          1
104    Tunja   PR          2
</code>```

Until now I have tried the following, but I am not able to get the whole data.

http://sqlfiddle.com/#!9/e74be/2/0

I am not an expert with inner query so help me with situation.

Thanks.

答:
Do a self join to pick highest count row

```<code>select a.*
from Tb_Employee a
left join Tb_Employee b
        on a.c_ID = b.c_ID
        and a.Name = b.Name
        and a.department = b.department
        and a.Count < b.Count
where b.c_ID is null
</code>```

Demo

Body:
Trying to extract the data from table called TB_Emloyee. There are 4 columns in table with C_ID, Name, Department, Count.

My table has following data

http://sqlfiddle.com/#!9/e74be

I would like to have following output.

C_ID   NAme    Department  Count
200    Max     IH          2
100    David   PR          1
101    Lex     PR          1
102    Alex    IT          2
103    Slava   IH          1
104    Tunja   PR          2

Until now I have tried the following, but I am not able to get the whole data.

http://sqlfiddle.com/#!9/e74be/2/0

I am not an expert with inner query so help me with situation.

Thanks.

Body:
Do a self join to pick highest count row

select a.*
from Tb_Employee a
left join Tb_Employee b
        on a.c_ID = b.c_ID
        and a.Name = b.Name
        and a.department = b.department
        and a.Count < b.Count
where b.c_ID is null

Demo


问:
How Can I make modal to become full-screen in Ionic2?
Here is my modal code:

```<code>    let modal = Modal.create(DailyReportPage);
    this.nav.present(modal);
</code>```

It works fine on Phone, however on the tablet it looks like this:

What I want is to make it look like this:

答:
You can override the related Ionic Sass variables in file variables.css:

```<code>$modal-inset-width: 100%;
$modal-inset-height-large: 100%;
</code>```

Documentation (current version is 3.9, but I use this with 3.7):
http://ionicframework.com/docs/theming/overriding-ionic-variables/

Body:
Here is my modal code:

    let modal = Modal.create(DailyReportPage);
    this.nav.present(modal);

It works fine on Phone, however on the tablet it looks like this:

What I want is to make it look like this:

Body:
You can override the related Ionic Sass variables in file variables.css:

$modal-inset-width: 100%;
$modal-inset-height-large: 100%;

Documentation (current version is 3.9, but I use this with 3.7):
http://ionicframework.com/docs/theming/overriding-ionic-variables/


问:
How to pass data from 2nd viewcontroller to tableviewcontroller using delegates
I have 2 viewcontrollers - one is a tableview and the other is a normal viewcontroller. I want pass data from the second viewcontroller to a tableview controller by using delegates. I have created a delegate and delegatemethod in viewcontroller and implemented delegatemethod in the tableview controller. The problem is that I am getting data to the array but tableview is not reloading. Why?

Can anyone help with this problem? Thanks in advance.

```<code>    #import "TableViewController.h"

        @interface TableViewController ()<name>{

            NSMutableArray *data;
        }

        @end

        @implementation TableViewController

        - (void)viewDidLoad {
            [super viewDidLoad];
            data = [NSMutableArray array];
            [self.tableView reloadData];
        }

        - (IBAction)callingSecondView:(id)sender {

            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
            ViewController *var = [storyboard instantiateViewControllerWithIdentifier:@"vc"];
            var.delegate = self;
            [self.navigationController pushViewController:var animated:YES];
        }
        -(void)getdata:(NSString *)name{

            [data addObject:name];
            [self.tableView reloadData];

        }
        #pragma mark - Table view data source

        - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

            return 1;
        }

        - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

            return [data count];
        }
        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"  forIndexPath:indexPath];

            if (cell != nil) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];

            }
            cell.textLabel.text = [data objectAtIndex:indexPath.row];
            return cell;
        }
</code>```

And I am creating delegate a object and protocol in ViewController.h

```<code>        #import <UIKit/UIKit.h>

        @protocol name <NSObject>

        -(void)getdata : (NSString *)name;

        @end

        @interface ViewController : UIViewController
        @property (strong, nonatomic) IBOutlet UITextField *txt;
        - (IBAction)done:(id)sender;

        @property(nonatomic,retain) id<name> delegate;
</code>```

ViewController.m

```<code>        #import "ViewController.h"

        @interface ViewController ()

        @end

        @implementation ViewController
        @synthesize delegate;
        - (void)viewDidLoad {
            [super viewDidLoad];

        }
        - (IBAction)done:(id)sender {

            [delegate getdata:self.txt.text];
            [self.navigationController popToRootViewControllerAnimated:YES];

        }
        @end
</code>```

答:
I think the first VC don't reloadData because it's not the visible VC. Try reloadData when the VC willAppear. </p>

```<code>-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}
</code>```

Body:
I have 2 viewcontrollers - one is a tableview and the other is a normal viewcontroller. I want pass data from the second viewcontroller to a tableview controller by using delegates. I have created a delegate and delegatemethod in viewcontroller and implemented delegatemethod in the tableview controller. The problem is that I am getting data to the array but tableview is not reloading. Why?

Can anyone help with this problem? Thanks in advance.

    #import "TableViewController.h"

        @interface TableViewController ()<name>{

            NSMutableArray *data;
        }

        @end

        @implementation TableViewController

        - (void)viewDidLoad {
            [super viewDidLoad];
            data = [NSMutableArray array];
            [self.tableView reloadData];
        }

        - (IBAction)callingSecondView:(id)sender {

            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
            ViewController *var = [storyboard instantiateViewControllerWithIdentifier:@"vc"];
            var.delegate = self;
            [self.navigationController pushViewController:var animated:YES];
        }
        -(void)getdata:(NSString *)name{

            [data addObject:name];
            [self.tableView reloadData];

        }
        #pragma mark - Table view data source

        - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

            return 1;
        }

        - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

            return [data count];
        }
        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"  forIndexPath:indexPath];

            if (cell != nil) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];

            }
            cell.textLabel.text = [data objectAtIndex:indexPath.row];
            return cell;
        }

And I am creating delegate a object and protocol in ViewController.h

        #import <UIKit/UIKit.h>

        @protocol name <NSObject>

        -(void)getdata : (NSString *)name;

        @end

        @interface ViewController : UIViewController
        @property (strong, nonatomic) IBOutlet UITextField *txt;
        - (IBAction)done:(id)sender;

        @property(nonatomic,retain) id<name> delegate;

ViewController.m

        #import "ViewController.h"

        @interface ViewController ()

        @end

        @implementation ViewController
        @synthesize delegate;
        - (void)viewDidLoad {
            [super viewDidLoad];

        }
        - (IBAction)done:(id)sender {

            [delegate getdata:self.txt.text];
            [self.navigationController popToRootViewControllerAnimated:YES];

        }
        @end

Body:
I think the first VC don't reloadData because it's not the visible VC. Try reloadData when the VC willAppear.

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}


问:
Why is unsigned 4 not considered greater than signed -2?
```<code>unsigned int x = 4;
int y = -2;
int z = x > y;
</code>```

When realizing this operation the value for the variable Z is 0, but why it is 0 and not 1?.

答:
This is a result of arithmetic conversions.

In the expression x > y, you have one int operand and one unsigned int operand.  y is promoted to unsigned int, and the value converted by adding one more than the maximum unsigned int value to the value of y.

Section 6.3.1.8 of the C standard covering arithmetic conversions states the following:

Many operators that expect operands of arithmetic type cause
  conversions and yield result types in a similar way. The purpose is to
  determine a common real type for the operands and result. For the
  specified operands, each operand is converted, without change of type
  domain, to a type whose corresponding real type is the common real
  type. Unless explicitly stated otherwise, the common real type is also
  the corresponding real type of the result, whose type domain is the
  type domain of the operands if they are the same, and complex
  otherwise. This pattern is called the usual arithmetic conversions

...

Otherwise, if the operand that has unsigned integer type has rank
  greater or equal to the rank of the type of the other operand, then
  the operand with signed integer type is converted to the type of the
  operand with unsigned integer type.

So now y is a very large value being compared against x which is 4.  Since x is smaller than this value, x > y evaluates to false, which has a value of 0.

Body:
unsigned int x = 4;
int y = -2;
int z = x > y;

When realizing this operation the value for the variable Z is 0, but why it is 0 and not 1?.


问:
Ext js Combo box help
I am trying to define a combo box drop down using Ext Js which would display my "Holidays" saved in array. Please correct me where I could be wrong as the JSP wont display combobox drop down.</p>

```<code>  ...
  <body>
  <div class="left " style="color:#333333;padding-bottom:8px;padding-left:13px;width:99%;" id="Holiday">

  <span class="formastrickmargin"><strong></strong></span>
  </div>
  <div id="Holiday" class="left " style="padding-bottom:6px;padding-left:15px;width:99%;">

  </div>
   </body>

  <script type="text/javascript">
  var availableTags = ["New years Day", "Martin Luther King Day", "Groundhog Day", "Valentine's Day", "Washington's Birthday",
                 "Easter", "Earth Day", "National Arbor Day", "Mother's Day", "Memorial Day", "Flag Day", "Father's Day",
                 "Independence Day", "Labor Day", "Columbus Day", "Halloween", "Veterans Day", "Thanksgiving Day"];
   var combo1;
   var defaultDDText = 'Enter the Site Id here, or select from dropdown.';
   var Holidaystore = new Ext.data.ArrayStore({
         root: 'availableTags',
         autoLoad:true,
         fields: ['availableTags'],
         data: availableTags
        });

   Ext.onReady(function(){
   Ext.QuickTips.init();
   function initializeHoliday(){

    combo1 = new Ext.form.ComboBox({
            id:'Holiday',
            typeAhead: true,
            triggerAction: 'all',
            emptyText: defaultDDText,
            store:Holidaystore,
            selectOnFocus:true,
            width:408,
            listWidth: '410',
            mode: 'local',
            minChars : '3',
            renderTo:'Holiday',
            displayField: 'availableTags',

}); }
initializeHoliday();
});

 </script>
</code>```

答:
I will start with removing root: or

```
var availableTags = {
  data : ["New years Day", "Martin Luther King Day", "Groundhog Day",
          "Valentine's Day", "Washington's Birthday", "Easter", "Earth Day",
          "National Arbor Day", "Mother's Day", "Memorial Day", "Flag Day",
          "Father's Day", "Independence Day", "Labor Day", "Columbus Day",
          "Halloween", "Veterans Day", "Thanksgiving Day"]
};
```

and next root: data

Title: Ext js Combo box help

Body:
I am trying to define a combo box drop down using Ext Js which would display my "Holidays" saved in array. Please correct me where I could be wrong as the JSP wont display combobox drop down.

  ...

Body:
I will start with removing root: or

var availableTags = {
  data : ["New years Day", "Martin Luther King Day", "Groundhog Day",
          "Valentine's Day", "Washington's Birthday", "Easter", "Earth Day",
          "National Arbor Day", "Mother's Day", "Memorial Day", "Flag Day",
          "Father's Day", "Independence Day", "Labor Day", "Columbus Day",
          "Halloween", "Veterans Day", "Thanksgiving Day"]
};

and next root: data


问:
how to find if a string has multiple phrases but in different order and cannot have more phrases or less and can have spaces in between
say for example I have a the following strings

```<code>$a = "crt d a e f b";
$b = "b e a d c f";
$c = "a b c d g e";
$d = "a b c";
$e = "abcdef";
$f = "a b c d e r f t";
$g = "aabc d e f";
</code>```

All i want to find is if my string is having "a", "b", "c", "d", "e", "f", "r", "t" where the string must not have anything other than the specified strings and the string must have all the specified strings in it may can separated by spaces.

maybe something like say compare($a, [ "a", "b", "c", "d", "e", "f", "r", "t" ]; should give me the output as follows.

```<code>$map = [ "a", "b", "c", "d", "e", "f", "r", "t" ];;
compare($a, $map); // false
compare($b, $map); // false
compare($c, $map); // false
compare($d, $map); // false
compare($e, $map); // false
compare($f, $map); // true
compare($g, $map); // false
</code>```

Can anyone help me out to solve this?

答:
Maybe you could create an array out of the strings, sort and compare them.</p>

```<code>$a = "crt d a e f b";
$b = "b e a d c f";
$c = "a b c d g e";
$d = "a b c";
$e = "abcdef";
$f = "a b c d e r f t";
$g = "aabc d e f";

$base = [ "a", "b", "c", "d", "e", "f", "r", "t" ];

var_dump(compare($a, $base)); //false
var_dump(compare($b, $base)); //false
var_dump(compare($c, $base)); //false
var_dump(compare($d, $base)); //false
var_dump(compare($e, $base)); //false
var_dump(compare($f, $base)); //true
var_dump(compare($g, $base)); //false

function compare($a, $map) {
    $stringParts = explode(' ', $a);
    sort($stringParts);
    sort($map);
    return $stringParts === $map;
}
</code>```

Body:
say for example I have a the following strings

$a = "crt d a e f b";
$b = "b e a d c f";
$c = "a b c d g e";
$d = "a b c";
$e = "abcdef";
$f = "a b c d e r f t";
$g = "aabc d e f";

All i want to find is if my string is having "a", "b", "c", "d", "e", "f", "r", "t" where the string must not have anything other than the specified strings and the string must have all the specified strings in it may can separated by spaces.

maybe something like say compare($a, [ "a", "b", "c", "d", "e", "f", "r", "t" ]; should give me the output as follows.

$map = [ "a", "b", "c", "d", "e", "f", "r", "t" ];;
compare($a, $map); // false
compare($b, $map); // false
compare($c, $map); // false
compare($d, $map); // false
compare($e, $map); // false
compare($f, $map); // true
compare($g, $map); // false

Can anyone help me out to solve this?

Body:
Maybe you could create an array out of the strings, sort and compare them.

$a = "crt d a e f b";
$b = "b e a d c f";
$c = "a b c d g e";
$d = "a b c";
$e = "abcdef";
$f = "a b c d e r f t";
$g = "aabc d e f";

$base = [ "a", "b", "c", "d", "e", "f", "r", "t" ];

var_dump(compare($a, $base)); //false
var_dump(compare($b, $base)); //false
var_dump(compare($c, $base)); //false
var_dump(compare($d, $base)); //false
var_dump(compare($e, $base)); //false
var_dump(compare($f, $base)); //true
var_dump(compare($g, $base)); //false

function compare($a, $map) {
    $stringParts = explode(' ', $a);
    sort($stringParts);
    sort($map);
    return $stringParts === $map;
}


问:
Selective read/write permissions on a samba share to a windows server
We have shared our file system across our ecosystem and we use samba to share it to our windows servers. The issue is that we would like the windows server to have only read permission to certain subfolders under the share. Is it even possible or is NFS better suited for this?</p>

答: Actually, I am not sure if you can just create read-only NFS shares for these certain subfolders separately. You can mount the main share as R/O and then export the subfolders (separate definition in /etc/exports) which can be read and written as another share. I am not sure of this solution, but you should try this to achieve what you intend.</p>


问:
boost::asio, threads and synchronization
This is somewhat related to this question, but I think I need to know a little bit more.  I've been trying to get my head around how to do this for a few days (whilst working on other parts), but the time has come for me to bite the bullet and get multi-threaded.  Also, I'm after a bit more information than the question linked.

Firstly, about multi-threading.  As I have been testing my code, I've not bothered with any multi-threading.  It's just a console application that starts a connection to a test server and everything else is then handled.  The main loop is this:

```<code>while(true)
{
    Root::instance().performIO(); // calls io_service::runOne();
}
</code>```

When I write my main application, I'm guessing this solution won't be acceptable (as it would have to be called in the message loop which, whilst possible, would have issues when the message queue blocks waiting for a message.  You could change it so that the message-loop doesn't block, but then isn't that going to whack the CPU usage through the roof?)

The solution it seems is to throw another thread at it.  Okay, fine.  But then I've read that io_service::run() returns when there is no work to do.  What is that?  Is that when there's no data, or no connections?  If at least one connection exists does it stay alive?  If so, that's not so much of a problem as I only have to start up a new thread when the first connection is made and I'm happy if it all stops when there is nothing going on at all.  I guess I am confused by the definition of 'no work to do'.

Then I have to worry about synchronizing my boost thread with my main GUI thread.  So, I guess my questions are:

What is the best-practice way of using boost::asio in a client application with regard to threads and keeping them alive?

When writing to a socket from the main thread to the IO thread, is synchronization achieved using boost::asio::post, so that the call happens later in the io_service?

When data is received, how do people get the data back to the UI thread?  In the past when I used completion ports, I made a special event that could post the data back to the main UI thread using a ::SendMessage.  It wasn't elegant, but it worked.

I'll be reading some more today, but it would be great to get a heads up from someone who has done this already.  The Boost::asio documentation isn't great, and most of my work so far has been based on a bit of the documentation, some trial/error, some example code on the web.

答:
1) Have a look at io_service::work. As long as an work object exists io_service::run will not return. So if you start doing your clean up, destroy the work object, cancel any outstanding operations, for example an async_read on a socket, wait for run to return and clean up your resources.

2) io_service::post will asynchronously execute the given handler from a thread running the io_service. A callback can be used to get the result of the operation executed.

3) You needs some form of messaging system to inform your GUI thread of the new data. There are several possibilities here.

As far as your remark about the documention, I thing Asio is one of the better documented boost libraries and it comes with clear examples.

Body:
This is somewhat related to this question, but I think I need to know a little bit more.  I've been trying to get my head around how to do this for a few days (whilst working on other parts), but the time has come for me to bite the bullet and get multi-threaded.  Also, I'm after a bit more information than the question linked.

Firstly, about multi-threading.  As I have been testing my code, I've not bothered with any multi-threading.  It's just a console application that starts a connection to a test server and everything else is then handled.  The main loop is this:

while(true)
{
    Root::instance().performIO(); // calls io_service::runOne();
}

When I write my main application, I'm guessing this solution won't be acceptable (as it would have to be called in the message loop which, whilst possible, would have issues when the message queue blocks waiting for a message.  You could change it so that the message-loop doesn't block, but then isn't that going to whack the CPU usage through the roof?)

The solution it seems is to throw another thread at it.  Okay, fine.  But then I've read that io_service::run() returns when there is no work to do.  What is that?  Is that when there's no data, or no connections?  If at least one connection exists does it stay alive?  If so, that's not so much of a problem as I only have to start up a new thread when the first connection is made and I'm happy if it all stops when there is nothing going on at all.  I guess I am confused by the definition of 'no work to do'.

Then I have to worry about synchronizing my boost thread with my main GUI thread.  So, I guess my questions are:

What is the best-practice way of using boost::asio in a client application with regard to threads and keeping them alive?

When writing to a socket from the main thread to the IO thread, is synchronization achieved using boost::asio::post, so that the call happens later in the io_service?

When data is received, how do people get the data back to the UI thread?  In the past when I used completion ports, I made a special event that could post the data back to the main UI thread using a ::SendMessage.  It wasn't elegant, but it worked.

I'll be reading some more today, but it would be great to get a heads up from someone who has done this already.  The Boost::asio documentation isn't great, and most of my work so far has been based on a bit of the documentation, some trial/error, some example code on the web.


问:
Angular 4 reactive form pattern
I've been trying to write a pattern that validates this kind of matriculation number HND/18/BAM/FT/033 or ND/18/BAM/FT/025...

I came up with this pattern but it's not working

... / "^[(NDY | (HND)] \/ [0-9]{2} \/ [a-zA-Z]{3} \/ [(FT) | (PT)] \/ [0-9]{3}$ "/

I would really appreciate it if I could get an answer

答:
Converting to an answer:

^(HND|ND)\/[0-9]{2}\/[a-zA-Z]{3}\/(FT|PT)\/[0-9]{3}$

Try it here: https://regex101.com/r/cjN4Am/1/

Tested here by inputting the regex returns:

```<code>HND/14/uad/FT/784
HND/24/Jqu/PT/425
HND/88/MJe/FT/398
ND/35/wXT/FT/306
HND/01/dGW/FT/973
</code>```

Title: Angular 4 reactive form pattern

Body:
Converting to an answer:

^(HND|ND)\/[0-9]{2}\/[a-zA-Z]{3}\/(FT|PT)\/[0-9]{3}$

Try it here: https://regex101.com/r/cjN4Am/1/

Tested here by inputting the regex returns:

HND/14/uad/FT/784
HND/24/Jqu/PT/425
HND/88/MJe/FT/398
ND/35/wXT/FT/306
HND/01/dGW/FT/973