问:
.net core IActionResult return OK()
I have follow next example
Link to source

And when I create my controller(which should be same as his TripsController) to return Ok with data, browser is not parsing to HTML it is only shown json format in browser.

```<code>using System;
using System.Collections.Generic;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RnD.Models.Repository;
using RnD.Models.ViewModels;

namespace RnD.Controllers.Web
{

    [Route("/machines")]
    [Authorize]
    public class MachineTypeController : Controller
    {
        private ILogger<MachineTypeController> _logger;
        private IMachineTypeRepository _repository;

        public MachineTypeController(IMachineTypeRepository repository, ILogger<MachineTypeController> logger)
        {
            _logger = logger;
            _repository = repository;
        }

        [HttpGet("")]
        public IActionResult Index()
        {
            try
            {
                var results = _repository.GetAllMachineTypes();

                return Ok(Mapper.Map<IEnumerable<MachineTypeViewModel>>(results));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to get all Machine types: {ex}");
                return BadRequest("Error Occurred");
            }

        }
    }
}
</code>```

If I put to return View it will work correctly.

Here is Startup.cs

```<code>using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using RnD.Models.DataFixtures;
using RnD.Models.Entity;
using RnD.Models.Repository;
using RnD.Models.ViewModels;

namespace RnD
{
    public class Startup
    {
        private IHostingEnvironment _env;
        private IConfigurationRoot _config;

        public Startup(IHostingEnvironment env)
        {
            _env = env;

            var builder = new ConfigurationBuilder()
                .SetBasePath(_env.ContentRootPath)
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();

            _config = builder.Build();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(_config);

            services.AddDbContext<RnDContext>();

            services.AddIdentity<ApplicationUser, IdentityRole>(config =>
            {
                config.User.RequireUniqueEmail = false;
                config.Password.RequireDigit = false;
                config.Password.RequireUppercase = false;
                config.Password.RequiredLength = 8;
                config.Cookies.ApplicationCookie.LoginPath = "/auth/login";
                config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
                {
                    OnRedirectToLogin = async ctx =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                        {
                            ctx.Response.StatusCode = 401;
                        }
                        else
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                        await Task.Yield();

                    }
                };
            }).AddEntityFrameworkStores<RnDContext>();

            services.AddScoped<IMachineTypeRepository, MachineTypeRepository>();

            services.AddTransient<RnDContextSeedData>();

            services.AddLogging();

            services.AddMvc(config =>
            {
                if (_env.IsProduction())
                {
                    config.Filters.Add(new RequireHttpsAttribute());
                }
            })
            .AddJsonOptions(config =>
            {
                config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
            IHostingEnvironment env,
            RnDContextSeedData seeder,
            ILoggerFactory loggerFactory

            )
        {

            Mapper.Initialize(config =>
            {
                config.CreateMap<MachineTypeViewModel, MachineType>().ReverseMap();
            });
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                loggerFactory.AddDebug(LogLevel.Information);
            }
            else
            {
                loggerFactory.AddDebug(LogLevel.Error);
            }
            app.UseStaticFiles();
            app.UseIdentity();
            app.UseMvc(config =>
            {
                config.MapRoute(
                  name: "Default",
                  template: "{controller}/{action}/{id?}",
                  defaults: new { controller = "Home", action = "Index" }
                  );
            });

            seeder.EnsureSeedData().Wait();
        }
    }
}
</code>```

Here is code from angular

app.js

```<code>// app.js
(function () {
    "use strict";

    angular.module("app",[]);
})();
</code>```

machineController.js

```<code>// machineController.js
(function () {
    "use strict";

    angular.module("app")
        .controller("machineController", machineController);

    function machineController($http) {
        /* jshint validthis:true */
        var vm = this;

        vm.machines = [];

        vm.errorMessage = "";

        $http.get("/machines")
            .then(function (response) {
                // Success
                angular.copy(response.data, vm.machines);
            }, function (error) {
                // Failure
                vm.errorMessage = "Failed: " + error;
            });

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

Index.cshtml

```<code>@model IEnumerable<RnD.Models.Entity.MachineType>
@{
    ViewBag.Title = "Machine Type List";
}

@section scripts{

    <script src="~/lib/angular/angular.js"></script>
    <script src="~/js/app.js"></script>
    <script src="~/js/machineController.js"></script>
}
<div class="row" ng-app="app">
    <div ng-controller="machineController as vm" class="col-md-6 col-md-offset-6">
        <table class="table table-responsive">
            <tr ng-repeat="machine in vm.machines">
                <td>{{machine.name}}</td>
            </tr>
        </table>
    </div>
</div>
</code>```

答:
I found what was the problem.

In Controller I add one more method

```<code>[HttpGet("GetMachines")]
public IActionResult GetMachines()
{
    try
    {
        var results = _repository.GetAllMachineTypes();

        return Ok(Mapper.Map<IEnumerable<MachineTypeViewModel>>(results));
    }
    catch (Exception ex)
    {
        _logger.LogError($"Failed to get all Machine types: {ex}");
        return BadRequest("Error Occurred");
    }
}
</code>```

Second I changed machineController.js

```<code>(function () {
"use strict";

angular.module("app")
    .controller("machineController", machineController);

function machineController($http) {
    /* jshint validthis:true */
    var vm = this;

    vm.machines = [];

    vm.errorMessage = "";

    $http.get("/machines/GetMachines")
        .then(function (response) {
            // Success
            angular.copy(response.data, vm.machines);
        }, function (error) {
            // Failure
            vm.errorMessage = "Failed: " + error;
        });

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

Title: .net core IActionResult return OK()

Body:
I have follow next example
Link to source

And when I create my controller(which should be same as his TripsController) to return Ok with data, browser is not parsing to HTML it is only shown json format in browser.

using System;
using System.Collections.Generic;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RnD.Models.Repository;
using RnD.Models.ViewModels;

namespace RnD.Controllers.Web
{

    [Route("/machines")]
    [Authorize]
    public class MachineTypeController : Controller
    {
        private ILogger<MachineTypeController> _logger;
        private IMachineTypeRepository _repository;

        public MachineTypeController(IMachineTypeRepository repository, ILogger<MachineTypeController> logger)
        {
            _logger = logger;
            _repository = repository;
        }

        [HttpGet("")]
        public IActionResult Index()
        {
            try
            {
                var results = _repository.GetAllMachineTypes();

                return Ok(Mapper.Map<IEnumerable<MachineTypeViewModel>>(results));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to get all Machine types: {ex}");
                return BadRequest("Error Occurred");
            }

        }
    }
}

If I put to return View it will work correctly.

Here is Startup.cs

using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using RnD.Models.DataFixtures;
using RnD.Models.Entity;
using RnD.Models.Repository;
using RnD.Models.ViewModels;

namespace RnD
{
    public class Startup
    {
        private IHostingEnvironment _env;
        private IConfigurationRoot _config;

        public Startup(IHostingEnvironment env)
        {
            _env = env;

            var builder = new ConfigurationBuilder()
                .SetBasePath(_env.ContentRootPath)
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();

            _config = builder.Build();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(_config);

            services.AddDbContext<RnDContext>();

            services.AddIdentity<ApplicationUser, IdentityRole>(config =>
            {
                config.User.RequireUniqueEmail = false;
                config.Password.RequireDigit = false;
                config.Password.RequireUppercase = false;
                config.Password.RequiredLength = 8;
                config.Cookies.ApplicationCookie.LoginPath = "/auth/login";
                config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
                {
                    OnRedirectToLogin = async ctx =>
                    {
                        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                        {
                            ctx.Response.StatusCode = 401;
                        }
                        else
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                        await Task.Yield();

                    }
                };
            }).AddEntityFrameworkStores<RnDContext>();

            services.AddScoped<IMachineTypeRepository, MachineTypeRepository>();

            services.AddTransient<RnDContextSeedData>();

            services.AddLogging();

            services.AddMvc(config =>
            {
                if (_env.IsProduction())
                {
                    config.Filters.Add(new RequireHttpsAttribute());
                }
            })
            .AddJsonOptions(config =>
            {
                config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
            IHostingEnvironment env,
            RnDContextSeedData seeder,
            ILoggerFactory loggerFactory

            )
        {

            Mapper.Initialize(config =>
            {
                config.CreateMap<MachineTypeViewModel, MachineType>().ReverseMap();
            });
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                loggerFactory.AddDebug(LogLevel.Information);
            }
            else
            {
                loggerFactory.AddDebug(LogLevel.Error);
            }
            app.UseStaticFiles();
            app.UseIdentity();
            app.UseMvc(config =>
            {
                config.MapRoute(
                  name: "Default",
                  template: "{controller}/{action}/{id?}",
                  defaults: new { controller = "Home", action = "Index" }
                  );
            });

            seeder.EnsureSeedData().Wait();
        }
    }
}

Here is code from angular

app.js

// app.js
(function () {
    "use strict";

    angular.module("app",[]);
})();

machineController.js

// machineController.js
(function () {
    "use strict";

    angular.module("app")
        .controller("machineController", machineController);

    function machineController($http) {
        /* jshint validthis:true */
        var vm = this;

        vm.machines = [];

        vm.errorMessage = "";

        $http.get("/machines")
            .then(function (response) {
                // Success
                angular.copy(response.data, vm.machines);
            }, function (error) {
                // Failure
                vm.errorMessage = "Failed: " + error;
            });

    }
})();

Index.cshtml

@model IEnumerable<RnD.Models.Entity.MachineType>
@{
    ViewBag.Title = "Machine Type List";
}

@section scripts{

}

                {{machine.name}}

Body:
I found what was the problem.

In Controller I add one more method

[HttpGet("GetMachines")]
public IActionResult GetMachines()
{
    try
    {
        var results = _repository.GetAllMachineTypes();

        return Ok(Mapper.Map<IEnumerable<MachineTypeViewModel>>(results));
    }
    catch (Exception ex)
    {
        _logger.LogError($"Failed to get all Machine types: {ex}");
        return BadRequest("Error Occurred");
    }
}

Second I changed machineController.js

(function () {
"use strict";

angular.module("app")
    .controller("machineController", machineController);

function machineController($http) {
    /* jshint validthis:true */
    var vm = this;

    vm.machines = [];

    vm.errorMessage = "";

    $http.get("/machines/GetMachines")
        .then(function (response) {
            // Success
            angular.copy(response.data, vm.machines);
        }, function (error) {
            // Failure
            vm.errorMessage = "Failed: " + error;
        });

}
 })();


来源: stackexchange

问:
Configure cucumber in TeamCity to run unit tests only using tags (Maven)
I have both unit and acceptance tests in a maven project (spring boot). I would like to run unit tests only when my build runs in TeamCity. I am using cucumber.

When i run the tests via command line, everything works as expected (only unit tests are run)

```<code> c:\apache-maven-3.3.9\bin\mvn package -Dcucumber.options="--tags @unit"
</code>```

However, in teamcity, all tests are being run (unit and acceptance). It seems teamcity ignores my cucumber.options

In addition, when I double click on the 'test' lifecycle in Intellij, all tests are run as well (not just unit tests) So my guess is that TeamCity is doing exactly what the 'test' lifecycle does.

How can i get around this problem (in TeamCity)?. I have tried using a 'Command line' step, which works, however, i lose all the tests reporting as well as test coverage reports.

i have solved the Intellij problem by creating (or changing) a configuration:

答:
Try writing it this way in TeamCity:
"-Dcucumber.options= --tags @unit"

ContentLicense: CC BY-SA 3.0

Body:
I have both unit and acceptance tests in a maven project (spring boot). I would like to run unit tests only when my build runs in TeamCity. I am using cucumber.

When i run the tests via command line, everything works as expected (only unit tests are run)

 c:\apache-maven-3.3.9\bin\mvn package -Dcucumber.options="--tags @unit"

However, in teamcity, all tests are being run (unit and acceptance). It seems teamcity ignores my cucumber.options

In addition, when I double click on the 'test' lifecycle in Intellij, all tests are run as well (not just unit tests) So my guess is that TeamCity is doing exactly what the 'test' lifecycle does.

How can i get around this problem (in TeamCity)?. I have tried using a 'Command line' step, which works, however, i lose all the tests reporting as well as test coverage reports.

i have solved the Intellij problem by creating (or changing) a configuration:


问:
What grid distributed computing frameworks are currently favoured for trading systems
There seems to a quite a few grid computing frameworks out there, but which ones are actually being used to any great extent by the investment banks for purposes of low latency distributing calculation? I'd be interested to hear answers covering both windows,Linux and cross platform. Also, what RPC mechanisms seem to be favoured most?

I've heard that for reason of low latency and speed, the calculations themselves are quite often written in C++/C as calculations running on VMs are several orders of magnitude slower than native code. Does this seem to be a common scenario in practice? e.g distributed .NET grid framework running calculations written in native c++/c?

答:
The G-WAN server is starting to get ground in this area. It mixes the speed (and footprint) of ANSI C with (fully-compliant ANSI C) scripts (allowing real-time editing/updating without stopping the server).

Full JSON RPC is expected by the end of this year, in the same spirit of efficiency. With it you will be able to implement distributed computing.

This is crazy to see what they managed to put in 200 KB (server + script engine + many features like charts, compression, crypto, etc.).

ContentLicense: CC BY-SA 2.5


问:
How to expand matplolib window without stretching the plot?
I want to increase the grey area around the plot, but keeping the plot the same size. I've already tried changing the figure size, which ends up stretching the plot.

答: In the window of a matplotlib figure, there's a button called 'Configure subplots' (see below picture, screenshot on Windows 10 with matplotlib version 1.5.2). Try to change the parameters 'left' and 'right'. You can also change these parameters with plt.subplots_adjust(left=..., bottom=..., right=..., top=..., wspace=..., hspace=...).


问:
Recent methods for finding semantic similarity between two short sentences or articles (on a concept level)
I'm working on finding similarities between short sentences and articles. I used many existing methods such as tf-idf, word2vec etc but the results are just okay. The most relevant measure which I found was word moving distance, however, its results are not that better than the other measures. I know it's a challenging problem, however, I am wondering if there are any new methods to find an approximate similarity more on a higher or concept level than just matching words.  Especially, any alternative new methods like word moving distance which looks at slightly higher semantic of a sentence or article?</p>

答:
Obviously, this is a huge and busy research area, but I'd say there are two broad types of approaches you could look into:

First, there are some methods that learn sentence embeddings in an unsupervised manner, such as Le and Mikolov's (2014) Paragraph Vectors, which are implemented in gensim, or Kiros et al.'s (2015) SkipThought vectors, with an implementation on Github.

Then there also exist supervised methods that learn sentence embeddings from labelled data. The most recent one is Conneau et al.'s (2017), which trains sentence embeddings on the Stanford Natural Language Inference dataset, and shows these embeddings can be used successfully across a range of NLP tasks. The code is available on Github.

You might also find some inspiration in a blog post I wrote earlier this year on the topic of embeddings.


问:
Read text from images in python
Is there a way for read text from an image, some kind of text recognition method using python??

I need to read some images and get the text written on them.

I have been searching libraries such as pytesser, PIL and pillow, but anyone knows something else?

For windows and python 3.6.1

Thank you,

Marcus

答:
The Google Vision API might help. It is able to pull out what objects are present in an image as well as other information (brands, colors, face detection etc). It can pull out text pretty reliably too.

https://cloud.google.com/vision/

Here is some example code from their website using the Python Client Library:

```<code>import io
import os

# Imports the Google Cloud client library
from google.cloud import vision

# Instantiates a client
vision_client = vision.Client()

# The name of the image file to annotate
file_name = os.path.join(
    os.path.dirname(__file__),
    'resources/wakeupcat.jpg')

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()
    image = vision_client.image(
        content=content)

# Performs label detection on the image file
labels = image.detect_labels()

print('Labels:')
for label in labels:
    print(label.description)
</code>```

Title: Read text from images in python

Body:
The Google Vision API might help. It is able to pull out what objects are present in an image as well as other information (brands, colors, face detection etc). It can pull out text pretty reliably too.

https://cloud.google.com/vision/

Here is some example code from their website using the Python Client Library:

import io
import os

# Imports the Google Cloud client library
from google.cloud import vision

# Instantiates a client
vision_client = vision.Client()

# The name of the image file to annotate
file_name = os.path.join(
    os.path.dirname(__file__),
    'resources/wakeupcat.jpg')

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()
    image = vision_client.image(
        content=content)

# Performs label detection on the image file
labels = image.detect_labels()

print('Labels:')
for label in labels:
    print(label.description)


问:
Doxygen 1.8.13 ignores parameters with default values (C++)
We are currently making our comments Doxygen-compatible, but have stumbled upon an issue with default parameters.

One example would be this function:

```<code>...
class String : public Object
{
     ...
    /*!
    * \brief Trim the string from the left while the characters matches any characters in the given string
    * \param In_pChar - (optional) The array of characters to be trimmed
    * \return The trimmed string object
    */
    String& trim_left(const char * In_pChar=" \t");
    ...
};
...
</code>```

Doxygen just completely omits the parameter and even warns about it:

```<code>warning: argument 'In_pChar' of command @param is not found in the argument list of String::trim_left()
</code>```

The resulting HTML isn't really what I expected it to be:

Does anyone have an idea on how to fix this?

答:
Your problem is almost certainly in one of your ...s or you have a bugged version of doxygen.

The following code works fine for me:

```<code>class String : public Object
{
public:

/*!
 * \brief Trim the string from the left while the characters matches any characters in the given string
 * \param In_pChar - (optional) The array of characters to be trimmed
 * \return The trimmed string object
 */
    String& trim_left(const char * In_pChar=" \t");

};
</code>```

Body:
We are currently making our comments Doxygen-compatible, but have stumbled upon an issue with default parameters.

One example would be this function:

...
class String : public Object
{
     ...
    /*!
    * \brief Trim the string from the left while the characters matches any characters in the given string
    * \param In_pChar - (optional) The array of characters to be trimmed
    * \return The trimmed string object
    */
    String& trim_left(const char * In_pChar=" \t");
    ...
};
...

Doxygen just completely omits the parameter and even warns about it:

warning: argument 'In_pChar' of command @param is not found in the argument list of String::trim_left()

The resulting HTML isn't really what I expected it to be:

Does anyone have an idea on how to fix this?

Body:
Your problem is almost certainly in one of your ...s or you have a bugged version of doxygen.

The following code works fine for me:

class String : public Object
{
public:

/*!
 * \brief Trim the string from the left while the characters matches any characters in the given string
 * \param In_pChar - (optional) The array of characters to be trimmed
 * \return The trimmed string object
 */
    String& trim_left(const char * In_pChar=" \t");

};


问:
How can I replace/speed up a text search query which uses LIKE?
I'm trying to speed up my query...

```<code>select PadID from Pads WHERE (keywords like '%$search%' or
ProgramName like '%$search%' or English45 like '%$search%') AND
RemovemeDate = '2001-01-01 00:00:00' ORDER BY VersionAddDate DESC
</code>```

I've done some work already, I have a keywords table so I can add

```<code>... PadID IN (SELECT PadID FROM Keywords WHERE word = '$search') ...
</code>```

However its going to be a nightmare to split up the words from English45 and ProgramName into a word table.

Any ideas ?
EDIT : (also provided actual table names)

答:
Jules,

There are few things to note based on the EXPLAIN output:

WHERE RemoveMeDate is constraining the clause.

ORDER BY is doing a 2nd pass over the data to sort it. Note that there is no index on VersionAddDate.

Choice of index depends on all other queries you are using, but for this particular query i'd like to add an index for VersionAddDate. However, since MySQL can use only single index for a query, the index would look like:

```<code>INDEX `removemedate` (`RemoveMeDate` ASC, `VersionAddDate` ASC)
</code>```

After doing this EXPLAIN should read something like:

```<code>+----+-------------+-------+------+---------------+--------------+---------+--------------+-------------+
| id | select_type | table | type | possible_keys | key          | key_len | ref   | rows | Extra       |
+----+-------------+-------+------+---------------+--------------+---------+-------+------+-------------+
|  1 | SIMPLE      | pads  | ref  | removemedate  | removemedate | 4       | const |    1 | Using where |
+----+-------------+-------+------+---------------+--------------+---------+-------+------+-------------+
</code>```

Note that filesort under Extra is gone. This should give better performance than your previous query.

Thanks.

Body:
I'm trying to speed up my query...

select PadID from Pads WHERE (keywords like '%$search%' or
ProgramName like '%$search%' or English45 like '%$search%') AND
RemovemeDate = '2001-01-01 00:00:00' ORDER BY VersionAddDate DESC

I've done some work already, I have a keywords table so I can add

... PadID IN (SELECT PadID FROM Keywords WHERE word = '$search') ...

However its going to be a nightmare to split up the words from English45 and ProgramName into a word table.

Any ideas ?
EDIT : (also provided actual table names)

Body:
Jules,

There are few things to note based on the EXPLAIN output:

WHERE RemoveMeDate is constraining the clause.

ORDER BY is doing a 2nd pass over the data to sort it. Note that there is no index on VersionAddDate.

Choice of index depends on all other queries you are using, but for this particular query i'd like to add an index for VersionAddDate. However, since MySQL can use only single index for a query, the index would look like:

INDEX `removemedate` (`RemoveMeDate` ASC, `VersionAddDate` ASC)

After doing this EXPLAIN should read something like:

+----+-------------+-------+------+---------------+--------------+---------+--------------+-------------+
| id | select_type | table | type | possible_keys | key          | key_len | ref   | rows | Extra       |
+----+-------------+-------+------+---------------+--------------+---------+-------+------+-------------+
|  1 | SIMPLE      | pads  | ref  | removemedate  | removemedate | 4       | const |    1 | Using where |
+----+-------------+-------+------+---------------+--------------+---------+-------+------+-------------+

Note that filesort under Extra is gone. This should give better performance than your previous query.

Thanks.


问:
Manipulating properties of SVG image
I'm trying to change "outline"(stroke in terms of svg properties) of my beetle after onclick button, but as I don't see any bugs in my code sample it doesn't work, why?

```<code>var beetlebtn=document.getElementById("btn");
var beetle =document.getElementById("Layer_1");

beetlebtn.addEventListener(click, function(){
    beetle.style.stroke="yellow";
});
</code>```

Link to my pen

答:
You forgot the quotation marks around the 'click' label, so it was just appearing as an undefined variable.

This will work

```<code>beetlebtn.addEventListener('click', function(){
  beetle.style.stroke="yellow";
});
</code>```

Link: https://codepen.io/anon/pen/pwOWjy

Title: Manipulating properties of SVG image

Body:
I'm trying to change "outline"(stroke in terms of svg properties) of my beetle after onclick button, but as I don't see any bugs in my code sample it doesn't work, why?

var beetlebtn=document.getElementById("btn");
var beetle =document.getElementById("Layer_1");

beetlebtn.addEventListener(click, function(){
    beetle.style.stroke="yellow";
});

Link to my pen

Body:
You forgot the quotation marks around the 'click' label, so it was just appearing as an undefined variable.

This will work

beetlebtn.addEventListener('click', function(){
  beetle.style.stroke="yellow";
});

Link: https://codepen.io/anon/pen/pwOWjy


问:
Compare two arrays contains integers, return the difference
I want to compare 2 arrays with integers.

what I have:

```<code>function findDeletedNumber(array $arr, array $mixedArr): int {
  $diff = array_diff($arr, $mixedArr);
  if ($diff != NULL) { return($diff); }
  return 0;
}
</code>```

But the problem is that I need to return the difference as a string. Not an array. the difference is always gonna be only one value

答:
use implode function     </p>

```<code>function findDeletedNumber(array $arr, array $mixedArr): int {
      $diff = array_diff($arr, $mixedArr);
      if ($diff != NULL) { return(implode(',',$diff)); }
      return 0;
    }
</code>```

Body:
I want to compare 2 arrays with integers.

what I have:

function findDeletedNumber(array $arr, array $mixedArr): int {
  $diff = array_diff($arr, $mixedArr);
  if ($diff != NULL) { return($diff); }
  return 0;
}

But the problem is that I need to return the difference as a string. Not an array. the difference is always gonna be only one value

Body:
use implode function

function findDeletedNumber(array $arr, array $mixedArr): int {
      $diff = array_diff($arr, $mixedArr);
      if ($diff != NULL) { return(implode(',',$diff)); }
      return 0;
    }


问:
Why did instruments report a leak while its ref count did become zero
green hand i am. I'm using instruments, and it did a great help to me so far, but I'm confused now 'cause it report a memory leak to me while its leaked block history shows me that the ref count of that memory had finally become 0. What does it mean?

It's really embarrassing that I couldn't post a image here... so I have to describe it in text. Hope it would be clear enough for you:

Event Type || RefCt || Responsible Library || Responsible Caller

Malloc         ||
1        ||
MyWeather              || +[ForecastData parseSingleForecastWithXMLElement:]

Autorelease||
           ||
MyWeather              ||
+[ForecastData parseSingleForecastWithXMLElement:]

Retain         ||
2        ||
MyWeather              ||
+[ForecastData parseWithData:]

Release      ||
1        ||
Foundation              ||
+[NSAutoreleasePool drain:]

Retain         ||
2        ||
Foundation              ||
+[NSThread initWithTarget:selector:object:]

Release      ||
1        ||
Foundation              ||
+[NSString compare:options:]

Release      ||
0        ||
MyWeather              ||
+[RootViewController dealloc]

Any help will be appreciated~

答: It was caused by the lack of [super dealloc] in dealloc of forecastData, so that part of memory of forecastData is never freed while the retain count of forecastData did have become zero. Anyway, thanks guys.</p>


问:
Change text in TextView doesn't show more than three lines but on layout its shown correctly
I have a layout with a TextView that receives some text from a BBDD. When I write a long string on the layout, it shows everything correctly. When the same text is written by texview.settext("sodjsdoifjsodfsd");

I see that the TextView can only show the lines of this string.

I mean, it can change its dimension on the layout and I can see it correctly, with four or more lines if it is necessary, but when I change the text with a long string (as the string on the layout), I only see three lines of this text. I have the same problem with the text of the buttons.

I put a image, hope it helps:

Here's my layout code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

<ScrollView
    android:layout_width="match_parent"
    android:fillViewport="true"
    android:layout_height="match_parent">
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/HeaderTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentStart="true"
            android:text="Which ability of metal AM improves the osseointegrationdddddddddddddddddddddddddddddddddddddddddddddddd capability and reduces surgical implants rejection rates?"
            android:textSize="20dp" />

        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/HeaderTextView"
            android:paddingEnd="10dp"
            android:paddingStart="10dp"
            android:paddingTop="20dp">

            <TableRow
                android:id="@+id/tableRow2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="2dp">

                <Button
                    android:id="@+id/answer1"
                    android:layout_width="0dip"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center"
                    android:layout_marginBottom="2dp"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="2dp"
                    android:layout_weight="1"
                    android:paddingLeft="20dp"
                    android:paddingRight="20dp"
                    android:background="@color/primary"
                    android:textColor="@color/accent"
                    android:text="It doesn't need supports and allows to build in several levels"
                    android:textSize="10dp" />

                <Button
                    android:id="@+id/answer2"
                    android:layout_width="0dip"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center"
                    android:layout_marginBottom="2dp"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="2dp"
                    android:layout_weight="1"
                    android:paddingLeft="20dp"
                    android:paddingRight="20dp"
                    android:background="@color/primary"
                    android:textColor="@color/accent"
                    android:text="ANSWER 2"
                    android:textSize="10dp" />
            </TableRow>

            <TableRow
                android:id="@+id/tableRow3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="2dp">

                <Button
                    android:id="@+id/answer3"
                    android:layout_width="0dip"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center"
                    android:layout_marginBottom="2dp"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="2dp"
                    android:layout_weight="1"
                    android:paddingLeft="20dp"
                    android:paddingRight="20dp"
                    android:background="@color/primary"
                    android:textColor="@color/accent"
                    android:text="ANSWER 3"
                    android:textSize="10dp" />

                <Button
                    android:id="@+id/answer4"
                    android:layout_width="0dip"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center"
                    android:layout_marginBottom="2dp"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="2dp"
                    android:layout_weight="1"
                    android:paddingLeft="20dp"
                    android:background="@color/primary"
                    android:textColor="@color/accent"
                    android:paddingRight="20dp"
                    android:text="ANSWER 4"
                    android:textSize="10dp" />
            </TableRow>

            <TableRow
                android:id="@+id/tableRow4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="2dp">

                <TextView
                    android:id="@+id/HeaderTextView2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="SEE ACRONYM BUTTON FOR MORE INFORMATION" />
            </TableRow>
        </TableLayout>

        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:paddingStart="10dp">

            <TableRow
                android:id="@+id/tableRow6"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="2dp">

                <Button
                    android:id="@+id/acronism"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:padding="5dp"

                    android:background="@color/primary"
                    android:textColor="@color/accent"
                    android:text="ACRONYM"
                    android:textSize="20dp" />

                <Button
                    android:id="@+id/explanation"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:padding="5dp"

                    android:background="@color/primary"
                    android:textColor="@color/accent"
                    android:layout_marginBottom="2dp"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="2dp"
                    android:text="Explanation"
                    android:textSize="20dp" />
            </TableRow>
        </TableLayout>

        <TextView
            android:id="@+id/PointsTextView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:padding="5dp"
            android:text="POINTS:  "
            android:textAlignment="textEnd" />
    </RelativeLayout>
</ScrollView>
</code>```

And the class code where I change the text:

```<code>header4questions.setText(listQuestions.get(questionPosition));
answer1.setText(listAnswers.get(questionPosition * 4));
answer2.setText(listAnswers.get((questionPosition * 4) + 1));
answer3.setText(listAnswers.get((questionPosition * 4) + 2));
answer4.setText(listAnswers.get((questionPosition * 4) + 3));
</code>```

I don't know why it works perfectly on the layout but not with the android code.

Can anyone help me?

Thanks a lot!

答:
There is a attribute called maxLines it goes like this </p>

```<code>android:maxLines="2"
</code>```

<p>try that.  </p>

Body:
I have a layout with a TextView that receives some text from a BBDD. When I write a long string on the layout, it shows everything correctly. When the same text is written by texview.settext("sodjsdoifjsodfsd");

I see that the TextView can only show the lines of this string.

I mean, it can change its dimension on the layout and I can see it correctly, with four or more lines if it is necessary, but when I change the text with a long string (as the string on the layout), I only see three lines of this text. I have the same problem with the text of the buttons.

I put a image, hope it helps:

Here's my layout code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

<ScrollView
    android:layout_width="match_parent"
    android:fillViewport="true"
    android:layout_height="match_parent">
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/HeaderTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentStart="true"
            android:text="Which ability of metal AM improves the osseointegrationdddddddddddddddddddddddddddddddddddddddddddddddd capability and reduces surgical implants rejection rates?"
            android:textSize="20dp" />

        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/HeaderTextView"
            android:paddingEnd="10dp"
            android:paddingStart="10dp"
            android:paddingTop="20dp">

            <TableRow
                android:id="@+id/tableRow2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="2dp">

                <Button
                    android:id="@+id/answer1"
                    android:layout_width="0dip"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center"
                    android:layout_marginBottom="2dp"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="2dp"
                    android:layout_weight="1"
                    android:paddingLeft="20dp"
                    android:paddingRight="20dp"
                    android:background="@color/primary"
                    android:textColor="@color/accent"
                    android:text="It doesn't need supports and allows to build in several levels"
                    android:textSize="10dp" />

                <Button
                    android:id="@+id/answer2"
                    android:layout_width="0dip"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center"
                    android:layout_marginBottom="2dp"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="2dp"
                    android:layout_weight="1"
                    android:paddingLeft="20dp"
                    android:paddingRight="20dp"
                    android:background="@color/primary"
                    android:textColor="@color/accent"
                    android:text="ANSWER 2"
                    android:textSize="10dp" />
            </TableRow>

            <TableRow
                android:id="@+id/tableRow3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="2dp">

                <Button
                    android:id="@+id/answer3"
                    android:layout_width="0dip"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center"
                    android:layout_marginBottom="2dp"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="2dp"
                    android:layout_weight="1"
                    android:paddingLeft="20dp"
                    android:paddingRight="20dp"
                    android:background="@color/primary"
                    android:textColor="@color/accent"
                    android:text="ANSWER 3"
                    android:textSize="10dp" />

                <Button
                    android:id="@+id/answer4"
                    android:layout_width="0dip"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center"
                    android:layout_marginBottom="2dp"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="2dp"
                    android:layout_weight="1"
                    android:paddingLeft="20dp"
                    android:background="@color/primary"
                    android:textColor="@color/accent"
                    android:paddingRight="20dp"
                    android:text="ANSWER 4"
                    android:textSize="10dp" />
            </TableRow>

            <TableRow
                android:id="@+id/tableRow4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="2dp">

                <TextView
                    android:id="@+id/HeaderTextView2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="SEE ACRONYM BUTTON FOR MORE INFORMATION" />
            </TableRow>
        </TableLayout>

        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:paddingStart="10dp">

            <TableRow
                android:id="@+id/tableRow6"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="2dp">

                <Button
                    android:id="@+id/acronism"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:padding="5dp"

                    android:background="@color/primary"
                    android:textColor="@color/accent"
                    android:text="ACRONYM"
                    android:textSize="20dp" />

                <Button
                    android:id="@+id/explanation"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:padding="5dp"

                    android:background="@color/primary"
                    android:textColor="@color/accent"
                    android:layout_marginBottom="2dp"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="2dp"
                    android:text="Explanation"
                    android:textSize="20dp" />
            </TableRow>
        </TableLayout>

        <TextView
            android:id="@+id/PointsTextView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:padding="5dp"
            android:text="POINTS:  "
            android:textAlignment="textEnd" />
    </RelativeLayout>
</ScrollView>

And the class code where I change the text:

header4questions.setText(listQuestions.get(questionPosition));
answer1.setText(listAnswers.get(questionPosition * 4));
answer2.setText(listAnswers.get((questionPosition * 4) + 1));
answer3.setText(listAnswers.get((questionPosition * 4) + 2));
answer4.setText(listAnswers.get((questionPosition * 4) + 3));

I don't know why it works perfectly on the layout but not with the android code.

Can anyone help me?

Thanks a lot!

Body:
There is a attribute called maxLines it goes like this

android:maxLines="2"

try that.


问:
InfluxDB templating query - referring to measuerments?
I'm trying to make templates for my dahboards, and I have problems when it comes to referring to measuerment names.

My variables:

```<code>$space = SHOW MEASUREMENTS
</code>```

Then I would like a variable that contains only values from a specific $space, which is actually a MEASUREMENT:

```<code>$app = SHOW TAG VALUES WITH KEY = "Application" WHERE MEASUREMENT =~ /^$space$/
</code>```

Here I get a message: Template variables could not be initialized: error parsing query: found MEASUREMENT, expected identifier, string, number, bool at line 1, char 48

In the official example it is like this, though it refers to another tag:

```<code>$datacenter = SHOW TAG VALUES WITH KEY = "datacenter"
$host = SHOW TAG VALUES WITH KEY = "hostname" WHERE "datacenter" =~ /^$datacenter$/
</code>```

I cannot find any info how to refer to MEASUREMENTS which would work. WHERE, WITH, etc.. Maybe is it not possible at all?
I found only this in the official tutorial, but this is for keys, not values.

```<code>SHOW TAG KEYS [FROM <measurement_name>]
</code>```

答:
I actually figured it out:</p>

```<code>SHOW TAG VALUES FROM  /^$space$/ WITH KEY = "Application"
</code>```

Body:
I'm trying to make templates for my dahboards, and I have problems when it comes to referring to measuerment names.

My variables:

$space = SHOW MEASUREMENTS

Then I would like a variable that contains only values from a specific $space, which is actually a MEASUREMENT:

$app = SHOW TAG VALUES WITH KEY = "Application" WHERE MEASUREMENT =~ /^$space$/

Here I get a message: Template variables could not be initialized: error parsing query: found MEASUREMENT, expected identifier, string, number, bool at line 1, char 48

In the official example it is like this, though it refers to another tag:

$datacenter = SHOW TAG VALUES WITH KEY = "datacenter"
$host = SHOW TAG VALUES WITH KEY = "hostname" WHERE "datacenter" =~ /^$datacenter$/

I cannot find any info how to refer to MEASUREMENTS which would work. WHERE, WITH, etc.. Maybe is it not possible at all?
I found only this in the official tutorial, but this is for keys, not values.

SHOW TAG KEYS [FROM <measurement_name>]

Body:
I actually figured it out:

SHOW TAG VALUES FROM  /^$space$/ WITH KEY = "Application"


问:
Syntax error when trying to import table
I'm trying to import a table from a database to another but keep getting this error

the command:

```<code>INSERT IGNORE INTO epdbraid.spawnpoints (
    id, spawn_id, lat, lon, despawn_time, updated
)
SELECT
    0,
    CAST(CONV(id,16,10) AS INTEGER),
    latitude, longitude, latest_seen, last_scanned
FROM rocketmapdb.spawnpoint;
</code>```

The error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTEGER), latitude, longitude, latest_seen, last_scanned FROM rocketmapdb.spawnp' at line 1

sql version: mysql  Ver 14.14 Distrib 5.7.18, for Linux (x86_64) using  EditLine wrapper

Any idea what I'm doing wrong?

答:
```<code>INSERT IGNORE INTO epdbraid.spawnpoints (
    id, spawn_id, lat, lon, despawn_time, updated
)
SELECT
    0,
    CAST(CONV(id,16,10) AS  UNSIGNED ),
    latitude, longitude, latest_seen, last_scanned
FROM rocketmapdb.spawnpoint;
</code>```

You can try above code.

Body:
I'm trying to import a table from a database to another but keep getting this error

the command:

INSERT IGNORE INTO epdbraid.spawnpoints (
    id, spawn_id, lat, lon, despawn_time, updated
)
SELECT
    0,
    CAST(CONV(id,16,10) AS INTEGER),
    latitude, longitude, latest_seen, last_scanned
FROM rocketmapdb.spawnpoint;

The error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTEGER), latitude, longitude, latest_seen, last_scanned FROM rocketmapdb.spawnp' at line 1

sql version: mysql  Ver 14.14 Distrib 5.7.18, for Linux (x86_64) using  EditLine wrapper

Any idea what I'm doing wrong?

Body:
INSERT IGNORE INTO epdbraid.spawnpoints (
    id, spawn_id, lat, lon, despawn_time, updated
)
SELECT
    0,
    CAST(CONV(id,16,10) AS  UNSIGNED ),
    latitude, longitude, latest_seen, last_scanned
FROM rocketmapdb.spawnpoint;

You can try above code.

ContentLicense: CC BY-SA 4.0


问:
Showing the URL of the view in the address bar, instead of the one of the action
```<code>@RequestMapping(value = "updatePatient", method = RequestMethod.POST)
public ModelAndView postUpdatePatientById(
        @ModelAttribute("patient") PatientForm patientForm,
        HttpSession session) {
    Long id = (Long) session.getAttribute("refId");
    if (id != 0 || id != null) {
        Patient patient1 = HospitalPatientHelper
                .getPatientFrom_PatientForm(patientForm);
        patientService.updatePatient(patient1, id);
        PatientService patientService) {
    Patient patient = patientService.getPatientById(id);
    ModelAndView mv;
    PatientForm patientForm = HospitalPatientHelper
            .getPatientForm_FromPatient(patient);
    List<Weight> weights = patientService.viewLast10RecordedWeight(patient);
    WeightTable weightTable = new WeightTable();
    List<WeightSummaryTable> summaryWeights = weightTable.summary(weights,
            patient.getHeight());
    mv = new ModelAndView("patient1/patientDetail");
    mv.addObject("patient", patientForm);
    mv.addObject("summaries", summaryWeights);
    mv.addObject("lastWeight", summaryWeights.get(0).getWeight());
    mv.addObject("bmi", summaryWeights.get(0).getBmi());
    return mv;
    } else {
        return new ModelAndView("patient1/patientDetail");
    }

}
</code>```

the page shown sucessfully, but the url dosn't change, means the url is not showing the address www.url.com/patient1/patientDetail.htm

and i want that the returning view address should also be shown in the url too.

please help me

答:
Use either </p>

```<code>new ModelAndView(new RedirectView(patient1/patientDetail)).
</code>```

<p>Or </p>

```<code>redirect:patient1/patientDetail
</code>```

Body:
@RequestMapping(value = "updatePatient", method = RequestMethod.POST)
public ModelAndView postUpdatePatientById(
        @ModelAttribute("patient") PatientForm patientForm,
        HttpSession session) {
    Long id = (Long) session.getAttribute("refId");
    if (id != 0 || id != null) {
        Patient patient1 = HospitalPatientHelper
                .getPatientFrom_PatientForm(patientForm);
        patientService.updatePatient(patient1, id);
        PatientService patientService) {
    Patient patient = patientService.getPatientById(id);
    ModelAndView mv;
    PatientForm patientForm = HospitalPatientHelper
            .getPatientForm_FromPatient(patient);
    List<Weight> weights = patientService.viewLast10RecordedWeight(patient);
    WeightTable weightTable = new WeightTable();
    List<WeightSummaryTable> summaryWeights = weightTable.summary(weights,
            patient.getHeight());
    mv = new ModelAndView("patient1/patientDetail");
    mv.addObject("patient", patientForm);
    mv.addObject("summaries", summaryWeights);
    mv.addObject("lastWeight", summaryWeights.get(0).getWeight());
    mv.addObject("bmi", summaryWeights.get(0).getBmi());
    return mv;
    } else {
        return new ModelAndView("patient1/patientDetail");
    }

}

the page shown sucessfully, but the url dosn't change, means the url is not showing the address www.url.com/patient1/patientDetail.htm

and i want that the returning view address should also be shown in the url too.

please help me

Body:
Use either

new ModelAndView(new RedirectView(patient1/patientDetail)).

Or

redirect:patient1/patientDetail


问:
how to make SSRS 2012 Report server url as SSL
To debug the SSRS webservice2010 method (logonUser) need Report Server as SSL.

How to display Installed certificate in the Reportingservice Congifuration manager-->WebserviceURL menu-->Advanced button -->Certificate list

kindly provide steps to create and install Trusted certificate for SSRS report 2012.

答:
Once you have your certificate created ,import it into the mmc using below steps :

To add the Certificates snap-in to an MMC for a computer account

1.Click Start, type mmc in the Search programs and files box, and then press ENTER.

2.On the File menu, click Add/Remove Snap-in.

3.Under Available snap-ins, double-click Certificates.

4.Select Computer account, and then click Next.

5.Do one of the following:
◦ To manage certificates for the local computer, click Local computer, and then click Finish.

◦ To manage certificates for a remote computer, click Another computer, and then type the name of the computer, or click Browse to select the computer name, and then click Finish.

6.If you have no more snap-ins to add to the console, click OK.

7.To save this console, on the File menu, click Save.

Now open the console and follow below steps :

A. Expand Certificates Node;
 B. Right click Personal -> All Tasks -> Import.

Once the certificate is imported it will appear in the drop down of advanced tab in the url section.

https://technet.microsoft.com/en-us/library/cc754431(v=ws.11).aspx


问:
Loading Bar on my website
Please I'm trying to knockoff a loading bar on my site, I have searched through the files, still can't find it. I also tried inspecting using google chrome, but I couldn't target the loader. Kindly help out

Click here for to visit website.

答:
just go the HTML of your page. there from the top, search for  tag. Just below it you'll find this :

```<code><div class="pace  pace-inactive"><div class="pace-progress" data-progress-text="100%" data-progress="99" style="width: 100%;">
  <div class="pace-progress-inner"></div>
</div>
<div class="pace-activity"></div></div>
</code>```

Remove all these lines and you'll be fine

and remove these two lines in your  tag

```<code><link href="assets/plugins/pace/pace.css" rel="stylesheet">
<script src="assets/plugins/pace/pace.min.js"></script>
</code>```

Title: Loading Bar on my website

Body:
just go the HTML of your page. there from the top, search for <body> tag. Just below it you'll find this :

<div class="pace  pace-inactive"><div class="pace-progress" data-progress-text="100%" data-progress="99" style="width: 100%;">
  <div class="pace-progress-inner"></div>
</div>
<div class="pace-activity"></div></div>

Remove all these lines and you'll be fine

and remove these two lines in your <head> tag

<link href="assets/plugins/pace/pace.css" rel="stylesheet">
<script src="assets/plugins/pace/pace.min.js"></script>


问:
Remember checked checkboxes in DataGridView
I have a DataGridView where the first column is a DataGridViewCheckBoxColumn. The user checks some checkboxes to indicate which items are to be deleted.

When I hide the form and reload it, I need the DataGridView to remember which checkboxes were checked.

答:
You need to save the changes at least at the point where you close your Form (if you just hide it, why reload then?).
The way I usually work this out is listening to the Dgv's CellEndEdit event:

```<code>SomeDataGridView.CellEndEdit += ObjectPropertyChanged
</code>```

then in the Callback you can get the Object back by using the "DataBoundItem" prop of the Dgv and process / save it however you need:

```<code>protected virtual void ObjectPropertyChanged(object sender, DataGridViewVellEventArgs e)
{
  var selectedObject = ((DataGridView)sender).Rows[e.RowIndex].DataBoundItem;
  //Assuming you stored in a List and each Object has an ID as prop:
  var indx = _Objects.IndexOf(_Objects.Where(o => o.ID.Equals(selectedObject.ID)))
  _Objects.Remove(indx)
  _Objects.Insert(indx, selectedObject)
}
</code>```

You could also do database update, write to a text-file, save in configuration, ...

Body:
You need to save the changes at least at the point where you close your Form (if you just hide it, why reload then?).
The way I usually work this out is listening to the Dgv's CellEndEdit event:

SomeDataGridView.CellEndEdit += ObjectPropertyChanged

then in the Callback you can get the Object back by using the "DataBoundItem" prop of the Dgv and process / save it however you need:

protected virtual void ObjectPropertyChanged(object sender, DataGridViewVellEventArgs e)
{
  var selectedObject = ((DataGridView)sender).Rows[e.RowIndex].DataBoundItem;
  //Assuming you stored in a List and each Object has an ID as prop:
  var indx = _Objects.IndexOf(_Objects.Where(o => o.ID.Equals(selectedObject.ID)))
  _Objects.Remove(indx)
  _Objects.Insert(indx, selectedObject)
}

You could also do database update, write to a text-file, save in configuration, ...


问:
Google ads does not open in new tab by clicking on ad. How to fix it so that it could be open in new tab?
I have created a Google ad and deploy it in my website. Any user/visitor when click on this ad it is opened in same tab instead of new tab. It must be open in new tab so that user/visitor could not lose website.

Sometimes ad is opened in same tab and sometimes ad is opened in new tab. What is happening there? I'm confused.

Is there any logic/selection to force ad to open in new tab during ad creation or something else?

答:
This is not allowed by google.

You can read more :

https://support.google.com/adsense/answer/1354740?hl=en&ref_topic=1271508

https://productforums.google.com/forum/#!topic/adsense/TMSSYotv_Xw


问:
How does these services get passed into the controller? version 1.0.8
I got a new job, and took over some systems from some people that isn't here anymore. The version is all the way down to 1.0.8 in angular.js though, and the implementations they have been using seems to be what the community has been saying not to do since forever.

My question is, how do the vvscontroller get the services in as arguments?

I have been trying to grep through the project for any reference for the args: ElReport, ElRow, User, PriorReports, Documentation but it seems like they just magically get parsed in, then i searched for dependency injection, looking if i could find any implementations of the different providers the angular.js mentions, but i can only find the routeProvider and maybe something else that didn't look like it was configured.

So there is a lot of code where i don't think its related - but it might be but obviously i cannot post the entire code here. I was thinking it might be configured into the HTML or something but when i grep for ng-controller i don't find anything related to the PlumbingCtrl, but i just can't quite point it out. Can anyone tell me in what direction i should be looking?? what classes are likely to be used in order to achive this?

app.js

```<code>angular.module('housingevaluation', ['ngRoute', 'housingServices', 'ngUpload', 'angucomplete', 'ui.bootstrap.datetimepicker', 'ngResource', 'fcsa-number']).
    config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl: 'partials/home.html', controller: HomeCtrl}).when('/vvs/:reportId', {templateUrl: 'partials/plumbing.html', controller: PlumbingCtrl}).
...more controllers + some config that does something with http/https(don't think thats related)
</code>```

services.js

```<code>angular.module('housingServices', ['ngResource']).
        factory('ElReport', function($resource) {
        return $resource('reports/el/:id', {id: '@Id'}, {
            query: {method: 'GET', isArray: false},
            get: {method: 'GET'},
            save: {method: 'POST'},
            completeReport: {method: 'POST', url: 'reports/el/:id/complete'},
            reopenReport: {method: 'POST', url: 'reports/el/:id/reopen'},
            queryPlumbing: {method: 'GET', isArray: false},
            createCopy: {method: 'POST', url: 'reports/el/:id/reevaluation'},
            createRealCopy: {method: 'POST', url: 'reports/el/:id/copy'},
            markBilled: {method: 'POST', url: 'reports/el/:id/markBilled'}
        });
    }).
...some more factories (Documentation, User, etc.)
...some more directives
</code>```

vvscontroller.js

```<code>function PlumbingCtrl($scope, $routeParams, $location, ElReport, ElRow, User, PriorReports, Documentation) {
...
}
</code>```

index.html

```<code><html ng-app>
</code>```

Thanks !

答:
you need to inject your controller in angularjs app module</p>

```<code>  angular.module('housingServices').controller('PlumbingCtrl', PlumbingCtrl);
PlumbingCtrl.$inject = ['$scope', '$routeParams', '$location', 'ElReport', 'ElRow', 'User', 'PriorReports', 'Documentation'];
function PlumbingCtrl($scope, $routeParams, $location, ElReport, ElRow, User,
PriorReports, Documentation) {
   ...
          }
</code>```

Body:
I got a new job, and took over some systems from some people that isn't here anymore. The version is all the way down to 1.0.8 in angular.js though, and the implementations they have been using seems to be what the community has been saying not to do since forever.

My question is, how do the vvscontroller get the services in as arguments?

I have been trying to grep through the project for any reference for the args: ElReport, ElRow, User, PriorReports, Documentation but it seems like they just magically get parsed in, then i searched for dependency injection, looking if i could find any implementations of the different providers the angular.js mentions, but i can only find the routeProvider and maybe something else that didn't look like it was configured.

So there is a lot of code where i don't think its related - but it might be but obviously i cannot post the entire code here. I was thinking it might be configured into the HTML or something but when i grep for ng-controller i don't find anything related to the PlumbingCtrl, but i just can't quite point it out. Can anyone tell me in what direction i should be looking?? what classes are likely to be used in order to achive this?

app.js

angular.module('housingevaluation', ['ngRoute', 'housingServices', 'ngUpload', 'angucomplete', 'ui.bootstrap.datetimepicker', 'ngResource', 'fcsa-number']).
    config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl: 'partials/home.html', controller: HomeCtrl}).when('/vvs/:reportId', {templateUrl: 'partials/plumbing.html', controller: PlumbingCtrl}).
...more controllers + some config that does something with http/https(don't think thats related)

services.js

angular.module('housingServices', ['ngResource']).
        factory('ElReport', function($resource) {
        return $resource('reports/el/:id', {id: '@Id'}, {
            query: {method: 'GET', isArray: false},
            get: {method: 'GET'},
            save: {method: 'POST'},
            completeReport: {method: 'POST', url: 'reports/el/:id/complete'},
            reopenReport: {method: 'POST', url: 'reports/el/:id/reopen'},
            queryPlumbing: {method: 'GET', isArray: false},
            createCopy: {method: 'POST', url: 'reports/el/:id/reevaluation'},
            createRealCopy: {method: 'POST', url: 'reports/el/:id/copy'},
            markBilled: {method: 'POST', url: 'reports/el/:id/markBilled'}
        });
    }).
...some more factories (Documentation, User, etc.)
...some more directives

vvscontroller.js

function PlumbingCtrl($scope, $routeParams, $location, ElReport, ElRow, User, PriorReports, Documentation) {
...
}

index.html

Thanks !

Body:
you need to inject your controller in angularjs app module

  angular.module('housingServices').controller('PlumbingCtrl', PlumbingCtrl);
PlumbingCtrl.$inject = ['$scope', '$routeParams', '$location', 'ElReport', 'ElRow', 'User', 'PriorReports', 'Documentation'];
function PlumbingCtrl($scope, $routeParams, $location, ElReport, ElRow, User,
PriorReports, Documentation) {
   ...
          }


问:
Python package basics
I have a python file named as test1.py.
This file contains few classes and a few functions.

I intend to package this and distribute so that others can use it via the pip install command.
From other posts, I understood how we build a package.

Q: When the package is imported in the end user's code, using the import <mypackage> command,

1. can the functions be called directly by simply writing the function name?

2. methods which are part of the class, are ideally called by objectname.methodname, how will they be called now?

答:
It depends on how you import the package. If you import the package as

```<code>import test1
</code>```

you will have to call all the classes and functions with test1.function(). The class methods like test1.objectname.methodname()

If you use

```<code>from test1 import *
</code>```

you can just use the function names, but your namespace is being polluted with all the function names.

You can also import only specific functions or classes using

```<code>from test1 import function1, function2, class1, class2
</code>```

To call them with just their respective name.

And lastly you can use import test1 as t1 to make it a bit shorter, calling functions can then be done using t1.function1()

Title: Python package basics

Body:
It depends on how you import the package. If you import the package as

import test1

you will have to call all the classes and functions with test1.function(). The class methods like test1.objectname.methodname()

If you use

from test1 import *

you can just use the function names, but your namespace is being polluted with all the function names.

You can also import only specific functions or classes using

from test1 import function1, function2, class1, class2

To call them with just their respective name.

And lastly you can use import test1 as t1 to make it a bit shorter, calling functions can then be done using t1.function1()


问:
Grunt Read json file and push field into another json file
I'm trying to read data from bower.json and push into an existing json file for my project

```<code>var mapping = grunt.file.readJSON('bower.json');
var map = grunt.file.readJSON('other.json);
</code>```

How can I push it into the other file ? I have already tried push() and write()
Thank you

答:
If you just want to hard copy one json file to another you could use something like:

```<code>  var mapping = grunt.file.readJSON('bower.json');//read in the current
  grunt.file.write("other.json", JSON.stringify(mapping, null, 2));
</code>```

Or if you wanted to set a certain field in other.json to be the same as bower.json:

```<code>  var mapping = grunt.file.readJSON('bower.json');//read in bower
  var map = grunt.file.readJSON('other.json');//read in other
  map["version"] = mapping["version"]; //copy mapping version to map version
  grunt.file.write("other.json", JSON.stringify(map, null, 2)); //save other.json
</code>```

Body:
I'm trying to read data from bower.json and push into an existing json file for my project

var mapping = grunt.file.readJSON('bower.json');
var map = grunt.file.readJSON('other.json);

How can I push it into the other file ? I have already tried push() and write()
Thank you

Body:
If you just want to hard copy one json file to another you could use something like:

  var mapping = grunt.file.readJSON('bower.json');//read in the current
  grunt.file.write("other.json", JSON.stringify(mapping, null, 2));

Or if you wanted to set a certain field in other.json to be the same as bower.json:

  var mapping = grunt.file.readJSON('bower.json');//read in bower
  var map = grunt.file.readJSON('other.json');//read in other
  map["version"] = mapping["version"]; //copy mapping version to map version
  grunt.file.write("other.json", JSON.stringify(map, null, 2)); //save other.json


问:
String replace expressions
I have the following string:

var myString = "Name: ";

function replaceName(str, name) {
  return str.replace(/Name:/gi, "Name:" + name);
}

myString = replaceName("Name: ", "Joe");
myString = replaceName("Name: ", "Jane");
```

I want to replace the entire line each time a new name is added. The above keeps appending the name to the end of the string.

How can I replace the name each time str.replace is called?

答:
Firstly, you could have mentioned clearly that calling the function second time messes up. And secondly, there's no functions in your code, so you need to tell which line is messing up. I understood the question with the help of Rory McCrossan and here's the answer.

I changed the code and using this RegEx worked:

var str = "Name: ";
str = str.replace(/Name:.*/gi, "Name:" + "Joe");
console.log(str);
str = str.replace(/Name:.*/gi, "Name:" + "Prav");
console.log(str);```

Explanation for the RegEx

psst: There's no better explanation than RegEx101...

Title: String replace expressions

Body:
I have the following string:

var myString = "Name: ";

function replaceName(str, name) {
  return str.replace(/Name:/gi, "Name:" + name);
}

myString = replaceName("Name: ", "Joe");
myString = replaceName("Name: ", "Jane");

I want to replace the entire line each time a new name is added. The above keeps appending the name to the end of the string.

How can I replace the name each time str.replace is called?

Body:
Firstly, you could have mentioned clearly that calling the function second time messes up. And secondly, there's no functions in your code, so you need to tell which line is messing up. I understood the question with the help of Rory McCrossan and here's the answer.

I changed the code and using this RegEx worked:

var str = "Name: ";
str = str.replace(/Name:.*/gi, "Name:" + "Joe");
console.log(str);
str = str.replace(/Name:.*/gi, "Name:" + "Prav");
console.log(str);

Explanation for the RegEx

psst: There's no better explanation than RegEx101...


问:
How do I print a variable from main with a function in a class, Help understanding OOP c++
Section 9(1/4) out of 11 of my c++ introduction webclass;

I have no idea what I'm doing.
I'm unsure even of what terms to search for(first touch with OOP).

-
I need to print the cin in main with a function in a class,
So far I have come up with a class with a string variable and a function that do nothing;

```<code>#include <iostream>
#include <string>
using namespace std;
        class printclass
    {
        public:
        string array;
        void print();
    };

    void printclass::print()
    {
        cout << array;
    }
</code>```

Main program(cannot be edited);

```<code>   int main()
{
  char array[50];

  cout << "Enter string:";
  cin.get(array, 50);

  printclass printer;
  printer.print(array);
}
</code>```

It is my understanding that the printclass printer; creates an object 'printer' with the printclass class and thus knows how to use the functions in the class
on sort-of a blank page that is declared with the call, am I far off?

How do I print the value of the array in main with the function?

The exercise has been translated from finnish, please excuse blunt grammar and user stupidity.
Thank you for your time!

答:
am I far off?

Kinda. You've incorrectly assumed the interface of your printclass. Here's a correct one1 from the example posted:

```<code>class printclass {
public:
    printclass();
    void print(const char* str);
};
</code>```

From that it's quite easy to spot your mistake; you've assumed that your class has to store the array to print, while the interface passes it directly. It's enough to implement the print in terms of str without any member variables:

```<code>void printclass::print(const char* str) { // could be const
    std::cout << str;
}
</code>```

Note: the constructor can of course be left alone and it will default to what you want.

1One of many possible interfaces, but I've picked the most likely.

Body:
Section 9(1/4) out of 11 of my c++ introduction webclass;

I have no idea what I'm doing.
I'm unsure even of what terms to search for(first touch with OOP).

-
I need to print the cin in main with a function in a class,
So far I have come up with a class with a string variable and a function that do nothing;

#include <iostream>
#include <string>
using namespace std;
        class printclass
    {
        public:
        string array;
        void print();
    };

    void printclass::print()
    {
        cout << array;
    }

Main program(cannot be edited);

   int main()
{
  char array[50];

  cout << "Enter string:";
  cin.get(array, 50);

  printclass printer;
  printer.print(array);
}

It is my understanding that the printclass printer; creates an object 'printer' with the printclass class and thus knows how to use the functions in the class
on sort-of a blank page that is declared with the call, am I far off?

How do I print the value of the array in main with the function?

The exercise has been translated from finnish, please excuse blunt grammar and user stupidity.
Thank you for your time!

Body:
am I far off?

Kinda. You've incorrectly assumed the interface of your printclass. Here's a correct one1 from the example posted:

class printclass {
public:
    printclass();
    void print(const char* str);
};

From that it's quite easy to spot your mistake; you've assumed that your class has to store the array to print, while the interface passes it directly. It's enough to implement the print in terms of str without any member variables:

void printclass::print(const char* str) { // could be const
    std::cout << str;
}

Note: the constructor can of course be left alone and it will default to what you want.

1One of many possible interfaces, but I've picked the most likely.


问:
How do i convert the following xml based spring bean to java annotation based beans?
```<code> <bean id="string.message.service" class="com.ce.indiabringsService">
 <constructor-arg ref="com.ce.indiabrings.consumer" />
 <constructor-arg ref="com.ce.indiabrings.value.function" />
 </bean>
</code>```

I want to convert this to java annotation based bean (@Bean).

答:
You need to create a class with org.springframework.context.annotation @Configuration annotation.

Then use @Bean annotation on a method and return appropriate bean object.

```<code>@Bean
public com.ce.indiabringsService getMessageService(){
    return new com.ce.indiabringsService(com.ce.indiabrings.consumer,com.ce.indiabrings.value.functioncom.ce.indiabrings.consumer);
}
</code>```

Hope this helps you out.

Body:
 <bean id="string.message.service" class="com.ce.indiabringsService">
 <constructor-arg ref="com.ce.indiabrings.consumer" />
 <constructor-arg ref="com.ce.indiabrings.value.function" />
 </bean>

I want to convert this to java annotation based bean (@Bean).

Body:
You need to create a class with org.springframework.context.annotation @Configuration annotation.

Then use @Bean annotation on a method and return appropriate bean object.

@Bean
public com.ce.indiabringsService getMessageService(){
    return new com.ce.indiabringsService(com.ce.indiabrings.consumer,com.ce.indiabrings.value.functioncom.ce.indiabrings.consumer);
}

Hope this helps you out.


问:
Align columns output c++
I want read a file where there are the names of AC Milan's players and their date of birth. I want display this in two aligned columns. I tried to use setw() and left but the result isn't what I want. This is the code that I used for read and print:

```<code>void read(char filename[]){
    fstream mio_file;
    char c;
    bool start_name = true;
    bool start_date = true;

    mio_file.open(filename, ios_base::in | ios_base::binary);

    mio_file.read(&c, sizeof(char));
    while(!mio_file.eof()){

        if(c >= 'A' && c <= 'z' && start_name){
            cout << endl << "Name : ";
            start_name = false;
            start_date = true;
        }
        if(c >= '0' && c <= '9' && start_date){
            cout << setw(25) << left << "Date of birth : ";
            start_date = false;
            start_name = true;
        }

        cout << c;
        mio_file.read(&c, sizeof(char));
    }

    mio_file.close();
}
</code>```

This is output :

And this is output that I want :

答:
You need to use the std::setw for each of the columns. Not just set it once. Example:

```<code>std::cout << std::left << std::setw(25) << "Column 1" << std::setw(25) << "Column 2" << std::endl;
</code>```

In your particular case you only need to apply it on the Name column:

```<code>std::cout << std::left << std::setw(25) << "Name : ";
</code>```

Title: Align columns output c++

Body:
I want read a file where there are the names of AC Milan's players and their date of birth. I want display this in two aligned columns. I tried to use setw() and left but the result isn't what I want. This is the code that I used for read and print:

void read(char filename[]){
    fstream mio_file;
    char c;
    bool start_name = true;
    bool start_date = true;

    mio_file.open(filename, ios_base::in | ios_base::binary);

    mio_file.read(&c, sizeof(char));
    while(!mio_file.eof()){

        if(c >= 'A' && c <= 'z' && start_name){
            cout << endl << "Name : ";
            start_name = false;
            start_date = true;
        }
        if(c >= '0' && c <= '9' && start_date){
            cout << setw(25) << left << "Date of birth : ";
            start_date = false;
            start_name = true;
        }

        cout << c;
        mio_file.read(&c, sizeof(char));
    }

    mio_file.close();
}

This is output :

And this is output that I want :

Body:
You need to use the std::setw for each of the columns. Not just set it once. Example:

std::cout << std::left << std::setw(25) << "Column 1" << std::setw(25) << "Column 2" << std::endl;

In your particular case you only need to apply it on the Name column:

std::cout << std::left << std::setw(25) << "Name : ";


问:
C++ : Avoid lot of boolean variable for multiple verification conditions in trading app
i am a junior dev in trading app... we have a order refresh verification unit. It has to verify order confirmation from exchange. We send a bunch of different request in bulk ( NEW, MODIFY, CANCEL ) to exchange... Verification has to happen for max N times with each T intervals for all orders. if verification successful for all the order before N retry then fine.. otherwise we need to indicate as verification unsuccessfull. i hv done a basic coding done in very urgent like below

```<code>for( N times )
{
   for_each ( sent_request_order )   // SENT
   {
       1) get all the  refreshed order from DB or shared mem i.e REFRESHED
       2) find current sent order in REFRESHED

       if( not_found )
            not refreshed from exchange, continue to next order

       if( found )

       case NEW :    //check for new status, mark verification done
       case MODIFY : //check for modified status..
                     //if not mark pending, go to next order,
                     //revisit the same after T time
       case CANCEL : //check for cancelled status..
                     //if not mark pending, go to next order,
                     //revisit the same after T time
   }

   if( all_verified )
       exit from verification.

   wait ( T sec )

}
</code>```

order_verification_pending, order_verification_done,  order_visited, order_not_visited, all_verified, all_not_verified ... lot of boolean flags used for indication..

is there any better approach for doing this.... splitting responsibilities across the classes......????

i know this is not a general question.... but still flags are making me tidious to handle...

答:
You talk about "order_verification_pending, order_verification_done, order_visited, order_not_visited, all_verified, all_not_verified"... but that seems to double the number of booleans, for example: if you have order_visited then you don't need order_not_visited... it is just "!order_visited".  When there are more than two states involved, use an enum instead of a lot of complicated, overlapping booleans.  For example, if verification might be pending, done, failed etc. but these are all mutually exclusive, then store the single current state in that enum.

It's more elegant to have a set of pending operations, and remove elements from that set until the set is empty or the whole verification times out.  That way, you're not checking operations you already found succeeded.

Body:
i am a junior dev in trading app... we have a order refresh verification unit. It has to verify order confirmation from exchange. We send a bunch of different request in bulk ( NEW, MODIFY, CANCEL ) to exchange... Verification has to happen for max N times with each T intervals for all orders. if verification successful for all the order before N retry then fine.. otherwise we need to indicate as verification unsuccessfull. i hv done a basic coding done in very urgent like below

for( N times )
{
   for_each ( sent_request_order )   // SENT
   {
       1) get all the  refreshed order from DB or shared mem i.e REFRESHED
       2) find current sent order in REFRESHED

       if( not_found )
            not refreshed from exchange, continue to next order

       if( found )

       case NEW :    //check for new status, mark verification done
       case MODIFY : //check for modified status..
                     //if not mark pending, go to next order,
                     //revisit the same after T time
       case CANCEL : //check for cancelled status..
                     //if not mark pending, go to next order,
                     //revisit the same after T time
   }

   if( all_verified )
       exit from verification.

   wait ( T sec )

}

order_verification_pending, order_verification_done,  order_visited, order_not_visited, all_verified, all_not_verified ... lot of boolean flags used for indication..

is there any better approach for doing this.... splitting responsibilities across the classes......????

i know this is not a general question.... but still flags are making me tidious to handle...


问:
Using GSON to parse Json into a JAVA Object where the Json Elements may vary
I am trying to parse a JSON .txt file into a JAVA object using GSON. The JSON file has the following structure:

```<code>    {
        "event0" : {
        "a" : "abc",
        "b" : "def"
        },

        "event1" : {
        "a" : "ghi",
        "b" : "jkl",
        "c" : "mno"
        }
    }
</code>```

I have read the text file into a String called dataStr. I want to use the fromJson method to capture the events into the following JAVA class:

```<code>public class Event {
    private String a;
    private String b;
    private String c;

    public Event() {}

}
</code>```

The problem is that the JSON might have one extra field "c" in some of the elements. I want to parse all the events into Event class objects, and for the cases where there is no "c" field, I want to make it null or zero in my object. It is not known beforehand which of the elements will have the "c" field.

Specifically, I was not able to figure out how to handle one extra field in some of the JSON elements. I want to do something along the lines of:

```<code>Gson gson = new Gson();
ArrayList<Event> events = gson.fromJson(dataStr, Event.class);
</code>```

But I am stuck with first, how to iterate over the events in the Json file, and secondly, how to handle some occasional missing fields into the same Event object. I would really appreciate a kick in the right direction. Thank you all.

I am fairly new to JSON parsing, and might have missed something in the following answers:

Using Gson to convert Json into Java Object

Mapping JSON into POJO using Gson

Using gson to parse json to java object

Parse JSON into a java object

How to parse a json file into a java POJO class using GSON

答:
I'm not sure if I understood your question right. As per my understanding, you are trying to convert a json object with an extra field which is not available in the java class. Frankly, I don't understand why you want that or if it's possible to start with. You can have a workaround by converting the json to Map.

Map map = gson.fromJson(jsonString, Map.class);

Body:
I am trying to parse a JSON .txt file into a JAVA object using GSON. The JSON file has the following structure:

    {
        "event0" : {
        "a" : "abc",
        "b" : "def"
        },

        "event1" : {
        "a" : "ghi",
        "b" : "jkl",
        "c" : "mno"
        }
    }

I have read the text file into a String called dataStr. I want to use the fromJson method to capture the events into the following JAVA class:

public class Event {
    private String a;
    private String b;
    private String c;

    public Event() {}

}

The problem is that the JSON might have one extra field "c" in some of the elements. I want to parse all the events into Event class objects, and for the cases where there is no "c" field, I want to make it null or zero in my object. It is not known beforehand which of the elements will have the "c" field.

Specifically, I was not able to figure out how to handle one extra field in some of the JSON elements. I want to do something along the lines of:

Gson gson = new Gson();
ArrayList<Event> events = gson.fromJson(dataStr, Event.class);

But I am stuck with first, how to iterate over the events in the Json file, and secondly, how to handle some occasional missing fields into the same Event object. I would really appreciate a kick in the right direction. Thank you all.

I am fairly new to JSON parsing, and might have missed something in the following answers:

Using Gson to convert Json into Java Object

Mapping JSON into POJO using Gson

Using gson to parse json to java object

Parse JSON into a java object

How to parse a json file into a java POJO class using GSON


问:
Android Service Stops When App Is Closed
I am starting a service from my main Android activity as follows:

```<code>final Context context = base.getApplicationContext();
final Intent intent = new Intent(context, MyService.class);
startService(intent);
</code>```

When I close the activity page by swiping it out from the recent apps list, the service stops running and restarts after some time. I can't use persistent services with notifications because of my app requirements. How can I make the service NOT restart or shutdown and just keep on running on app exit?

答:
```<code><service android:name=".Service2"
            android:process="@string/app_name"
            android:exported="true"
            android:isolatedProcess="true"
            />
</code>```

<p>Declare this in your manifest.  Give a custom name to your process and make that process isolated and exported . </p>

Body:
I am starting a service from my main Android activity as follows:

final Context context = base.getApplicationContext();
final Intent intent = new Intent(context, MyService.class);
startService(intent);

When I close the activity page by swiping it out from the recent apps list, the service stops running and restarts after some time. I can't use persistent services with notifications because of my app requirements. How can I make the service NOT restart or shutdown and just keep on running on app exit?

Body:
<service android:name=".Service2"
            android:process="@string/app_name"
            android:exported="true"
            android:isolatedProcess="true"
            />

Declare this in your manifest.  Give a custom name to your process and make that process isolated and exported .


答:
functions will be appended to the package name. For example:

```<code>import numpy
# Calling the square root function from numpy
val = 4
newVal = numpy.sqrt(val)

# You can also do this, but it is not recommended as it pollutes your name space
from numpy import sqrt

# Now I can call sqrt directly
val = 4
newVal = sqrt(val)
</code>```

Class methods work similarly.

Title: Python package basics

Body:
I have a python file named as test1.py.
This file contains few classes and a few functions.

I intend to package this and distribute so that others can use it via the pip install command.
From other posts, I understood how we build a package.

Q: When the package is imported in the end user's code, using the import <mypackage> command,

1. can the functions be called directly by simply writing the function name?

2. methods which are part of the class, are ideally called by objectname.methodname, how will they be called now?

Body:
functions will be appended to the package name. For example:

import numpy
# Calling the square root function from numpy
val = 4
newVal = numpy.sqrt(val)

# You can also do this, but it is not recommended as it pollutes your name space
from numpy import sqrt

# Now I can call sqrt directly
val = 4
newVal = sqrt(val)

Class methods work similarly.


问:
Can I host two separate web servers on a LAN to the outside world through 1 IP address?
I am a web programmer with a home web dev operation. I have multiple web servers in my house on a FIOS connection. I have my own domain pointed to my router through dyndns.org's custom domain service.

My ISP gives me ONE static IP address, which at the moment allows me to configure my router to direct outbound web traffic from one server through port 80 and another server through port 8080. This sucks because many companies block port 8080 these days causing some of my corporate clients to not be able to hit my second web server.

Is there any way for me to direct regular old port 80 web traffic to TWO SEPARATE web servers internally on my network using two separate host names?

For instance. I want http://webserver1.mydomain.com to hit one web server on my network, and http://webserver2.mydomain.com to hit another web server and have both sets of traffic served on port 80.

Is this even possible? If not, can I do a hack by programmatically routing traffic from one web server transparently to another?

For the record I run MS Windows Server 2008 IIS 7.0 stack, a D-link DIR-655 router, and use DynDNS for my domain needs.

答:
The name of the solution you looking for is called reverse proxy'ing.

There are implementations in apache, squid and Mircosoft ISA Server.

If your adventurous you can always roll your own? or modify something like this to meet your your needs.

I've had customers using squid reverse proxy that's high volume and it works perfectly!

It does tend to screw up your web logs on the webserver though, traffic will all appear to come from your internal proxy host that's doing the redirection/rewriting.

OwnerDisplayName: Matias Nino

OwnerDisplayName: Nick Kavadias

LastEditorDisplayName: Nick Kavadias


问:
how can i make an interface in php to add data csv file
hey...i need to create a html+php+javascript interface

where i got three text area  and i want::::

that if i'll enter some data into text area and pressing submit button,,then it'll enter that textarea's data into a csv file..

pls some one help....

答:
```<code><?php

$list = arrary();
//your array will have all the fields from the form, textfields and textareas

$fp = fopen('output.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>
</code>```