问:
How to print PartialView
i was looking for this and tried to fix for couple of days but with no sucess. What wrong im doing in this code? I want to print _Champions
and _SearchEngine as PartialView in Home/Index but it show error.

My HomeController

```<code> public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
[HttpGet]
        public ActionResult _SearchEngine()
        {
            SearchLeagueModel searchLeagueModel = new SearchLeagueModel();
            searchLeagueModel.MainSelector = "champions";
            return PartialView("_SearchEngine", searchLeagueModel);
        }
        public ActionResult _SearchEngine(SearchLeagueModel searchLeagueModel)
        {
            if (searchLeagueModel.MainSelector == "champions")
            {
                return RedirectToAction("_Champions", searchLeagueModel);
            }
            else return View();
        }
        [HttpPost]
        public ActionResult _Champions(SearchLeagueModel searchLeagueModel)
        {
            string chooser = searchLeagueModel.MainSelector;
            string selector;
            if (searchLeagueModel.MainSelector != null)
            {
                selector = "filter[name]=" + searchLeagueModel.MainSelector;
            }
            else
            {
                selector = "";
            }
                WebRequest request = WebRequest.Create("https://api.pandascore.co/lol/" + chooser + "?" + selector + "&token=mytoken);
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                string responseFromServer = reader.ReadToEnd();
                List<ChampionsModel> champions = JsonConvert.DeserializeObject<List<ChampionsModel>>(responseFromServer);
                return PartialView("_Champions", champions);
        }
//other views
}
</code>```

My IndexModelView

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace LeagueAPI.Models
{
    public class IndexModelView
    {
        public IndexModelView()
        {
            ChampionsList = new ChampionsModel();
            Searcher = new SearchLeagueModel();
        }
        public ChampionsModel ChampionsList { get; set; }
        public SearchLeagueModel Searcher { get; set; }
    }

    public class ChampionsModel
    {
        public List<string> videogame_versions { get; set; }
        public double spellblockperlevel { get; set; }
        public double spellblock { get; set; }
        public string name { get; set; }
        public double mpregenperlevel { get; set; }
        public double mpregen { get; set; }
        public double mpperlevel { get; set; }
        public double mp { get; set; }
        public double movespeed { get; set; }
        public string image_url { get; set; }
        public int id { get; set; }
        public double hpregenperlevel { get; set; }
        public double hpregen { get; set; }
        public double hpperlevel { get; set; }
        public double hp { get; set; }
        public double critperlevel { get; set; }
        public double crit { get; set; }
        public string big_image_url { get; set; }
        public double attackspeedperlevel { get; set; }
        public object attackspeedoffset { get; set; }
        public double attackrange { get; set; }
        public double attackdamageperlevel { get; set; }
        public double attackdamage { get; set; }
        public double armorperlevel { get; set; }
        public double armor { get; set; }
    }
}
</code>```

My _Champions.cshtml PartialView(made as PartialView)

```<code>@using LeagueAPI.Models
@model System.Collections.Generic.List<ChampionsModel>
<fieldset>
    <div class="d-flex p-3 w-auto h-auto">
        @foreach (var element in @Model)
        {
            <div class="p-3 flex-lg-wrap">
                <div class="card p-2" style="width: 15rem ;">
                    <img class="card-img-top" src="@Html.DisplayFor(model => element.big_image_url)">
                    <div class="card-body p-0 m-0">
                        <h5 class="card-title p-0 m-0 text-center">@Html.DisplayFor(model => element.name)</h5>
                        <p class="card-text p-0 m-0">DMG/LVL: @Html.DisplayFor(model => element.attackdamageperlevel)</p>
                        <p class="card-text p-0 m-0">ARMOR/LVL: @Html.DisplayFor(model => element.armorperlevel)</p>
                        <p class="card-text p-0 m-0">MOVEMENT SPEED: @Html.DisplayFor(model => element.movespeed)</p>
                        <p class="card-text p-0 m-0">ATTACK RANGE: @Html.DisplayFor(model => element.attackrange)</p>
                        <a href="/Home/Details"
                           class="btn btn-primary m-1 "
                           OnClick="GreetingBtn_Click">More details</a>
                    </div>
                </div>
            </div>
        }
    </div>
</fieldset>
</code>```

Index View

```<code>@model LeagueAPI.Models.IndexModelView

@Html.Action("_SearchEngine", Model.Searcher)
@Html.Action("_Champions", Model.ChampionsList)

</code>```

Everything else looks standard, in _Layout i have @RenderBody()
My second question is about _Champions Controller. Why when i put IndexModelView indexModelView = new IndexModelView() as parametr and bring necessary changes in code to this ActionResult, the MainSelector is null in that case.
Im still learning, if You can explain whats wrong here i will be thankful. cheers

答:
Try this java Script:-</p>

```<code><script>
function printContent(el){
    var restorepage = document.body.innerHTML;
    var printcontent = document.getElementById(el).innerHTML;
    document.body.innerHTML = printcontent;
    window.print();
    document.body.innerHTML = restorepage;
}
</script>
</code>```

Title: How to print PartialView

Body:
i was looking for this and tried to fix for couple of days but with no sucess. What wrong im doing in this code? I want to print _Champions
and _SearchEngine as PartialView in Home/Index but it show error.

My HomeController

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
[HttpGet]
        public ActionResult _SearchEngine()
        {
            SearchLeagueModel searchLeagueModel = new SearchLeagueModel();
            searchLeagueModel.MainSelector = "champions";
            return PartialView("_SearchEngine", searchLeagueModel);
        }
        public ActionResult _SearchEngine(SearchLeagueModel searchLeagueModel)
        {
            if (searchLeagueModel.MainSelector == "champions")
            {
                return RedirectToAction("_Champions", searchLeagueModel);
            }
            else return View();
        }
        [HttpPost]
        public ActionResult _Champions(SearchLeagueModel searchLeagueModel)
        {
            string chooser = searchLeagueModel.MainSelector;
            string selector;
            if (searchLeagueModel.MainSelector != null)
            {
                selector = "filter[name]=" + searchLeagueModel.MainSelector;
            }
            else
            {
                selector = "";
            }
                WebRequest request = WebRequest.Create("https://api.pandascore.co/lol/" + chooser + "?" + selector + "&token=mytoken);
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                string responseFromServer = reader.ReadToEnd();
                List<ChampionsModel> champions = JsonConvert.DeserializeObject<List<ChampionsModel>>(responseFromServer);
                return PartialView("_Champions", champions);
        }
//other views
}

My IndexModelView

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace LeagueAPI.Models
{
    public class IndexModelView
    {
        public IndexModelView()
        {
            ChampionsList = new ChampionsModel();
            Searcher = new SearchLeagueModel();
        }
        public ChampionsModel ChampionsList { get; set; }
        public SearchLeagueModel Searcher { get; set; }
    }

    public class ChampionsModel
    {
        public List<string> videogame_versions { get; set; }
        public double spellblockperlevel { get; set; }
        public double spellblock { get; set; }
        public string name { get; set; }
        public double mpregenperlevel { get; set; }
        public double mpregen { get; set; }
        public double mpperlevel { get; set; }
        public double mp { get; set; }
        public double movespeed { get; set; }
        public string image_url { get; set; }
        public int id { get; set; }
        public double hpregenperlevel { get; set; }
        public double hpregen { get; set; }
        public double hpperlevel { get; set; }
        public double hp { get; set; }
        public double critperlevel { get; set; }
        public double crit { get; set; }
        public string big_image_url { get; set; }
        public double attackspeedperlevel { get; set; }
        public object attackspeedoffset { get; set; }
        public double attackrange { get; set; }
        public double attackdamageperlevel { get; set; }
        public double attackdamage { get; set; }
        public double armorperlevel { get; set; }
        public double armor { get; set; }
    }
}

My _Champions.cshtml PartialView(made as PartialView)

@using LeagueAPI.Models
@model System.Collections.Generic.List<ChampionsModel>
<fieldset>

        @foreach (var element in @Model)
        {

                     element.big_image_url)">

@Html.DisplayFor(model => element.name)

DMG/LVL: @Html.DisplayFor(model => element.attackdamageperlevel)

ARMOR/LVL: @Html.DisplayFor(model => element.armorperlevel)

MOVEMENT SPEED: @Html.DisplayFor(model => element.movespeed)

ATTACK RANGE: @Html.DisplayFor(model => element.attackrange)

                        More details

        }

</fieldset>

Index View

@model LeagueAPI.Models.IndexModelView

@Html.Action("_SearchEngine", Model.Searcher)
@Html.Action("_Champions", Model.ChampionsList)

Everything else looks standard, in _Layout i have @RenderBody()
My second question is about _Champions Controller. Why when i put IndexModelView indexModelView = new IndexModelView() as parametr and bring necessary changes in code to this ActionResult, the MainSelector is null in that case.
Im still learning, if You can explain whats wrong here i will be thankful. cheers

Body:
Try this java Script:-

<script>
function printContent(el){
    var restorepage = document.body.innerHTML;
    var printcontent = document.getElementById(el).innerHTML;
    document.body.innerHTML = printcontent;
    window.print();
    document.body.innerHTML = restorepage;
}
</script>


来源: stackexchange

问:
Fatal error: Call to undefined method Action::execute() /home/public_html/system/engine/event.php on line 62
Hi tried refreshing the modification cache cache in opencart and since then i am getting a blank page in front end with this error message.

```<code>public function trigger($event, array $args = array()) {
        foreach ($this->data as $value) {
            if (preg_match('/^' . str_replace(array('\*', '\?'), array('.*', '.'), preg_quote($value['trigger'], '/')) . '/', $event)) {
                $result = $value['action']->execute($this->registry, $args);

            if (!is_null($result) && !($result instanceof Exception)) {
                return $result;
            }
        }
    }
}
</code>```

Thanks,

答:
It seems your have an OC version 3.0.2.x or above.

In your $this->data of the Event Class, you have an event registered that is missing an action parameter.

$this->data[] = array(
    'trigger'  => $trigger,
    'action'   => $action, // <-- this must be an Action Object with a method execute()
    'priority' => $priority
);
```

<p>All events are registered via the <code>register()</code> method which explicitly requests that an Action object is being passed as a parameter.</p>

<p>Since the error is pointing to "Call to undefined method Action::execute()", I can assume, you have an issue with the action class.</p>

<p>Most likely you need to check the Modifications of the <code>system/engine/action.php</code> file in your <code>system/storage/modifications</code>.</p>

<p>It could be that the method <code>execute()</code> is either missing or somehow corrupt.</p>

<h2>Debug</h2>

<p>try to var_dump the $value to see what is there:</p>

<pre class="lang-php prettyprint-override"><code>public function trigger($event, array $args = array()) {
        foreach ($this->data as $value) {
//log out the $value before the error to see if the Action object is actually there and see what trigger causes this.
var_dump($value);
            if (preg_match('/^' . str_replace(array('\*', '\?'), array('.*', '.'), preg_quote($value['trigger'], '/')) . '/', $event)) {
                $result = $value['action']->execute($this->registry, $args);

            if (!is_null($result) && !($result instanceof Exception)) {
                return $result;
            }
        }
    }
}
</code>```

Hope this helps

ContentLicense: CC BY-SA 4.0

Body:
Hi tried refreshing the modification cache cache in opencart and since then i am getting a blank page in front end with this error message.

public function trigger($event, array $args = array()) {
        foreach ($this->data as $value) {
            if (preg_match('/^' . str_replace(array('\*', '\?'), array('.*', '.'), preg_quote($value['trigger'], '/')) . '/', $event)) {
                $result = $value['action']->execute($this->registry, $args);

            if (!is_null($result) && !($result instanceof Exception)) {
                return $result;
            }
        }
    }
}

Thanks,

Body:
It seems your have an OC version 3.0.2.x or above.

In your $this->data of the Event Class, you have an event registered that is missing an action parameter.

$this->data[] = array(
    'trigger'  => $trigger,
    'action'   => $action, // <-- this must be an Action Object with a method execute()
    'priority' => $priority
);

All events are registered via the register() method which explicitly requests that an Action object is being passed as a parameter.

Since the error is pointing to "Call to undefined method Action::execute()", I can assume, you have an issue with the action class.

Most likely you need to check the Modifications of the system/engine/action.php file in your system/storage/modifications.

It could be that the method execute() is either missing or somehow corrupt.

Debug

try to var_dump the $value to see what is there:

public function trigger($event, array $args = array()) {
        foreach ($this->data as $value) {
//log out the $value before the error to see if the Action object is actually there and see what trigger causes this.
var_dump($value);
            if (preg_match('/^' . str_replace(array('\*', '\?'), array('.*', '.'), preg_quote($value['trigger'], '/')) . '/', $event)) {
                $result = $value['action']->execute($this->registry, $args);

            if (!is_null($result) && !($result instanceof Exception)) {
                return $result;
            }
        }
    }
}

Hope this helps


问:
library for editing photos
I want to implement an algorithm for compressing BMP images. What library/sdk would you recommend for helping with reading a picture's pixels, and creating an image pixel by pixel?</p>

答:
Try this tutorial. this will help you to do normal jobs with images in a tutorial format using C#:

http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-rotate

for working with images in pixel level see this thread :

How to manipulate images at the pixel level in C#

ContentLicense: CC BY-SA 3.0

Title: library for editing photos


问:
Spring: ExceptionTranslator of OAuth2 not working
In Spring with OAuth2, with an invalid access token, InvalidTokenException will occur and output:

```<code>{"error":"invalid_token","error_description":"Invalid access token: asdfasdf"}
</code>```

when in json format.

I am trying to customize the output, such as

```<code>{"code": 123, "error":"invalid_token","error_description":"Invalid access token: asdfasdf"}
</code>```

To do this I followed this example on Github https://github.com/spring-projects/spring-security-oauth/issues/375 and my code looks like this below. The problem is that my webResponseExceptionTranslator() never gets called. What is the problem?

```<code>package com.my.config;

import....

@Configuration
public class OAuth2ServerConfiguration {

    private final DataSource dataSource;

    public OAuth2ServerConfiguration(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Bean
    public JdbcTokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        private final TokenStore tokenStore;

        private final Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint;

        private final AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;

        private final CorsFilter corsFilter;

        public ResourceServerConfiguration(TokenStore tokenStore, Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint,
                                           AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler, CorsFilter corsFilter) {

            this.tokenStore = tokenStore;
            this.http401UnauthorizedEntryPoint = http401UnauthorizedEntryPoint;
            this.ajaxLogoutSuccessHandler = ajaxLogoutSuccessHandler;
            this.corsFilter = corsFilter;
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .exceptionHandling()
                .authenticationEntryPoint(http401UnauthorizedEntryPoint)
                .and()
                .logout()
                .logoutUrl("/api/logout")
                .logoutSuccessHandler(ajaxLogoutSuccessHandler)
                .and()
                .csrf()
                .disable()
                .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
                .headers()
                .frameOptions().disable()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers("/api/authenticate").permitAll()
                .antMatchers("/api/register").permitAll()
                .antMatchers("/api/profile-info").permitAll()
                .antMatchers("/api/**").authenticated()
                .antMatchers(G.IFTTT_PATH).permitAll()
                .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/v2/api-docs/**").permitAll()
                .antMatchers("/swagger-resources/configuration/ui").permitAll()
                .antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN);
        }

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources.resourceId("res_q").tokenStore(tokenStore)
                .accessDeniedHandler(new OAuth2AccessDeniedHandler());
        }
    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        private final AuthenticationManager authenticationManager;

        private final TokenStore tokenStore;

        private final DataSource dataSource;

        public AuthorizationServerConfiguration(@Qualifier("authenticationManagerBean") AuthenticationManager authenticationManager,
                                                TokenStore tokenStore, DataSource dataSource) {

            this.authenticationManager = authenticationManager;
            this.tokenStore = tokenStore;
            this.dataSource = dataSource;
        }

        @Bean
        protected AuthorizationCodeServices authorizationCodeServices() {
            return new JdbcAuthorizationCodeServices(dataSource);
        }

        @Bean
        public WebResponseExceptionTranslator webResponseExceptionTranslator() {
            return new DefaultWebResponseExceptionTranslator() {

                @Override
                public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
                    // ==================== never gets called ===============
                    ResponseEntity<OAuth2Exception> responseEntity = super.translate(e);
                    OAuth2Exception body = responseEntity.getBody();
                    HttpHeaders headers = new HttpHeaders();
                    headers.setAll(responseEntity.getHeaders().toSingleValueMap());
                    // do something with header or response
                    System.out.println("========================== in webResponseExceptionTranslator  ===============================");
                    return new ResponseEntity<>(body, headers, responseEntity.getStatusCode());
                }
            };
        }

        @Bean
        public ApprovalStore approvalStore() {
            return new JdbcApprovalStore(dataSource);
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
            endpoints
                //========================== here ====================
                .exceptionTranslator(webResponseExceptionTranslator())
                //====================================================
                .authorizationCodeServices(authorizationCodeServices())
                .approvalStore(approvalStore())
                .tokenStore(tokenStore)
                .authenticationManager(authenticationManager);
        }

        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            oauthServer.allowFormAuthenticationForClients();
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.jdbc(dataSource);
        }
    }
}
</code>```

答:
My working solution for customizing the default oauth error message is this:

```<code>@Configurationpublic class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

@Override
public void configure(ResourceServerSecurityConfigurer resources) {
    OAuth2AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
    authenticationEntryPoint.setExceptionTranslator(new CustomWebResponseExceptionTranslator());
    resources.authenticationEntryPoint(authenticationEntryPoint);
}

private class CustomWebResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator  {
    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
        ResponseEntity<OAuth2Exception> responseEntity = super.translate(e);
        OAuth2Exception body = responseEntity.getBody();
        HttpHeaders headers = new HttpHeaders();
        headers.setAll(responseEntity.getHeaders().toSingleValueMap());
        // do something with header or response
        return new ResponseEntity<>(body, headers, responseEntity.getStatusCode());
    }
}
</code>```

}

Body:
In Spring with OAuth2, with an invalid access token, InvalidTokenException will occur and output:

{"error":"invalid_token","error_description":"Invalid access token: asdfasdf"}

when in json format.

I am trying to customize the output, such as

{"code": 123, "error":"invalid_token","error_description":"Invalid access token: asdfasdf"}

To do this I followed this example on Github https://github.com/spring-projects/spring-security-oauth/issues/375 and my code looks like this below. The problem is that my webResponseExceptionTranslator() never gets called. What is the problem?

package com.my.config;

import....

@Configuration
public class OAuth2ServerConfiguration {

    private final DataSource dataSource;

    public OAuth2ServerConfiguration(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Bean
    public JdbcTokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        private final TokenStore tokenStore;

        private final Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint;

        private final AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;

        private final CorsFilter corsFilter;

        public ResourceServerConfiguration(TokenStore tokenStore, Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint,
                                           AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler, CorsFilter corsFilter) {

            this.tokenStore = tokenStore;
            this.http401UnauthorizedEntryPoint = http401UnauthorizedEntryPoint;
            this.ajaxLogoutSuccessHandler = ajaxLogoutSuccessHandler;
            this.corsFilter = corsFilter;
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .exceptionHandling()
                .authenticationEntryPoint(http401UnauthorizedEntryPoint)
                .and()
                .logout()
                .logoutUrl("/api/logout")
                .logoutSuccessHandler(ajaxLogoutSuccessHandler)
                .and()
                .csrf()
                .disable()
                .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
                .headers()
                .frameOptions().disable()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers("/api/authenticate").permitAll()
                .antMatchers("/api/register").permitAll()
                .antMatchers("/api/profile-info").permitAll()
                .antMatchers("/api/**").authenticated()
                .antMatchers(G.IFTTT_PATH).permitAll()
                .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/v2/api-docs/**").permitAll()
                .antMatchers("/swagger-resources/configuration/ui").permitAll()
                .antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN);
        }

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources.resourceId("res_q").tokenStore(tokenStore)
                .accessDeniedHandler(new OAuth2AccessDeniedHandler());
        }
    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        private final AuthenticationManager authenticationManager;

        private final TokenStore tokenStore;

        private final DataSource dataSource;

        public AuthorizationServerConfiguration(@Qualifier("authenticationManagerBean") AuthenticationManager authenticationManager,
                                                TokenStore tokenStore, DataSource dataSource) {

            this.authenticationManager = authenticationManager;
            this.tokenStore = tokenStore;
            this.dataSource = dataSource;
        }

        @Bean
        protected AuthorizationCodeServices authorizationCodeServices() {
            return new JdbcAuthorizationCodeServices(dataSource);
        }

        @Bean
        public WebResponseExceptionTranslator webResponseExceptionTranslator() {
            return new DefaultWebResponseExceptionTranslator() {

                @Override
                public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
                    // ==================== never gets called ===============
                    ResponseEntity<OAuth2Exception> responseEntity = super.translate(e);
                    OAuth2Exception body = responseEntity.getBody();
                    HttpHeaders headers = new HttpHeaders();
                    headers.setAll(responseEntity.getHeaders().toSingleValueMap());
                    // do something with header or response
                    System.out.println("========================== in webResponseExceptionTranslator  ===============================");
                    return new ResponseEntity<>(body, headers, responseEntity.getStatusCode());
                }
            };
        }

        @Bean
        public ApprovalStore approvalStore() {
            return new JdbcApprovalStore(dataSource);
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
            endpoints
                //========================== here ====================
                .exceptionTranslator(webResponseExceptionTranslator())
                //====================================================
                .authorizationCodeServices(authorizationCodeServices())
                .approvalStore(approvalStore())
                .tokenStore(tokenStore)
                .authenticationManager(authenticationManager);
        }

        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            oauthServer.allowFormAuthenticationForClients();
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.jdbc(dataSource);
        }
    }
}

Body:
My working solution for customizing the default oauth error message is this:

@Configurationpublic class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

@Override
public void configure(ResourceServerSecurityConfigurer resources) {
    OAuth2AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
    authenticationEntryPoint.setExceptionTranslator(new CustomWebResponseExceptionTranslator());
    resources.authenticationEntryPoint(authenticationEntryPoint);
}

private class CustomWebResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator  {
    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
        ResponseEntity<OAuth2Exception> responseEntity = super.translate(e);
        OAuth2Exception body = responseEntity.getBody();
        HttpHeaders headers = new HttpHeaders();
        headers.setAll(responseEntity.getHeaders().toSingleValueMap());
        // do something with header or response
        return new ResponseEntity<>(body, headers, responseEntity.getStatusCode());
    }
}

}


问:
Building Kernel from a custom .config with Buildroot
I'm trying to generate a custom image for raspberrypi 3 with the usage of buildroot. I have a custom .config for Buildroot options where I give the path to BR2_KERNEL_CUSTOM_CONFIG_FILE which is located in /boards/raspberrypi3/linux.config

But in the patching stage of the build I find the following error:

```<code>for f in boards/raspberrypi3/.config ; do
    if [ ! -f "${f}" ]; then
        printf "Kconfig fragment '%s' for '%s' does not exist\n" "${f}" "linux";
        exit 1;
    fi;
done
</code>```

Kconfig fragment

```<code>'boards/raspberrypi3/linux.config' for 'linux' does not exist
linux/linux.mk:555: recipe for target 'boards/raspberrypi3/.config' failed
</code>```

When I only use the .config of buildroot without any path to a custom Linux Kernel config (using the default kernel in menuconfig) everything builds fine.

答:
What is the correct file name for your linux configuration file? You mention that you point BR2_KERNEL_CUSTOM_CONFIG_FILE to /boards/raspberrypi3/linux.config (presumably without the leading slash), but your output snippet shows boards/raspberrypi3/.config?

The upstream location for raspberrypi 3 files is under board/raspberrypi3 (notice BOARD not BOARDS). Please double check

Body:
I'm trying to generate a custom image for raspberrypi 3 with the usage of buildroot. I have a custom .config for Buildroot options where I give the path to BR2_KERNEL_CUSTOM_CONFIG_FILE which is located in /boards/raspberrypi3/linux.config

But in the patching stage of the build I find the following error:

for f in boards/raspberrypi3/.config ; do
    if [ ! -f "${f}" ]; then
        printf "Kconfig fragment '%s' for '%s' does not exist\n" "${f}" "linux";
        exit 1;
    fi;
done

Kconfig fragment

'boards/raspberrypi3/linux.config' for 'linux' does not exist
linux/linux.mk:555: recipe for target 'boards/raspberrypi3/.config' failed

When I only use the .config of buildroot without any path to a custom Linux Kernel config (using the default kernel in menuconfig) everything builds fine.


问:
Webpack Encore didn't write css and js in folder "build" in production environment of Symfony 4
I'm working with Symfony 4 and my deployment platform is Microsoft Azure. This is my website :https://synergie-2i.azurewebsites.net/SynergieInformatique/public/index.php/.

My problem is when my environment is in production, my css and js aren't loaded. When inspect my page in services i see my folder SynergieInformatique/public and an other folder name build. Inside there is 3 css files but there is nothing inside. I think webpack didn't write my css in these files.

I have try to copy my css and put in the empty css file and it works but i don't know how make this with symfony.

When i'm in dev environement, the folder build is in SynergieInformatique/public and my css is loaded.

```<code>###webpack.config.js : ###
var Encore = require('@symfony/webpack-encore');
Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .addEntry('app', './assets/js/app.js')
   .addEntry('owlcarouselcss','./node_modules/owl.carousel/dist/assets/owl.carousel.min.css')
    .addEntry('owlcarouseljs','./node_modules/owl.carousel/dist/owl.carousel.min.js')
    .splitEntryChunks()
    .enableSingleRuntimeChunk()
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    .enableVersioning(Encore.isProduction())
    .configureBabel(() => {}, {
        useBuiltIns: 'usage',
        corejs: 3
    })
    .enableSassLoader()
    .autoProvideVariables({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery',
    });
module.exports = Encore.getWebpackConfig();`
</code>```

What are the step for deploy an symfony 4 application with Webpack and how i can have my css and js load on production environement ?
If you need more informations ask me :)

答: I have found, my links were bad. I use {{ encore_entry_link_tags('app') }} and this doesn't search at the good folder so i remplace this by <link rel="stylesheet" href="/SynergieInformatique/public//build/app.css"> and it works.

Body:
I'm working with Symfony 4 and my deployment platform is Microsoft Azure. This is my website :https://synergie-2i.azurewebsites.net/SynergieInformatique/public/index.php/.

My problem is when my environment is in production, my css and js aren't loaded. When inspect my page in services i see my folder SynergieInformatique/public and an other folder name build. Inside there is 3 css files but there is nothing inside. I think webpack didn't write my css in these files.

I have try to copy my css and put in the empty css file and it works but i don't know how make this with symfony.

When i'm in dev environement, the folder build is in SynergieInformatique/public and my css is loaded.

###webpack.config.js : ###
var Encore = require('@symfony/webpack-encore');
Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .addEntry('app', './assets/js/app.js')
   .addEntry('owlcarouselcss','./node_modules/owl.carousel/dist/assets/owl.carousel.min.css')
    .addEntry('owlcarouseljs','./node_modules/owl.carousel/dist/owl.carousel.min.js')
    .splitEntryChunks()
    .enableSingleRuntimeChunk()
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    .enableVersioning(Encore.isProduction())
    .configureBabel(() => {}, {
        useBuiltIns: 'usage',
        corejs: 3
    })
    .enableSassLoader()
    .autoProvideVariables({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery',
    });
module.exports = Encore.getWebpackConfig();`

What are the step for deploy an symfony 4 application with Webpack and how i can have my css and js load on production environement ?
If you need more informations ask me :)


问:
Change doxygen comment style in Eclipse
Does anyone know how to edit the style used for Doxygen comments in Eclipse CDT?

In other words type /** and pressing enter on a line before a function currently gives me something like:

```<code>/**
 *
 * @param one
 * @param two
 * @return
 */
Foo(int one, int two);
</code>```

and I want it to give me something like:

```<code>/**********************************************************************/
///
/// \param one
/// \param two
/// \return
/***********************************************************************/
Foo(int one, int two);
</code>```

Also, plus one if anyone knows how to bind this to a keyboard shortcut (like alt-shift-j for Eclipse JDT).

Also, FYI, the fact that Eclipse CDT supports Doxygen now seems to be a little known fact based on Google.  See here for details.  Doxygen can be enabled under the project properties by selecting "Enable project specific settings" in the "C/C++ General" tab and selecting "Doxygen".  My CDT version is 7.0.1, but I think this became available in 5.0.

Lastly, the comments section under code templates in preferences doesn't accomplish this based on my testing.

EDIT:
See here.  It seems like the comment style is hard coded.  If anyone finds otherwise, I'd love to know about it.  I guess templates will be the best thing for now unless the Javadoc style is okay for you.

答:
I can get some of the way to what you want by going to:
Preferences - PHP - Code Style - Code Templates - Comments.

I'm not sure that this will enable you to use backslashes instead of @s for your keywords, but I think it should achieve most of what you want.

Title: Change doxygen comment style in Eclipse

Body:
Does anyone know how to edit the style used for Doxygen comments in Eclipse CDT?

In other words type /** and pressing enter on a line before a function currently gives me something like:

/**
 *
 * @param one
 * @param two
 * @return
 */
Foo(int one, int two);

and I want it to give me something like:

/**********************************************************************/
///
/// \param one
/// \param two
/// \return
/***********************************************************************/
Foo(int one, int two);

Also, plus one if anyone knows how to bind this to a keyboard shortcut (like alt-shift-j for Eclipse JDT).

Also, FYI, the fact that Eclipse CDT supports Doxygen now seems to be a little known fact based on Google.  See here for details.  Doxygen can be enabled under the project properties by selecting "Enable project specific settings" in the "C/C++ General" tab and selecting "Doxygen".  My CDT version is 7.0.1, but I think this became available in 5.0.

Lastly, the comments section under code templates in preferences doesn't accomplish this based on my testing.

EDIT:
See here.  It seems like the comment style is hard coded.  If anyone finds otherwise, I'd love to know about it.  I guess templates will be the best thing for now unless the Javadoc style is okay for you.


问:
Intellisense not inserting when I press enter in C#
When I type I get the usual suggestion from Intellisense,

but when I press enter or space bar to select (as I always have done), I get this

Been looking for info on this for a couple of hours now :/
I am using Visual Studio 2017 - Community Edition with the latest ReSharper

答: The promlem was the ReSharper. Propebly caused by some settings I could not find. Re-installed the ReSharper, problem solved</p>


问:
Is there a ways for cinemachine to retarget player after it is destroyed and instantiated as a clone?
I am working on a 2D platformer and I am using cinemachine to follow my player.

When a player drops off a platform under -20 y, the player is destroyed and instantiated as a clone to the spawn point as expected, but the camera is not following, as the original player is destroyed: it says missing on the "Follow" Slot.

Is there any way to solve it? I prefer using Destroy and Instantiate as respawning instead of teleporting the original player to the respawn point.

This is the respawn script (GameMaster)

public class GameMaster : MonoBehaviour
{

    public static GameMaster gm;

    void Start()
    {
        if (gm == null)
        {
            gm = GameObject.FindGameObjectWithTag("GM").GetComponent<GameMaster>();
        }
    }
    public Transform playerPrefab, spawnPoint;
    public int spawnDelay = 2;

    public void RespawnPlayer() {
        //yield return new WaitForSeconds(spawnDelay);

        Instantiate(playerPrefab, spawnPoint.position, spawnPoint.rotation);
        Debug.Log("ADD SPAWN PARITCAL");
    }

    public static void Killplayer(Player player) {
        Destroy(player.gameObject);
        gm.RespawnPlayer();
    }
}
```

<p>here is the player script if it is needed</p>

```public class Player : MonoBehaviour
{
    [System.Serializable]
    public class PlayerStats
    {
        public int Health = 100;

    }
    public PlayerStats playerStats = new PlayerStats();
    public int FallBoundary = -20;
    void FixedUpdate()
    {
        if (transform.position.y <= FallBoundary)
        {
            DamagePlayer(1000);
        }
    }

    public void DamagePlayer(int damage) {
        playerStats.Health -= damage;
        if (playerStats.Health<=0)
        {
            Debug.Log("Kill Player");
            GameMaster.Killplayer(this);
        }
    }
}
```

答:
You must assign the new object to follow like this:</p>

```<code>myCinemachine.m_Follow = spawnedPlayer;
</code>```

Body:
I am working on a 2D platformer and I am using cinemachine to follow my player.

When a player drops off a platform under -20 y, the player is destroyed and instantiated as a clone to the spawn point as expected, but the camera is not following, as the original player is destroyed: it says missing on the "Follow" Slot.

Is there any way to solve it? I prefer using Destroy and Instantiate as respawning instead of teleporting the original player to the respawn point.

This is the respawn script (GameMaster)

public class GameMaster : MonoBehaviour
{

    public static GameMaster gm;

    void Start()
    {
        if (gm == null)
        {
            gm = GameObject.FindGameObjectWithTag("GM").GetComponent<GameMaster>();
        }
    }
    public Transform playerPrefab, spawnPoint;
    public int spawnDelay = 2;

    public void RespawnPlayer() {
        //yield return new WaitForSeconds(spawnDelay);

        Instantiate(playerPrefab, spawnPoint.position, spawnPoint.rotation);
        Debug.Log("ADD SPAWN PARITCAL");
    }

    public static void Killplayer(Player player) {
        Destroy(player.gameObject);
        gm.RespawnPlayer();
    }
}

here is the player script if it is needed

public class Player : MonoBehaviour
{
    [System.Serializable]
    public class PlayerStats
    {
        public int Health = 100;

    }
    public PlayerStats playerStats = new PlayerStats();
    public int FallBoundary = -20;
    void FixedUpdate()
    {
        if (transform.position.y <= FallBoundary)
        {
            DamagePlayer(1000);
        }
    }

    public void DamagePlayer(int damage) {
        playerStats.Health -= damage;
        if (playerStats.Health<=0)
        {
            Debug.Log("Kill Player");
            GameMaster.Killplayer(this);
        }
    }
}

Body:
You must assign the new object to follow like this:

myCinemachine.m_Follow = spawnedPlayer;


问:
Calling another Controller post method
I am using ASP.NET MVC 3 for my website.

I have created a partial view that has "Previous, Next and Save" buttons. I am calling this partial view on my master page.

My requirement is that on what ever View I am I must be able to call different Save methods in different controllers by passing respective Model data to controller actions.

Example

I have 4 step data input, I have a different controller for each step.

If i am on step 1 and i click Save the form Values should go to Step1Controller's action method,

If I am on step 2 then post should call Step2Controller

Something like this this:

```<code>public ActionResult Save(GenericModel model)
{
    //use reflection to find out model type

    //call appropriate controller action with model

    return RedirectToAction("Create", new { Controller = "Conference", Action = "Create" });
}
</code>```

This save method will be called for Save button on the Master page. How can I achieve this?

答:
Are the forms on separate actions on the controllers?

If so, just set the form action on each page to point to the relevant controller. So form 1 is

```<code><form method="post" action="/step1controller/action">
</code>```

Form 2 is:

```<code><form method="post" action="/step2controller/action">
</code>```

Does that solve your problem?

Title: Calling another Controller post method

Body:
I am using ASP.NET MVC 3 for my website.

I have created a partial view that has "Previous, Next and Save" buttons. I am calling this partial view on my master page.

My requirement is that on what ever View I am I must be able to call different Save methods in different controllers by passing respective Model data to controller actions.

Example

I have 4 step data input, I have a different controller for each step.

If i am on step 1 and i click Save the form Values should go to Step1Controller's action method,

If I am on step 2 then post should call Step2Controller

Something like this this:

public ActionResult Save(GenericModel model)
{
    //use reflection to find out model type

    //call appropriate controller action with model

    return RedirectToAction("Create", new { Controller = "Conference", Action = "Create" });
}

This save method will be called for Save button on the Master page. How can I achieve this?

Body:
Are the forms on separate actions on the controllers?

If so, just set the form action on each page to point to the relevant controller. So form 1 is

<form method="post" action="/step1controller/action">

Form 2 is:

<form method="post" action="/step2controller/action">

Does that solve your problem?


问:
How to Setstate array in React Native
How to set state field in array.

Below is my code:

```<code>constructor() {
  super();
  arrayCheck: [
    isCheck = false
  ]
}

</code>```

I want to get isCheck and then set state to true.
How can I set it?

Below is my function setState

```<code>onCheckBoxChange(isCheck, index, item) {
  this.setState({........});
}
</code>```

答:
First you need arrayCheck to be in the state object:

```<code>this.state = {
    arrayCheck = [...]
}
</code>```

Second, I would suggest using an object rather than an array. In array you can only access the index that holds the value.
With an object you may do something like:

```<code>constructor () {
   super();
   this.state = {
        objectChecks: { // my also just set isCheck on the state
            isCheck: false
        }
   }
}
</code>```

And then when you want to change it:

```<code>this.setState({objectChecks: {isCheck: true}})
</code>```

Hope it helps

Title: How to Setstate array in React Native

Body:
How to set state field in array.

Below is my code:

constructor() {
  super();
  arrayCheck: [
    isCheck = false
  ]
}

I want to get isCheck and then set state to true.
How can I set it?

Below is my function setState

onCheckBoxChange(isCheck, index, item) {
  this.setState({........});
}

Body:
First you need arrayCheck to be in the state object:

this.state = {
    arrayCheck = [...]
}

Second, I would suggest using an object rather than an array. In array you can only access the index that holds the value.
With an object you may do something like:

constructor () {
   super();
   this.state = {
        objectChecks: { // my also just set isCheck on the state
            isCheck: false
        }
   }
}

And then when you want to change it:

this.setState({objectChecks: {isCheck: true}})

Hope it helps


问:
VUE js call a child component method in a different component hierarchy
I have this following vuejs component hierarchy.
What i want to do it to invoke COMP_B_ONE validate() method, when COMP_A_TWO submit() method is invoked EVERY TIME.

```<code>MAIN_COMPONENT
              COMP_A_ONE
                    COMP_B_ONE
                          validate()
                    COMP_B_TWO
                          validate()
              COMP_A_TWO
                    submit()
</code>```

I've already implemented an emit when submit is triggered in COMP_A_TWO   which can be listened in MAIN_COMPONENT

```<code>submit() {
  this.$emit('submit')
}
</code>```

what seems to be the best approach in this regard? any suggestions appreciated.

答:
I can get this done by two ways.

1 - Global EventBus
I will create an eventBus and register events on it from any file and listen it anywhere -

```<code>import { EventBus } from '@/eventBus'
// simply import it to component which need listen the event

//Register Event where you have your methods - like In your COMP_B_TWO
 EventBus.$on('validate', () => { this.validate() })

// Emit event from another component
EventBus.$emit('validate')// Like directly from your COMP_A_TWO
</code>```

To know how to create a eventBus follow this - Global Event Bus Vue

Another way I can think is

2 - Refs

Add reference to COMP_A_ONE like

```<code><COMP_A_ONE ref = "one" />
</code>```

Then add reference to COMP_B_ONE

```<code><COMP_B_ONE ref = "b-one" />
</code>```

Now when you trigger submit from main component

execute it -

```<code>this.$on('submit', () => {
  this.$refs.one['b-one'].validate()
})
</code>```

It totally depends which way you wanna go -

If you need to call validate for many more places, I would suggest choosing EventBus

You just need current component to have it, use Refs

Body:
I have this following vuejs component hierarchy.
What i want to do it to invoke COMP_B_ONE validate() method, when COMP_A_TWO submit() method is invoked EVERY TIME.

MAIN_COMPONENT
              COMP_A_ONE
                    COMP_B_ONE
                          validate()
                    COMP_B_TWO
                          validate()
              COMP_A_TWO
                    submit()

I've already implemented an emit when submit is triggered in COMP_A_TWO   which can be listened in MAIN_COMPONENT

submit() {
  this.$emit('submit')
}

what seems to be the best approach in this regard? any suggestions appreciated.

Body:
I can get this done by two ways.

1 - Global EventBus
I will create an eventBus and register events on it from any file and listen it anywhere -

import { EventBus } from '@/eventBus'
// simply import it to component which need listen the event

//Register Event where you have your methods - like In your COMP_B_TWO
 EventBus.$on('validate', () => { this.validate() })

// Emit event from another component
EventBus.$emit('validate')// Like directly from your COMP_A_TWO

To know how to create a eventBus follow this - Global Event Bus Vue

Another way I can think is

2 - Refs

Add reference to COMP_A_ONE like

<COMP_A_ONE ref = "one" />

Then add reference to COMP_B_ONE

<COMP_B_ONE ref = "b-one" />

Now when you trigger submit from main component

execute it -

this.$on('submit', () => {
  this.$refs.one['b-one'].validate()
})

It totally depends which way you wanna go -

If you need to call validate for many more places, I would suggest choosing EventBus

You just need current component to have it, use Refs


问:
How to use variables defined through vars_prompt of one host in another host vars?
I am having 2 plays in a playbook. One of them prompts for input from user and I want to use that variable in another play. Please suggest me how to do that

```<code>---
- hosts: workers
  gather_facts: false
  sudo: true
  vars_prompt:
     - name: "server_ip"
       prompt: "Enter the Server IP"
       private: no

  roles:
    - client-setup-worker

- hosts: master
  gather_facts: false
  sudo: true
  vars:
    server: "{{ hostvars['workers']['server_ip'] }}"

  roles:
    - client-setup-master
</code>```

In the above playbook I want to use server_ip defined in workers hosts to be used in master hosts.

I am facing the error "The error was: \"hostvars['workers']\" is undefined" while doing so

答:
I am facing the error "The error was: \"hostvars['workers']\" is undefined" while doing so

That's because workers is evidently a group, and not a host, which is the only thing one will find declared in hostvars

You'll need to grab one of the hosts at random from the workers group, and then extract its fact; I believe this will do that:

update after seeing the mostly correct answer by @VladimirBotka

```<code>- hosts: workers
  vars_prompt:
  # as before ...
  pre_tasks:
  - name: re-export the vars_prompt for cross playbook visibility
    set_fact:
      server_ip: '{{ server_ip }}'
  roles:
  # as before

- hosts: masters
  vars:
    server: '{{ hostvars[(groups.workers|first)].server_ip }}'
</code>```

Body:
I am having 2 plays in a playbook. One of them prompts for input from user and I want to use that variable in another play. Please suggest me how to do that

---
- hosts: workers
  gather_facts: false
  sudo: true
  vars_prompt:
     - name: "server_ip"
       prompt: "Enter the Server IP"
       private: no

  roles:
    - client-setup-worker

- hosts: master
  gather_facts: false
  sudo: true
  vars:
    server: "{{ hostvars['workers']['server_ip'] }}"

  roles:
    - client-setup-master

In the above playbook I want to use server_ip defined in workers hosts to be used in master hosts.

I am facing the error "The error was: \"hostvars['workers']\" is undefined" while doing so

Body:
I am facing the error "The error was: \"hostvars['workers']\" is undefined" while doing so

That's because workers is evidently a group, and not a host, which is the only thing one will find declared in hostvars

You'll need to grab one of the hosts at random from the workers group, and then extract its fact; I believe this will do that:

update after seeing the mostly correct answer by @VladimirBotka

- hosts: workers
  vars_prompt:
  # as before ...
  pre_tasks:
  - name: re-export the vars_prompt for cross playbook visibility
    set_fact:
      server_ip: '{{ server_ip }}'
  roles:
  # as before

- hosts: masters
  vars:
    server: '{{ hostvars[(groups.workers|first)].server_ip }}'


问:
If/else conditional rendering of React components not working
```<code>import React, { Component } from 'react';
import axios from 'axios';
import { Button, Card } from 'semantic-ui-react';

class Games extends Component {

  state = { games:[], showGames: false }

  componentDidMount() {
    axios.get('/api/board_games')
      .then(res => {
        this.setState({games: res.data});
      })
  }

  toggleGames = () => {
    this.setState({ showGames: !this.state.showGames })
  }

  gamesList = () => {
    const {games} = this.state
    return games.map( game =>
        <Card key={game.id}>
          <Card.Content>
            <Card.Header>{game.title}</Card.Header>
            <Card.Description>Players: {game.min_players} - {game.max_players}</Card.Description>
            <Card.Description>Company: {game.company}</Card.Description>
            <Card.Description>Time Needed: {game.time_needed}</Card.Description>
          </Card.Content>
          <Card.Content extra>
              <Button basic color='green'>
                Add to Library
              </Button>
          </Card.Content>
        </Card>
      )
  }

  render() {
    const showGames = this.state
    return (
      <div>
        <h1>Games</h1>
        <h3>Your Games</h3>
        { showGames ? (
          <div>

            <Card.Group itemsPerRow={4}>{this.gamesList()}</Card.Group>
          </div>
        )
          : (
          <button onClick={this.toggleGames()}>Add a Game</button>
        )
        }
      </div>
    )
  }
}

export default Games;
</code>```

In my mind, the render return should be checking if showGames is true or false. It's defaulted to false in the state at the beginning. For that reason, it should render the "add a game" button. But if you click that button, it should toggle the showGames to true and render the game cards. Instead, it automatically renders the cards when I arrive on the page. I would also like to add Done Adding to the first part of the if/else, but when I do that I get " Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops."

答:
Just edit the following line in your render() :

```<code>const showGames = this.state.showGames;
or
const { showGames } = this.state;
</code>```

At the moment your showGames constant is an object instead of a boolean. Hence you are not able to use it conditionally.

Hope this helps!

Body:
import React, { Component } from 'react';
import axios from 'axios';
import { Button, Card } from 'semantic-ui-react';

class Games extends Component {

  state = { games:[], showGames: false }

  componentDidMount() {
    axios.get('/api/board_games')
      .then(res => {
        this.setState({games: res.data});
      })
  }

  toggleGames = () => {
    this.setState({ showGames: !this.state.showGames })
  }

  gamesList = () => {
    const {games} = this.state
    return games.map( game =>
        <Card key={game.id}>
          <Card.Content>
            <Card.Header>{game.title}</Card.Header>
            <Card.Description>Players: {game.min_players} - {game.max_players}</Card.Description>
            <Card.Description>Company: {game.company}</Card.Description>
            <Card.Description>Time Needed: {game.time_needed}</Card.Description>
          </Card.Content>
          <Card.Content extra>
              <Button basic color='green'>
                Add to Library
              </Button>
          </Card.Content>
        </Card>
      )
  }

  render() {
    const showGames = this.state
    return (

Games

Your Games

        { showGames ? (

            <Card.Group itemsPerRow={4}>{this.gamesList()}</Card.Group>

        )
          : (
          <button onClick={this.toggleGames()}>Add a Game</button>
        )
        }

    )
  }
}

export default Games;

In my mind, the render return should be checking if showGames is true or false. It's defaulted to false in the state at the beginning. For that reason, it should render the "add a game" button. But if you click that button, it should toggle the showGames to true and render the game cards. Instead, it automatically renders the cards when I arrive on the page. I would also like to add Done Adding to the first part of the if/else, but when I do that I get " Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops."

Body:
Just edit the following line in your render() :

const showGames = this.state.showGames;
or
const { showGames } = this.state;

At the moment your showGames constant is an object instead of a boolean. Hence you are not able to use it conditionally.

Hope this helps!


问:
How can I create two separate pygame displays? If I can't, how could I create two instances of pygame?
I want to create two separate pygame displays. I know that it's impossible to do that with a single instance of pygame. I was wondering how/if I could implement any of the following solutions:

Create a separate module to run the function that uses the separate display. Will this use a separate instance of pygame from my main code and therefore be able to run?

Run the script from within itself with some special parameters using a subshell, parse sys.argv, and then run the function in the second instance. How would I ensure cross-platform compatibility?

Something else?

I don't care about how inefficient, ugly, etc. the program is as a result.  I simply want to make this work.

Importantly, the main code must communicate with the relevant code (i.e. change some variables belonging to extraDisplayManager below) but I plan to use pickle to save to a file and communicate that way. I'm already multi-threading the relevant part though, so a lack of synchronicity doesn't matter.

My code is fairly long and complicated, so I won't post it here, but the gist of the relevant part is:

def mainCode(*someargs):
    d = pygame.display.set_mode(dimensions)
    if relevantArg:
        extraDisplayManager = RelevantClass(*someotherargs)
        threading.Thread(target=extraDisplayManager.relevantFunction,
                         daemon=True).start()

...

class RelevantClass:
    def relevantFunction(self, *someotherargs):
        self.d = pygame.display.set_mode(dimensions)
        while True:
            updateDisplay(someargs) # This is part of my main code, but it
            # is standalone, so I could copy it to a new module

```

I'd appreciate if you could answer some of my questions or show me some relevant documentation.

答:
If you really (really) need two displays, you can use python's multiprocessing module to spawn a process and use a Queue to pass data between the two processes.

Here's an example I hacked together:

```<code>import pygame
import pygame.freetype
import random
import multiprocessing as mp

# a simple class that renders a button
# if you press it, it calls a callback function
class Button(pygame.sprite.Sprite):
    def __init__(self, callback, *grps):
        super().__init__(*grps)
        self.image = pygame.Surface((200, 200))
        self.image.set_colorkey((1,2,3))
        self.image.fill((1,2,3))
        pygame.draw.circle(self.image, pygame.Color('red'), (100, 100), 50)
        self.rect = self.image.get_rect(center=(300, 240))
        self.callback = callback

    def update(self, events, dt):
        for e in events:
            if e.type == pygame.MOUSEBUTTONDOWN:
                if (pygame.Vector2(e.pos) - pygame.Vector2(self.rect.center)).length() <= 50:
                    pygame.draw.circle(self.image, pygame.Color('darkred'), (100, 100), 50)
                    self.callback()
            if e.type == pygame.MOUSEBUTTONUP:
                    pygame.draw.circle(self.image, pygame.Color('red'), (100, 100), 50)

# a simple class that display a text for 1 second anywhere
class Message(pygame.sprite.Sprite):
    def __init__(self, screen_rect, text, font, *grps):
        super().__init__(*grps)
        self.image = pygame.Surface((300, 100))
        self.image.set_colorkey((1,2,3))
        self.image.fill((1,2,3))
        self.rect = self.image.get_rect(center=(random.randint(0, screen_rect.width),
                                                random.randint(0, screen_rect.height)))
        font.render_to(self.image, (5, 5), text)
        self.timeout = 1000
        self.rect.clamp_ip(screen_rect)

    def update(self, events, dt):
        if self.timeout > 0:
            self.timeout = max(self.timeout - dt, 0)
        else:
            self.kill()

# Since we start multiple processes, let's create a mainloop function
# that can be used by all processes. We pass a logic_init_func-function
# that can do some initialisation and returns a callback function itself.
# That callback function is called before all the events are handled.
def mainloop(logic_init_func, q):
    import pygame
    import pygame.freetype
    pygame.init()
    screen = pygame.display.set_mode((600, 480))
    screen_rect = screen.get_rect()
    clock = pygame.time.Clock()
    dt = 0
    sprites_grp = pygame.sprite.Group()

    callback = logic_init_func(screen, sprites_grp, q)

    while True:
        events = pygame.event.get()
        callback(events)

        for e in events:
            if e.type == pygame.QUIT:
                return

        sprites_grp.update(events, dt)
        screen.fill((80, 80, 80))
        sprites_grp.draw(screen)
        pygame.display.flip()
        dt = clock.tick(60)

# The main game function is returned by this function.
# We need a reference to the slave process so we can terminate it when
# we want to exit the game.
def game(slave):
    def game_func(screen, sprites_grp, q):

        # This initializes the game.
        # A bunch of words, and one of it is randomly choosen to be
        # put into the queue once the button is pressed
        words = ('Ouch!', 'Hey!', 'NOT AGAIN!', 'that hurts...', 'STOP IT')

        def trigger():
            q.put_nowait(random.choice(words))

        Button(trigger, sprites_grp)

        def callback(events):
            # in the mainloop, we check for the QUIT event
            # and kill the slave process if we want to exit
            for e in events:
                if e.type == pygame.QUIT:
                    slave.terminate()
                    slave.join()

        return callback

    return game_func

def second_display(screen, sprites_grp, q):

    # we create font before the mainloop
    font = pygame.freetype.SysFont(None, 48)

    def callback(events):
        try:
            # if there's a message in the queue, we display it
            word = q.get_nowait()
            Message(screen.get_rect(), word, font, sprites_grp)
        except:
            pass

    return callback

def main():
    # we use the spawn method to create the other process
    # so it will use the same method on each OS.
    # Otherwise, fork will be used on Linux instead of spawn
    mp.set_start_method('spawn')
    q = mp.Queue()

    slave = mp.Process(target=mainloop, args=(second_display, q))
    slave.start()

    mainloop(game(slave), q)

if __name__ == '__main__':
    main()
</code>```

Of course this is only a simple example; you probably want more error handling, stop nesting functions like crazy, etc etc. Also, there are also other ways to do IPC in python.

Last, but not least, think about if you really need two pygame displays, because multiprocessing adds a ton of complexity. I answered some pygame questions on SO already and almost always the OP was asking an XY question when asking about threading/multiprocessing with pygame.

Body:
I want to create two separate pygame displays. I know that it's impossible to do that with a single instance of pygame. I was wondering how/if I could implement any of the following solutions:

Create a separate module to run the function that uses the separate display. Will this use a separate instance of pygame from my main code and therefore be able to run?

Run the script from within itself with some special parameters using a subshell, parse sys.argv, and then run the function in the second instance. How would I ensure cross-platform compatibility?

Something else?

I don't care about how inefficient, ugly, etc. the program is as a result.  I simply want to make this work.

Importantly, the main code must communicate with the relevant code (i.e. change some variables belonging to extraDisplayManager below) but I plan to use pickle to save to a file and communicate that way. I'm already multi-threading the relevant part though, so a lack of synchronicity doesn't matter.

My code is fairly long and complicated, so I won't post it here, but the gist of the relevant part is:

def mainCode(*someargs):
    d = pygame.display.set_mode(dimensions)
    if relevantArg:
        extraDisplayManager = RelevantClass(*someotherargs)
        threading.Thread(target=extraDisplayManager.relevantFunction,
                         daemon=True).start()

...

class RelevantClass:
    def relevantFunction(self, *someotherargs):
        self.d = pygame.display.set_mode(dimensions)
        while True:
            updateDisplay(someargs) # This is part of my main code, but it
            # is standalone, so I could copy it to a new module

I'd appreciate if you could answer some of my questions or show me some relevant documentation.

Body:
If you really (really) need two displays, you can use python's multiprocessing module to spawn a process and use a Queue to pass data between the two processes.

Here's an example I hacked together:

import pygame
import pygame.freetype
import random
import multiprocessing as mp

# a simple class that renders a button
# if you press it, it calls a callback function
class Button(pygame.sprite.Sprite):
    def __init__(self, callback, *grps):
        super().__init__(*grps)
        self.image = pygame.Surface((200, 200))
        self.image.set_colorkey((1,2,3))
        self.image.fill((1,2,3))
        pygame.draw.circle(self.image, pygame.Color('red'), (100, 100), 50)
        self.rect = self.image.get_rect(center=(300, 240))
        self.callback = callback

    def update(self, events, dt):
        for e in events:
            if e.type == pygame.MOUSEBUTTONDOWN:
                if (pygame.Vector2(e.pos) - pygame.Vector2(self.rect.center)).length() <= 50:
                    pygame.draw.circle(self.image, pygame.Color('darkred'), (100, 100), 50)
                    self.callback()
            if e.type == pygame.MOUSEBUTTONUP:
                    pygame.draw.circle(self.image, pygame.Color('red'), (100, 100), 50)

# a simple class that display a text for 1 second anywhere
class Message(pygame.sprite.Sprite):
    def __init__(self, screen_rect, text, font, *grps):
        super().__init__(*grps)
        self.image = pygame.Surface((300, 100))
        self.image.set_colorkey((1,2,3))
        self.image.fill((1,2,3))
        self.rect = self.image.get_rect(center=(random.randint(0, screen_rect.width),
                                                random.randint(0, screen_rect.height)))
        font.render_to(self.image, (5, 5), text)
        self.timeout = 1000
        self.rect.clamp_ip(screen_rect)

    def update(self, events, dt):
        if self.timeout > 0:
            self.timeout = max(self.timeout - dt, 0)
        else:
            self.kill()

# Since we start multiple processes, let's create a mainloop function
# that can be used by all processes. We pass a logic_init_func-function
# that can do some initialisation and returns a callback function itself.
# That callback function is called before all the events are handled.
def mainloop(logic_init_func, q):
    import pygame
    import pygame.freetype
    pygame.init()
    screen = pygame.display.set_mode((600, 480))
    screen_rect = screen.get_rect()
    clock = pygame.time.Clock()
    dt = 0
    sprites_grp = pygame.sprite.Group()

    callback = logic_init_func(screen, sprites_grp, q)

    while True:
        events = pygame.event.get()
        callback(events)

        for e in events:
            if e.type == pygame.QUIT:
                return

        sprites_grp.update(events, dt)
        screen.fill((80, 80, 80))
        sprites_grp.draw(screen)
        pygame.display.flip()
        dt = clock.tick(60)

# The main game function is returned by this function.
# We need a reference to the slave process so we can terminate it when
# we want to exit the game.
def game(slave):
    def game_func(screen, sprites_grp, q):

        # This initializes the game.
        # A bunch of words, and one of it is randomly choosen to be
        # put into the queue once the button is pressed
        words = ('Ouch!', 'Hey!', 'NOT AGAIN!', 'that hurts...', 'STOP IT')

        def trigger():
            q.put_nowait(random.choice(words))

        Button(trigger, sprites_grp)

        def callback(events):
            # in the mainloop, we check for the QUIT event
            # and kill the slave process if we want to exit
            for e in events:
                if e.type == pygame.QUIT:
                    slave.terminate()
                    slave.join()

        return callback

    return game_func

def second_display(screen, sprites_grp, q):

    # we create font before the mainloop
    font = pygame.freetype.SysFont(None, 48)

    def callback(events):
        try:
            # if there's a message in the queue, we display it
            word = q.get_nowait()
            Message(screen.get_rect(), word, font, sprites_grp)
        except:
            pass

    return callback

def main():
    # we use the spawn method to create the other process
    # so it will use the same method on each OS.
    # Otherwise, fork will be used on Linux instead of spawn
    mp.set_start_method('spawn')
    q = mp.Queue()

    slave = mp.Process(target=mainloop, args=(second_display, q))
    slave.start()

    mainloop(game(slave), q)

if __name__ == '__main__':
    main()

Of course this is only a simple example; you probably want more error handling, stop nesting functions like crazy, etc etc. Also, there are also other ways to do IPC in python.

Last, but not least, think about if you really need two pygame displays, because multiprocessing adds a ton of complexity. I answered some pygame questions on SO already and almost always the OP was asking an XY question when asking about threading/multiprocessing with pygame.


问:
karate - how to match partial string of the field in response?
i have a json response as below where i just want to match the string "harry"

in autoComplete, id in autoCompleteAuthors

Response {"data": {
        "autoComplete": [
            "Harry Hole"
        ],
        "autoCompleteAuthors": [
            {
                "id": "search_authors_harry martinson",
                "title": "Harry Martinson",
                "type": "Authors"
            }
          ]
 }
}

Please suggest how to perform this validations using contains?

i tried like below which is not working
    * def autoComlete = get response.data.autoComplete[*]
    * match autoComlete contains any 'harry'

答:
you can use match each and #regex marker in karate,

Case sensitive matching

* match each $response.data.autoComplete == "#regex .*Harry.*"

Case in sensitive matching

* match each $response.data.autoComplete == "#regex (?i).*harry.*"

Hope this works for your need.

Edit:
As requested on comments to pass name

```<code> * def query = 'harry'
 * match each $response.data.autoComplete == "#regex (?i).*" + query + ".*"
</code>```

Body:
you can use match each and #regex marker in karate,

Case sensitive matching

* match each $response.data.autoComplete == "#regex .*Harry.*"

Case in sensitive matching

* match each $response.data.autoComplete == "#regex (?i).*harry.*"

Hope this works for your need.

Edit:
As requested on comments to pass name

 * def query = 'harry'
 * match each $response.data.autoComplete == "#regex (?i).*" + query + ".*"


问:
How to get Git Tag in Azure Pipelines
In Azure Pipelines, I have enabled git tags to trigger pipelines like so:

```<code>trigger:
  branches:
    include:
    - '*'
  tags:
    include:
    - '*'
</code>```

Now I want to know if there is a way to determine programmatically:

Was the pipeline started from a git commit or git tag?

If the pipeline was started from a git tag, what is the tag name?

答:
This need to consider different situations. If you just push tag or create it with UI, the pipeline are started from git tag. Just commit without any tag, it will started from git commit. No doubt, the build will be triggered just once.

But if you push commit with tag, the build will be triggered twice. First is triggered by commit, and second is by tag. Check this pic.

These means the pipeline started from a commit instead of tag.

All in all, no matter which is first, the tag which trigger the build are all you pushed or created.

For getting more intuitive view about this, you can add variable ' $(Build.SourceBranch)' in your build number. Here is my code about how to configure build number in YAML file:

```<code>name: $(Build.SourceBranch)-$(date:yyyyMMdd)$(rev:.r)
trigger:
  branches:
    include:
    - '*'
  tags:
    include:
    - '*'
</code>```

Here is the result of what triggered the build. If tag, it will shows refs_tags_{tagname}, if it's commit, it will shows refs_heads_{branchname}.

Title: How to get Git Tag in Azure Pipelines

Body:
In Azure Pipelines, I have enabled git tags to trigger pipelines like so:

trigger:
  branches:
    include:
    - '*'
  tags:
    include:
    - '*'

Now I want to know if there is a way to determine programmatically:

Was the pipeline started from a git commit or git tag?

If the pipeline was started from a git tag, what is the tag name?

Body:
This need to consider different situations. If you just push tag or create it with UI, the pipeline are started from git tag. Just commit without any tag, it will started from git commit. No doubt, the build will be triggered just once.

But if you push commit with tag, the build will be triggered twice. First is triggered by commit, and second is by tag. Check this pic.

These means the pipeline started from a commit instead of tag.

All in all, no matter which is first, the tag which trigger the build are all you pushed or created.

For getting more intuitive view about this, you can add variable ' $(Build.SourceBranch)' in your build number. Here is my code about how to configure build number in YAML file:

name: $(Build.SourceBranch)-$(date:yyyyMMdd)$(rev:.r)
trigger:
  branches:
    include:
    - '*'
  tags:
    include:
    - '*'

Here is the result of what triggered the build. If tag, it will shows refs_tags_{tagname}, if it's commit, it will shows refs_heads_{branchname}.


问:
Stop the autoscroll in scrollview on user interaction swift
I using the pagecontroller in my application.

it is working fine every thing it will scroll automatically for every 3 sec time and current position also changed based on user custom swipe.

But I having one issue here when user manually swipe the scrollview on that time I want to stop the auto scroll.

Please find with the my following code.

```<code>var slides:[Slide] = [];
var offSet: CGFloat = 0
override func viewDidLoad() {
    super.viewDidLoad()

    slides = createSlides()
    setupSlideScrollView(slides: slides)

    pageControl.numberOfPages = slides.count
    pageControl.currentPage = 0
    view.bringSubview(toFront: pageControl)

    let timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)

}

@objc func autoScroll() {
    let totalPossibleOffset = CGFloat(slides.count - 1) * self.view.bounds.size.width
    if offSet == totalPossibleOffset {
        offSet = 0 // come back to the first image after the last image
    }
    else {
        offSet += self.view.bounds.size.width
    }
    DispatchQueue.main.async() {
        UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: {
            self.scrollView.contentOffset.x = CGFloat(self.offSet)
        }, completion: nil)
    }
}
</code>```

答: Add scroll view delegate and use scrollViewDidEndDragging methods when it calls just reset your timer so after 3 sec start again it working as it is.

Body:
I using the pagecontroller in my application.

it is working fine every thing it will scroll automatically for every 3 sec time and current position also changed based on user custom swipe.

But I having one issue here when user manually swipe the scrollview on that time I want to stop the auto scroll.

Please find with the my following code.

var slides:[Slide] = [];
var offSet: CGFloat = 0
override func viewDidLoad() {
    super.viewDidLoad()

    slides = createSlides()
    setupSlideScrollView(slides: slides)

    pageControl.numberOfPages = slides.count
    pageControl.currentPage = 0
    view.bringSubview(toFront: pageControl)

    let timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)

}

@objc func autoScroll() {
    let totalPossibleOffset = CGFloat(slides.count - 1) * self.view.bounds.size.width
    if offSet == totalPossibleOffset {
        offSet = 0 // come back to the first image after the last image
    }
    else {
        offSet += self.view.bounds.size.width
    }
    DispatchQueue.main.async() {
        UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: {
            self.scrollView.contentOffset.x = CGFloat(self.offSet)
        }, completion: nil)
    }
}


问:
Where is my "stdio.h" in Mac?
I know that Mac OS X is a Unix-based system. And I heard that C standard library such as stdio.h, is located in /usr/local/include or /usr/include. But there is not any kind of library in this directory. I use Terminal to search this directory and I also use command like find ./ -iname "stdio.h", but nothing comes out. However, strangely enough, gcc -test.c -o test command works out. How did it happen? I want to know where my C library is located.
p.s I also use Xcode, too. Is it related with this application? help me!
    And I have AWS EC2 linux server, and it has both libraries that i refereed above.

答:
The root reason is missing the /usr/include folder, installing command-line tools sometimes will not automatically add it.

Install the package at

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

Title: Where is my "stdio.h" in Mac?


答:
The scope of variables declared in vars_prompt is the play.

Such variable may be put into the hostvars by set_facts "to use that variable in another play". For example the play below

```<code>- hosts: test_01
  gather_facts: false
  vars_prompt:
     - name: "server_ip"
       prompt: "Enter the Server IP"
       private: no
  tasks:
    - set_fact:
        stored_server_ip: "{{ server_ip }}"
    - debug:
        var: stored_server_ip

- hosts: test_02
  gather_facts: false
  vars:
    server: "{{ hostvars.test_01.stored_server_ip }}"
  tasks:
    - debug:
        var: server
</code>```

gives (abridged):

```<code>ok: [test_01] => {
    "stored_server_ip": "10.1.0.10"
}
ok: [test_02] => {
    "server": "10.1.0.10"
}
</code>```

Title: How to use variables defined through vars_prompt of one host in another host vars?

Body:
The scope of variables declared in vars_prompt is the play.

Such variable may be put into the hostvars by set_facts "to use that variable in another play". For example the play below

- hosts: test_01
  gather_facts: false
  vars_prompt:
     - name: "server_ip"
       prompt: "Enter the Server IP"
       private: no
  tasks:
    - set_fact:
        stored_server_ip: "{{ server_ip }}"
    - debug:
        var: stored_server_ip

- hosts: test_02
  gather_facts: false
  vars:
    server: "{{ hostvars.test_01.stored_server_ip }}"
  tasks:
    - debug:
        var: server

gives (abridged):

ok: [test_01] => {
    "stored_server_ip": "10.1.0.10"
}
ok: [test_02] => {
    "server": "10.1.0.10"
}


问:
RegEx for matching specific numeric patterns
I want to match numbers without signs or operator, So I came up this regex.

```<code>echo "-123 +1234" | grep -Po '(?<=-)123 (?<=\+)1234'
</code>```

but it's not matching the string. Why two lookbehind not working? If I do

```<code>echo "-123 +1234" | grep -Po '(?<=-)123
</code>```

I get the correct result 123 but when I do grep -Po '(?<=-)123 (?<=\+)1234' the second part is not matching.

My desired result:

```<code>123 1234
</code>```

答:
It may be that you want to just match numbers

```<code>echo "-123 +1234" | perl -wnE'@m = /([0-9]+)/g; say for @m'
</code>```

unless you'd like to match numbers only if they come with signs, in which case

```<code>echo "-123 +1234" | perl -wnE'@m = /(?<=[+-])([0-9]+)/g; say for @m'
</code>```

or just

```<code>echo "-123 +1234" | perl -wnE'@m = /[+-]([0-9]+)/g; say for @m'
</code>```

in which case the + or - are consumed.

Body:
I want to match numbers without signs or operator, So I came up this regex.

echo "-123 +1234" | grep -Po '(?<=-)123 (?<=\+)1234'

but it's not matching the string. Why two lookbehind not working? If I do

echo "-123 +1234" | grep -Po '(?<=-)123

I get the correct result 123 but when I do grep -Po '(?<=-)123 (?<=\+)1234' the second part is not matching.

My desired result:

123 1234

Body:
It may be that you want to just match numbers

echo "-123 +1234" | perl -wnE'@m = /([0-9]+)/g; say for @m'

unless you'd like to match numbers only if they come with signs, in which case

echo "-123 +1234" | perl -wnE'@m = /(?<=[+-])([0-9]+)/g; say for @m'

or just

echo "-123 +1234" | perl -wnE'@m = /[+-]([0-9]+)/g; say for @m'

in which case the + or - are consumed.


问:
How to get token value from jsonconvert.deserializeobject
I'm trying to get the token value from a JsonConvert.DeserializeObject

```<code>   static async Task Main(string[] args)
    {
        var apiClient = new ApiClient("https://connect.test.com/test/");
        var authenticate =  await Authenticate(apiClient);
        var token =JsonConvert.DeserializeObject(authenticate.RawContent.ReadAsStringAsync().Result);
        Console.ReadKey();
    }
</code>```

Value token:

```<code>    {{
  "token": "eyJraWQiOiJNSytSKzRhYUk4YjBxVkhBMkZLZFN4Ykdpb3RXbTNXOGhZWE45dXF3K3YwPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIxYmRlZjJkNy05YTRlLTRmYmYtYTk4Zi02Y2EwNzE0NTgzNzgiLCJlbWFpb
}}
</code>```

I've tried to split the string but thats not the clean way is there a another way to solve this ?

答:
You can try this</p>

```<code> dynamic obj =JsonConvert.DeserializeObject<dynamic>(authenticate.RawContent.ReadAsStringAsync().Result);
    string token = Convert.ToString(obj.token);
</code>```

Body:
I'm trying to get the token value from a JsonConvert.DeserializeObject

   static async Task Main(string[] args)
    {
        var apiClient = new ApiClient("https://connect.test.com/test/");
        var authenticate =  await Authenticate(apiClient);
        var token =JsonConvert.DeserializeObject(authenticate.RawContent.ReadAsStringAsync().Result);
        Console.ReadKey();
    }

Value token:

    {{
  "token": "eyJraWQiOiJNSytSKzRhYUk4YjBxVkhBMkZLZFN4Ykdpb3RXbTNXOGhZWE45dXF3K3YwPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIxYmRlZjJkNy05YTRlLTRmYmYtYTk4Zi02Y2EwNzE0NTgzNzgiLCJlbWFpb
}}

I've tried to split the string but thats not the clean way is there a another way to solve this ?

Body:
You can try this

 dynamic obj =JsonConvert.DeserializeObject<dynamic>(authenticate.RawContent.ReadAsStringAsync().Result);
    string token = Convert.ToString(obj.token);


答:
Assuming this is the JSON you're getting (as the JSON in your question is invalid)

```<code>{
    "token":"eyJraWQiOiJNSytSKzRhYUk4YjBxVkhBMkZLZFN4Ykdpb3RXbTNXOGhZWE45dXF3K3YwPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIxYmRlZjJkNy05YTRlLTRmYmYtYTk4Zi02Y2EwNzE0NTgzNzgiLCJlbWFpb"
}
</code>```

you can 1: Deserialize it to a dynamic like so: (as mentioned in this answer)

dynamic parsed = JObject.Parse(authenticate.RawContent.ReadAsStringAsync().Result)
Console.WriteLine(parsed.token);
```

<p>or (my preferred typesafe way) use a model class to deserialize to like so:</p>

<pre class="lang-cs prettyprint-override"><code>class AuthenticationModel
{
    [JsonProperty("token")]
    public string Token {get; set;}
}

static async Task Main(string[] args)
{
    var parsed = JsonConvert.DeserializeObject<AuthenticationModel>(await authenticate.RawContent.ReadAsStringAsync());
    Console.WriteLine(parsed.Token);
}
</code>```

Title: How to get token value from jsonconvert.deserializeobject

Body:
Assuming this is the JSON you're getting (as the JSON in your question is invalid)

{
    "token":"eyJraWQiOiJNSytSKzRhYUk4YjBxVkhBMkZLZFN4Ykdpb3RXbTNXOGhZWE45dXF3K3YwPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIxYmRlZjJkNy05YTRlLTRmYmYtYTk4Zi02Y2EwNzE0NTgzNzgiLCJlbWFpb"
}

you can 1: Deserialize it to a dynamic like so: (as mentioned in this answer)

dynamic parsed = JObject.Parse(authenticate.RawContent.ReadAsStringAsync().Result)
Console.WriteLine(parsed.token);

or (my preferred typesafe way) use a model class to deserialize to like so:

class AuthenticationModel
{
    [JsonProperty("token")]
    public string Token {get; set;}
}

static async Task Main(string[] args)
{
    var parsed = JsonConvert.DeserializeObject<AuthenticationModel>(await authenticate.RawContent.ReadAsStringAsync());
    Console.WriteLine(parsed.Token);
}


问:
Where to learn Tizen Native Wearable Basics
I'm trying to develop an app for my Galaxy Watch which runs on Tizen. I'm not able to find any wholesome tutorial out there for Tizen. Do you mind recommending me some?

Thanks

答:
How about to use .NET and C# for your Watch application?

Click here!

You can also use Native Application Model (C based) for your Watch application.
Plz, visit Tizen developer site


问:
Open source in-memory & persistent & distributed time series database
I am looking to write a distribution application that will need a time series in-memory database (that needs to be persistent as well).
I will need to do various analytics on this time series data like aggregation, filtering, etc.
And ideally i want to scale these seperately.

Meaning something like lets say there is a process that appends to these time series data and then exposes this data to a set of applications (processes which are for various analytics) like say a shared memory handle.
The application will need to go over the time series mostly as readonly in order to compute the analytics. So once can see this as one process that will be writing (adding/modifying the time series). And other applications which will  be accesseing those time series data as a read only to evaluate analytics.

Further i need the timeseries data to be persisent and preferrably persistent and distributed cache if possible (something based on redis possibly).

I would like to explore what alternatives I have.

答:
The handling of time series data seems to be suitable for the Druid engine.
Druid provides fast response to the OLAP data engine for time series data.
In addition, metatron Discovery, a Druid-based analysis platform. Check it out!.</p>


问:
How to filter a List using Java 8 stream and startwith array of values
I have 2 Lists, the one contains a list of numbers and the other a list of names. I have prefixed the names with a number from the first list, followed by an underscore. I want to filter the second list based on all the numbers found in the first list.

What I have tried.

```<code>List<String> numberList = new ArrayList<>();
numberList.add("1_");
numberList.add("9_");

List<String> nameList = new ArrayList<>();
nameList.add("1_John");
nameList.add("2_Peter");
nameList.add("9_Susan");

List<String> filteredList = Stream.of(numberList.toArray(new String[0]))
                .filter(str -> nameList.stream().anyMatch(str::startsWith))
                .collect(Collectors.toList());
</code>```

The code above runs with no error, but the filteredList is empty. Clearly I am doing something wrong.

The filteredList should contain only:

1_John

9_Susan

答:
You call startsWith on the wrong Strings (for example, you test if "1_".startsWith("1_John") instead of "1_John".startsWith("1_")).

You should stream over nameList and use numberList for the filtering:

```<code>List<String> filteredList =
    nameList.stream()
            .filter(str -> numberList.stream().anyMatch(str::startsWith))
            .collect(Collectors.toList());
</code>```

P.S. Stream.of(numberList.toArray(new String[0])) is redundant. Use numberList.stream() instead.

Body:
I have 2 Lists, the one contains a list of numbers and the other a list of names. I have prefixed the names with a number from the first list, followed by an underscore. I want to filter the second list based on all the numbers found in the first list.

What I have tried.

List<String> numberList = new ArrayList<>();
numberList.add("1_");
numberList.add("9_");

List<String> nameList = new ArrayList<>();
nameList.add("1_John");
nameList.add("2_Peter");
nameList.add("9_Susan");

List<String> filteredList = Stream.of(numberList.toArray(new String[0]))
                .filter(str -> nameList.stream().anyMatch(str::startsWith))
                .collect(Collectors.toList());

The code above runs with no error, but the filteredList is empty. Clearly I am doing something wrong.

The filteredList should contain only:

1_John

9_Susan

Body:
You call startsWith on the wrong Strings (for example, you test if "1_".startsWith("1_John") instead of "1_John".startsWith("1_")).

You should stream over nameList and use numberList for the filtering:

List<String> filteredList =
    nameList.stream()
            .filter(str -> numberList.stream().anyMatch(str::startsWith))
            .collect(Collectors.toList());

P.S. Stream.of(numberList.toArray(new String[0])) is redundant. Use numberList.stream() instead.


问:
Ui overflow when Keyboard opens in flutter
In design, I have divided screen in three-part using Expanded but in Second part have a textfield when user try to input something the design overflows by some pixel, I have been trying to use SingleChildScrollView inside Expanded with container widget to get rid of the rendering problem but my design disappears.

```<code>return Scaffold(
      body: Stack(
        children: <Widget>[
          Container(
            decoration: _buildBackground(),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              Expanded(
                flex: 13,
                //child:_toolBar('VENUE LOGIN')
                child:MyWidget(headerText: 'Player Option',)
              ),
             Expanded(
                flex: 70,
                child: Container(
                  margin: EdgeInsets.only(top: width*0.03),
                  decoration: BoxDecoration(color: Colors.transparent),child: PlayerOptionContainer(),),
              ),

              Expanded(
                flex: 17,
                child: _bottomView1(width),
              ),
            ],
          )
        ],
      ),
    );
</code>```

PlayerOptionWidget method

```<code> Widget PlayerOptionContainer(){
      return Column(
        children: <Widget>[
          Expanded(flex:25,
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Expanded(flex: 30,child: _logoContainer(width),),
                Expanded(flex: 70,child:  searchContainer(),),

            ],),),
          Expanded(flex:75,child: Container(
            decoration: BoxDecoration(color: Colors.transparent),
            child: GridView.count(
              crossAxisCount: 3,
              children: List.generate(20, (index) {
                return Container(
                  margin: EdgeInsets.only(left: width*0.02, bottom: width*0.02, right: width*0.02),
                  decoration: BoxDecoration(
                    color: MyColors.yellowBg,
                    borderRadius: new BorderRadius.circular(12.0),
                  ),
                  child: Center(child: MyFeedTile(),),
                );
              }),
            ),
           ),)],
      );
    }
</code>```

This is the design trying to achieve

But it gets overflow by some pixel

答:
Common problem. There are a couple solutions

You can wrap body (Stack) in SingleChildScrollView

You can try resizeToAvoidBottomInset parameter of Scaffold:

```<code>Scaffold(
  resizeToAvoidBottomInset: false, ... )
</code>```

Body:
In design, I have divided screen in three-part using Expanded but in Second part have a textfield when user try to input something the design overflows by some pixel, I have been trying to use SingleChildScrollView inside Expanded with container widget to get rid of the rendering problem but my design disappears.

return Scaffold(
      body: Stack(
        children: <Widget>[
          Container(
            decoration: _buildBackground(),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              Expanded(
                flex: 13,
                //child:_toolBar('VENUE LOGIN')
                child:MyWidget(headerText: 'Player Option',)
              ),
             Expanded(
                flex: 70,
                child: Container(
                  margin: EdgeInsets.only(top: width*0.03),
                  decoration: BoxDecoration(color: Colors.transparent),child: PlayerOptionContainer(),),
              ),

              Expanded(
                flex: 17,
                child: _bottomView1(width),
              ),
            ],
          )
        ],
      ),
    );

PlayerOptionWidget method

 Widget PlayerOptionContainer(){
      return Column(
        children: <Widget>[
          Expanded(flex:25,
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Expanded(flex: 30,child: _logoContainer(width),),
                Expanded(flex: 70,child:  searchContainer(),),

            ],),),
          Expanded(flex:75,child: Container(
            decoration: BoxDecoration(color: Colors.transparent),
            child: GridView.count(
              crossAxisCount: 3,
              children: List.generate(20, (index) {
                return Container(
                  margin: EdgeInsets.only(left: width*0.02, bottom: width*0.02, right: width*0.02),
                  decoration: BoxDecoration(
                    color: MyColors.yellowBg,
                    borderRadius: new BorderRadius.circular(12.0),
                  ),
                  child: Center(child: MyFeedTile(),),
                );
              }),
            ),
           ),)],
      );
    }

This is the design trying to achieve

But it gets overflow by some pixel

Body:
Common problem. There are a couple solutions

You can wrap body (Stack) in SingleChildScrollView

You can try resizeToAvoidBottomInset parameter of Scaffold:

Scaffold(
  resizeToAvoidBottomInset: false, ... )