问:
MVC application Viewengine not looking in Areas/{name}/Views instead looking in default Views folder
I am using 2017 VC for mac, the xamarian version of vs does not have the auto Areas Mapper. I manually added Areas folder and configured the routing properly, when I add an actionLink to my main csHTML page it is throwing an 500 error and stating.

```<code>System.InvalidOperationException
The view 'Billing' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/BillingMain/Billing.cshtml
~/Views/BillingMain/Billing.vbhtml
~/Views/Shared/Billing.cshtml
~/Views/Shared/Billing.vbhtml
~/Views/BillingMain/Billing.aspx
~/Views/BillingMain/Billing.ascx
~/Views/Shared/Billing.aspx
~/Views/Shared/Billing.ascx
</code>```

Instead it should be searching in ~/Areas/Billing/Views/BillingMainController.cshtml

I have tried everything to get this to work, but only keep on getting stuck.

Here is my directory hierarchy

```<code>Project-
    AppStart-
    Areas-
        Billing-
        Invoice-
    Controllers-
    Scripts-
    Views-
    Global.asax
</code>```

I am only testing Billing area for now, below is the rest of my code.

RouteConfig

```<code>using System.Web.Mvc;
using System.Web.Routing;

namespace WORK_GODDAMN
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            //AreaRegistration.RegisterAllAreas();
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                //,namespaces: new string[] { "WORK_GODDAMN.Areas.Controllers" }
            );

        }
    }
</code>```

}

BillingAreaRegistration.cs

```<code>using System;
using System.Web.Mvc;

namespace WORK_GODDAMN.Areas.Billing
{

    public class BillingAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Billing";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Billing_Default",
                "Billing/{controller}/{action}/{id}",
                new {controller = "BillingMain", action = "Index", id = UrlParameter.Optional }
                , namespaces: new string[] { "WORK_GODDAMN.Areas.Billing.Controllers" }
            );

        }
    }

}
</code>```

Global.asax

```<code>using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Http;

namespace WORK_GODDAMN
{
    public class Global : HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }
}
</code>```

main _Layout.cshtml this is where the Action Link redirects and believe I might be doing something wrong here, but at this point I have no clue what could be causing the problem.

```<code><!DOCTYPE html>

<html>
    @using System.Web.Optimization
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Scripts.Render("~/Scripts/modernizr.js")
</head>
<body>
    <div>
        <div>
            <h2>{Demo}- Pluggable Modules</h2>
        </div>
        <div id="nav">
            @Html.ActionLink("Home","Index","Home", new {Area=""}, null)
            @Html.ActionLink("Invoice","Index","InvoiceMain", new {Area=""}, null)
            @Html.ActionLink("Billing","Index","BillingMain", new {Area=""}, null)
        </div>
        <hr />
        <div>
                @RenderBody()
        </div>
    </div>
    @Scripts.Render("~/Scripts/jquery.js")
    @RenderSection("Scripts", required: false)
</body>
</html>
</code>```

答:
Specify the name of area in Html.ActionLink.</p>

```<code>@Html.ActionLink("Billing", "Index", "BillingMain", new { Area = "Billing" }, null)
</code>```

Body:
I am using 2017 VC for mac, the xamarian version of vs does not have the auto Areas Mapper. I manually added Areas folder and configured the routing properly, when I add an actionLink to my main csHTML page it is throwing an 500 error and stating.

System.InvalidOperationException
The view 'Billing' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/BillingMain/Billing.cshtml
~/Views/BillingMain/Billing.vbhtml
~/Views/Shared/Billing.cshtml
~/Views/Shared/Billing.vbhtml
~/Views/BillingMain/Billing.aspx
~/Views/BillingMain/Billing.ascx
~/Views/Shared/Billing.aspx
~/Views/Shared/Billing.ascx

Instead it should be searching in ~/Areas/Billing/Views/BillingMainController.cshtml

I have tried everything to get this to work, but only keep on getting stuck.

Here is my directory hierarchy

Project-
    AppStart-
    Areas-
        Billing-
        Invoice-
    Controllers-
    Scripts-
    Views-
    Global.asax

I am only testing Billing area for now, below is the rest of my code.

RouteConfig

using System.Web.Mvc;
using System.Web.Routing;

namespace WORK_GODDAMN
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            //AreaRegistration.RegisterAllAreas();
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                //,namespaces: new string[] { "WORK_GODDAMN.Areas.Controllers" }
            );

        }
    }

}

BillingAreaRegistration.cs

using System;
using System.Web.Mvc;

namespace WORK_GODDAMN.Areas.Billing
{

    public class BillingAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Billing";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Billing_Default",
                "Billing/{controller}/{action}/{id}",
                new {controller = "BillingMain", action = "Index", id = UrlParameter.Optional }
                , namespaces: new string[] { "WORK_GODDAMN.Areas.Billing.Controllers" }
            );

        }
    }

}

Global.asax

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Http;

namespace WORK_GODDAMN
{
    public class Global : HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }
}

main _Layout.cshtml this is where the Action Link redirects and believe I might be doing something wrong here, but at this point I have no clue what could be causing the problem.

<!DOCTYPE html>

    @using System.Web.Optimization

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Scripts.Render("~/Scripts/modernizr.js")

{Demo}- Pluggable Modules

            @Html.ActionLink("Home","Index","Home", new {Area=""}, null)
            @Html.ActionLink("Invoice","Index","InvoiceMain", new {Area=""}, null)
            @Html.ActionLink("Billing","Index","BillingMain", new {Area=""}, null)

                @RenderBody()

    @Scripts.Render("~/Scripts/jquery.js")
    @RenderSection("Scripts", required: false)

Body:
Specify the name of area in Html.ActionLink.

@Html.ActionLink("Billing", "Index", "BillingMain", new { Area = "Billing" }, null)


来源: stackexchange

问:
Bootstrap table not working good with ng-repeat
```<code><div ng-controller="reportCtrl">
      <table class="table table-hover">
          <thead class="row col-md-3">
              <tr class="row">
                  <th class="col-md-6">Key </th>
                  <th class="col-md-6"> Value</th>
              </tr>
          </thead>
          <tbody ng-repeat="param in params" class="row col-md-3">
              <tr class="row">
                  <td class="col-md-6 info">{{param.key}}</td>
                  <td class="col-md-6 info">{{param.val}}</td>
              </tr>
          </tbody>
      </table>
</div>
</code>```

I have this table, when i'm using the bootstrap grid system with ng-repeat the results are very strange..

I've tried to play with the grid system but it dosent seem that it helps..

答:
Try remove the class="row .."</p>

```<code><div ng-controller="reportCtrl">
      <table class="table table-hover">
          <thead>
              <tr>
                  <th>Key </th>
                  <th> Value</th>
              </tr>
          </thead>
          <tbody ng-repeat="param in params">
              <tr>
                  <td>{{param.key}}</td>
                  <td>{{param.val}}</td>
              </tr>
          </tbody>
      </table>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
                  Key
                   Value

                  {{param.key}}
                  {{param.val}}

I have this table, when i'm using the bootstrap grid system with ng-repeat the results are very strange..

I've tried to play with the grid system but it dosent seem that it helps..

Body:
Try remove the class="row .."

<div ng-controller="reportCtrl">
      <table class="table table-hover">
          <thead>
              <tr>
                  <th>Key </th>
                  <th> Value</th>
              </tr>
          </thead>
          <tbody ng-repeat="param in params">
              <tr>
                  <td>{{param.key}}</td>
                  <td>{{param.val}}</td>
              </tr>
          </tbody>
      </table>
</div>


问:
Is there any way to avoid CORS error with linkpreview.net in axios like trustAsResourceUrl() in Angular?
I'm trying to implement linkpreview.net API in my reactJS app using axios but it gives me followin CORS error

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
  the remote resource at
  http://api.linkpreview.net/?callback=JSON_CALLBACK&q=abc.xyz&key='my
  key here'. (Reason: CORS header ‘Access-Control-Allow-Origin’
  missing).

here is my axios code

```<code>axios({
          method:'post',
          url:"http://api.linkpreview.net/?callback=JSON_CALLBACK&q="+res+"&key="+UserSetting.fetchUrlKey,
          headers: {'Access-Control-Allow-Origin': '*'},
          data: data
      })
      .then(response => {
        console.log(response);

      })
      .catch((error) => {
        console.log(error);
      })
</code>```

Please do let me know if I'm doing something wrong!!

答:
For some reason Axios won't provide support for jsonp requests and that is mentioned here: https://github.com/mzabriskie/axios/pull/15

With that he has also provided another recipe for jsonp using npm package jsonp

So, you can try it and use something like:

```<code>var j = require('jsonp');

j('http://api.linkpreview.net/?key=123456&q=https://www.google.com', function (err, data) {
  if (err) {
    console.error(err.message);
  } else {
    console.log(data);
  }
});
</code>```

Body:
I'm trying to implement linkpreview.net API in my reactJS app using axios but it gives me followin CORS error

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
  the remote resource at
  http://api.linkpreview.net/?callback=JSON_CALLBACK&q=abc.xyz&key='my
  key here'. (Reason: CORS header ‘Access-Control-Allow-Origin’
  missing).

here is my axios code

axios({
          method:'post',
          url:"http://api.linkpreview.net/?callback=JSON_CALLBACK&q="+res+"&key="+UserSetting.fetchUrlKey,
          headers: {'Access-Control-Allow-Origin': '*'},
          data: data
      })
      .then(response => {
        console.log(response);

      })
      .catch((error) => {
        console.log(error);
      })

Please do let me know if I'm doing something wrong!!

Body:
For some reason Axios won't provide support for jsonp requests and that is mentioned here: https://github.com/mzabriskie/axios/pull/15

With that he has also provided another recipe for jsonp using npm package jsonp

So, you can try it and use something like:

var j = require('jsonp');

j('http://api.linkpreview.net/?key=123456&q=https://www.google.com', function (err, data) {
  if (err) {
    console.error(err.message);
  } else {
    console.log(data);
  }
});


问:
Install GraphLab Package in python 3.6.1
I tried to install GraphLab, but the result became like this:

AttributeError: module 'graphlab' has no attribute 'connect'

My python version is 3.6.1. And I also tried the code:

python -m pip install connect

But it didn't work.

Does anyone know how to solve this problems? Thanks!

答:
This happens when Version in python on system is different from Anaconda. Anaconda Python is mixing in imports from the regular Python on the system. Make sure "which python" points to the right Python (whereever you installed Anaconda Python. And similarly "which pip" Otherwise you will want to run python (or pip) from [where ever you installed Anaconda]/bin/python. You can try the Dato Launcher  which tries to set it all up for you.

Also, if you are not using Anaconda, on Graphlab support of installation, they recommended only two option for installation, one on Anaconda and the other on Virtualenv. I personally recommend you to use Anaconda for Graphlab as most of the development support and learning is totally based on Anaconda usage. You may follow this link to install Graphlab and Anaconda Here. I hope this helps.

Note: In installation of Anaconda, Python Version can be different like Python 2.7, but after installation of Anaconda, you can update to latest version of your choice.


问:
Simplest way to store data persistently server-side
(I understand this is probably a broad subject, but I don't know enough to ask a more precise question.)
I'd like to develop a very simple web application in html and javascript. This app could be for instance a map on which users could create / edit / delete markers (CRUD).
This requires very simple data (i.e. coordinates of the markers) to be stored persistently. Since I want all users to see everybody else's marker I suppose that the data should be stored server-side.
I would prefer to use PHP over other languages as that's what my current server supports. </p>

<p>What would be the simplest options to achieve this ? </p>

答:
You need three things.

PHP

MySQL

Google Maps Javascript API
Check Google API Console

Body:
(I understand this is probably a broad subject, but I don't know enough to ask a more precise question.)
I'd like to develop a very simple web application in html and javascript. This app could be for instance a map on which users could create / edit / delete markers (CRUD).
This requires very simple data (i.e. coordinates of the markers) to be stored persistently. Since I want all users to see everybody else's marker I suppose that the data should be stored server-side.
I would prefer to use PHP over other languages as that's what my current server supports.

What would be the simplest options to achieve this ?


问:
How to replace everything with blank after question mark in a string?
I am trying to replace everything with blank after question mark.

Suppose I have a string like below:

```<code>var str = "/root/Users?SkillId=201;"
</code>```

Now I want to replace everything with blank after ?.

Expected output: "/root/Users"

I tried below solution:

```<code>var str = "/root/Users?SkillId=201;".replace(/[^? ]/g, "");
console.log(str); // output : ?

str = str.split('?')[0] // though worked but not readable
</code>```

I don't want to use for loop for this. Isn't there is any better way to do this?

答:
Another option is to get the substring before the '?':

str = str.substr(0, str.indexOf('?'));

ContentLicense: CC BY-SA 4.0

Body:
I am trying to replace everything with blank after question mark.

Suppose I have a string like below:

var str = "/root/Users?SkillId=201;"

Now I want to replace everything with blank after ?.

Expected output: "/root/Users"

I tried below solution:

var str = "/root/Users?SkillId=201;".replace(/[^? ]/g, "");
console.log(str); // output : ?

str = str.split('?')[0] // though worked but not readable

I don't want to use for loop for this. Isn't there is any better way to do this?


问:
How know if ModelState contains errors
When a form is posted in my controller, I make the following check:

```<code>if(ModelState.IsValid)
</code>```

If the model is not valid, errors are added to the ModelState. The model is then passed to the view with validation summary.

However, I want to check if the ModelState has errors from inside the jQuery ready handler, so that I can add some additional behavior if the form has errors. Is that possible?

答:
In addition to Darins Answer:

In .cshtml:

```<code>@Html.Hidden("IsValid", Json.Encode(ViewData.ModelState.IsValid))
</code>```

in JS

```<code>var isValid = $('#IsValid').val().toLowerCase() == "true";
</code>```

Title: How know if ModelState contains errors

Body:
When a form is posted in my controller, I make the following check:

if(ModelState.IsValid)

If the model is not valid, errors are added to the ModelState. The model is then passed to the view with validation summary.

However, I want to check if the ModelState has errors from inside the jQuery ready handler, so that I can add some additional behavior if the form has errors. Is that possible?

Body:
In addition to Darins Answer:

In .cshtml:

@Html.Hidden("IsValid", Json.Encode(ViewData.ModelState.IsValid))

in JS

var isValid = $('#IsValid').val().toLowerCase() == "true";


问:
Use variable names in functions of dplyr
I want to use variable names as strings in functions of dplyr. See the example below:

```<code>df <- data.frame(
      color = c("blue", "black", "blue", "blue", "black"),
      value = 1:5)
filter(df, color == "blue")
</code>```

It works perfectly, but I would like to refer to color by string, something like this:

```<code>var <- "color"
filter(df, this_probably_should_be_a_function(var) == "blue").
</code>```

I would be happy, to do this by any means and super-happy to make use of easy-to-read dplyr syntax.

答:
As of dplyr 0.7, some things have changed again.

```<code>library(dplyr)
df <- data.frame(
  color = c("blue", "black", "blue", "blue", "black"),
  value = 1:5)
filter(df, color == "blue")

# it was already possible to use a variable for the value
val <- 'blue'
filter(df, color == val)

# As of dplyr 0.7, new functions were introduced to simplify the situation
col_name <- quo(color) # captures the current environment
df %>% filter((!!col_name) == val)

# Remember to use enquo within a function
filter_col <- function(df, col_name, val){
  col_name <- enquo(col_name) # captures the environment in which the function was called
  df %>% filter((!!col_name) == val)
}
filter_col(df, color, 'blue')
</code>```

More general cases are explained in the dplyr programming vignette.

Body:
I want to use variable names as strings in functions of dplyr. See the example below:

df <- data.frame(
      color = c("blue", "black", "blue", "blue", "black"),
      value = 1:5)
filter(df, color == "blue")

It works perfectly, but I would like to refer to color by string, something like this:

var <- "color"
filter(df, this_probably_should_be_a_function(var) == "blue").

I would be happy, to do this by any means and super-happy to make use of easy-to-read dplyr syntax.

Body:
As of dplyr 0.7, some things have changed again.

library(dplyr)
df <- data.frame(
  color = c("blue", "black", "blue", "blue", "black"),
  value = 1:5)
filter(df, color == "blue")

# it was already possible to use a variable for the value
val <- 'blue'
filter(df, color == val)

# As of dplyr 0.7, new functions were introduced to simplify the situation
col_name <- quo(color) # captures the current environment
df %>% filter((!!col_name) == val)

# Remember to use enquo within a function
filter_col <- function(df, col_name, val){
  col_name <- enquo(col_name) # captures the environment in which the function was called
  df %>% filter((!!col_name) == val)
}
filter_col(df, color, 'blue')

More general cases are explained in the dplyr programming vignette.


问:
.NET Core Web API async data return
I'm trying to handle returning data to APi client in GET HTTP response in asynchronous manner but with no luck so far.

My code :

```<code>using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Server.Database;
using System;
using System.Threading.Tasks;

namespace Server.Controllers
{
    //[Produces("application/json")]
    [Route("api/[Controller]")]
    public class UserController : Controller
    {
        private readonly DBContext _context;

        public UserController(DBContext context)
        {
            _context = context;
        }

        [HttpGet("/Users")]
        public async Task<IAsyncResult> GetUsers()
        {
            using (_context)
            {
                // how to properly return data asynchronously ?
                var col = await _context.Users.ToListAsync();
            }
        }

        [HttpGet("/Users/{id}")]
        public async Task<IActionResult> GetUserByID(Int32 id)
        {

            using (_context)
            {
                //this is wrong, I don't knwo how to do it properly
                //var item = await new ObjectResult(_context.Users.FirstOrDefault(user => user.IDUser == id));
            }
        }
    }
}
</code>```

As you can see I would like to handle GET request asynchronously by returning all users and in another method single user by his ID. I don't know if I need ObjectResultclass as well but I need to respons with JSON object to the client. Someone know how to do this ?

答:
Here, try this:

```<code>using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Server.Database;
using System;
using System.Threading.Tasks;

namespace Server.Controllers
{
    //[Produces("application/json")]
    [Route("api/[Controller]")]
    public class UserController : Controller
    {
        private readonly DBContext _context;

        public UserController(DBContext context)
        {
            _context = context;
        }

        [HttpGet("/Users")]
        public async Task<IActionResult> GetUsers()
        {
            return Json(await _context.Users.ToListAsync());
        }

        [HttpGet("/Users/{id}")]
        public async Task<IActionResult> GetUserByID(Int32 id)
        {
            return Json(await new _context.Users.FirstOrDefault(user => user.IDUser == id));
        }
    }
}
</code>```

Note, that in GetUsers you must return IActionResult, not IAsyncResult.

Title: .NET Core Web API async data return

Body:
I'm trying to handle returning data to APi client in GET HTTP response in asynchronous manner but with no luck so far.

My code :

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Server.Database;
using System;
using System.Threading.Tasks;

namespace Server.Controllers
{
    //[Produces("application/json")]
    [Route("api/[Controller]")]
    public class UserController : Controller
    {
        private readonly DBContext _context;

        public UserController(DBContext context)
        {
            _context = context;
        }

        [HttpGet("/Users")]
        public async Task<IAsyncResult> GetUsers()
        {
            using (_context)
            {
                // how to properly return data asynchronously ?
                var col = await _context.Users.ToListAsync();
            }
        }

        [HttpGet("/Users/{id}")]
        public async Task<IActionResult> GetUserByID(Int32 id)
        {

            using (_context)
            {
                //this is wrong, I don't knwo how to do it properly
                //var item = await new ObjectResult(_context.Users.FirstOrDefault(user => user.IDUser == id));
            }
        }
    }
}

As you can see I would like to handle GET request asynchronously by returning all users and in another method single user by his ID. I don't know if I need ObjectResultclass as well but I need to respons with JSON object to the client. Someone know how to do this ?

Body:
Here, try this:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Server.Database;
using System;
using System.Threading.Tasks;

namespace Server.Controllers
{
    //[Produces("application/json")]
    [Route("api/[Controller]")]
    public class UserController : Controller
    {
        private readonly DBContext _context;

        public UserController(DBContext context)
        {
            _context = context;
        }

        [HttpGet("/Users")]
        public async Task<IActionResult> GetUsers()
        {
            return Json(await _context.Users.ToListAsync());
        }

        [HttpGet("/Users/{id}")]
        public async Task<IActionResult> GetUserByID(Int32 id)
        {
            return Json(await new _context.Users.FirstOrDefault(user => user.IDUser == id));
        }
    }
}

Note, that in GetUsers you must return IActionResult, not IAsyncResult.


问:
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...

答:
Your algorithm looks workable. Implement it.

Do not try to optimize your code before you got it working. Once you have a working version running, nevermind how ugly, then you look at ways & means to optimize. Chances are good that you will then find a way to handle the flags that gives you so much trouble.

ContentLicense: CC BY-SA 2.5

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...


问:
My Navbar Does not appear
I am doing this on Codepen,
A dark-color navbar should appear with my name in a light color, but it does not happen. I am following the guide of bootstrap 4.0 that is online.

I have included all the necessary classes as per the guide and examples that i read.

```<code><div id="entire" class="container-fluid">

  <div id="topbar">
    <nav class="navbar navbar-brand navbar-inverse bg-inverse">
      <h1>Vishwad Desai</h1>
    </nav>
  </div>

  <div id="actual">
    <p> Start</p>
  </div>
  <div id="bottom"></div>
</div>
</code>```

Screenshot

答:
You have to make sure to include all the necessary CSS and JS files:

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</code>```

Additional you have to set the class .navbar-brand to the
 element directly (not to the ). See the following working example:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Vishwad Desai

 Start

```

Title: My Navbar Does not appear

Body:
I am doing this on Codepen,
A dark-color navbar should appear with my name in a light color, but it does not happen. I am following the guide of bootstrap 4.0 that is online.

I have included all the necessary classes as per the guide and examples that i read.

Vishwad Desai

 Start

Screenshot

Body:
You have to make sure to include all the necessary CSS and JS files:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>

Additional you have to set the class .navbar-brand to the <h1> element directly (not to the <nav>). See the following working example:

<!-- include all the required CSS and JS files -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>

<!-- your code -->
<div id="entire" class="container-fluid">
  <div id="topbar">
    <nav class="navbar navbar-inverse bg-inverse">
      <h1 class="navbar-brand">Vishwad Desai</h1>
    </nav>
  </div>
  <div id="actual">
    <p> Start</p>
  </div>
  <div id="bottom"></div>
</div>


问:
How to make grid Responsive Overlapping Content
Hello there i have made a grid for my website and the issue I am having is the grid overlaps the footer element I have been trying everything from setting the grid container to height Auto to see if it automatically adjusts I can't give it a set height as the website is responsive any help would be appreciated attached is my HTML and CSS code for the grid :)

```<code>    <html>
<head>
<link href="/styles.css" rel="stylesheet" type="text/css">
<link href="/services-styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="header">
<div class="nav">
<ul>
<li><a href="/index.html">Home</a></li>
<li><a href="/services.html">Services</a></li>
<li><a href="/aboutus.html">About us</a></li>
<li><a href="/contact.html">Contact</a></li>
</ul>
</div>
</div>
<div class="content">
<div class="title logo">
<h1>Logo's</h1>
</div>

<div class="title">
<h1>"Just a Glimpse of what we can do for you and your business"</h1>
    </div>
<div class="Grid1">
<div class="Gallery1">
<a href="Images/logo1.jpg">
<img src="/Images/logo1.jpg" style="width:100%; height:100%;">
    </a>
    </div>
<div class="Gallery1">
<a href="Images/logo2.png">
<img src="/Images/logo2.png"style="width:100%; height:100%;">
    </a>
    </div>
<div class="Gallery1">
<a href="Images/logo3.jpg">
<img src="/Images/logo3.jpg" style="width:100%; height:100%;">
    </a>
    </div>
    <div class="Gallery1">
<a href="Images/logo-grid3.jpg">
<img src="/Images/logo-grid3.jpg" style="width:100%; height:100%;">
    </a>
    </div>

    <div class="Gallery1">
<a href="Images/logo-grid3.jpg">
<img src="/Images/logo-grid3.jpg" style="width:100%; height:100%;">
    </a>
    </div>

    <div class="Gallery1">
<a href="Images/logo-grid3.jpg">
<img src="/Images/logo-grid3.jpg" style="width:100%; height:100%;">
    </a>
    </div>

        <div class="Gallery1">
<a href="Images/logo-grid3.jpg">
<img src="/Images/logo-grid3.jpg" style="width:100%; height:100%;">
    </a>
    </div>

    <div class="Gallery1">
<a href="Images/logo-grid3.jpg">
<img src="/Images/logo-grid3.jpg" style="width:100%; height:100%;">
    </a>
    </div>

    <div class="Gallery1">
<a href="Images/logo-grid3.jpg">
<img src="/Images/logo-grid3.jpg" style="width:100%; height:100%;">
    </a>

    </div>
    </div>
    </div>
    <footer>
<div class="Footer-Nav">
<ul>
<li><a href="/index.html">Home</a></li>
<li><a href="/services.html">Services</a></li>
<li><a href="/aboutus.html">About us</a></li>
<li><a href="/contact.html">Contact</a></li>
</ul>
</div>
</footer>
    </div>
</body>
</html>
</code>```

Here is code from main styles for all pages

```<code>    .Gallery1{
 margin:5px;
float: left;
width:300px;
height:200px;
position:relative;
border: 1px solid #ccc;
}

.Grid1{
max-width:945px;
position: relative;
height:auto;
margin:0 auto;
margin-top: 25px;
}

div.logo{
 margin-top: 15px;
 text-align: center;
 font-size: 40px;
 font-family: Monospace;
 padding: 5px;

}
div.Gallery1:hover{
border-color:#777;
}
.title{
position: relative;
text-align: center;
margin-top:25px;
font-family: Monospace;
}

@media screen and (max-width:928px){
div.Grid1 {
width:308px;
margin:0 auto;
 }

}
@media screen and (max-width:487px){
div.Gallery1{
width:100%;
 }
div.Grid1{
width:90%;
 }
.title{
 margin:25px;
 }

}
.Grid1{
height: auto;
position: relative;
}
.content{
height:100%;
margin: 0;
padding: 0;
position: relative;
}
</code>```

Media Queries

```<code>    @media screen and (max-width:928px){
   div.Grid1 {
   width:308px;
   margin:0 auto;
   }

   }

   @media screen and (max-width:487px){
   div.Gallery1{
   width:100%;
   }
</code>```

答:
just add float left to your footer and width 100%</p>

```<code>footer{
width:100%;
float:left;
}
</code>```

Body:
Hello there i have made a grid for my website and the issue I am having is the grid overlaps the footer element I have been trying everything from setting the grid container to height Auto to see if it automatically adjusts I can't give it a set height as the website is responsive any help would be appreciated attached is my HTML and CSS code for the grid :)

<link href="/styles.css" rel="stylesheet" type="text/css">
<link href="/services-styles.css" rel="stylesheet" type="text/css">

Home

Services

About us

Contact

Logo's

"Just a Glimpse of what we can do for you and your business"

Home

Services

About us

Contact

Here is code from main styles for all pages

    .Gallery1{
 margin:5px;
float: left;
width:300px;
height:200px;
position:relative;
border: 1px solid #ccc;
}

.Grid1{
max-width:945px;
position: relative;
height:auto;
margin:0 auto;
margin-top: 25px;
}

div.logo{
 margin-top: 15px;
 text-align: center;
 font-size: 40px;
 font-family: Monospace;
 padding: 5px;

}
div.Gallery1:hover{
border-color:#777;
}
.title{
position: relative;
text-align: center;
margin-top:25px;
font-family: Monospace;
}

@media screen and (max-width:928px){
div.Grid1 {
width:308px;
margin:0 auto;
 }

}
@media screen and (max-width:487px){
div.Gallery1{
width:100%;
 }
div.Grid1{
width:90%;
 }
.title{
 margin:25px;
 }

}
.Grid1{
height: auto;
position: relative;
}
.content{
height:100%;
margin: 0;
padding: 0;
position: relative;
}

Media Queries

    @media screen and (max-width:928px){
   div.Grid1 {
   width:308px;
   margin:0 auto;
   }

   }

   @media screen and (max-width:487px){
   div.Gallery1{
   width:100%;
   }

Body:
just add float left to your footer and width 100%

footer{
width:100%;
float:left;
}


问:
Bash script breaks out of loop without sending the mail
I have a small snippet in bash

```<code>retries = 3

for (( i=0; i<retries; i++)); do
    curl -1 --cipher ALL --connect-timeout 90 -T $zip_name ftps://ftp.box.com/Backup/$zip_name --user service.box.kto@crab.com:§fHyFSDF$o6
    [[ $? -eq 0 ]] && break
    echo "something went wrong, let's wait 6 seconds and retry"
    sleep 6
done

[[ $retries -eq i ]] && { echo "This email is a notification of Failure" | mail -s "Failed" "admin.box@text.com"  ; exit 1; }
</code>```

The above loop should retry 3 times if there is a error doing curl, so if a curl error comes up it should mail to the email. But to test it out i revoked the access of the user, so i expected a email but this didn't work and i received following on console:

```<code>  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:--  0:00:03 --:--:--     0
curl: (9) Server denied you to change to the given directory
</code>```

Why is the code breaking in the first attempt if access if revoked from uploading the server

答:
```<code>retries = 3

for (( i=0; i<$retries; i++))
do
    curl -1 --cipher ALL --connect-timeout 90 -T $zip_name
ftps://ftp.box.com/Backup/$zip_name --user service.box.kto@crab.com:§fHyFSDF$o6
    if [[ $? -eq 0 ]]
    then
        break
        echo "something went wrong, let's wait 6 seconds and retry"
        sleep 6
    fi
done

if [[ $retries -eq $i ]]
then
     echo "This email is a notification of Failure" | mail -s "Failed" "admin.box@text.com"
     exit 1
fi
</code>```

You are better off using if syntax I think and I've noticed that you are not referring to the retries variable correctly. i.e. with $retries as opposed to retries and $i instead of i

Body:
I have a small snippet in bash

retries = 3

for (( i=0; i<retries; i++)); do
    curl -1 --cipher ALL --connect-timeout 90 -T $zip_name ftps://ftp.box.com/Backup/$zip_name --user service.box.kto@crab.com:§fHyFSDF$o6
    [[ $? -eq 0 ]] && break
    echo "something went wrong, let's wait 6 seconds and retry"
    sleep 6
done

[[ $retries -eq i ]] && { echo "This email is a notification of Failure" | mail -s "Failed" "admin.box@text.com"  ; exit 1; }

The above loop should retry 3 times if there is a error doing curl, so if a curl error comes up it should mail to the email. But to test it out i revoked the access of the user, so i expected a email but this didn't work and i received following on console:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:--  0:00:03 --:--:--     0
curl: (9) Server denied you to change to the given directory

Why is the code breaking in the first attempt if access if revoked from uploading the server

Body:
retries = 3

for (( i=0; i<$retries; i++))
do
    curl -1 --cipher ALL --connect-timeout 90 -T $zip_name
ftps://ftp.box.com/Backup/$zip_name --user service.box.kto@crab.com:§fHyFSDF$o6
    if [[ $? -eq 0 ]]
    then
        break
        echo "something went wrong, let's wait 6 seconds and retry"
        sleep 6
    fi
done

if [[ $retries -eq $i ]]
then
     echo "This email is a notification of Failure" | mail -s "Failed" "admin.box@text.com"
     exit 1
fi

You are better off using if syntax I think and I've noticed that you are not referring to the retries variable correctly. i.e. with $retries as opposed to retries and $i instead of i


问:
Selecting records with latest year using data.table in R
I have a datatable where the same entity appears more than one time with a different date.

My objective is to retain a single record for each entity, the one with the latest date.

My code is not right though.  For a reproducible example see below:

```<code>data(mtcars)
mtcars
mtcars$model <- row.names(mtcars)
setDT(mtcars)
mtcars[, year := 2000]
mtcars1 <- mtcars[sample(nrow(mtcars), 5) , ]
mtcars1[, year := 2001]
mtcars2 <- mtcars[sample(nrow(mtcars), 5) , ]
mtcars2[, year := 2002]
mtcars <- rbind(mtcars, mtcars1, mtcars2)
setDT(mtcars)
mtcars

mtcars_latest <- mtcars[year == max(year) , names(mtcars), with = FALSE , by = model]
</code>```

With the last line I intend to group by model and then within each group select the record with the latest year (year == max(year)).  Moreover, I want all the variables (columns) of the original datatable to be returned, so I put names(mtcars), with = FALSE.

Body:
I have a datatable where the same entity appears more than one time with a different date.

My objective is to retain a single record for each entity, the one with the latest date.

My code is not right though.  For a reproducible example see below:

data(mtcars)
mtcars
mtcars$model <- row.names(mtcars)
setDT(mtcars)
mtcars[, year := 2000]
mtcars1 <- mtcars[sample(nrow(mtcars), 5) , ]
mtcars1[, year := 2001]
mtcars2 <- mtcars[sample(nrow(mtcars), 5) , ]
mtcars2[, year := 2002]
mtcars <- rbind(mtcars, mtcars1, mtcars2)
setDT(mtcars)
mtcars

mtcars_latest <- mtcars[year == max(year) , names(mtcars), with = FALSE , by = model]

With the last line I intend to group by model and then within each group select the record with the latest year (year == max(year)).  Moreover, I want all the variables (columns) of the original datatable to be returned, so I put names(mtcars), with = FALSE.

Body:
I think it is what you are looking for :

library(data.table)

mtcars[, names(mtcars), with = FALSE, by = .(model, max(year))]

> mtcars[, names(mtcars), with = FALSE, by = .(model, max(year))]
     mpg cyl  disp  hp drat    wt  qsec vs am gear carb               model year
 1: 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4           Mazda RX4 2000
 2: 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4       Mazda RX4 Wag 2000
 3: 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1          Datsun 710 2000
 4: 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1      Hornet 4 Drive 2000
 5: 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2   Hornet Sportabout 2000
 6: 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1             Valiant 2000
 7: 14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4          Duster 360 2000
 8: 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2           Merc 240D 2000
 9: 22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2            Merc 230 2000
10: 19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4            Merc 280 2000
11: 17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4           Merc 280C 2000
12: 16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3          Merc 450SE 2000
13: 17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3          Merc 450SL 2000
14: 15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3         Merc 450SLC 2000
15: 10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4  Cadillac Fleetwood 2000
16: 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4 Lincoln Continental 2000
17: 14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4   Chrysler Imperial 2000
18: 32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1            Fiat 128 2000
19: 30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2         Honda Civic 2000
20: 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1      Toyota Corolla 2000
21: 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1       Toyota Corona 2000
22: 15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2    Dodge Challenger 2000
23: 15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2         AMC Javelin 2000
24: 13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4          Camaro Z28 2000
25: 19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2    Pontiac Firebird 2000
26: 27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1           Fiat X1-9 2000
27: 26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2       Porsche 914-2 2000
28: 30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2        Lotus Europa 2000
29: 15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4      Ford Pantera L 2000
30: 19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6        Ferrari Dino 2000
31: 15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8       Maserati Bora 2000
32: 21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2          Volvo 142E 2000
33: 21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2          Volvo 142E 2001
34: 27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1           Fiat X1-9 2001
35: 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2   Hornet Sportabout 2001
36: 17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3          Merc 450SL 2001
37: 14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4   Chrysler Imperial 2001
38: 15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4      Ford Pantera L 2002
39: 15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3         Merc 450SLC 2002
40: 15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2         AMC Javelin 2002
41: 15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2    Dodge Challenger 2002
42: 19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4            Merc 280 2002


问:
How to increase the size of icons in jqgrid?
How should I increase the size of icons(add,delete..) in jqgrid?I have written following code in ui.jqgrid.css</p>

```<code>.ui-jqgrid .ui-jqgrid-pager .ui-pg-div  span.ui-icon,
.ui-jqgrid .ui-jqgrid-toppager .ui-pg-div  span.ui-icon{float:left;margin: 2px; width:18px;}
.ui-jqgrid .ui-jqgrid-toppager {border-left: 0 none !important;border-right: 0 none !important; border-top: 0 none
!important; margin: 0 !important; padding: 0 !important; position: relative;white-space: nowrap;overflow: hidden;}
</code>```

答: Your query is missing some valid information but you can always use zoom in your CSS over proper selectors. </p>

Body:
How should I increase the size of icons(add,delete..) in jqgrid?I have written following code in ui.jqgrid.css

.ui-jqgrid .ui-jqgrid-pager .ui-pg-div  span.ui-icon,
.ui-jqgrid .ui-jqgrid-toppager .ui-pg-div  span.ui-icon{float:left;margin: 2px; width:18px;}
.ui-jqgrid .ui-jqgrid-toppager {border-left: 0 none !important;border-right: 0 none !important; border-top: 0 none
!important; margin: 0 !important; padding: 0 !important; position: relative;white-space: nowrap;overflow: hidden;}


问:
Pause or stop the video when close icon is clicked
i want to pause/stop the video when close(X) icon is pressed.
Now when i click the X button video keeps playing in the background.
 Also i want that the close icon should come on the player itseld not outside the player.

var hideStr = 'X', showStr = 'Show', hideClass = 'hide';
var buttons = document.querySelectorAll('video + button.close');
for(var b = 0; b < buttons.length; b++){
  var button = buttons[b];
  button.addEventListener('click', function(){
    var video = this.parentNode.childNodes[1];
    video.muted = !video.muted;
    video.classList.toggle (hideClass);
    if(this.textContent == hideStr) this.textContent = showStr;
    else this.textContent = hideStr;
  });
}
$('hideStr').click(function(){
  $(".playvideo").pause();       // Tag name used as a selector
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.relative {
    position: relative;
  left: 00px;
}
.close {
    font-size: 10px;
    position: inherit;
    top: 5px; right: 5px;
}
.hide {
    display: none;
}</code>```

    <video id="playvideo" width="450" controls="controls" >
    <source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
    </video>
     <button class="close">X</button>

```

答:
No need for separate event handler for play and pause. You already have click event handler on the button.

Just check for the button text. If it is X then pause the video, else play it.

Please see my code below. (I don't know if you want the playing video part in else part. comment it if you don't need)

var hideStr = 'X', showStr = 'Show', hideClass = 'hide';
var buttons = document.querySelectorAll('video + button.close');
for(var b = 0; b < buttons.length; b++){
  var button = buttons[b];
  button.addEventListener('click', function(){
    var video = this.parentNode.childNodes[1];
    video.muted = !video.muted;
    if(this.textContent === hideStr){ //Pause the video.
       video.pause();
    } else {
       video.play();
    }
    video.classList.toggle (hideClass);
    if(this.textContent == hideStr) this.textContent = showStr;
    else this.textContent = hideStr;
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.relative {
    position: relative;
  left: 00px;
}
.close {
    font-size: 10px;
    position: inherit;
    top: 5px; right: 5px;
}
.hide {
    display: none;
}</code>```

    <video id="playvideo" width="450" controls="controls" >
    <source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
    </video>
     <button class="close">X</button>

```

Body:
i want to pause/stop the video when close(X) icon is pressed.
Now when i click the X button video keeps playing in the background.
 Also i want that the close icon should come on the player itseld not outside the player.

var hideStr = 'X', showStr = 'Show', hideClass = 'hide';
var buttons = document.querySelectorAll('video + button.close');
for(var b = 0; b < buttons.length; b++){
  var button = buttons[b];
  button.addEventListener('click', function(){
    var video = this.parentNode.childNodes[1];
    video.muted = !video.muted;
    video.classList.toggle (hideClass);
    if(this.textContent == hideStr) this.textContent = showStr;
    else this.textContent = hideStr;
  });
}
$('hideStr').click(function(){
  $(".playvideo").pause();       // Tag name used as a selector
});

div.relative {
    position: relative;
  left: 00px;
}
.close {
    font-size: 10px;
    position: inherit;
    top: 5px; right: 5px;
}
.hide {
    display: none;
}

    <video id="playvideo" width="450" controls="controls" >
    <source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
    </video>
     <button class="close">X</button>

Body:
No need for separate event handler for play and pause. You already have click event handler on the button.

Just check for the button text. If it is X then pause the video, else play it.

Please see my code below. (I don't know if you want the playing video part in else part. comment it if you don't need)

var hideStr = 'X', showStr = 'Show', hideClass = 'hide';
var buttons = document.querySelectorAll('video + button.close');
for(var b = 0; b < buttons.length; b++){
  var button = buttons[b];
  button.addEventListener('click', function(){
    var video = this.parentNode.childNodes[1];
    video.muted = !video.muted;
    if(this.textContent === hideStr){ //Pause the video.
       video.pause();
    } else {
       video.play();
    }
    video.classList.toggle (hideClass);
    if(this.textContent == hideStr) this.textContent = showStr;
    else this.textContent = hideStr;
  });
}

div.relative {
    position: relative;
  left: 00px;
}
.close {
    font-size: 10px;
    position: inherit;
    top: 5px; right: 5px;
}
.hide {
    display: none;
}

<div>
    <video id="playvideo" width="450" controls="controls" >
    <source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
    </video>
     <button class="close">X</button>
 </div>


问:
"this" is not refering the the user object in mongoose model
I have the following code to save user object to database from express,

```<code>api.post('/signup', function (req, res) {
    var user = new User();
    user.name = req.body.name;
    user.email = req.body.email;
    user.setPassword(req.body.password);
    user.save(function (err) {
        err ? res.send(err) : res.json({ message: 'User Created!'})
    })
})
</code>```

and below here for the user schema,

```<code>var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var SALT_WORK_FACTOR = 10;

var Schema = mongoose.Schema;

var userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        unique: true,
        required: true
    },
    password: String,
})

userSchema.methods.setPassword = function (password) {
    bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
        if (err) return console.log(err);
        bcrypt.hash(password, salt, function (err, hash) {
            if (err) return console.log(err);
            this.password = hash; // <= `this` will not be saved to mongoDB
        })
    })
}

module.exports = mongoose.model('User', userSchema);
</code>```

When it performed the save function, it will show that the password was undefined and will save the object to mongodb without password value.

I've checked the this question as well and changed all my functions to not using arrow method but it still got the same error.

The same issue when i was using middleware hook that this reference was not referring to user object. Below here for my another approach,

```<code>userSchema.pre('save', (next) => {

    bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
        if(err) return next(err);
        bcrypt.hash(this.password, salt, function (err, hash) {
            if (err) return next(err);

            this.password = hash; // <= `this` will not be saved to mongoDB
            next();
        })
    })
})
</code>```

Any idea for this value to be saved to database when perform save?

答:
You should try below code, Hope it will work for you:</p>

```<code>userSchema.methods.setPassword = function (password) {
    var pswd=password;
    bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
        if (err) return console.log(err);
        bcrypt.hash(pswd, salt, function (err, hash) {
            if (err) return console.log(err);
            pswd = hash;
            console.log(pwsd); // your decripted password
        })
    })
}
</code>```

Body:
I have the following code to save user object to database from express,

api.post('/signup', function (req, res) {
    var user = new User();
    user.name = req.body.name;
    user.email = req.body.email;
    user.setPassword(req.body.password);
    user.save(function (err) {
        err ? res.send(err) : res.json({ message: 'User Created!'})
    })
})

and below here for the user schema,

var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var SALT_WORK_FACTOR = 10;

var Schema = mongoose.Schema;

var userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        unique: true,
        required: true
    },
    password: String,
})

userSchema.methods.setPassword = function (password) {
    bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
        if (err) return console.log(err);
        bcrypt.hash(password, salt, function (err, hash) {
            if (err) return console.log(err);
            this.password = hash; // <= `this` will not be saved to mongoDB
        })
    })
}

module.exports = mongoose.model('User', userSchema);

When it performed the save function, it will show that the password was undefined and will save the object to mongodb without password value.

I've checked the this question as well and changed all my functions to not using arrow method but it still got the same error.

The same issue when i was using middleware hook that this reference was not referring to user object. Below here for my another approach,

userSchema.pre('save', (next) => {

    bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
        if(err) return next(err);
        bcrypt.hash(this.password, salt, function (err, hash) {
            if (err) return next(err);

            this.password = hash; // <= `this` will not be saved to mongoDB
            next();
        })
    })
})

Any idea for this value to be saved to database when perform save?

Body:
You should try below code, Hope it will work for you:

userSchema.methods.setPassword = function (password) {
    var pswd=password;
    bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
        if (err) return console.log(err);
        bcrypt.hash(pswd, salt, function (err, hash) {
            if (err) return console.log(err);
            pswd = hash;
            console.log(pwsd); // your decripted password
        })
    })
}


问:
React Js Looping over a parent array for login authorisation
Right so I have passed an array down to the child from the parent and I will include all code below

so what I am trying to do is loop over my array and check that my user input matches one of the objects in the array if it does continue with the code if not give an error prompt

my code for the parent is

```<code>...
state = {
    AuthResults: [
        {
            id: 1,
            username: "Andy",
            password: "Andy"
        },
        {
            id: 2,
            username: "Dan",
            password: "Dan"
        },
        {
            id: 3,
            username: "Naheem",
            password: "Naheem"
        }
    ],
}
...
<LoginBar AuthRes={this.state.AuthRes}/>
...
</code>```

My Code for the child is

```<code>CheckLoginAuth(){
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    Object.keys(this.state.AuthRes).map(function(key){
        console.log(AuthRes[key]);
    })

}
...
<TextField floatingLabelText="Username" name="Username" onChange={this.handleUsername} value={this.state.Username} type="text" />
<TextField floatingLabelText="Password" name="Password" onChange={this.handlePassword} value={this.state.Password} type="text" />
<RaisedButton label="Login" secondary={true} onClick={() => this.onRealLoginClick()} /><span> </span>
...
</code>```

it pulls the object in fine as it prints it but i cant seem to do the loop and auth.

EDIT: Right so i got no errors now by changing my CheckLoginAuth function to this

```<code>CheckLoginAuth(){
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    this.props.AuthRes.map(function(Res){
        console.log(Res.id);
        console.log(Res.username);
        console.log(Res.password);
    })
}
</code>```

how do i loop through the ids in Res and compare them to the user inputs

答:
I fixed this by doing

```<code>CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.map(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        self.LoginAuth(Res);
    });
}
</code>```

instead of what i wrote above

Body:
Right so I have passed an array down to the child from the parent and I will include all code below

so what I am trying to do is loop over my array and check that my user input matches one of the objects in the array if it does continue with the code if not give an error prompt

my code for the parent is

...
state = {
    AuthResults: [
        {
            id: 1,
            username: "Andy",
            password: "Andy"
        },
        {
            id: 2,
            username: "Dan",
            password: "Dan"
        },
        {
            id: 3,
            username: "Naheem",
            password: "Naheem"
        }
    ],
}
...
<LoginBar AuthRes={this.state.AuthRes}/>
...

My Code for the child is

CheckLoginAuth(){
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    Object.keys(this.state.AuthRes).map(function(key){
        console.log(AuthRes[key]);
    })

}
...
<TextField floatingLabelText="Username" name="Username" onChange={this.handleUsername} value={this.state.Username} type="text" />
<TextField floatingLabelText="Password" name="Password" onChange={this.handlePassword} value={this.state.Password} type="text" />
<RaisedButton label="Login" secondary={true} onClick={() => this.onRealLoginClick()} />
...

it pulls the object in fine as it prints it but i cant seem to do the loop and auth.

EDIT: Right so i got no errors now by changing my CheckLoginAuth function to this

CheckLoginAuth(){
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    this.props.AuthRes.map(function(Res){
        console.log(Res.id);
        console.log(Res.username);
        console.log(Res.password);
    })
}

how do i loop through the ids in Res and compare them to the user inputs

Body:
I fixed this by doing

CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.map(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        self.LoginAuth(Res);
    });
}

instead of what i wrote above


问:
When to use what type of padding for convolution layers?
I know when we are using convolution layers in a neural net we usually use padding and mainly constant padding(e.g. zero padding). And there are different kinds of padding(e.g. symmetric, reflective, constant). But I am not sure what are the advantages and disadvantages of using different padding methods and when to use which one.</p>

答:
it really depends on the situation for what the neural network is intended. I would not tell it pros and cons. This time the world cannot put into a binary scheme.

I will give you some interesting links:

https://adeshpande3.github.io/A-Beginner%27s-Guide-To-Understanding-Convolutional-Neural-Networks-Part-2/

http://web.stanford.edu/class/cs20si/lectures/

When you try to design a network, then start to think about what it should be designed for. Then, you try some things, it will be logical that , in case of convolutional networks, valid padding makes the image smaller and full padding makes the image bigger, but it uses, e.g zero padding, what adds 0 at the edges and could lead to veils... and so on... you must try a lot...

For pixelwise deep convolutional networks, people use valid, such as semantic segmentation. No/less "smear-effect".
For object detection, people use same, only a bounding box is needed for the detected object.

HTH


问:
function returning a string of zeros in c
i trying to create a function that return an array of zeros us a char array
and print this array in a file text but when i return a string an addition char was returned

this the text file string the program wrote

this my fuction :

```<code> char *zeros_maker (int kj,int kj1)
{
     char *zeros;
    zeros = (char *) malloc(sizeof(char)*(kj-kj1));
    int i;
    for(i =0;i<kj-kj1;i++)
        zeros[i]='0';
    printf("%s\n",zeros);
    return zeros;
}
</code>```

the instruction i used when i printed in the file

```<code>fprintf(pFile,"%c%s%c &",34,zeros_maker(added_zeros,0),34);
</code>```

Thanks in advance

答:
Instead of for loop, you may get hand of memset.

```<code>char* zeros_maker(int kj,int kj1)
{
    int len=kj-kj1;
    char *zeros=malloc(sizeof(char)*(len));
    memset(zeros,'0',len-1);
    zeros[len-1]=0;
    printf("%s\n",zeros);
    //fflush(stdout);
    return zeros;
}
</code>```

Or if you are not fan of C-style string, and it's going to be ASCII only, following could be used too. Just be careful what your are doing this way.

```<code>char* zeros_maker_pascal_form(int kj,int kj1)
{
    int len=kj-kj1;
    char *zeros=malloc(sizeof(char)*(len));
    memset(zeros,'0',len);
    for(int a=0;a<len;a++){
      printf("%c",zeros[a]);
    }
    printf("\n");
    //fflush(stdout);
    return zeros;
}
</code>```

Body:
i trying to create a function that return an array of zeros us a char array
and print this array in a file text but when i return a string an addition char was returned

this the text file string the program wrote

this my fuction :

 char *zeros_maker (int kj,int kj1)
{
     char *zeros;
    zeros = (char *) malloc(sizeof(char)*(kj-kj1));
    int i;
    for(i =0;i<kj-kj1;i++)
        zeros[i]='0';
    printf("%s\n",zeros);
    return zeros;
}

the instruction i used when i printed in the file

fprintf(pFile,"%c%s%c &",34,zeros_maker(added_zeros,0),34);

Thanks in advance

Body:
Instead of for loop, you may get hand of memset.

char* zeros_maker(int kj,int kj1)
{
    int len=kj-kj1;
    char *zeros=malloc(sizeof(char)*(len));
    memset(zeros,'0',len-1);
    zeros[len-1]=0;
    printf("%s\n",zeros);
    //fflush(stdout);
    return zeros;
}

Or if you are not fan of C-style string, and it's going to be ASCII only, following could be used too. Just be careful what your are doing this way.

char* zeros_maker_pascal_form(int kj,int kj1)
{
    int len=kj-kj1;
    char *zeros=malloc(sizeof(char)*(len));
    memset(zeros,'0',len);
    for(int a=0;a<len;a++){
      printf("%c",zeros[a]);
    }
    printf("\n");
    //fflush(stdout);
    return zeros;
}


问:
Response for preflight 403 forbidden
I've been trying to make a simple iron-ajax post to the server, but it keeps failing at the preflight call. For the life of me I can't figure out what's going on, all the CORS headers seem to be correct on the server.

Response headers

```<code>Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST, PUT, OPTIONS
Access-Control-Allow-Origin:*
cache-control:must-revalidate, private, no-cache, no-store, max-age=0
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:138
Content-Type:text/html
</code>```

Request headers

```<code>Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
</code>```

The request is indeed made from localhost, but I would have thought that the * should take care of that.

Errors that are showing up in the console are:
OPTIONS https://... 403 (Forbidden) and

```<code>XMLHttpRequest cannot load https://.... Response for preflight has invalid HTTP status code 403
</code>```

Any help/advice is appreciated.

答:
The 403 response status indicates a general problem with the server backend not being configured to handle OPTIONS requests, not just CORS preflight OPTIONS requests.

The server must respond to OPTIONS requests with a 2xx success status—typically 200 or 204.

If the server doesn’t do that, it makes no difference what Access-Control-* headers you have it configured to send. And the answer to configuring it to handle OPTIONS requests in the right way — to send a 200 or 204 success message — depends on what server software it’s running.

Title: Response for preflight 403 forbidden

Body:
I've been trying to make a simple iron-ajax post to the server, but it keeps failing at the preflight call. For the life of me I can't figure out what's going on, all the CORS headers seem to be correct on the server.

Response headers

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST, PUT, OPTIONS
Access-Control-Allow-Origin:*
cache-control:must-revalidate, private, no-cache, no-store, max-age=0
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:138
Content-Type:text/html

Request headers

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive

The request is indeed made from localhost, but I would have thought that the * should take care of that.

Errors that are showing up in the console are:
OPTIONS https://... 403 (Forbidden) and

XMLHttpRequest cannot load https://.... Response for preflight has invalid HTTP status code 403

Any help/advice is appreciated.


问:
find dead JavaScript code?
We are refactoring a legacy web app and as a result are "killing" quite a lot of JavaScript code but we're afraid of deleting what we think is dead code due to not being sure.  Is there any tool / technique for positively identifying dead code in JavaScript?</p>

答:
Chrome has come up with new feature which lets developer see the code coverage, ie., which lines of codes were executed.

This certainly is not a one stop solution, but can extend a helping hand to developers to get code insights.

Check this link for details

Rolled as apart of Chrome 59 release

Title: find dead JavaScript code?


问:
Why does spark-shell fail with "'""C:\Program' is not recognized as an internal or external command" on Windows?
While running the following command prompt I am getting the error as in the screenshot.

Command:

```<code>c:\spark>spark-shell
</code>```

Error:

```<code>'""C:\Program' is not recognized as an internal or external command,
operable program or batch file.
</code>```

Why?

答:
I had the same problem.
It happens with version spark-2.1.1-bin-hadoop2.7 but not with the previous version spark-2.1.0-bin-hadoop2.7.

Edit line 54 of spark-2.1.1-bin-hadoop2.7/bin/spark-class2.cmd by removing the quotes as:

```<code>set RUNNER=%JAVA_HOME%\bin\java
</code>```

Then it should work.

Body:
While running the following command prompt I am getting the error as in the screenshot.

Command:

c:\spark>spark-shell

Error:

'""C:\Program' is not recognized as an internal or external command,
operable program or batch file.

Why?

Body:
I had the same problem.
It happens with version spark-2.1.1-bin-hadoop2.7 but not with the previous version spark-2.1.0-bin-hadoop2.7.

Edit line 54 of spark-2.1.1-bin-hadoop2.7/bin/spark-class2.cmd by removing the quotes as:

set RUNNER=%JAVA_HOME%\bin\java

Then it should work.


问:
Understanding Type keyword in haskell
From my understanding of type keyword, type keyword creates synonyms.

```<code>type String = [Char]
</code>```

But how can I interpret something like this :

```<code>type Newtype = Bool
      Int
      String
</code>```

答:
As one can read in the documentation:

2 Type and newtype

The other two ways one may introduce types to Haskell programs are via
  the type and newtype statements. type introduces a synonym
  for a type and uses the same data constructors. (..) When using a type
  declaration, the type synonym and its base type are interchangeble
  almost everywhere (There are some restrictions when dealing with
  instance declarations).

So type <name> = <type-expression> simply renames a (usually more complex) type expression. As a result the second code fragment is invalid.

It is however possible that there are higher order types in the <type-expression> like:

```<code>type Alias = Either Int String
</code>```

This is because the Either type is a higher order type: it has "meta-type" * -> * -> *. So here you thus "apply" Int and String to Either.

Note that an alias does not have any special semantics: for Haskell Alias is the same as Either Int String and vice versa: every method that is defined on Alias works with Either Int String as well.

If you however write type NewType = Bool Int String, then the type system will complain that:

```<code>• Expecting two fewer arguments to ‘Bool’
  Expected kind ‘* -> * -> k0’, but ‘Bool’ has kind ‘*’
• In the type ‘Bool Int String’
  In the type declaration for ‘NewType’
</code>```

So it complains that Bool is a type that does not accept any (two) type parameters. Therefore it cannot construct such a type.

Title: Understanding Type keyword in haskell

Body:
From my understanding of type keyword, type keyword creates synonyms.

type String = [Char]

But how can I interpret something like this :

type Newtype = Bool
      Int
      String

Body:
As one can read in the documentation:

2 Type and newtype

The other two ways one may introduce types to Haskell programs are via
  the type and newtype statements. type introduces a synonym
  for a type and uses the same data constructors. (..) When using a type
  declaration, the type synonym and its base type are interchangeble
  almost everywhere (There are some restrictions when dealing with
  instance declarations).

So type <name> = <type-expression> simply renames a (usually more complex) type expression. As a result the second code fragment is invalid.

It is however possible that there are higher order types in the <type-expression> like:

type Alias = Either Int String

This is because the Either type is a higher order type: it has "meta-type" * -> * -> *. So here you thus "apply" Int and String to Either.

Note that an alias does not have any special semantics: for Haskell Alias is the same as Either Int String and vice versa: every method that is defined on Alias works with Either Int String as well.

If you however write type NewType = Bool Int String, then the type system will complain that:

• Expecting two fewer arguments to ‘Bool’
  Expected kind ‘* -> * -> k0’, but ‘Bool’ has kind ‘*’
• In the type ‘Bool Int String’
  In the type declaration for ‘NewType’

So it complains that Bool is a type that does not accept any (two) type parameters. Therefore it cannot construct such a type.


问:
Multiple small inserts in clickhouse
I have an event table (MergeTree) in clickhouse and want to run a lot of small inserts at the same time. However the server becomes overloaded and unresponsive. Moreover, some of the inserts are lost. There are a lot of records in clickhouse error log:

```<code>01:43:01.668 [ 16 ] <Error> events (Merger): Part 201 61109_20161109_240760_266738_51 intersects previous part
</code>```

Is there a way to optimize such queries? I know I can use bulk insert for some types of events. Basically, running one insert with many records, which clickhouse handles pretty well. However, some of the events, such as clicks or opens could not be handled in this way.

The other question: why clickhouse decides that similar records exist, when they don't? There are similar records at the time of insert, which have the same fields as in index, but other fields are different.

From time to time I also receive the following error:

```<code>Caused by: ru.yandex.clickhouse.except.ClickHouseUnknownException: ClickHouse exception, message: Connect to localhost:8123 [ip6-localhost/0:0:0:0:0:0:0:1] timed out, host: localhost, port: 8123; Connect to ip6-localhost:8123 [ip6-localhost/0:0:0:0:0:0:0:1] timed out
    ... 36 more
</code>```

Mostly during project build when test against clickhouse database are run.

答: I've had a similar problem, although not as bad - making ~20 inserts per second caused the server to reach a high loadavg, memory consumption and CPU use. I created a Buffer table which buffers the inserts in memory, and then they are flushed periodically to the "real" on-disk table. And just like magic, everything went quite: loadavg, memory and CPU usage came down to normal levels. The nice thing is that you can run queries against the buffer table, and get back matching rows from both memory and disk - so clients are unaffected by the buffering. See https://clickhouse.tech/docs/en/engines/table-engines/special/buffer/</p>

Title: Multiple small inserts in clickhouse

Body:
I have an event table (MergeTree) in clickhouse and want to run a lot of small inserts at the same time. However the server becomes overloaded and unresponsive. Moreover, some of the inserts are lost. There are a lot of records in clickhouse error log:

01:43:01.668 [ 16 ] <Error> events (Merger): Part 201 61109_20161109_240760_266738_51 intersects previous part

Is there a way to optimize such queries? I know I can use bulk insert for some types of events. Basically, running one insert with many records, which clickhouse handles pretty well. However, some of the events, such as clicks or opens could not be handled in this way.

The other question: why clickhouse decides that similar records exist, when they don't? There are similar records at the time of insert, which have the same fields as in index, but other fields are different.

From time to time I also receive the following error:

Caused by: ru.yandex.clickhouse.except.ClickHouseUnknownException: ClickHouse exception, message: Connect to localhost:8123 [ip6-localhost/0:0:0:0:0:0:0:1] timed out, host: localhost, port: 8123; Connect to ip6-localhost:8123 [ip6-localhost/0:0:0:0:0:0:0:1] timed out
    ... 36 more

Mostly during project build when test against clickhouse database are run.


问:
Regarding understanding Android resource folder
I make a research, and I delve deep into Android resources files. According to this link, it says that Android externalize and separate users' resources from the code to allow using
these resources by Ids that will be generated in R.class, here is the text:</p>

```<code>Once you externalize your application resources, you can access them using resource IDs that are generated in your project's R class.
</code>```

<p>(1): Does being the 'res' folder exists means generating the R.java class? In other words, is R.java a representation to "ids" assigned to any values inside 'res' folder? </p>

<p>(2): Is it possible to place my 'layout' or 'string' files in any other folders aside from 'res'? </p>

答:
Is R.java a representation to "ids" assigned to any values inside
  'res' folder?

It is most likely the idea of R.java.

Is it possible to place my 'layout' or 'string' files in any other
  folders aside from 'res'?

Yes you can do that but before you start make sure you checked the project structure view and not the other options like android structure view.

In your build.gradle

```<code>android {
   ....

   sourceSets {
        main {
            res.srcDirs = [
                    "src/main/module-res/compose"
            ];
        }
    }

}
</code>```

Then create the desired directory similar to what you have declared.
Here is an example image showing that it will work.

What's good about it is that you can make more res folder (just add it in the array and separate it with comma). Take note that each res folder must have its own drawable, layout etc. folder.

Example:

```<code>res.srcDirs = [
               "src/main/module-res/compose",
               "src/main/module-res/design",
               "src/main/module-res/extra"
              ];
</code>```

Body:
I make a research, and I delve deep into Android resources files. According to this link, it says that Android externalize and separate users' resources from the code to allow using
these resources by Ids that will be generated in R.class, here is the text:

Once you externalize your application resources, you can access them using resource IDs that are generated in your project's R class.

(1): Does being the 'res' folder exists means generating the R.java class? In other words, is R.java a representation to "ids" assigned to any values inside 'res' folder?

(2): Is it possible to place my 'layout' or 'string' files in any other folders aside from 'res'?

Body:
Is R.java a representation to "ids" assigned to any values inside
  'res' folder?

It is most likely the idea of R.java.

Is it possible to place my 'layout' or 'string' files in any other
  folders aside from 'res'?

Yes you can do that but before you start make sure you checked the project structure view and not the other options like android structure view.

In your build.gradle

android {
   ....

   sourceSets {
        main {
            res.srcDirs = [
                    "src/main/module-res/compose"
            ];
        }
    }

}

Then create the desired directory similar to what you have declared.
Here is an example image showing that it will work.

What's good about it is that you can make more res folder (just add it in the array and separate it with comma). Take note that each res folder must have its own drawable, layout etc. folder.

Example:

res.srcDirs = [
               "src/main/module-res/compose",
               "src/main/module-res/design",
               "src/main/module-res/extra"
              ];


问:
Adding non-string fields with SolrJ
I have a class called Dataset that has an Organization field. I want to add this to the solr index. I gave to Organization's fields proper annotation as well.

```<code>public class Dataset {

    @Field("publisher")
    @rdf("http://www.w3.org/ns/foaf#publisher")
    private Organization publisher;
</code>```

```<code>public class Organization  {

    @Field("OrganizationName")
    @rdf("http://www.w3.org/ns/foaf#name")
    private String name;
</code>```

But when I add the bean to solr what I get is something like this:

```<code><doc>
<arr name="keyword">
<str>public</str>
</arr>
...
<date name="modified">1995-12-31T23:59:59Z</date>
<str name="publisher">Organization [name=MECON]</str>
...
<str name="type">dataset</str>
</doc>
</code>```

I don't really like how it looks and is ugly to get facets from that. I would like to get something like an individual field called publisherName or something like that (one string for each field in Organization class).
Do i need to define a fieldType to the publisher field? How can resolve this issue? Is there any example?

答: The issue is fixed now, how ever it's difficult to figure out how to use document object binding in general, so I requested an update of the solj tutorial at https://issues.apache.org/jira/browse/SOLR-11032 and will update this answer as soon as it's fixed.</p>

Title: Adding non-string fields with SolrJ

Body:
I have a class called Dataset that has an Organization field. I want to add this to the solr index. I gave to Organization's fields proper annotation as well.

public class Dataset {

    @Field("publisher")
    @rdf("http://www.w3.org/ns/foaf#publisher")
    private Organization publisher;

public class Organization  {

    @Field("OrganizationName")
    @rdf("http://www.w3.org/ns/foaf#name")
    private String name;

But when I add the bean to solr what I get is something like this:

<doc>
<arr name="keyword">
<str>public</str>
</arr>
...
<date name="modified">1995-12-31T23:59:59Z</date>
<str name="publisher">Organization [name=MECON]</str>
...
<str name="type">dataset</str>
</doc>

I don't really like how it looks and is ugly to get facets from that. I would like to get something like an individual field called publisherName or something like that (one string for each field in Organization class).
Do i need to define a fieldType to the publisher field? How can resolve this issue? Is there any example?


问:
BDD - Test pass on chrome but not on Phantomjs
I have a web app built by Django, front-end is built by React. I tried to test bdd with behave and selenium. I run a test with Chrome web driver and phantomjs one but the tests only passed using chrome. I captured a screenshot when it runs on phantom and saw that the page is not fully rendered. Please give some suggestions about this issue. Do I need do further configuration to test with phantomjs. Thank you. </p>

答: Try adding an explicit wait on a locator (waitForElementToBePresent) that exists on the part of page that is not rendered on Phantomjs.</p>