问:
R Loop code over several lists of dataframes
I have several lists of dataframes and I want to format the date in each single dataframe within all lists of dataframes. Here is an example code:

```<code>v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(2,20, length = 5)
v3 = seq(-2,7, length = 5)
v4 = seq(-6,3, length = 5)

df1 = data.frame(Date = v1, df1_Tmax = v2, df1_Tmean = v3, df1_Tmin = v4)
dfl1 <- list(df1, df1, df1, df1)
names(dfl1) = c("ABC_1", "DEF_1", "GHI_1", "JKL_1")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(3,21, length = 5)
v3 = seq(-3,8, length = 5)
v4 = seq(-7,4, length = 5)

df2 = data.frame(Date = v1, df2_Tmax = v2, df2_Tmean = v3, df2_Tmin = v4)
dfl2 <- list(df2, df2, df2, df2)
names(dfl2) = c("ABC_2", "DEF_2", "GHI_2", "JKL_2")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(4,22, length = 5)
v3 = seq(-4,9, length = 5)
v4 = seq(-8,5, length = 5)

df3 = data.frame(Date = v1, df3_Tmax = v2, df3_Tmean = v3, df3_Tmin = v4)
dfl3 <- list(df3, df3, df3, df3)
names(dfl3) = c("ABC_3", "DEF_3", "GHI_3", "JKL_3")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(2,20, length = 5)
v3 = seq(-2,8, length = 5)
v4 = seq(-6,3, length = 5)

abc = data.frame(Date = v1, ABC_Tmax = v2, ABC_Tmean = v3, ABC_Tmin = v4)

abclist <-list(abc, abc, abc, abc)

names(abclist) = c("ABC_abc", "DEF_abc", "GHI_abc", "JKL_abc")
</code>```

I know how to change the date-column manually:

```<code>dfl1$ABC_1$Date = as.Date(dfl1$ABC_1$Date,format="%Y-%m-%d")
class(dfl1$ABC_1$Date)
</code>```

But how can I do that for each single Date-Column in all of my lists of dataframes?

答:
This can be done with lapply:

```<code>lapply(dfl1, function(x) {
  x$Date <- as.Date(x$Date, format="%Y-%m-%d")
  return(x)})
</code>```

If you want to do this for all of you df-lists you need to store them in a list and then you can use a slightly modified version of the above call:

```<code>df_list <- list(dfl1, dfl2, dfl3, abclist)

lapply(df_list, function(x) {
  x[[1]]$Date <- as.Date(x[[1]]$Date, format="%Y-%m-%d")
  return(x)})
</code>```

This assumes that the Date-column has always the same name "Date".

Body:
I have several lists of dataframes and I want to format the date in each single dataframe within all lists of dataframes. Here is an example code:

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(2,20, length = 5)
v3 = seq(-2,7, length = 5)
v4 = seq(-6,3, length = 5)

df1 = data.frame(Date = v1, df1_Tmax = v2, df1_Tmean = v3, df1_Tmin = v4)
dfl1 <- list(df1, df1, df1, df1)
names(dfl1) = c("ABC_1", "DEF_1", "GHI_1", "JKL_1")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(3,21, length = 5)
v3 = seq(-3,8, length = 5)
v4 = seq(-7,4, length = 5)

df2 = data.frame(Date = v1, df2_Tmax = v2, df2_Tmean = v3, df2_Tmin = v4)
dfl2 <- list(df2, df2, df2, df2)
names(dfl2) = c("ABC_2", "DEF_2", "GHI_2", "JKL_2")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(4,22, length = 5)
v3 = seq(-4,9, length = 5)
v4 = seq(-8,5, length = 5)

df3 = data.frame(Date = v1, df3_Tmax = v2, df3_Tmean = v3, df3_Tmin = v4)
dfl3 <- list(df3, df3, df3, df3)
names(dfl3) = c("ABC_3", "DEF_3", "GHI_3", "JKL_3")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(2,20, length = 5)
v3 = seq(-2,8, length = 5)
v4 = seq(-6,3, length = 5)

abc = data.frame(Date = v1, ABC_Tmax = v2, ABC_Tmean = v3, ABC_Tmin = v4)

abclist <-list(abc, abc, abc, abc)

names(abclist) = c("ABC_abc", "DEF_abc", "GHI_abc", "JKL_abc")

I know how to change the date-column manually:

dfl1$ABC_1$Date = as.Date(dfl1$ABC_1$Date,format="%Y-%m-%d")
class(dfl1$ABC_1$Date)

But how can I do that for each single Date-Column in all of my lists of dataframes?

Body:
This can be done with lapply:

lapply(dfl1, function(x) {
  x$Date <- as.Date(x$Date, format="%Y-%m-%d")
  return(x)})

If you want to do this for all of you df-lists you need to store them in a list and then you can use a slightly modified version of the above call:

df_list <- list(dfl1, dfl2, dfl3, abclist)

lapply(df_list, function(x) {
  x[[1]]$Date <- as.Date(x[[1]]$Date, format="%Y-%m-%d")
  return(x)})

This assumes that the Date-column has always the same name "Date".


来源: stackexchange

问:
How to get data from URI in js in a synchronous way
I'm trying to get data from a uri. I use the exemple at :

https://jsonplaceholder.typicode.com/users/1

and try to display the id ("id" : "1").

I have to get this value into a variable because I'm also using vuejs template.

Is there a simple way to get a cute little data ?

I tried Promises, and XMLHttpRequest, but send() throws error "fs.writeFileSync is not a function", and I failed to synchronise Promises...

There is my code before the export for vuejs template :

```<code>var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var fs = require('browserify-fs');
var xhr = new XMLHttpRequest();

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

/*function succes(msg){
  console.log('ok : '+msg);
  changeAffichage(msg);
}
function echec(msg){console.log('ko : '+msg); changeAffichage("error");}
function uri(){
  return fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(function(response){
      return response.json()
      .then(function(value) {
        console.log('value : ');
        console.log(value);
        console.log('id = '+value.id);
        return value.id;
      }).catch(function(error) {
  console.log('Il y a eu un problème avec l\'opération fetch: ' + error.message);
});
    }).catch(function(error) {
  console.log('Il y a eu un problème avec l\'opération fetch: ' + error.message);
});
}*/
function changeAffichage(msg){
  window.affichage=msg;
  console.log("new affichage : "+window.affichage);
}
window.affichage="Meow";
//Promise.all([uri()]).then(succes, echec);

sleep(200);

xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users/1', false);
xhr.send(null);
if (xhr.status === 200) {
    console.log("Réponse reçue: %s", xhr.responseText);
} else {
    console.log("Status de la réponse: %d (%s)", xhr.status, xhr.statusText);
}
changeAffichage(xhr.responseText);

console.log('affichage final = ' + window.affichage);
</code>```

I want to get the value of id into window.affichage, please :(

答:
So, I found how to do :</p>

```<code>var request = require('sync-request');
var res = request('POST', 'http://MyAPIIP/connect?mail='+this.model.email+'&pass='+this.model.password);
reponse = String(JSON.parse(res.body)[0]['rep']);
console.log(reponse);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get data from a uri. I use the exemple at :

https://jsonplaceholder.typicode.com/users/1

and try to display the id ("id" : "1").

I have to get this value into a variable because I'm also using vuejs template.

Is there a simple way to get a cute little data ?

I tried Promises, and XMLHttpRequest, but send() throws error "fs.writeFileSync is not a function", and I failed to synchronise Promises...

There is my code before the export for vuejs template :

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var fs = require('browserify-fs');
var xhr = new XMLHttpRequest();

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

/*function succes(msg){
  console.log('ok : '+msg);
  changeAffichage(msg);
}
function echec(msg){console.log('ko : '+msg); changeAffichage("error");}
function uri(){
  return fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(function(response){
      return response.json()
      .then(function(value) {
        console.log('value : ');
        console.log(value);
        console.log('id = '+value.id);
        return value.id;
      }).catch(function(error) {
  console.log('Il y a eu un problème avec l\'opération fetch: ' + error.message);
});
    }).catch(function(error) {
  console.log('Il y a eu un problème avec l\'opération fetch: ' + error.message);
});
}*/
function changeAffichage(msg){
  window.affichage=msg;
  console.log("new affichage : "+window.affichage);
}
window.affichage="Meow";
//Promise.all([uri()]).then(succes, echec);

sleep(200);

xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users/1', false);
xhr.send(null);
if (xhr.status === 200) {
    console.log("Réponse reçue: %s", xhr.responseText);
} else {
    console.log("Status de la réponse: %d (%s)", xhr.status, xhr.statusText);
}
changeAffichage(xhr.responseText);

console.log('affichage final = ' + window.affichage);

I want to get the value of id into window.affichage, please :(

Body:
So, I found how to do :

var request = require('sync-request');
var res = request('POST', 'http://MyAPIIP/connect?mail='+this.model.email+'&pass='+this.model.password);
reponse = String(JSON.parse(res.body)[0]['rep']);
console.log(reponse);


问:
Find out mouse button state via Xlib in Python
I can determine the current mouse pointer position with:

```<code>from Xlib.display import Display
display = Display()
qp = display.screen().root.query_pointer()
print(qp.root_x, qp.root_y)
</code>```

How do I get the current mouse button states like left/right button pressed/released via Xlib, too? (Or if this is not possible - why not?)

答:
If the X server has the RECORD extension enabled, it can be used to find out the current mouse button state. However, it won't provide the information directly: The individual button up and down events have to be tracked.

This also means that the current state will only be known, once the program has received at least one first event on mouse button up or down.

python-xlib provides the following example script at https://github.com/python-xlib/python-xlib/blob/master/examples/record_demo.py

```<code>from __future__ import print_function

import sys
import os

# Change path so we find Xlib
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from Xlib import X, XK, display
from Xlib.ext import record
from Xlib.protocol import rq

local_dpy = display.Display()
record_dpy = display.Display()

def lookup_keysym(keysym):
    for name in dir(XK):
        if name[:3] == "XK_" and getattr(XK, name) == keysym:
            return name[3:]
    return "[%d]" % keysym

def record_callback(reply):
    if reply.category != record.FromServer:
        return
    if reply.client_swapped:
        print("* received swapped protocol data, cowardly ignored")
        return
    if not len(reply.data) or reply.data[0] < 2:
        # not an event
        return

    data = reply.data
    while len(data):
        event, data = rq.EventField(None).parse_binary_value(
            data, record_dpy.display, None, None)

        if event.type in [X.KeyPress, X.KeyRelease]:
            pr = event.type == X.KeyPress and "Press" or "Release"

            keysym = local_dpy.keycode_to_keysym(event.detail, 0)
            if not keysym:
                print("KeyCode%s" % pr, event.detail)
            else:
                print("KeyStr%s" % pr, lookup_keysym(keysym))

            if event.type == X.KeyPress and keysym == XK.XK_Escape:
                local_dpy.record_disable_context(ctx)
                local_dpy.flush()
                return
        elif event.type == X.ButtonPress:
            print("ButtonPress", event.detail)
        elif event.type == X.ButtonRelease:
            print("ButtonRelease", event.detail)
        elif event.type == X.MotionNotify:
            print("MotionNotify", event.root_x, event.root_y)

# Check if the extension is present
if not record_dpy.has_extension("RECORD"):
    print("RECORD extension not found")
    sys.exit(1)
r = record_dpy.record_get_version(0, 0)
print("RECORD extension version %d.%d" % (r.major_version, r.minor_version))

# Create a recording context; we only want key and mouse events
ctx = record_dpy.record_create_context(
    0,
    [record.AllClients],
    [{
        'core_requests': (0, 0),
        'core_replies': (0, 0),
        'ext_requests': (0, 0, 0, 0),
        'ext_replies': (0, 0, 0, 0),
        'delivered_events': (0, 0),
        'device_events': (X.KeyPress, X.MotionNotify),
        'errors': (0, 0),
        'client_started': False,
        'client_died': False,
    }])

# Enable the context; this only returns after a call to record_disable_context,
# while calling the callback function in the meantime
record_dpy.record_enable_context(ctx, record_callback)

# Finally free the context
record_dpy.record_free_context(ctx)
</code>```

Body:
I can determine the current mouse pointer position with:

from Xlib.display import Display
display = Display()
qp = display.screen().root.query_pointer()
print(qp.root_x, qp.root_y)

How do I get the current mouse button states like left/right button pressed/released via Xlib, too? (Or if this is not possible - why not?)

Body:
If the X server has the RECORD extension enabled, it can be used to find out the current mouse button state. However, it won't provide the information directly: The individual button up and down events have to be tracked.

This also means that the current state will only be known, once the program has received at least one first event on mouse button up or down.

python-xlib provides the following example script at https://github.com/python-xlib/python-xlib/blob/master/examples/record_demo.py

from __future__ import print_function

import sys
import os

# Change path so we find Xlib
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from Xlib import X, XK, display
from Xlib.ext import record
from Xlib.protocol import rq

local_dpy = display.Display()
record_dpy = display.Display()

def lookup_keysym(keysym):
    for name in dir(XK):
        if name[:3] == "XK_" and getattr(XK, name) == keysym:
            return name[3:]
    return "[%d]" % keysym

def record_callback(reply):
    if reply.category != record.FromServer:
        return
    if reply.client_swapped:
        print("* received swapped protocol data, cowardly ignored")
        return
    if not len(reply.data) or reply.data[0] < 2:
        # not an event
        return

    data = reply.data
    while len(data):
        event, data = rq.EventField(None).parse_binary_value(
            data, record_dpy.display, None, None)

        if event.type in [X.KeyPress, X.KeyRelease]:
            pr = event.type == X.KeyPress and "Press" or "Release"

            keysym = local_dpy.keycode_to_keysym(event.detail, 0)
            if not keysym:
                print("KeyCode%s" % pr, event.detail)
            else:
                print("KeyStr%s" % pr, lookup_keysym(keysym))

            if event.type == X.KeyPress and keysym == XK.XK_Escape:
                local_dpy.record_disable_context(ctx)
                local_dpy.flush()
                return
        elif event.type == X.ButtonPress:
            print("ButtonPress", event.detail)
        elif event.type == X.ButtonRelease:
            print("ButtonRelease", event.detail)
        elif event.type == X.MotionNotify:
            print("MotionNotify", event.root_x, event.root_y)

# Check if the extension is present
if not record_dpy.has_extension("RECORD"):
    print("RECORD extension not found")
    sys.exit(1)
r = record_dpy.record_get_version(0, 0)
print("RECORD extension version %d.%d" % (r.major_version, r.minor_version))

# Create a recording context; we only want key and mouse events
ctx = record_dpy.record_create_context(
    0,
    [record.AllClients],
    [{
        'core_requests': (0, 0),
        'core_replies': (0, 0),
        'ext_requests': (0, 0, 0, 0),
        'ext_replies': (0, 0, 0, 0),
        'delivered_events': (0, 0),
        'device_events': (X.KeyPress, X.MotionNotify),
        'errors': (0, 0),
        'client_started': False,
        'client_died': False,
    }])

# Enable the context; this only returns after a call to record_disable_context,
# while calling the callback function in the meantime
record_dpy.record_enable_context(ctx, record_callback)

# Finally free the context
record_dpy.record_free_context(ctx)


问:
Does Swagger (Asp.Net Core) have a controller description?
I'm building a REST service that will host multiple controllers (microservices). As a whole, lets call the service "Bob". So swagger displays "Bob" / "A collection of Bob Microservices". Then the controller names are listed. Right now, it just shows XYZ, ABC, etc. Is there a way to maybe have swagger show "XYZ - A collection of XYZ APIs" or something of that sort?

Seems like swagger shows the ///Summary on the methods, but not on the controllers.

答:
If you are using Swashbuckle 4.0.x and ASP.NET Core 2.x, you may have something like this which also works by including the NuGet package for Swashbuckle.AspNetCore.Annotations.

```<code>using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Annotations;

namespace MyExample.Controllers
{
/// <summary>
/// Example of a .NET Core controller based on the controller name
/// api/[controller] on ValuesController becomes api/values
/// endpoint: "/Values" from [controller] and name of controller , which is "ValuesController"
/// </summary>
[Route("[controller]")]
[ApiController]
[SwaggerTag("This is an example controller generated by ASP.NET Core 2.x")]
public class ValuesController : ControllerBase
{
...
}
</code>```

Then my Startup.cs swagger code in the ConfigureServices Method looks like this, (edited to include contribution from Iain Carlin to include controller header comments) :

```<code>services.AddSwaggerGen(c =>
{
    // Set Title and version
    c.SwaggerDoc("v1", new Info { Title = "My Example API", Version = "v1", Description = "The API for my application" });
    // Set the comments path for the Swagger JSON and UI.
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    // pick comments from classes, including controller summary comments
    c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
    // _OR_ enable the annotations on Controller classes [SwaggerTag], if no class comments present
    c.EnableAnnotations();
});
</code>```

Then my Controller will get decorated

ContentLicense: CC BY-SA 3.0

Body:
If you are using Swashbuckle 4.0.x and ASP.NET Core 2.x, you may have something like this which also works by including the NuGet package for Swashbuckle.AspNetCore.Annotations.

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Annotations;

namespace MyExample.Controllers
{
/// <summary>
/// Example of a .NET Core controller based on the controller name
/// api/[controller] on ValuesController becomes api/values
/// endpoint: "/Values" from [controller] and name of controller , which is "ValuesController"
/// </summary>
[Route("[controller]")]
[ApiController]
[SwaggerTag("This is an example controller generated by ASP.NET Core 2.x")]
public class ValuesController : ControllerBase
{
...
}

Then my Startup.cs swagger code in the ConfigureServices Method looks like this, (edited to include contribution from Iain Carlin to include controller header comments) :

services.AddSwaggerGen(c =>
{
    // Set Title and version
    c.SwaggerDoc("v1", new Info { Title = "My Example API", Version = "v1", Description = "The API for my application" });
    // Set the comments path for the Swagger JSON and UI.
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    // pick comments from classes, including controller summary comments
    c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
    // _OR_ enable the annotations on Controller classes [SwaggerTag], if no class comments present
    c.EnableAnnotations();
});

Then my Controller will get decorated


问:
Svn Synchronize in Android Studio
Am just move to Android Studio (I/O Preview) 0.2.0 from Eclipse. But the SVN plugin in Android Studio is quite hard to understand for me, I was trying to synchronize from repository to see the changes made by other developers like we doing in Eclipse but unfortunately I am struck to find such things in Android studio. Plz help  </p>

答: Right click on your project app folder and click subversion > commit Directory  and you will get the commit changes window where in you can see all the files which are changed which is equivalent to svn synchronize in eclipse. </p>

Title: Svn Synchronize in Android Studio


问:
Gradle: Could not determine java version from '11.0.2'
I ran the following comment:

```<code>./gradlew app:installDebug
</code>```

only to be met with the log:

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Could not determine java version from '11.0.2'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org
</code>```

My version of gradle is 5.1.1:

```<code>------------------------------------------------------------
Gradle 5.1.1
------------------------------------------------------------

Build time:   2019-01-10 23:05:02 UTC
Revision:     3c9abb645fb83932c44e8610642393ad62116807

Kotlin DSL:   1.1.1
Kotlin:       1.3.11
Groovy:       2.5.4
Ant:          Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM:          11.0.2 (Oracle Corporation 11.0.2+9-LTS)
OS:           Mac OS X 10.13.6 x86_64
</code>```

I'm not sure how to proceed (I tried upgrading/downgrading, but nothing has worked so far).

UPDATE: When I ran ./gradlew --version, I got the following:

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Could not determine java version from '11.0.2'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org
</code>```

My .../gradle/wrapper/gradle-wrapper.properties contains the following including distributionUrl=.../gradle-4.1-rc-1-all.zip:

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-rc-1-all.zip
</code>```

答:
I ran into a similar issue. I deleted these:

libraries and caches from the .idea folder ( YourApp > .idea > .. ) AND

contents of the build folder.

then rebuild.

* DON'T FORGET TO BACKUP YOUR PROJECT FIRST *

Body:
I ran the following comment:

./gradlew app:installDebug

only to be met with the log:

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine java version from '11.0.2'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

My version of gradle is 5.1.1:

------------------------------------------------------------
Gradle 5.1.1
------------------------------------------------------------

Build time:   2019-01-10 23:05:02 UTC
Revision:     3c9abb645fb83932c44e8610642393ad62116807

Kotlin DSL:   1.1.1
Kotlin:       1.3.11
Groovy:       2.5.4
Ant:          Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM:          11.0.2 (Oracle Corporation 11.0.2+9-LTS)
OS:           Mac OS X 10.13.6 x86_64

I'm not sure how to proceed (I tried upgrading/downgrading, but nothing has worked so far).

UPDATE: When I ran ./gradlew --version, I got the following:

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine java version from '11.0.2'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

My .../gradle/wrapper/gradle-wrapper.properties contains the following including distributionUrl=.../gradle-4.1-rc-1-all.zip:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-rc-1-all.zip


问:
how to display all product category images
i am having problem of getting images of all product category in wordpress. please help me to solve this error.

here is my code-

```<code>          <div class="row">
          <?php $sub_count=1; foreach ($product_categories as $key => $category_) {
         $cat_thumb_id = get_woocommerce_term_meta( $category_->term_id, 'thumbnail_id', true );
        $shop_catalog_img = wp_get_attachment_image_src( $cat_thumb_id, 'shop_catalog' );
            if($sub_count<5){ ?>
           <div class="col-md-6 col-sm-6 col-xs-12 nogap">
            <div class="bannerbox2img">
           <a href="<?php echo get_term_link($category_); ?>"><img src="<?php echo $shop_catalog_img; ?>" alt="<?php echo $category_->name; ?>" /></a>
          <?php echo '<a href="'.get_term_link($category_).'" >';
                echo $category_->name;
                echo '</a>'; ?>
          </div>
           </div>
          <?php } $sub_count++; } wp_reset_query(); ?>
          </div>
</code>```

thanks in advance

答:
```<code>    Please try this code

    <div class="row">
<?php
// Get all product categories
$product_category_terms = get_terms( array(
    'taxonomy'   => "product_cat",
    'hide_empty' => 1,
));

$sub_count=1;
foreach($product_category_terms as $term){
    // Get the term link (if needed)
    $term_link = get_term_link( $term, 'product_cat' );

    ## -- Output Example -- ##

    if($sub_count<5){
        echo '<div class="col-md-6 col-sm-6 col-xs-12 nogap">';
            echo '<div class="bannerbox2img">';

            // The link (start)
            echo '<a href="' . $term_link . '" style="display:inline-block; text-align:center; margin-bottom: 14px;">';

            // Display the product category thumbnail
            woocommerce_subcategory_thumbnail( $term );

            // Display the term name
            echo '<a href="' . $term_link . '" >';
                echo $term->name;
            echo '</a>';

            // Link close
            echo '</a>';

            echo '</div>';
        echo '</div>';
    }
     $sub_count++;
} wp_reset_query(); ?>
</div>
</code>```

Body:
i am having problem of getting images of all product category in wordpress. please help me to solve this error.

here is my code-

          <?php $sub_count=1; foreach ($product_categories as $key => $category_) {
         $cat_thumb_id = get_woocommerce_term_meta( $category_->term_id, 'thumbnail_id', true );
        $shop_catalog_img = wp_get_attachment_image_src( $cat_thumb_id, 'shop_catalog' );
            if($sub_count<5){ ?>

           <a href="<?php echo get_term_link($category_); ?>"><img src="<?php echo $shop_catalog_img; ?>" alt="<?php echo $category_->name; ?>" />
          <?php echo '';
                echo $category_->name;
                echo ''; ?>

          <?php } $sub_count++; } wp_reset_query(); ?>

thanks in advance


问:
Cypress - Can't type in field
I have problem with typing in one of my fields in automated test.
I can't get this field but I don't know why.

This is my code:

cy.get('#reasonRecommendationByAgent')
  .type('Zdůvodnění doporučení zprostředkovatele', {force: true})
  .should('have.value', 'Zdůvodnění doporučení zprostředkovatele')
```

And this is the error message:

Is there anyone who has the same problem?

答:
According to the error message, it sounds like your code is removing/adding the #reasonRecommendationByAgent when it's typed into, which is causing Cypress to lose access to it.

Remove any code that might be causing this DOM element to change as it's being typed into and you shouldn't have a problem.

Title: Cypress - Can't type in field

Body:
I have problem with typing in one of my fields in automated test.
I can't get this field but I don't know why.

This is my code:

cy.get('#reasonRecommendationByAgent')
  .type('Zdůvodnění doporučení zprostředkovatele', {force: true})
  .should('have.value', 'Zdůvodnění doporučení zprostředkovatele')

And this is the error message:

Is there anyone who has the same problem?


问:
K6 Memory Consumption per VU
I have recently started to work with k6 and really liked the approach of writing tests. When I started my first serious test I found that the memory consumption per VU is pretty high even though my test was not huge. As I read here memory consumption should be around 1-2 MB per VU if the scripts are small. In my case the memory consumption is around 5 MB per VU.

To verify how much memory a very simple script needs I created a script that is doing nothing:

```<code>export default function() {

}
</code>```

When I run this script with 2000 users

docker run --rm -v /tmp:/tmp loadimpact/k6 run -u 2000 --paused --no-teardown --no-setup /tmp/MemTest.js

I end up with memory usage of 10 GB (about 5MB per VU)

So even if the JS is empty the memory usage is quite high. Is this expected?

答:
Unfortunately you are right, it seems like either the memory usage has grown, or our previous measurements were incorrect. A brief investigation revealed that the chief culprit of the current memory usage was our use of the core.js library. I've created a new github issue to further investigate how we can improve or ameliorate the situation: https://github.com/loadimpact/k6/issues/1036

@user1171006, try using the loadimpact/k6:master docker image, VU memory usage should have been almost halved after we merged https://github.com/loadimpact/k6/pull/1038. That 2000 VU test you tried is taking just under 5GB of RAM on my machine now.

Title: K6 Memory Consumption per VU

Body:
I have recently started to work with k6 and really liked the approach of writing tests. When I started my first serious test I found that the memory consumption per VU is pretty high even though my test was not huge. As I read here memory consumption should be around 1-2 MB per VU if the scripts are small. In my case the memory consumption is around 5 MB per VU.

To verify how much memory a very simple script needs I created a script that is doing nothing:

export default function() {

}

When I run this script with 2000 users

docker run --rm -v /tmp:/tmp loadimpact/k6 run -u 2000 --paused --no-teardown --no-setup /tmp/MemTest.js

I end up with memory usage of 10 GB (about 5MB per VU)

So even if the JS is empty the memory usage is quite high. Is this expected?


问:
SQL to count number for each value
I have a SQL query and I want to be able to count the total number of priorities which has values set to low, medium, high or unspecified.

Currently it counts to a maximum of 13 rows, i'd expect there to be multiple columns with counts such as... 2, 4, 0

Code:

```<code> SELECT c.Name, COUNT(*) as Count_By_Priority,
 CASE WHEN cb.Priority = 0 THEN "Unspecified" WHEN cb.Priority = 1 THEN "Low" WHEN cb.Priority = 2 THEN "Medium" WHEN cb.Priority = 3 THEN "High" END as PriorityNumber
 FROM TABLE 1 cb
 LEFT JOIN Co c ON c.Id = cb.Id
 WHERE c.Name LIKE %Name%"
 GROUP BY c.Id;
</code>```

It seems to print "Unspecified" for the priority keys when I would be expecting low or alternatives.

答:
If you want a count of each priority in a separate column use conditional aggregation.</p>

```<code>SELECT c.Name,
 sum(CASE WHEN cb.Priority = 0 THEN 1 else 0 end) as "Unspecified"
 sum(case WHEN cb.Priority = 1 THEN 1 else 0 end) as "Low"
 sum(case WHEN cb.Priority = 2 THEN 1 else 0 end) as "Medium"
 sum(case WHEN cb.Priority = 3 THEN 1 else 0 end) as "High"
 FROM TABLE 1 cb
 LEFT JOIN Co c ON c.Id = cb.Id
 WHERE c.Name LIKE %Name%"
 GROUP BY c.name;
</code>```

Title: SQL to count number for each value

Body:
I have a SQL query and I want to be able to count the total number of priorities which has values set to low, medium, high or unspecified.

Currently it counts to a maximum of 13 rows, i'd expect there to be multiple columns with counts such as... 2, 4, 0

Code:

 SELECT c.Name, COUNT(*) as Count_By_Priority,
 CASE WHEN cb.Priority = 0 THEN "Unspecified" WHEN cb.Priority = 1 THEN "Low" WHEN cb.Priority = 2 THEN "Medium" WHEN cb.Priority = 3 THEN "High" END as PriorityNumber
 FROM TABLE 1 cb
 LEFT JOIN Co c ON c.Id = cb.Id
 WHERE c.Name LIKE %Name%"
 GROUP BY c.Id;

It seems to print "Unspecified" for the priority keys when I would be expecting low or alternatives.

Body:
If you want a count of each priority in a separate column use conditional aggregation.

SELECT c.Name,
 sum(CASE WHEN cb.Priority = 0 THEN 1 else 0 end) as "Unspecified"
 sum(case WHEN cb.Priority = 1 THEN 1 else 0 end) as "Low"
 sum(case WHEN cb.Priority = 2 THEN 1 else 0 end) as "Medium"
 sum(case WHEN cb.Priority = 3 THEN 1 else 0 end) as "High"
 FROM TABLE 1 cb
 LEFT JOIN Co c ON c.Id = cb.Id
 WHERE c.Name LIKE %Name%"
 GROUP BY c.name;


问:
how to add custom field in customer registration page in shopify?
I have added a Custom field in the customer registration page.

Fieldname: Area.

I have tried to save them, all details are saved expect but the Area value not saved.

Can anyone help me to fix that issue?

      {% form 'create_customer' %}

```<code>    {{ form.errors | default_errors }}

    <label for="FirstName" class="hidden-label">{{ 'customer.register.first_name' | t }}</label>
    <input type="text" name="customer[first_name]" id="FirstName" class="input-full" placeholder="{{ 'customer.register.first_name' | t }}" {% if form.first_name %}value="{{ form.first_name }}"{% endif %} autocapitalize="words" autofocus required>

    <label for="LastName" class="hidden-label">{{ 'customer.register.last_name' | t }}</label>
    <input type="text" name="customer[last_name]" id="LastName" class="input-full" placeholder="{{ 'customer.register.last_name' | t }}" {% if form.last_name %}value="{{ form.last_name }}"{% endif %} autocapitalize="words" required>

    <label for="Email" class="hidden-label">{{ 'customer.register.email' | t }}</label>
    <input type="email" name="customer[email]" id="Email" class="input-full{% if form.errors contains 'email' %} error{% endif %}" placeholder="{{ 'customer.register.email' | t }}" {% if form.email %} value="{{ form.email }}"{% endif %} autocorrect="off" autocapitalize="off" required>

  <label for="Area" class="hidden-label">{{ 'customer.register.area' | t }}</label>

  <input type="text" id="Area" name="customer[note][area]" placeholder="Customer Area" class="input-full"  autocorrect="off" autocapitalize="off">

    <label for="CreatePassword" class="hidden-label">{{ 'customer.register.password' | t }}</label>
    <input type="password" name="customer[password]" id="CreatePassword" class="input-full{% if form.errors contains 'password' %} error{% endif %}" placeholder="{{ 'customer.register.password' | t }}" required>

    <p>
      <input type="submit" value="{{ 'customer.register.submit' | t }}" class="btn btn--full registerBtn" ng-click="myfunction();" id="create">
    </p>
    <a href="{{ shop.url }}">{{ 'customer.register.cancel' | t }}</a>

  {% endform %}
</div>
</code>```

答:
There is no way to show a note field in the front end but you should be able to store it the way you are saving it.

If you like to output something you will have to use a tag instead.

For example: <input type="text" class="field" name="customer[tags]" value="" >

And you will have access to the tags from customer.tags. That way you will be able to show the tag/field.

Body:
I have added a Custom field in the customer registration page.

Fieldname: Area.

I have tried to save them, all details are saved expect but the Area value not saved.

Can anyone help me to fix that issue?

      {% form 'create_customer' %}

    {{ form.errors | default_errors }}

    {{ 'customer.register.first_name' | t }}
    <input type="text" name="customer[first_name]" id="FirstName" class="input-full" placeholder="{{ 'customer.register.first_name' | t }}" {% if form.first_name %}value="{{ form.first_name }}"{% endif %} autocapitalize="words" autofocus required>

    {{ 'customer.register.last_name' | t }}
    <input type="text" name="customer[last_name]" id="LastName" class="input-full" placeholder="{{ 'customer.register.last_name' | t }}" {% if form.last_name %}value="{{ form.last_name }}"{% endif %} autocapitalize="words" required>

    {{ 'customer.register.email' | t }}
    <input type="email" name="customer[email]" id="Email" class="input-full{% if form.errors contains 'email' %} error{% endif %}" placeholder="{{ 'customer.register.email' | t }}" {% if form.email %} value="{{ form.email }}"{% endif %} autocorrect="off" autocapitalize="off" required>

  {{ 'customer.register.area' | t }}

  <input type="text" id="Area" name="customer[note][area]" placeholder="Customer Area" class="input-full"  autocorrect="off" autocapitalize="off">

    {{ 'customer.register.password' | t }}
    <input type="password" name="customer[password]" id="CreatePassword" class="input-full{% if form.errors contains 'password' %} error{% endif %}" placeholder="{{ 'customer.register.password' | t }}" required>

      <input type="submit" value="{{ 'customer.register.submit' | t }}" class="btn btn--full registerBtn" ng-click="myfunction();" id="create">

    {{ 'customer.register.cancel' | t }}

  {% endform %}


问:
Running Docker inside Docker container: Cannot connect to the Docker daemon
I created a Dockerfile to run Docker inside Docker:

```<code>FROM ubuntu:16.04
RUN apt-get update && \
    apt-get install -y \
    apt-transport-https \
    ca-certificates \
    curl \
    software-properties-common && \
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - &&\
    apt-key fingerprint 0EBFCD88

RUN add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" && \
   apt-get update && \
   apt-get install -y docker-ce && \
   systemctl enable docker
</code>```

After I launched my container and ran docker ps, I got:

```<code>Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?"
</code>```

I executed the command dockerd inside my container, here's the result:

```<code>Error starting daemon: Error initializing network controller: error obtaining controller instance:
failed to create NAT chain DOCKER: iptables failed: iptables -t nat -N DOCKER: iptables v1.6.0: can't initialize iptables table nat': Permission denied (you must be root)
Perhaps iptables or your kernel needs to be upgraded.
 (exit status 3)
</code>```

答:
The recommendation I received for this was to use the -v parameter in docker run to map the docker socket between containers like this:</p>

```<code>-v /var/run/docker.sock:/var/run/docker.sock
</code>```

Body:
I created a Dockerfile to run Docker inside Docker:

FROM ubuntu:16.04
RUN apt-get update && \
    apt-get install -y \
    apt-transport-https \
    ca-certificates \
    curl \
    software-properties-common && \
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - &&\
    apt-key fingerprint 0EBFCD88

RUN add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" && \
   apt-get update && \
   apt-get install -y docker-ce && \
   systemctl enable docker

After I launched my container and ran docker ps, I got:

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?"

I executed the command dockerd inside my container, here's the result:

Error starting daemon: Error initializing network controller: error obtaining controller instance:
failed to create NAT chain DOCKER: iptables failed: iptables -t nat -N DOCKER: iptables v1.6.0: can't initialize iptables table nat': Permission denied (you must be root)
Perhaps iptables or your kernel needs to be upgraded.
 (exit status 3)

Body:
The recommendation I received for this was to use the -v parameter in docker run to map the docker socket between containers like this:

-v /var/run/docker.sock:/var/run/docker.sock


问:
C#, calling an instance of a class from a string
I've been struggling for a while to find a way of calling an instance of a class from a user defined input.

Essentially I want to call an instance from my StandardVehicle class that has already been defined, however the problem is that the name of the instance that I'm calling is defined by a users selection on a combo box on a form.

This is how I assumed it would be formatted, however I get an error when I try calling the instance saying that I cannot complicitly convert from string to StandardVehicle.

```<code>        StandardVehicle VauxhallB = new StandardVehicle();
        VauxhallB.Model = "B";
        VauxhallB.Manufacturer = "Vauxhall";
        VauxhallB.Doors = 5;
        VauxhallB.HorsePower = 200;
        VauxhallB.Transmission = "Manual";
        VauxhallB.Year = 2009;
        VauxhallB.Cylinders = 6;
        VauxhallB.Seats = 7;
        VauxhallB.Price = 17000;
        VauxhallB.Registration = "abc1243";

        StandardVehicle objname = comboBox1.Text;
</code>```

I'm assuming it's just a case of formatting the string, but I've been searching for hours and can't figure out what format it needs to be in to define it as an instance.

Any help would be appreciated.

Regards,
S.

答:
VauxhallB is just a symbol to the computer. The user shouldn't reference your variable names -- although it is probably possible to do so via reflection, but that's a complicated aspect of programming.

A better way to do this would be to associate each instance with a string "name" in a Dictionary<string, StandardVehicle>, and look up with that. Something like:

```<code>Dictionary<string, StandardVehicle> nameMap = new Dictionary<string, StandardVehicle>();
nameMap["VauxhallB"] = VauxhallB;
StandardVehicle objname = nameMap[comboBox1.Text];
</code>```

Also, it's generally more readable if you only use lower case names for local variables, to better distinguish them from classes, public methods, and properties.

Body:
I've been struggling for a while to find a way of calling an instance of a class from a user defined input.

Essentially I want to call an instance from my StandardVehicle class that has already been defined, however the problem is that the name of the instance that I'm calling is defined by a users selection on a combo box on a form.

This is how I assumed it would be formatted, however I get an error when I try calling the instance saying that I cannot complicitly convert from string to StandardVehicle.

        StandardVehicle VauxhallB = new StandardVehicle();
        VauxhallB.Model = "B";
        VauxhallB.Manufacturer = "Vauxhall";
        VauxhallB.Doors = 5;
        VauxhallB.HorsePower = 200;
        VauxhallB.Transmission = "Manual";
        VauxhallB.Year = 2009;
        VauxhallB.Cylinders = 6;
        VauxhallB.Seats = 7;
        VauxhallB.Price = 17000;
        VauxhallB.Registration = "abc1243";

        StandardVehicle objname = comboBox1.Text;

I'm assuming it's just a case of formatting the string, but I've been searching for hours and can't figure out what format it needs to be in to define it as an instance.

Any help would be appreciated.

Regards,
S.

Body:
VauxhallB is just a symbol to the computer. The user shouldn't reference your variable names -- although it is probably possible to do so via reflection, but that's a complicated aspect of programming.

A better way to do this would be to associate each instance with a string "name" in a Dictionary<string, StandardVehicle>, and look up with that. Something like:

Dictionary<string, StandardVehicle> nameMap = new Dictionary<string, StandardVehicle>();
nameMap["VauxhallB"] = VauxhallB;
StandardVehicle objname = nameMap[comboBox1.Text];

Also, it's generally more readable if you only use lower case names for local variables, to better distinguish them from classes, public methods, and properties.


问:
Split text in cells and create additional rows for the tokens
Let's suppose that I have the following in a DataFrame in pandas:

```<code>id  text
1   I am the first document and I am very happy.
2   Here is the second document and it likes playing tennis.
3   This is the third document and it looks very good today.
</code>```

and I want to split the text of each id in tokens of 3 words so I finally want to have the following:

```<code>id  text
1   I am the
1   first document and
1   I am very
1   happy
2   Here is the
2   second document and
2   it likes playing
2   tennis
3   This is the
3   third document and
3   it looks very
3   good today
</code>```

Keep in mind that my dataframe may also have other columns except for these two which should be simply copied at the new dataframe in the same way as id above.

What is the most efficient way to do this?

I reckon that the solution to my question is quite close to the solution given here: Tokenise text and create more rows for each row in dataframe.

This may help too: Python: Split String every n word in smaller Strings.

答:
You can use something like:

```<code>def divide_chunks(l, n):
    # looping till length l
    for i in range(0, len(l), n):
        yield l[i:i + n]
</code>```

Then using unnesting:

```<code>df['text_new']=df.text.apply(lambda x: list(divide_chunks(x.split(),3)))
df_new=unnesting(df,['text_new']).drop('text',1)
df_new.text_new=df_new.text_new.apply(' '.join)
print(df_new)
</code>```

```<code>              text_new  id
0             I am the   1
0   first document and   1
0            I am very   1
0               happy.   1
1          Here is the   2
1  second document and   2
1     it likes playing   2
1              tennis.   2
2          This is the   3
2   third document and   3
2        it looks very   3
2          good today.   3
</code>```

EDIT:

```<code>m=(pd.DataFrame(df.text.apply(lambda x: list(divide_chunks(x.split(),3))).values.tolist())
.unstack().sort_index(level=1).apply(' '.join).reset_index(level=1))
m.columns=df.columns
print(m)
</code>```

```<code>   id                 text
0   0             I am the
1   0   first document and
2   0            I am very
3   0               happy.
0   1          Here is the
1   1  second document and
2   1     it likes playing
3   1              tennis.
0   2          This is the
1   2   third document and
2   2        it looks very
3   2          good today.
</code>```

Body:
Let's suppose that I have the following in a DataFrame in pandas:

id  text
1   I am the first document and I am very happy.
2   Here is the second document and it likes playing tennis.
3   This is the third document and it looks very good today.

and I want to split the text of each id in tokens of 3 words so I finally want to have the following:

id  text
1   I am the
1   first document and
1   I am very
1   happy
2   Here is the
2   second document and
2   it likes playing
2   tennis
3   This is the
3   third document and
3   it looks very
3   good today

Keep in mind that my dataframe may also have other columns except for these two which should be simply copied at the new dataframe in the same way as id above.

What is the most efficient way to do this?

I reckon that the solution to my question is quite close to the solution given here: Tokenise text and create more rows for each row in dataframe.

This may help too: Python: Split String every n word in smaller Strings.

Body:
You can use something like:

def divide_chunks(l, n):
    # looping till length l
    for i in range(0, len(l), n):
        yield l[i:i + n]

Then using unnesting:

df['text_new']=df.text.apply(lambda x: list(divide_chunks(x.split(),3)))
df_new=unnesting(df,['text_new']).drop('text',1)
df_new.text_new=df_new.text_new.apply(' '.join)
print(df_new)

              text_new  id
0             I am the   1
0   first document and   1
0            I am very   1
0               happy.   1
1          Here is the   2
1  second document and   2
1     it likes playing   2
1              tennis.   2
2          This is the   3
2   third document and   3
2        it looks very   3
2          good today.   3

EDIT:

m=(pd.DataFrame(df.text.apply(lambda x: list(divide_chunks(x.split(),3))).values.tolist())
.unstack().sort_index(level=1).apply(' '.join).reset_index(level=1))
m.columns=df.columns
print(m)

   id                 text
0   0             I am the
1   0   first document and
2   0            I am very
3   0               happy.
0   1          Here is the
1   1  second document and
2   1     it likes playing
3   1              tennis.
0   2          This is the
1   2   third document and
2   2        it looks very
3   2          good today.


问:
Flutter - TextField focus changes TabBar selected index
I have a Scaffold, within it I have a TabBar, TabBarView and a TextField.

The TabBar has 3 tabs (e.g. tabs A, B and C), the TabBarView has 3 views and this TextField is at the last tab (tab C).

Everything is working, but whenever I put the focus on the TextField to type something, the TabBar is changed from tab C to tab A. Very annoying. This should not happen. The TabBarView remains unchanged.

I created the controller in the initState. like this:

```<code>@override
void initState() {
  super.initState();
  widget._tabBarController =
      new TabController(length: 3, vsync: this);
}
</code>```

Any idea why it happens?

Code:

```<code>class AtendimentoOrtoWidget extends StatefulWidget {
  TabController _tabBarController;

  @override
  _AtendimentoOrtoWidgetState createState() => _AtendimentoOrtoWidgetState();
}

class _AtendimentoOrtoWidgetState extends State<AtendimentoOrtoWidget>
    with SingleTickerProviderStateMixin {

      @override
  void initState() {
    super.initState();

    widget._tabBarController =
        new TabController(length: 3, vsync: this);

  }

 @override
    Widget build(BuildContext context) {
    return SafeArea(
        top: false,
        child: new DefaultTabController(
            length: 3,
            child: new Scaffold(
                resizeToAvoidBottomPadding: false,
                appBar: new AppBar(
                  toolbarOpacity: 0.5,
                  automaticallyImplyLeading: true,
                  backgroundColor: Colors.white,
                  elevation: 2.0,
                  title: new TabBar(
                    controller: widget._tabBarController,
                    unselectedLabelColor: Colors.black,
                    indicatorColor: Colors.black,
                    labelColor: Colors.black,
                    // indicatorWeight: 0.0,
                    isScrollable: true,
                    labelStyle: new TextStyle(
                        fontSize: 16.0,
                        fontFamily: 'Caecilia',
                        fontWeight: FontWeight.w700),
                    tabs: <Widget>[
                      new Tab(
                              text: "TAB A",
                      ),
                      new Tab(
                              text: "TAB B",
                      ),
                      new Tab(
                              text: "TAB C",
                            )
                    ],
                  ),
                ),
                backgroundColor: Colors.white,
                body: new TabBarView(
                        controller: widget._tabBarController,
                        children: <Widget>[
                          new Container(),
                          new Container(),
                          new TextField()
                        ],
                      ))));
  }

  }
</code>```

答:
I tried it. Check the below code. If you still facing the same issue then share your implementation.

```<code>import 'package:flutter/material.dart';

class TabScreen extends StatefulWidget {
  @override
  _TabScreenState createState() => _TabScreenState();
}

class _TabScreenState extends State<TabScreen> with SingleTickerProviderStateMixin {
  GlobalKey<ScaffoldState> _scaffoldKey = new GlobalObjectKey<ScaffoldState>('TabScreen');

  TabController tabController;

  @override
  void initState() {
    super.initState();
    tabController = new TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    super.dispose();
    tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text("Tab Demo"),
      ),
      backgroundColor: Colors.white,
      body: Column(
        children: <Widget>[
          TabBar(
            controller: tabController,
            tabs: <Widget>[
              Tab(
                child: Container(
                  child: new Text(
                    'A',
                    style: TextStyle(color: Colors.black),
                  ),
                ),
              ),
              Tab(
                child: Container(
                  child: Text(
                    'B',
                    style: TextStyle(color: Colors.black),
                  ),
                ),
              ),
              Tab(
                child: Container(
                  child: Text(
                    'C',
                    style: TextStyle(color: Colors.black),
                  ),
                ),
              )
            ],
          ),
          Flexible(
              child: TabBarView(
            controller: tabController,
            children: <Widget>[
              Placeholder(),
              Placeholder(),
              ListView(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextField(
                      decoration: InputDecoration(labelText: "Name"),
                    ),
                  ),
                ],
              ),
            ],
          ))
        ],
      ),
    );
  }
}
</code>```

Body:
I have a Scaffold, within it I have a TabBar, TabBarView and a TextField.

The TabBar has 3 tabs (e.g. tabs A, B and C), the TabBarView has 3 views and this TextField is at the last tab (tab C).

Everything is working, but whenever I put the focus on the TextField to type something, the TabBar is changed from tab C to tab A. Very annoying. This should not happen. The TabBarView remains unchanged.

I created the controller in the initState. like this:

@override
void initState() {
  super.initState();
  widget._tabBarController =
      new TabController(length: 3, vsync: this);
}

Any idea why it happens?

Code:

class AtendimentoOrtoWidget extends StatefulWidget {
  TabController _tabBarController;

  @override
  _AtendimentoOrtoWidgetState createState() => _AtendimentoOrtoWidgetState();
}

class _AtendimentoOrtoWidgetState extends State<AtendimentoOrtoWidget>
    with SingleTickerProviderStateMixin {

      @override
  void initState() {
    super.initState();

    widget._tabBarController =
        new TabController(length: 3, vsync: this);

  }

 @override
    Widget build(BuildContext context) {
    return SafeArea(
        top: false,
        child: new DefaultTabController(
            length: 3,
            child: new Scaffold(
                resizeToAvoidBottomPadding: false,
                appBar: new AppBar(
                  toolbarOpacity: 0.5,
                  automaticallyImplyLeading: true,
                  backgroundColor: Colors.white,
                  elevation: 2.0,
                  title: new TabBar(
                    controller: widget._tabBarController,
                    unselectedLabelColor: Colors.black,
                    indicatorColor: Colors.black,
                    labelColor: Colors.black,
                    // indicatorWeight: 0.0,
                    isScrollable: true,
                    labelStyle: new TextStyle(
                        fontSize: 16.0,
                        fontFamily: 'Caecilia',
                        fontWeight: FontWeight.w700),
                    tabs: <Widget>[
                      new Tab(
                              text: "TAB A",
                      ),
                      new Tab(
                              text: "TAB B",
                      ),
                      new Tab(
                              text: "TAB C",
                            )
                    ],
                  ),
                ),
                backgroundColor: Colors.white,
                body: new TabBarView(
                        controller: widget._tabBarController,
                        children: <Widget>[
                          new Container(),
                          new Container(),
                          new TextField()
                        ],
                      ))));
  }

  }

Body:
I tried it. Check the below code. If you still facing the same issue then share your implementation.

import 'package:flutter/material.dart';

class TabScreen extends StatefulWidget {
  @override
  _TabScreenState createState() => _TabScreenState();
}

class _TabScreenState extends State<TabScreen> with SingleTickerProviderStateMixin {
  GlobalKey<ScaffoldState> _scaffoldKey = new GlobalObjectKey<ScaffoldState>('TabScreen');

  TabController tabController;

  @override
  void initState() {
    super.initState();
    tabController = new TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    super.dispose();
    tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text("Tab Demo"),
      ),
      backgroundColor: Colors.white,
      body: Column(
        children: <Widget>[
          TabBar(
            controller: tabController,
            tabs: <Widget>[
              Tab(
                child: Container(
                  child: new Text(
                    'A',
                    style: TextStyle(color: Colors.black),
                  ),
                ),
              ),
              Tab(
                child: Container(
                  child: Text(
                    'B',
                    style: TextStyle(color: Colors.black),
                  ),
                ),
              ),
              Tab(
                child: Container(
                  child: Text(
                    'C',
                    style: TextStyle(color: Colors.black),
                  ),
                ),
              )
            ],
          ),
          Flexible(
              child: TabBarView(
            controller: tabController,
            children: <Widget>[
              Placeholder(),
              Placeholder(),
              ListView(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextField(
                      decoration: InputDecoration(labelText: "Name"),
                    ),
                  ),
                ],
              ),
            ],
          ))
        ],
      ),
    );
  }
}


问:
Jmeter: Http POST request with body data and file upload
I'm trying to test a Rest api which is working on postman but not on Jmeter,
the request takes (2 parameters):

a pdf file

a body data (json containing pdf information)

on Postman : when I put the Content-Type = application/x-www-form-urlencoded, and I upload the json file and the pdf file it works
but on jmeter I'm always getting errors such as "Unsupported Media Type"

答:
Please check both the requests(Postman and jmeter) are same with all the values header and content type.

Check “Use multipart/form-data for POST” box is not selected.

Use a multipart/form-data or application/x-www-form-urlencoded post
  request

Reference;-https://jmeter.apache.org/usermanual/component_reference.html#HTTP_Request

For more information, please check this blog.

Hope this helps.


问:
wcf and inserting information into the web.config
Why does WCF not insert basic information about my service into the web.config?  Is there a way to make it to that?

I'm talking about when you add a wcf service to project explorer

答: You can always use SvcConfigEditor to configure your services or clients. This has a nicer (but far from perfect) UI which can help you going quickly.


问:
How to create multi steps form
I have been trying to create a multi steps form, working on my css to achieve the result I want but I couldn't achieved the exact solution I wanted.

I was able to design its layout but the issue I am facing is the line I wanted through those links.

Below is what I am trying to achieve:

What I was able to come up with:

If you take a look at the top of the second image. you will see the grey line at the top of those links.

Html Markup

```<code><ul id="owp-checkout-timeline" class="owp-woo-checkout-timeline clr square step-4">

            <li id="timeline-0" data-step="0" class="timeline login active">
            <div class="timeline-wrapper">
                <span class="timeline-step">1.</span>
                <span class="timeline-label">Login</span>
            </div>
        </li>

    <li id="timeline-1" data-step="1" class="timeline billing ">
        <div class="timeline-wrapper">
            <span class="timeline-step">2.</span>
            <span class="timeline-label">Billing</span>
        </div>
    </li>

    <li id="timeline-2" data-step="2" class="timeline shipping" >
        <div class="timeline-wrapper">
            <span class="timeline-step">3.</span>
            <span class="timeline-label">Shipping</span>
        </div>
    </li>

    <li id="timeline-3" data-step="3" class="timeline payment">
        <div class="timeline-wrapper">
            <span class="timeline-step">4.</span>
            <span class="timeline-label">Payment Info</span>
        </div>
    </li>

</ul>
</code>```

Css code

```<code>.owp-woo-checkout-timeline{
        display:-webkit-box;
        display:-moz-box;
        display:-ms-flexbox;
        display:-webkit-flex;
        display:flex;
        margin:0 0 1em;
        padding:0;
        font-size:90%;
        text-transform:uppercase;
}
.owp-woo-checkout-timeline>li.timeline{
    list-style:none;
    text-align:center;
    width:auto;
    padding:0;
    margin:0;
    position:relative;
    text-overflow:ellipsis;
    color:#b71c1c;
    display:block

}

    .timeline-wrapper{
                 display: table-row;
            }
    .timeline-wrapper:before {
    top: 14px;
    bottom: 0;
    position: absolute;
    content: " ";
    width: 100%;
    height: 1px;
    background-color: #ccc;
    z-order: 0;
}

.owp-woo-checkout-timeline>li.timeline .timeline-step,.owp-woo-checkout-timeline>li.timeline .timeline-step:after,
        .owp-woo-checkout-timeline>li.timeline .timeline-step:before{
            background-color:#e65100;
            color:#fff;
            font-weight:bold;
            border-color:#247830;
            padding:6px;
            border-radius:800px;
            }

.owp-woo-checkout-timeline>li.timeline .timeline-step:before{left:0}
.owp-woo-checkout-timeline>li.timeline .timeline-step:after{right:0}

.owp-woo-checkout-timeline>li:first-child .timeline-step:after,
.owp-woo-checkout-timeline>li:first-child
.owp-woo-checkout-timeline{width:50%;margin-left:50%}
.owp-woo-checkout-timeline>li:last-child .timeline-step:after,
.owp-woo-checkout-timeline>li:last-child .timeline-step:before{width:50%;margin-right:50%}
.owp-woo-checkout-timeline>li.active,.progress-indicator>li.active .timeline-step{color:#337AB7}
.owp-woo-checkout-timeline>li.active .timeline-step,.progress-indicator>li.active .timeline-step:after,
.owp-woo-checkout-timeline>li.active .timeline-step:before{background-color:#337AB7;border-color:#122a3f}
.owp-woo-checkout-timeline>li a:hover .timeline-step,.progress-indicator>li a:hover .timeline-step:after,
.owp-woo-checkout-timeline>li a:hover .timeline-step:before{background-color:#5671d0;border-color:#1f306e}
.owp-woo-checkout-timeline>li a:hover .timeline-step{color:#5671d0}
</code>```

答:
please try this code :

<!DOCTYPE html>

  <title>Accordians</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

</script>

          1

              Login

          2

              Billing

          3

              Shipping

          4

              Payment Info

```

Title: How to create multi steps form

Body:
I have been trying to create a multi steps form, working on my css to achieve the result I want but I couldn't achieved the exact solution I wanted.

I was able to design its layout but the issue I am facing is the line I wanted through those links.

Below is what I am trying to achieve:

What I was able to come up with:

If you take a look at the top of the second image. you will see the grey line at the top of those links.

Html Markup

                1.
                Login

            2.
            Billing

            3.
            Shipping

            4.
            Payment Info

Css code

.owp-woo-checkout-timeline{
        display:-webkit-box;
        display:-moz-box;
        display:-ms-flexbox;
        display:-webkit-flex;
        display:flex;
        margin:0 0 1em;
        padding:0;
        font-size:90%;
        text-transform:uppercase;
}
.owp-woo-checkout-timeline>li.timeline{
    list-style:none;
    text-align:center;
    width:auto;
    padding:0;
    margin:0;
    position:relative;
    text-overflow:ellipsis;
    color:#b71c1c;
    display:block

}

    .timeline-wrapper{
                 display: table-row;
            }
    .timeline-wrapper:before {
    top: 14px;
    bottom: 0;
    position: absolute;
    content: " ";
    width: 100%;
    height: 1px;
    background-color: #ccc;
    z-order: 0;
}

.owp-woo-checkout-timeline>li.timeline .timeline-step,.owp-woo-checkout-timeline>li.timeline .timeline-step:after,
        .owp-woo-checkout-timeline>li.timeline .timeline-step:before{
            background-color:#e65100;
            color:#fff;
            font-weight:bold;
            border-color:#247830;
            padding:6px;
            border-radius:800px;
            }

.owp-woo-checkout-timeline>li.timeline .timeline-step:before{left:0}
.owp-woo-checkout-timeline>li.timeline .timeline-step:after{right:0}

.owp-woo-checkout-timeline>li:first-child .timeline-step:after,
.owp-woo-checkout-timeline>li:first-child
.owp-woo-checkout-timeline{width:50%;margin-left:50%}
.owp-woo-checkout-timeline>li:last-child .timeline-step:after,
.owp-woo-checkout-timeline>li:last-child .timeline-step:before{width:50%;margin-right:50%}
.owp-woo-checkout-timeline>li.active,.progress-indicator>li.active .timeline-step{color:#337AB7}
.owp-woo-checkout-timeline>li.active .timeline-step,.progress-indicator>li.active .timeline-step:after,
.owp-woo-checkout-timeline>li.active .timeline-step:before{background-color:#337AB7;border-color:#122a3f}
.owp-woo-checkout-timeline>li a:hover .timeline-step,.progress-indicator>li a:hover .timeline-step:after,
.owp-woo-checkout-timeline>li a:hover .timeline-step:before{background-color:#5671d0;border-color:#1f306e}
.owp-woo-checkout-timeline>li a:hover .timeline-step{color:#5671d0}

Body:
please try this code :

<!DOCTYPE html>
<html>
<head>
  <title>Accordians</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<style>
    .form_wizard .stepContainer {
  display: block;
  position: relative;
  margin: 0;
  padding: 0;
  border: 0 solid #CCC;
  overflow-x: hidden;
}

/**-------**/

.wizard_horizontal ul.wizard_steps {
  display: table;
  list-style: none;
  position: relative;
  width: 100%;
  margin: 0 0 20px;
  padding: 0;
}
.wizard_horizontal ul.wizard_steps li {
  display: table-cell;
  text-align: center;
}
.wizard_horizontal ul.wizard_steps li a, .wizard_horizontal ul.wizard_steps li:hover {
  display: block;
  position: relative;
  -moz-opacity: 1;
  filter: alpha(opacity: 100);
  opacity: 1;
  color: #666;
}
.wizard_horizontal ul.wizard_steps li a:before {
  content: "";
  position: absolute;
  height: 8px;
  background: #ccc;
  top: 40px;
  width: 100%;
  z-index: 4;
  left: 0;
}
.wizard_horizontal ul.wizard_steps li a.disabled .step_no {
  background: #ccc;
}
.wizard_horizontal ul.wizard_steps li a .step_no {
  width: 80px;
  height: 80px;
  line-height: 80px;
  border-radius: 100px;
  display: block;
  margin: 0 auto 5px;
  font-size: 16px;
  text-align: center;
  position: relative;
  z-index: 5;
}
.wizard_horizontal ul.wizard_steps li a.selected:before, .step_no {
  background: #34495E;
  color: #fff;
}
.wizard_horizontal ul.wizard_steps li a.done:before, .wizard_horizontal ul.wizard_steps li a.done .step_no {
  background: #1ABB9C;
  color: #fff;
}
.wizard_horizontal ul.wizard_steps li:first-child a:before {
  left: 50%;
}
.wizard_horizontal ul.wizard_steps li:last-child a:before {
  right: 50%;
  width: 50%;
  left: auto;
}

/**-------**/

.wizard_verticle .stepContainer {
  width: 80%;
  float: left;
  padding: 0 10px;
}
.form_wizard .stepContainer div.content {
  display: block;
  position: absolute;
  float: left;
  margin: 0;
  padding: 5px;
  font: normal 12px Verdana, Arial, Helvetica, sans-serif;
  color: #5A5655;
  height: 300px !important;
  text-align: left;
  overflow: auto;
  z-index: 88;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  clear: both;
}
.actionBar {
  width: 100%;
  border-top: 1px solid #ddd;
  padding: 10px 5px;
  text-align: right;
  margin-top: 10px;
}
.actionBar .buttonDisabled {
  cursor: not-allowed;
  pointer-events: none;
  opacity: .65;
  filter: alpha(opacity=65);
  -webkit-box-shadow: none;
  box-shadow: none;
}
.actionBar a {
  margin: 0 3px;
}

/**-------**/
</style>
</script>
</head>
<body>
  <div id="wizard" class="form_wizard wizard_horizontal">
    <ul class="wizard_steps anchor">
      <li>
        <a href="#step-1" class="selected" isdone="1" rel="1">
          <span class="step_no">1</span>
          <span class="step_descr">
              <small>Login</small>
          </span>
        </a>
      </li>
      <li>
        <a href="#step-2" class="done" isdone="1" rel="2">
          <span class="step_no">2</span>
          <span class="step_descr">
              <small>Billing</small>
          </span>
        </a>
      </li>
      <li>
        <a href="#step-3" class="done" isdone="1" rel="3">
          <span class="step_no">3</span>
          <span class="step_descr">
              <small>Shipping</small>
          </span>
        </a>
      </li>
      <li>
        <a href="#step-4" class="done" isdone="1" rel="4">
          <span class="step_no">4</span>
          <span class="step_descr">
              <small>Payment Info</small>
          </span>
        </a>
      </li>
    </ul>
      <div class="stepContainer">
         <div id="step-1" class="wizard_content" style="display: block;">
         </div>
         <div id="step-2" class="wizard_content" style="display: none;">

         </div>
         <div id="step-3" class="wizard_content" style="display: none;">

         </div>
         <div id="step-4" class="wizard_content" style="display: none;">

         </div>
      </div>
      <!-- <div class="actionBar">
        <a href="#" class="btn btn-default">Finish</a>
        <a href="#" class="btn btn-success">Next</a>
        <a href="#" class="btn btn-primary buttonDisabled">Previous</a>
      </div> -->
  </div>

<!-- form wizard -->

  <script type="text/javascript" src="http://xn--80akiaokt3b4b.xn--d1acnqm.xn--j1amh/templates/demo/gentelella/js/wizard/jquery.smartWizard.js"></script>

  <script type="text/javascript">
    $(document).ready(function() {
      // Smart Wizard
      $('#wizard').smartWizard();

      function onFinishCallback() {
        $('#wizard').smartWizard('showMessage', 'Finish Clicked');
        //alert('Finish Clicked');
      }
    });

    $(document).ready(function() {
      // Smart Wizard
      $('#wizard_verticle').smartWizard({
        transitionEffect: 'slide'
      });
    });
  </script>

</body>
</html>


问:
Does Clang have something like #pragma GCC target?
I have some code written that uses AVX intrinsics when they are available on the current CPU.  In GCC and Clang, unlike Visual C++, in order to use intrinsics, you must enable them on the command line.

The problem with GCC and Clang is that when you enable these options, you're giving the compiler free reign to use those instructions everywhere in your source file.  This is very bad when you have header files containing inline functions or template functions, because the compiler will generate these functions with AVX instructions.

When linking, duplicate functions will be discarded.  However, because some source files were compiled with -mavx and some were not, the various compilations of the inline/template functions will be different.  If you're unlucky, the linker will randomly choose the version that has AVX instructions, causing the program to crash when run on a system without AVX.

GCC solves this with #pragma GCC target.  You can turn off the special instructions for the header files, and the code generated will not use AVX:

```<code>#pragma GCC push_options
#pragma GCC target("no-avx")

#include "MyHeader.h"

#pragma GCC pop_options
</code>```

Does Clang have anything like this?  It seems to ignore these options and generates AVX code anyway.

答:
The Clang equivalent to GCC push_options / GCC target / GCC pop_options are the clang attribute push / clang attribute pop pragmas along with the target attribute:

```<code>#pragma clang attribute push (__attribute__((target("pclmul,sse4.1,ssse3"))), apply_to=function)
// ...
#pragma clang attribute pop
</code>```

This is the equivalent of:

```<code>#pragma GCC push_options
#pragma GCC target("pclmul", "sse4.1", "ssse3")
// ...
#pragma GCC pop_options
</code>```

Note that where the GCC target pragma takes a comma-delimited list of target options, the clang target attribute takes a single string, comma-delimited internally.

Clang supports negative target options (such as "no-avx"), but I prefer to use positive options to add to the feature set selected by command line options.

Body:
I have some code written that uses AVX intrinsics when they are available on the current CPU.  In GCC and Clang, unlike Visual C++, in order to use intrinsics, you must enable them on the command line.

The problem with GCC and Clang is that when you enable these options, you're giving the compiler free reign to use those instructions everywhere in your source file.  This is very bad when you have header files containing inline functions or template functions, because the compiler will generate these functions with AVX instructions.

When linking, duplicate functions will be discarded.  However, because some source files were compiled with -mavx and some were not, the various compilations of the inline/template functions will be different.  If you're unlucky, the linker will randomly choose the version that has AVX instructions, causing the program to crash when run on a system without AVX.

GCC solves this with #pragma GCC target.  You can turn off the special instructions for the header files, and the code generated will not use AVX:

#pragma GCC push_options
#pragma GCC target("no-avx")

#include "MyHeader.h"

#pragma GCC pop_options

Does Clang have anything like this?  It seems to ignore these options and generates AVX code anyway.

Body:
The Clang equivalent to GCC push_options / GCC target / GCC pop_options are the clang attribute push / clang attribute pop pragmas along with the target attribute:

#pragma clang attribute push (__attribute__((target("pclmul,sse4.1,ssse3"))), apply_to=function)
// ...
#pragma clang attribute pop

This is the equivalent of:

#pragma GCC push_options
#pragma GCC target("pclmul", "sse4.1", "ssse3")
// ...
#pragma GCC pop_options

Note that where the GCC target pragma takes a comma-delimited list of target options, the clang target attribute takes a single string, comma-delimited internally.

Clang supports negative target options (such as "no-avx"), but I prefer to use positive options to add to the feature set selected by command line options.


问:
Nonzero function argument becomes zero inside function
I'm working on a C#/Unity project using 64-bit Ubuntu 18.04. I have two non-static classes, ClassA and ClassB, and inside the instance method classA.Foo(), there are two calls to the public static int method ClassB.Floor(float x). In one of the two places where Foo calls Floor, if I follow the stack trace of values passed from classA.Foo to ClassB.Floor, nonzero inputs from Foo become 0 inside Floor before any computation happens.

I've searched stackoverflow, stackexchange, and google in general for people who have had problems with variables changing from nonzero to 0 when passed into functions, either in C# or another language. I found some results regarding passing reference vs. value types, but ClassB.Floor is receiving a float and returning an int. I've confirmed that values of the proper type (non-double floats) are being input to ClassB.Floor.

ClassB.Floor is defined as

public class ClassB : MonoBehaviour {
    [...]

    public static int Floor(float x) {
        int xi = (int)x;
        return x < xi ? xi - 1 : xi;
    }
}
```

<p>Example with debugger value comments:</p>

<pre class="lang-cs prettyprint-override"><code>public class ClassA {
    # Set somewhere else during initialization, but definitely
    # exists by the time `Foo` is called.
    private GameObject gameObject;

    [...]

    public byte Foo(Vector3 pos) {  # pos: "(-17f, 0f, 15f)"
        [...]

        int x = ClassB.Floor(pos.x);  # x: -17
        Vector3 objPosition = gameObject.transform.position;  # objPosition: "(-16f, 0f, 0f)"
        float xx = objPosition.x;  # xx: -16f
        int px = ClassB.Floor(xx);  # px: 0

        [...]
    }
}
</code>```

So, the px value isn't being set correctly by ClassB.Floor, even though it's working correctly in the calculation of x. Moreover, if I go into the debugger and follow the program flow from int px = ClassB.Floor(xx); in classA.Foo into ClassB.Floor, I immediately see this:

public static int Floor(float x) {  # x: 0
```

<p>And the output value of 0 is correctly computed from that input of 0.  If I use Rider's debugger's Evaluate Expression functionality at any point during program execution after <code>xx</code> is defined, <code>ClassB.Floor(xx)</code> returns the correct value of <code>-16</code> even though the program itself does not.</p>

<p>No errors or warnings are generated in the course of program flow through this part of the code. Does anybody have any idea what could be causing this? I am really baffled. Thanks in advance!</p>

<p>[Update] Here is a more minimal example demonstrating the same behavior. <code>ClassB.Floor</code> does not seem to matter at all:</p>

<pre class="lang-cs prettyprint-override"><code>public class ClassA {
    public byte Foo(Vector3 pos) {  # pos: "(-17f, 0f, 15f)"
        float xx = -16f;  # xx: -16f
        int px = Mathf.FloorToInt(xx);  # px: 0
        return 0;
    }
}
</code>```

Same deal: If I step into Mathf.FloorToInt, defined as

public static int FloorToInt(float f)
{
  return (int) Math.Floor((double) f);
}
```

I find that f=0 from the start of the function, even though xx=-16f.

答:
This works perfectly fine for me :</p>

```<code>public class ClassB : MonoBehaviour
{
    void Start(){
        ClassA instance = new ClassA(gameObject);
        instance.Foo(new Vector3(10.5f,15.2f,20.8f));
    }
    public static int Floor(float x) // 10.5f and 12.19f
    {
        int xi = (int)x;
        return x < xi ? xi - 1 : xi;
    }
}

public class ClassA
{
    private GameObject gameObject;
    public ClassA(GameObject go){
        gameObject = go;
    }
    public byte Foo(Vector3 pos) // new Vector3(10.5f,15.2f,20.8f)
    {
        int x = ClassB.Floor(pos.x);  // 10
        //Debug.Log(x);
        Vector3 objPosition = gameObject.transform.position; // new Vector3(12.19f, 1f, -10f);
        float xx = objPosition.x; // 12.19f
        int px = ClassB.Floor(xx); //12
        //Debug.Log(px);
        return new byte();
    }
}
</code>```

Body:
I'm working on a C#/Unity project using 64-bit Ubuntu 18.04. I have two non-static classes, ClassA and ClassB, and inside the instance method classA.Foo(), there are two calls to the public static int method ClassB.Floor(float x). In one of the two places where Foo calls Floor, if I follow the stack trace of values passed from classA.Foo to ClassB.Floor, nonzero inputs from Foo become 0 inside Floor before any computation happens.

I've searched stackoverflow, stackexchange, and google in general for people who have had problems with variables changing from nonzero to 0 when passed into functions, either in C# or another language. I found some results regarding passing reference vs. value types, but ClassB.Floor is receiving a float and returning an int. I've confirmed that values of the proper type (non-double floats) are being input to ClassB.Floor.

ClassB.Floor is defined as

public class ClassB : MonoBehaviour {
    [...]

    public static int Floor(float x) {
        int xi = (int)x;
        return x < xi ? xi - 1 : xi;
    }
}

Example with debugger value comments:

public class ClassA {
    # Set somewhere else during initialization, but definitely
    # exists by the time `Foo` is called.
    private GameObject gameObject;

    [...]

    public byte Foo(Vector3 pos) {  # pos: "(-17f, 0f, 15f)"
        [...]

        int x = ClassB.Floor(pos.x);  # x: -17
        Vector3 objPosition = gameObject.transform.position;  # objPosition: "(-16f, 0f, 0f)"
        float xx = objPosition.x;  # xx: -16f
        int px = ClassB.Floor(xx);  # px: 0

        [...]
    }
}

So, the px value isn't being set correctly by ClassB.Floor, even though it's working correctly in the calculation of x. Moreover, if I go into the debugger and follow the program flow from int px = ClassB.Floor(xx); in classA.Foo into ClassB.Floor, I immediately see this:

public static int Floor(float x) {  # x: 0

And the output value of 0 is correctly computed from that input of 0.  If I use Rider's debugger's Evaluate Expression functionality at any point during program execution after xx is defined, ClassB.Floor(xx) returns the correct value of -16 even though the program itself does not.

No errors or warnings are generated in the course of program flow through this part of the code. Does anybody have any idea what could be causing this? I am really baffled. Thanks in advance!

[Update] Here is a more minimal example demonstrating the same behavior. ClassB.Floor does not seem to matter at all:

public class ClassA {
    public byte Foo(Vector3 pos) {  # pos: "(-17f, 0f, 15f)"
        float xx = -16f;  # xx: -16f
        int px = Mathf.FloorToInt(xx);  # px: 0
        return 0;
    }
}

Same deal: If I step into Mathf.FloorToInt, defined as

public static int FloorToInt(float f)
{
  return (int) Math.Floor((double) f);
}

I find that f=0 from the start of the function, even though xx=-16f.

Body:
This works perfectly fine for me :

public class ClassB : MonoBehaviour
{
    void Start(){
        ClassA instance = new ClassA(gameObject);
        instance.Foo(new Vector3(10.5f,15.2f,20.8f));
    }
    public static int Floor(float x) // 10.5f and 12.19f
    {
        int xi = (int)x;
        return x < xi ? xi - 1 : xi;
    }
}

public class ClassA
{
    private GameObject gameObject;
    public ClassA(GameObject go){
        gameObject = go;
    }
    public byte Foo(Vector3 pos) // new Vector3(10.5f,15.2f,20.8f)
    {
        int x = ClassB.Floor(pos.x);  // 10
        //Debug.Log(x);
        Vector3 objPosition = gameObject.transform.position; // new Vector3(12.19f, 1f, -10f);
        float xx = objPosition.x; // 12.19f
        int px = ClassB.Floor(xx); //12
        //Debug.Log(px);
        return new byte();
    }
}


问:
How to connect to Kafka cluster with Kerberos Authentication on Windows using the Cofluent library?
I'm working on a project which requires me to connect to an existing Kafka cluster using dotnet and the Confluent library. The Kafka cluster uses Kerberous/Keytab authentication. Looking at some of the documentation it looks like you can pass through the keytab file using the JAAS configuration, but when I look at the properties for the ProudcerConfig in Confluent I don't see anything about authentication. So how do I specify the keytab file so that I can authenticate against the Kafka cluster?</p>

答:
I think this section of Confluent docs mentions how to configure clients:

In your client.properties file you'd need the following configuration:

```<code>sasl.mechanism=GSSAPI
# Configure SASL_SSL if SSL encryption is enabled, otherwise configure SASL_PLAINTEXT
security.protocol=SASL_SSL

sasl.kerberos.service.name=kafka

sasl.jaas.config=com.sun.security.auth.module.Krb5LoginModule required \
    useKeyTab=true \
    storeKey=true \
    keyTab="/etc/security/keytabs/kafka_client.keytab" \
    principal="kafkaclient1@EXAMPLE.COM";

# optionally - kafka-console-consumer or kafka-console-producer, kinit can be used along with useTicketCache=true
sasl.jaas.config=com.sun.security.auth.module.Krb5LoginModule required \
   useTicketCache=true;
</code>```

In order to pass client.properties to e.g. kafka-console-consumer you need to provide --consumer.config parameter as well:

For Linux:

```<code>bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test  --consumer.config client.properties --from-beginning
</code>```

For Windows:

```<code>bin/kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic test --consumer.config client.properties --from-beginning
</code>```

Body:
I think this section of Confluent docs mentions how to configure clients:

In your client.properties file you'd need the following configuration:

sasl.mechanism=GSSAPI
# Configure SASL_SSL if SSL encryption is enabled, otherwise configure SASL_PLAINTEXT
security.protocol=SASL_SSL

sasl.kerberos.service.name=kafka

sasl.jaas.config=com.sun.security.auth.module.Krb5LoginModule required \
    useKeyTab=true \
    storeKey=true \
    keyTab="/etc/security/keytabs/kafka_client.keytab" \
    principal="kafkaclient1@EXAMPLE.COM";

# optionally - kafka-console-consumer or kafka-console-producer, kinit can be used along with useTicketCache=true
sasl.jaas.config=com.sun.security.auth.module.Krb5LoginModule required \
   useTicketCache=true;

In order to pass client.properties to e.g. kafka-console-consumer you need to provide --consumer.config parameter as well:

For Linux:

bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test  --consumer.config client.properties --from-beginning

For Windows:

bin/kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic test --consumer.config client.properties --from-beginning


问:
Array of objects not getting detected in Web API
I am developing a Web API with .NET Core 2.1 where the response is manipulated based on the output received from a WCF service.

I need to have a API with Get verb and need to pass an array of complex objects as the input to it.The challenge currently I am facing is, the array is not getting detected from the input.I have added [FromQuery] along with the input parameter. I am trying the same from Swagger UI.

Tried adding Name along with FromQuery .

```<code>[HttpGet("test")]
public IActionResult Testmethod([FromQuery] Person person)
{
    return Ok(person);
}
</code>```

Model classes:

```<code>public class Person
{
    public string Name{ get; set; }
    public int Age{ get; set; }
    public Grade[] grades{ get; set; }
}

public class Grade
{
    public int GradeId { get; set; }
    public string GradeName { get; set; }
    public string Section { get; set; }
}
</code>```

答:
Try the below</p>

```<code>[FromBody] IEnumerable<Person> persons
</code>```

Body:
I am developing a Web API with .NET Core 2.1 where the response is manipulated based on the output received from a WCF service.

I need to have a API with Get verb and need to pass an array of complex objects as the input to it.The challenge currently I am facing is, the array is not getting detected from the input.I have added [FromQuery] along with the input parameter. I am trying the same from Swagger UI.

Tried adding Name along with FromQuery .

[HttpGet("test")]
public IActionResult Testmethod([FromQuery] Person person)
{
    return Ok(person);
}

Model classes:

public class Person
{
    public string Name{ get; set; }
    public int Age{ get; set; }
    public Grade[] grades{ get; set; }
}

public class Grade
{
    public int GradeId { get; set; }
    public string GradeName { get; set; }
    public string Section { get; set; }
}

Body:
Try the below

[FromBody] IEnumerable<Person> persons