问:
Cannot update state from render method React
I have a NavLink component like this:

```<code><NavLink  isActive={(match, location) => this.isActiveFunc(match, location)}  className={classes.subLink} to={{ pathname: "/admin/users" }}>
    <ListItem button className={classes.nested}>
       <ListItemText disableTypography={this.state.activePath === "/admin/users"} inset primary="Users" />
    </ListItem>
</NavLink>
</code>```

and try to set my state every time the NavLink is active as follows:

```<code> updateActivePath = (match) => {
    if (match && this.state.activePath !== match.path) {
      this.setState({activePath: match.path})
    }
  };

  isActiveFunc = (match, location) => {
    this.updateActivePath(match);
  };
</code>```

This however gives me the following error:

Warning: Cannot update during an existing state transition (such as
  within render or another component's constructor). Render methods
  should be a pure function of props and state; constructor side-effects
  are an anti-pattern, but can be moved to componentWillMount.

Any ideas how I can fix this?

答:
You use a setState in react lifecycle. You call your method updateActivePath in render or other lifecycle method react. This trigger an extra rendering for your component.

For fix this warning change your setState location in componentWillMount method or in function call by action (click, ...).

For must information go to lifecycle component documentation: https://reactjs.org/docs/react-component.html

Body:
I have a NavLink component like this:

<NavLink  isActive={(match, location) => this.isActiveFunc(match, location)}  className={classes.subLink} to={{ pathname: "/admin/users" }}>
    <ListItem button className={classes.nested}>
       <ListItemText disableTypography={this.state.activePath === "/admin/users"} inset primary="Users" />
    </ListItem>
</NavLink>

and try to set my state every time the NavLink is active as follows:

 updateActivePath = (match) => {
    if (match && this.state.activePath !== match.path) {
      this.setState({activePath: match.path})
    }
  };

  isActiveFunc = (match, location) => {
    this.updateActivePath(match);
  };

This however gives me the following error:

Warning: Cannot update during an existing state transition (such as
  within render or another component's constructor). Render methods
  should be a pure function of props and state; constructor side-effects
  are an anti-pattern, but can be moved to componentWillMount.

Any ideas how I can fix this?


来源: stackexchange

问:
List only files in a directory?
Is there a way to list the files (not directories) in a directory with Python? I know I could use os.listdir and a loop of os.path.isfile()s, but if there's something simpler (like a function os.path.listfilesindir or something), it would probably be better.

答:
Using pathlib, the shortest way to list only files is:

```<code>[x for x in Path("your_path").iterdir() if x.is_file()]
</code>```

with depth support if need be.

ContentLicense: CC BY-SA 3.0

Title: List only files in a directory?

Body:
Using pathlib, the shortest way to list only files is:

[x for x in Path("your_path").iterdir() if x.is_file()]

with depth support if need be.


问:
Bcrypt stretches (with Devise) and Heroku dynos
I am currently reviewing security of my admin model generated with Devise. It raises a lot of questions on how a web dyno at Heroku processes the password encription.

first question :

My default Devise setup for bcrypt cost is config.stretches = Rails.env.test? ? 1 : 11 Does it mean there are eleven stretches for the test environment ? It seems the default stretches is 11 and I can confirm my hash under development environment is 11 too. So why specifiying 11 for test ?

I plan raising to 12 with config.stretches = 12

second question :

If I raise the strectches, the encryption time will increase. Will it freeze my app and prevent other visitors to make http requests to the app ? How many concurrent http requests can be made to a web dyno and how many concurrent password encryption can also be made to a web dyno (if this is different).

My knowledge of dynos is not deep, but I know a worker dyno can thread multiple Sidekiq workers depending on the processor cores .. Though the dyno don't specify the number of cores, and I don't know if this apply to web dynos too.

Basically I know that raising strectches will increase encrypting time, yet will it affect the whole app efficiency ?

答:
Author of devise-async-stretch here. It was built to do the password stretching in a background job queue.

I no longer actively use it (or maintain it) and would encourage it's use only if you're securing your redis connection (which most background processors rely on) with SSL.

https://github.com/danielwestendorf/devise-async-stretch


问:
headache for clEnqueueNDRangeKernel local work size
For opencl optimization, my idea is try to make match for

1 workgroup(kernel coding) as compute unit(GPU Hardware)
1 workitem(kernel coding) as process element(GPU Hardware)
( Maybe my idea is not correct, please teach me )

for example:
1. I have a global work size of 4000 by 3000.
2. My GPU opnecl device has a maximum work-group-size of 8192.
3. I call clEnqueueNDRangeKernel with the desired local-work-size (along with all other necessary parameters)
4. by fucntion call:
      a. clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), (void*)&workGroupSizeUsed, NULL);
      b. clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, sizeof(size_t), (void*)&workGroupSizeUsed, NULL);

above a and b are return 8192.
maximum work-group-size, CL_KERNEL_WORK_GROUP_SIZE, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE all are 8192.

I have no idea what I should follow to define my local work size...

(Q1)Any good idea for setting the local work size? (10x10? 40x30, X by Y )

clEnqueueNDRangeKernel(command_queue, kernel, 2, NULL, global_work_item_size, local_work_item_size, 0, NULL, NULL);
Very headache to define this "local_work_item_size" of clEnqueueNDRangeKernel function.

(Q2)
Could some one explain the difference if I set local work size = 1,1 between
local work size = 4000,3000 ?

Thank you in advance!

答:
(Q1)Any good idea for setting the local work size? (10x10? 40x30, X by Y )

As pmdj pointed out, this highly depends on your application. Since it is unclear how you selected your global_work_size and it is also linked to the local_work_size I would like to explain that one first. Usually what you would want to do is to map the size of the data you want to process to the global_work_size. E.g. if you have an array with 1024 values you would also pick a global_work_size of 1024 because then you can easily use the global id as an index in your OpenCL program:

```<code>int index = get_global_id(0);
input_array[index]++;   // your data processing
</code>```

However, the global_work_size is limited to a maximum 2^32 - 1. If you have more data to process than that you can pass your global_work_size and data size as parameters and use a loop like the following one:

```<code>int index = get_global_id(0);
for (int i = index; i < data_size; i += global_work_size) {
    input_array[i]++;   // your data processing
}
</code>```

The last fact which is important for the global_work_size is that it needs to be dividable by the local_work_size. This can result into a your global_work_size being bigger than your data size, e.g. you could have 1000 values while your local_work_size is 32. Then you would make your global_work_size 1024 and ensure through a condition like the one above (i < data_size) that the redundant work items are not doing anything weird like accessing not allocated memory areas.

The local_work_size depends on your platform. First of all you should always have a local_work_size which is a multiple of 32 for NVIDIA or a multiple of 64 for AMD GPUs. This represents the amount of operations which are scheduled together anyway. If you use a different number the GPU will have idle threads which won't do anything but decrease your performance.

Not only the manufacturer but also the specific type of your GPU has to be considered to find the optimal local_work_size. The global_work_size divided by the local_work_size is the number of work groups. Each work group is executed by one thread inside your CPU/GPU. If you use OpenCL to run your application on powerful hardware you want to make sure that it runs as parallel as possible. E.g. if you use an Intel i7 with 8 threads you would want to make sure that you have at least 8 work groups (global_work_size / local_work_size >= 8). If you use a NVIDIA GeForce GTX 1060 with 1280 CUDA Cores you would want to have at least 1280 work groups. But never at the cost of having a local_work_size of less than 32 which is more important!

If you are having more work groups than your hardware has threads that does not matter, they will be processed sequentially. Hence for most applications you can always set your local_work_size to 32/64. The only exception is if you require synchronization among more than work items. E.g. barriers only work inside work groups but not among different work groups. An example: If you need to to sum up chunks of 1024 values before being able to proceed with your algorithm you would need to set your local_work_size to 1024 for the barrier to work as desired.

(Q2) Could some one explain the difference if I set local work size = 1,1 between local work size = 4000,3000 ?

Both, the global_work_size and the local_work_size can have more than one dimension. If this is used or not solely depends on the preference of the programmer. All algorithms can be implemented in one dimension as well and the number of work groups is calculated by multiplying the dimensions, e.g. if your global_work_size is 20*20 and your local_work_size is 10*10 you would run the program with (20*20) / (10*10) = 400 work groups.

I personally like to use the dimensions if I am processing data which has multiple dimensions. Imagine your input is a two-dimensional image, you could simply use its width and height as global_work_size (e.g. 1024 * 1024) and the local_work_size accordingly (e.g. 32 * 32). In your code you could then use the following indices:

```<code>int x = get_global_id(0);
int y = get_global_id(1);
input_array[x][y]++;   // your data processing
</code>```

Body:
(Q1)Any good idea for setting the local work size? (10x10? 40x30, X by Y )

As pmdj pointed out, this highly depends on your application. Since it is unclear how you selected your global_work_size and it is also linked to the local_work_size I would like to explain that one first. Usually what you would want to do is to map the size of the data you want to process to the global_work_size. E.g. if you have an array with 1024 values you would also pick a global_work_size of 1024 because then you can easily use the global id as an index in your OpenCL program:

int index = get_global_id(0);
input_array[index]++;   // your data processing

However, the global_work_size is limited to a maximum 2^32 - 1. If you have more data to process than that you can pass your global_work_size and data size as parameters and use a loop like the following one:

int index = get_global_id(0);
for (int i = index; i < data_size; i += global_work_size) {
    input_array[i]++;   // your data processing
}

The last fact which is important for the global_work_size is that it needs to be dividable by the local_work_size. This can result into a your global_work_size being bigger than your data size, e.g. you could have 1000 values while your local_work_size is 32. Then you would make your global_work_size 1024 and ensure through a condition like the one above (i < data_size) that the redundant work items are not doing anything weird like accessing not allocated memory areas.

The local_work_size depends on your platform. First of all you should always have a local_work_size which is a multiple of 32 for NVIDIA or a multiple of 64 for AMD GPUs. This represents the amount of operations which are scheduled together anyway. If you use a different number the GPU will have idle threads which won't do anything but decrease your performance.

Not only the manufacturer but also the specific type of your GPU has to be considered to find the optimal local_work_size. The global_work_size divided by the local_work_size is the number of work groups. Each work group is executed by one thread inside your CPU/GPU. If you use OpenCL to run your application on powerful hardware you want to make sure that it runs as parallel as possible. E.g. if you use an Intel i7 with 8 threads you would want to make sure that you have at least 8 work groups (global_work_size / local_work_size >= 8). If you use a NVIDIA GeForce GTX 1060 with 1280 CUDA Cores you would want to have at least 1280 work groups. But never at the cost of having a local_work_size of less than 32 which is more important!

If you are having more work groups than your hardware has threads that does not matter, they will be processed sequentially. Hence for most applications you can always set your local_work_size to 32/64. The only exception is if you require synchronization among more than work items. E.g. barriers only work inside work groups but not among different work groups. An example: If you need to to sum up chunks of 1024 values before being able to proceed with your algorithm you would need to set your local_work_size to 1024 for the barrier to work as desired.

(Q2) Could some one explain the difference if I set local work size = 1,1 between local work size = 4000,3000 ?

Both, the global_work_size and the local_work_size can have more than one dimension. If this is used or not solely depends on the preference of the programmer. All algorithms can be implemented in one dimension as well and the number of work groups is calculated by multiplying the dimensions, e.g. if your global_work_size is 20*20 and your local_work_size is 10*10 you would run the program with (20*20) / (10*10) = 400 work groups.

I personally like to use the dimensions if I am processing data which has multiple dimensions. Imagine your input is a two-dimensional image, you could simply use its width and height as global_work_size (e.g. 1024 * 1024) and the local_work_size accordingly (e.g. 32 * 32). In your code you could then use the following indices:

int x = get_global_id(0);
int y = get_global_id(1);
input_array[x][y]++;   // your data processing


问:
Azure function Skype bot output binding
I'm building a bot which should receive message from azure function and display that message to the user.

In this page there is the documentation for bindings of all azure services, but the bot output binding isn't documented.

I know that the output binding can be created setting the configuration from bindings.json and using parameter out BotMessage message in the function as described here, but this is the approach when developing functions with C# scripts. Instead I'm using .NET class libraries.

How can I achieve the ouput binding using .NET class libraries?

答:
Install the following NuGet package : Microsoft.Azure.WebJobs.Extensions.BotFramework (check Include prerelease if you don't see it in Visual Studio 2017).

Then you should be able to mark your output parameter with corresponding binding attribute:

[Bot(BotId = "...")] out BotMessage message
```

Title: Azure function Skype bot output binding


问:
Why are there Debug & Release builds for .Net, but not for Java?
In .Net, you can specifically compile your projects under "Debug" or "Release" settings, Release having more optimizations. I know that this is deemed unnecessary in Java, because the jitter does these optimizations. What is the reason for the difference? (meaning, why is a pre-"jitter" compilation required/helpful)

Why is it deemed necessary in .Net/CLR, but not in Java/JDK?

答:
Earlier Java compilers had an -O flag to enable (source code) compilation optimizations. Since JDK 1.2, the -O flag had no effect and I believe the flag was removed with JDK 1.4. As the Java runtime improved, it probably turned more and more reasonable to delegate the optimization to the JRE, since the source code compiler has absolutely no knowledge about the hardware, which will eventually execute the code.

Articles like this one and the documentation of the csc /optimize flag indicate that the optimization has very little effect (if any at all?) on the actual generation of the CLR code. The /optimize flag does however set a flag in the compiled assembly, which controls the level of optimization allowed to be applied by the runtime. I haven't tried it, but I"ve read that runtime optimized code is not necessarily debuggable, although debug information is included (the /optimize and /debug flags can be enabled or disabled independently for the C# compiler).

Ι don't really see the point in controlling the runtime optimization level at compile time. The Java runtime has several detailed options to control runtime performance and optimization, but these must be defined when starting the JRE and not at compile time.

ContentLicense: CC BY-SA 2.5


问:
502 Bad Gateway with nginx | Google App Engine | Node JS
I am hosting the web app on Google Cloud Platform with App Engine and I am using ExpressJS and MongoDB, which is hosted on mLab.

Everything worked well until 1/1/2017. I had vm:true before and now was forced to change the env to flex. Now I am getting 502 bad gateway error with nginx. App engine doesn't allow us to change the nginx config file.

I had tried the suggestion from this post: Google App Engine 502 (Bad Gateway) with NodeJS but still doesn't work.

For some reason, I have another app with exactly the same setting on app engine and it works perfectly.

Any suggestion will be greatly appreciated. Thank you.

答:
I had the same problem with Express. What solved it for me was to not provide an IP address for the app.

So my old code would be:

```<code>var ip = "127.0.0.1";
var port = "8080";
var server = http.createServer(app);
server.listen(port, ip);
</code>```

This would result in a 502 in app engine.

Removing the ip was the solution for me.

```<code>server.listen(port);
</code>```

Body:
I had the same problem with Express. What solved it for me was to not provide an IP address for the app.

So my old code would be:

var ip = "127.0.0.1";
var port = "8080";
var server = http.createServer(app);
server.listen(port, ip);

This would result in a 502 in app engine.

Removing the ip was the solution for me.

server.listen(port);


问:
Is checking for true explicity bad by design?
Is it considered bad to explicitly check for the boolean true. Would it be better to do a simple if(success) ?

I've seen various jokes made about how if (someBoolean === true) is horrible code in a strongly typed language but is it also considered bad in weakly typed languages?

This would apply for any weakly typed language that does type coercion on an if statement.

A specific example would be :

```<code>var onSuccess = function (JSONfromServer) {
    // explicitly check for the boolean value `true`
    if (JSONfromServer === true) {
         // do some things
    }
}

// pass it to an ajax as a callback
doSomeAjax(onSuccess);
</code>```

[Edit]

In this particular case the success variable is any valid JSON returned from a server. So it could be anything. if its the boolean true then a success happened. If it's some error handling object then it will be handled. If it's something else then it will probably be handled quietly.

The question was is getting the server to return true as JSON and checking for a good way to handle the case where the action succeeded.

I wanted to avoid being specific to JavaScript & AJAX though.

答:
Generally, you expect boolean variable names like:

```<code>success, enabled, pass
</code>```

to have a true value. So

```<code>if(success) //or

if(enabled) //or

if(pass) //or

if(enabled) //or
</code>```

is understandably and logically readable. But if you have variables like:

```<code>result, status, port1.bit7
</code>```

it is better to write:

```<code>if(result == true) //or

if(status == false) //or

if(port1.bit7 == true)
</code>```

because it is easily understood in that way than the example below:

```<code>if(result)
{
  ....
}
</code>```

Readability is maintainability.

Body:
Is it considered bad to explicitly check for the boolean true. Would it be better to do a simple if(success) ?

I've seen various jokes made about how if (someBoolean === true) is horrible code in a strongly typed language but is it also considered bad in weakly typed languages?

This would apply for any weakly typed language that does type coercion on an if statement.

A specific example would be :

var onSuccess = function (JSONfromServer) {
    // explicitly check for the boolean value `true`
    if (JSONfromServer === true) {
         // do some things
    }
}

// pass it to an ajax as a callback
doSomeAjax(onSuccess);

[Edit]

In this particular case the success variable is any valid JSON returned from a server. So it could be anything. if its the boolean true then a success happened. If it's some error handling object then it will be handled. If it's something else then it will probably be handled quietly.

The question was is getting the server to return true as JSON and checking for a good way to handle the case where the action succeeded.

I wanted to avoid being specific to JavaScript & AJAX though.

Body:
Generally, you expect boolean variable names like:

success, enabled, pass

to have a true value. So

if(success) //or

if(enabled) //or

if(pass) //or

if(enabled) //or

is understandably and logically readable. But if you have variables like:

result, status, port1.bit7

it is better to write:

if(result == true) //or

if(status == false) //or

if(port1.bit7 == true)

because it is easily understood in that way than the example below:

if(result)
{
  ....
}

Readability is maintainability.


问:
Difference between RxJava API and the Java 9 Flow API
It seems on every iteration of Java for the last few major releases, there are consistently new ways to manage concurrent tasks.

In Java 9, we have the Flow API which resembles the Flowable API of RxJava but with Java 9 has a much simpler set of classes and interfaces.

Java 9

Has a Flow.Publisher, Flow.Subscriber, Flow.Processor, Flow.Subscription, and SubmissionPublisher, and that's about it.

RxJava

Has whole packages of Flow API-like classes, i.e. io.reactivex.flowables, io.reactivex.subscribers, io.reactivex.processors, io.reactivex.observers, and io.reactivex.observables which seem to do something similar.

What are the main differences between these two libraries? Why would someone use the Java 9 Flow library over the much more diverse RxJava library or vice versa?

答:
"What are the main differences between these two libraries?"

As you noted yourself, the Java 9 library is much more basic and basically serves as a general API for reactive streams instead of a full-fledged solution.

"Why would someone use the Java 9 Flow library over the much more diverse RxJava library or vice versa?"

Well, for the same reason people use basic library constructs over libraries - one less dependency to manage. Also, due to the fact that the Flow API in Java 9 is more general, it is less constrained by the specific implementation.


问:
Is there any generic Parse() function that will convert a string to any type using parse?
I want to convert a string to a generic type like int or date or long based on the generic return type.

Basically a function like Parse<T>(String) that returns an item of type T.

For example if a int was passed the function should do int.parse internally.

答:
There are a couple of conventions in the .NET to convert objects of one type to another.

Convert.ChangeType if the type implements IConvertible

TypeDescriptor.GetConverter if the type has a TypeConverterAttribute

But these methods are much slower than your typical T.Parse(string), cause boxing and involve lots of allocations each time you want to convert a single value.

For ValueString, I chose to find a suitable, static parsing method of the type using reflection, build a lambda expression calling it and cache the compiled delegate for future use (See this answer for an example).

It also fallbacks to the ways I mentioned above if the type doesn't have a suitable parsing method (See the performance section in the readme).

```<code>var v = new ValueString("15"); // struct
var i = v.As<int>(); // Calls int.Parse.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There are a couple of conventions in the .NET to convert objects of one type to another.

Convert.ChangeType if the type implements IConvertible

TypeDescriptor.GetConverter if the type has a TypeConverterAttribute

But these methods are much slower than your typical T.Parse(string), cause boxing and involve lots of allocations each time you want to convert a single value.

For ValueString, I chose to find a suitable, static parsing method of the type using reflection, build a lambda expression calling it and cache the compiled delegate for future use (See this answer for an example).

It also fallbacks to the ways I mentioned above if the type doesn't have a suitable parsing method (See the performance section in the readme).

var v = new ValueString("15"); // struct
var i = v.As<int>(); // Calls int.Parse.


问:
SQL : Multiple left joins with similar tables
I have the following tables:

```<code>TABLE A
id
info

TABLE B
f_id
question
choices

TABLE C
f_id
question
lines
</code>```

The id from the Table A always match a f_id from either Table B or C, but never both. I want to join Table B and Table C on table A only when it matches so I would get a table with the following columns :

```<code>id |   info   |   question   | choices | lines
</code>```

where all rows are filled in the question column, some are NULL in the column choices and some are NULL in the column lines.

What I tried is to do two consecutive left joins, but the second one overrides the first so all the rows that doesn't match in Table C (second left join) get a NULL value in the question column.

Is there a way to do a query that will not override previously joined data with NULL values? I'm working with Laravel Eloquent, so any of raw SQL or Eloquent Query would help me.

答:
You could use UNION to combine two different queries.

```<code>SELECT
    `id`, `info`, `question`, `choices` AS `lines`
FROM
    `TABLE_A`  INNER JOIN
    `TABLE_B` ON `TABLE_A`.`id` = `TABLE_B`.`f_id`

UNION

SELECT
    `id`, `info`, `question`, `lines`
FROM
    `TABLE_A` INNER JOIN
    `TABLE_C` ON `TABLE_A`.`id` = `TABLE_C`.`f_id`
</code>```

Make sure to use JOIN or INNER JOIN (JOIN defaults to INNER JOIN on MySQL) AND not LEFT JOIN, RIGHT JOIN, OUTER JOIN otherwise you'll end up with partially filled results.

Body:
I have the following tables:

TABLE A
id
info

TABLE B
f_id
question
choices

TABLE C
f_id
question
lines

The id from the Table A always match a f_id from either Table B or C, but never both. I want to join Table B and Table C on table A only when it matches so I would get a table with the following columns :

id |   info   |   question   | choices | lines

where all rows are filled in the question column, some are NULL in the column choices and some are NULL in the column lines.

What I tried is to do two consecutive left joins, but the second one overrides the first so all the rows that doesn't match in Table C (second left join) get a NULL value in the question column.

Is there a way to do a query that will not override previously joined data with NULL values? I'm working with Laravel Eloquent, so any of raw SQL or Eloquent Query would help me.

Body:
You could use UNION to combine two different queries.

SELECT
    `id`, `info`, `question`, `choices` AS `lines`
FROM
    `TABLE_A`  INNER JOIN
    `TABLE_B` ON `TABLE_A`.`id` = `TABLE_B`.`f_id`

UNION

SELECT
    `id`, `info`, `question`, `lines`
FROM
    `TABLE_A` INNER JOIN
    `TABLE_C` ON `TABLE_A`.`id` = `TABLE_C`.`f_id`

Make sure to use JOIN or INNER JOIN (JOIN defaults to INNER JOIN on MySQL) AND not LEFT JOIN, RIGHT JOIN, OUTER JOIN otherwise you'll end up with partially filled results.


问:
Updating values in a static html file
I have searched for an answer for this question but cannot find anything that relates directly to the requirement.  Perhaps i'm asking the wrong question and someone could advise how best to do this.

Requirement: There is a static HTML file sitting in a file system with values such  as latitude / longitude.  An integration tool receives updated lat/lng values every 2 minutes and these need to be updated in the HTML file so the web page updates a marker with the new co-ords. The integration tool is capable of parsing the html file, opening it for read or replacing it entirely, for example.

Question: How best should this be achieved?

For example,

I thought of parameterising lat/lng in the html file then using java script or other coding language to update the variables using the data from the integration tool? For info, the integration tool has java, php and other functionality available to parse the html file and update it, etc.

static html before: {lat:12.1234, lng:-12.1234}

static html after: {$lat, $lng}

Open file for read, replace the variables with the updated values then save / close the file.

Using (which technique?) the integration tool would update the above values in the html file.

Is there a better or standard way to do this?

Any guidance would be appreciated.

Thanks,

GR

答: If your integration tool is making an API call to external server and retrieving the lat/lng and then updating HTML file, then I suggest you to make AJAX call from JavaScript and update the lat/lng in HTML at runtime on browser. If there is CORS issue then you can create your on API/Handler in PHP which can be invoked via AJAX call from JavaScript.</p>

Title: Updating values in a static html file


问:
"the label [5] is not in the [index]" while duplicating rows
I'm trying to reformat a CSV to turn each month column into a separate row per record (essentially rotating it), i.e.,:

Into:

To do this, I thought the best way would be to:

loop through each row, loop through for each month column (Jan-17, Feb-17, etc...), then duplicate the row.

Then insert the month and totals into Date and Totals columns.

Then remove that record that was duplicated and start where the index left off (I.e., after 5 record loops for each date, the index to start on would be 5).

Then when all rows are duplicated, remove, the month columns (Jan-17, Feb-17, etc...)

It does it for the first data row (i.e., brand1), but after the first outer loop completes, it breaks with:

the label [5] is not in the [index]

```<code>df['date'] = ''
df['totals'] = 0
months = ['Jan-17', 'Feb-17', 'Mar-17', 'Apr-17', 'May-17']

dropRowIndex = 0
nextDuplicateRowStartIndex = 0
totalRows = df.shape[0]

for i in range(0, totalRows):
    print('--------------')
    print(df)
    for col in df:
        if col in months:
            # Insert a row above 0th index with 0th row's values
            # Duplicate the row at this index for each month
            # Then move on to the next "row", which would be the latest index count
            df.loc[nextDuplicateRowStartIndex-1] = df.loc[nextDuplicateRowStartIndex].values
            df.loc[nextDuplicateRowStartIndex-1, 'date'] = col
            df.loc[nextDuplicateRowStartIndex-1, 'totals'] = df.loc[nextDuplicateRowStartIndex-1][col]

            df.index = df.index + 1
            df = df.sort_index()
            dropRowIndex += 1

    # Drop duplicated row by index
    df.drop(dropRowIndex, inplace=True)
    nextDuplicateRowStartIndex = dropRowIndex

# Remove months columns
for col in df:
    if col in months:
        df = df.drop(col, 1)
</code>```

Terminal output:

```<code>-------------- INITIAL DATA FRAME:
    brand  Jan-17  Feb-17  Mar-17  Apr-17  May-17 date  totals
0  brand1     222     333     444     555     666            0
1  brand2    7777    8888    9999    1010    1111            0
2  brand3   12121   13131   14141   15151   16161            0
-------------- DATA FRAME AFTER FIRST OUTER LOOP (ROW) ITERATION:
    brand  Jan-17  Feb-17  Mar-17  Apr-17  May-17    date  totals
0  brand1     222     333     444     555     666  May-17     666
1  brand1     222     333     444     555     666  Apr-17     555
2  brand1     222     333     444     555     666  Mar-17     444
3  brand1     222     333     444     555     666  Feb-17     333
4  brand1     222     333     444     555     666  Jan-17     222
6  brand2    7777    8888    9999    1010    1111               0
7  brand3   12121   13131   14141   15151   16161               0
Traceback (most recent call last):
  File "/Users/danielturcotte/Sites/project/env/lib/python3.6/site-packages/pandas/core/indexing.py", line 1506, in _has_valid_type
    error()
  File "/Users/danielturcotte/Sites/project/env/lib/python3.6/site-packages/pandas/core/indexing.py", line 1501, in error
    axis=self.obj._get_axis_name(axis)))
KeyError: 'the label [5] is not in the [index]'
</code>```

ERROR

KeyError: 'the label [5] is not in the [index]'

One thought I had was because I'm using .loc[index], where index is an integer, perhaps .loc doesn't work with integers, but .iloc[] does. If I do

```<code>df.iloc[nextDuplicateRowStartIndex-1] = df.iloc[nextDuplicateRowStartIndex].values
</code>```

I get ERROR:

ValueError: labels [10] not contained in axis

And the terminal output produces NaNs:

```<code>    brand  Jan-17  Feb-17  Mar-17  Apr-17  May-17    date  totals
0     NaN     NaN     NaN     NaN     NaN     NaN  May-17     NaN
1     NaN     NaN     NaN     NaN     NaN     NaN  Apr-17     NaN
2     NaN     NaN     NaN     NaN     NaN     NaN  Mar-17     NaN
3     NaN     NaN     NaN     NaN     NaN     NaN  Feb-17     NaN
4     NaN     NaN     NaN     NaN     NaN     NaN  Jan-17     NaN
6  brand2  7777.0  8888.0  9999.0  1010.0  1111.0             0.0
7     NaN     NaN     NaN     NaN     NaN     NaN  Apr-17     NaN
</code>```

Though I'm not convinced this is the issue as both print(df.iloc[0]) and print(df.loc[0]) yield the same results (even though I'm accessing loc[0] with an integer).

Doing melt:

答:
You can use melt for this. It allows you to select a number of ID columns and value columns. In your case, the value columns are everything apart from 'brand', so we can ignore that parameter. As such, you can do everything in one line:

```<code>import pandas as pd

df = pd.DataFrame({
    'brand': ['brand1', 'brand2', 'brand3'],
    'Jan-17': [22, 232, 324],
    'Feb-17': [333, 424, 999]
    # ...
})

rearranged = pd.melt(df, id_vars=['brand'], var_name='Date',
                     value_name='Total')

print(rearranged)
</code>```

This prints:

```<code>    brand    Date  Total
0  brand1  Feb-17    333
1  brand2  Feb-17    424
2  brand3  Feb-17    999
3  brand1  Jan-17     22
4  brand2  Jan-17    232
5  brand3  Jan-17    324
</code>```

Body:
I'm trying to reformat a CSV to turn each month column into a separate row per record (essentially rotating it), i.e.,:

Into:

To do this, I thought the best way would be to:

loop through each row, loop through for each month column (Jan-17, Feb-17, etc...), then duplicate the row.

Then insert the month and totals into Date and Totals columns.

Then remove that record that was duplicated and start where the index left off (I.e., after 5 record loops for each date, the index to start on would be 5).

Then when all rows are duplicated, remove, the month columns (Jan-17, Feb-17, etc...)

It does it for the first data row (i.e., brand1), but after the first outer loop completes, it breaks with:

the label [5] is not in the [index]

df['date'] = ''
df['totals'] = 0
months = ['Jan-17', 'Feb-17', 'Mar-17', 'Apr-17', 'May-17']

dropRowIndex = 0
nextDuplicateRowStartIndex = 0
totalRows = df.shape[0]

for i in range(0, totalRows):
    print('--------------')
    print(df)
    for col in df:
        if col in months:
            # Insert a row above 0th index with 0th row's values
            # Duplicate the row at this index for each month
            # Then move on to the next "row", which would be the latest index count
            df.loc[nextDuplicateRowStartIndex-1] = df.loc[nextDuplicateRowStartIndex].values
            df.loc[nextDuplicateRowStartIndex-1, 'date'] = col
            df.loc[nextDuplicateRowStartIndex-1, 'totals'] = df.loc[nextDuplicateRowStartIndex-1][col]

            df.index = df.index + 1
            df = df.sort_index()
            dropRowIndex += 1

    # Drop duplicated row by index
    df.drop(dropRowIndex, inplace=True)
    nextDuplicateRowStartIndex = dropRowIndex

# Remove months columns
for col in df:
    if col in months:
        df = df.drop(col, 1)

Terminal output:

-------------- INITIAL DATA FRAME:
    brand  Jan-17  Feb-17  Mar-17  Apr-17  May-17 date  totals
0  brand1     222     333     444     555     666            0
1  brand2    7777    8888    9999    1010    1111            0
2  brand3   12121   13131   14141   15151   16161            0
-------------- DATA FRAME AFTER FIRST OUTER LOOP (ROW) ITERATION:
    brand  Jan-17  Feb-17  Mar-17  Apr-17  May-17    date  totals
0  brand1     222     333     444     555     666  May-17     666
1  brand1     222     333     444     555     666  Apr-17     555
2  brand1     222     333     444     555     666  Mar-17     444
3  brand1     222     333     444     555     666  Feb-17     333
4  brand1     222     333     444     555     666  Jan-17     222
6  brand2    7777    8888    9999    1010    1111               0
7  brand3   12121   13131   14141   15151   16161               0
Traceback (most recent call last):
  File "/Users/danielturcotte/Sites/project/env/lib/python3.6/site-packages/pandas/core/indexing.py", line 1506, in _has_valid_type
    error()
  File "/Users/danielturcotte/Sites/project/env/lib/python3.6/site-packages/pandas/core/indexing.py", line 1501, in error
    axis=self.obj._get_axis_name(axis)))
KeyError: 'the label [5] is not in the [index]'

ERROR

KeyError: 'the label [5] is not in the [index]'

One thought I had was because I'm using .loc[index], where index is an integer, perhaps .loc doesn't work with integers, but .iloc[] does. If I do

df.iloc[nextDuplicateRowStartIndex-1] = df.iloc[nextDuplicateRowStartIndex].values

I get ERROR:

ValueError: labels [10] not contained in axis

And the terminal output produces NaNs:

    brand  Jan-17  Feb-17  Mar-17  Apr-17  May-17    date  totals
0     NaN     NaN     NaN     NaN     NaN     NaN  May-17     NaN
1     NaN     NaN     NaN     NaN     NaN     NaN  Apr-17     NaN
2     NaN     NaN     NaN     NaN     NaN     NaN  Mar-17     NaN
3     NaN     NaN     NaN     NaN     NaN     NaN  Feb-17     NaN
4     NaN     NaN     NaN     NaN     NaN     NaN  Jan-17     NaN
6  brand2  7777.0  8888.0  9999.0  1010.0  1111.0             0.0
7     NaN     NaN     NaN     NaN     NaN     NaN  Apr-17     NaN

Though I'm not convinced this is the issue as both print(df.iloc[0]) and print(df.loc[0]) yield the same results (even though I'm accessing loc[0] with an integer).

Doing melt:

Body:
You can use melt for this. It allows you to select a number of ID columns and value columns. In your case, the value columns are everything apart from 'brand', so we can ignore that parameter. As such, you can do everything in one line:

import pandas as pd

df = pd.DataFrame({
    'brand': ['brand1', 'brand2', 'brand3'],
    'Jan-17': [22, 232, 324],
    'Feb-17': [333, 424, 999]
    # ...
})

rearranged = pd.melt(df, id_vars=['brand'], var_name='Date',
                     value_name='Total')

print(rearranged)

This prints:

    brand    Date  Total
0  brand1  Feb-17    333
1  brand2  Feb-17    424
2  brand3  Feb-17    999
3  brand1  Jan-17     22
4  brand2  Jan-17    232
5  brand3  Jan-17    324


问:
Creating a web farm in PowerShell
I'm trying to automate the creation of a server farm in PowerShell. Through manual creation I've got the following XML:

```<code><webFarms>
    <webFarm name="alwaysup" enabled="true">
        <server address="alwaysup-blue" enabled="true">
            <applicationRequestRouting httpPort="8001" />
        </server>
        <server address="alwaysup-green" enabled="true">
            <applicationRequestRouting httpPort="8002" />
        </server>
        <applicationRequestRouting>
            <healthCheck url="http://alwaysup/up.html" interval="00:00:05" responseMatch="up" />
        </applicationRequestRouting>
    </webFarm>
    <applicationRequestRouting>
        <hostAffinityProviderList>
            <add name="Microsoft.Web.Arr.HostNameRoundRobin" />
        </hostAffinityProviderList>
    </applicationRequestRouting>
</webFarms>
</code>```

Trying to do this via PS proves troublesome however: as far as I can tell there is no dedicated API to do this through (WebFarmSnapin is meant for an older version).

I have shifted my attention to IIS Administration Cmdlets but only got it half working.

The code that I have:

```<code>#####
# Overwriting the server farm
#####

Write-Host "Overwriting the server farm $($webFarmName)"

$webFarm = @{};
$webFarm["name"] = 'siteFarm'

Set-WebConfiguration "/webFarms" -Value $webFarm

#####
# Adding the servers
#####

Write-Host "Adding the servers"

$blueServer = @{}
$blueServer["address"] = 'site-blue'
$blueServer["applicationRequestRouting"] = @{}

$greenServer = @{}
$greenServer["address"] = 'site-green'
$greenServer["applicationRequestRouting"] = @{}

$servers = @($blueServer, $greenServer)

Add-WebConfiguration -Filter "/webFarms/webFarm[@name='siteFarm']" -Value $servers

#####
# Adding routing
#####

Write-Host "Adding the routing configurations"

$blueServerRouting = @{}
$blueServerRouting["httpPort"] = "8001"
Add-WebConfiguration -Filter "/webFarms/webFarm[@name='siteFarm']/server[@address='site-blue']" -Value $blueServerRouting
</code>```

This generates

```<code><webFarms>
    <webFarm name="siteFarm">
        <server address="site-blue" />
        <server address="site-green" />
    </webFarm>
    <applicationRequestRouting>
        <hostAffinityProviderList>
            <add name="Microsoft.Web.Arr.HostNameRoundRobin" />
        </hostAffinityProviderList>
    </applicationRequestRouting>
</webFarms>
</code>```

As you can see it's missing the port related to the routing. And I haven't even started with trying to add the healthcheck at this point.

What am I doing wrong? Is there some Cmdlet that I haven't found which makes this easier?

Related but without much of a useful answer (the PowerShell tab with generated code stays empty).

答:
Seeing as nobody has come up with a solution: I've taken the very simple workaround of just editing the XML directly instead of going through an API.

The actual webfarm functionality I haven't got to work yet but it seems like all the parts are there at least.

An example of manipulating the XML can be this:

```<code>$configPath = "C:\Windows\System32\inetsrv\config\applicationHost.config"
$configXml = [xml] (type $configPath)

[xml] $webFarmXml = @"
<webFarms>
    <webFarm name="siteFarm" enabled="true">
        <server address="site-blue" enabled="true">
            <applicationRequestRouting httpPort="$bluePort" />
        </server>
        <server address="site-green" enabled="true">
            <applicationRequestRouting httpPort="$greenPort" />
        </server>
        <applicationRequestRouting>
            <healthCheck url="http://mySite/up.html" interval="00:00:05" responseMatch="up" />
            <protocol reverseRewriteHostInResponseHeaders="true">
                <cache enabled="false" queryStringHandling="NoCaching" />
            </protocol>
        </applicationRequestRouting>
    </webFarm>
    <applicationRequestRouting>
        <hostAffinityProviderList>
            <add name="Microsoft.Web.Arr.HostNameRoundRobin" />
        </hostAffinityProviderList>
    </applicationRequestRouting>
</webFarms>
"@

$configXml.configuration.AppendChild($configXml.ImportNode($webFarmXml.webFarms, $true))
$configXml.Save($configPath)
</code>```

Title: Creating a web farm in PowerShell

Body:
I'm trying to automate the creation of a server farm in PowerShell. Through manual creation I've got the following XML:

<webFarms>
    <webFarm name="alwaysup" enabled="true">
        <server address="alwaysup-blue" enabled="true">
            <applicationRequestRouting httpPort="8001" />
        </server>
        <server address="alwaysup-green" enabled="true">
            <applicationRequestRouting httpPort="8002" />
        </server>
        <applicationRequestRouting>
            <healthCheck url="http://alwaysup/up.html" interval="00:00:05" responseMatch="up" />
        </applicationRequestRouting>
    </webFarm>
    <applicationRequestRouting>
        <hostAffinityProviderList>
            <add name="Microsoft.Web.Arr.HostNameRoundRobin" />
        </hostAffinityProviderList>
    </applicationRequestRouting>
</webFarms>

Trying to do this via PS proves troublesome however: as far as I can tell there is no dedicated API to do this through (WebFarmSnapin is meant for an older version).

I have shifted my attention to IIS Administration Cmdlets but only got it half working.

The code that I have:

#####
# Overwriting the server farm
#####

Write-Host "Overwriting the server farm $($webFarmName)"

$webFarm = @{};
$webFarm["name"] = 'siteFarm'

Set-WebConfiguration "/webFarms" -Value $webFarm

#####
# Adding the servers
#####

Write-Host "Adding the servers"

$blueServer = @{}
$blueServer["address"] = 'site-blue'
$blueServer["applicationRequestRouting"] = @{}

$greenServer = @{}
$greenServer["address"] = 'site-green'
$greenServer["applicationRequestRouting"] = @{}

$servers = @($blueServer, $greenServer)

Add-WebConfiguration -Filter "/webFarms/webFarm[@name='siteFarm']" -Value $servers

#####
# Adding routing
#####

Write-Host "Adding the routing configurations"

$blueServerRouting = @{}
$blueServerRouting["httpPort"] = "8001"
Add-WebConfiguration -Filter "/webFarms/webFarm[@name='siteFarm']/server[@address='site-blue']" -Value $blueServerRouting

This generates

<webFarms>
    <webFarm name="siteFarm">
        <server address="site-blue" />
        <server address="site-green" />
    </webFarm>
    <applicationRequestRouting>
        <hostAffinityProviderList>
            <add name="Microsoft.Web.Arr.HostNameRoundRobin" />
        </hostAffinityProviderList>
    </applicationRequestRouting>
</webFarms>

As you can see it's missing the port related to the routing. And I haven't even started with trying to add the healthcheck at this point.

What am I doing wrong? Is there some Cmdlet that I haven't found which makes this easier?

Related but without much of a useful answer (the PowerShell tab with generated code stays empty).

Body:
Seeing as nobody has come up with a solution: I've taken the very simple workaround of just editing the XML directly instead of going through an API.

The actual webfarm functionality I haven't got to work yet but it seems like all the parts are there at least.

An example of manipulating the XML can be this:

$configPath = "C:\Windows\System32\inetsrv\config\applicationHost.config"
$configXml = [xml] (type $configPath)

[xml] $webFarmXml = @"
<webFarms>
    <webFarm name="siteFarm" enabled="true">
        <server address="site-blue" enabled="true">
            <applicationRequestRouting httpPort="$bluePort" />
        </server>
        <server address="site-green" enabled="true">
            <applicationRequestRouting httpPort="$greenPort" />
        </server>
        <applicationRequestRouting>
            <healthCheck url="http://mySite/up.html" interval="00:00:05" responseMatch="up" />
            <protocol reverseRewriteHostInResponseHeaders="true">
                <cache enabled="false" queryStringHandling="NoCaching" />
            </protocol>
        </applicationRequestRouting>
    </webFarm>
    <applicationRequestRouting>
        <hostAffinityProviderList>
            <add name="Microsoft.Web.Arr.HostNameRoundRobin" />
        </hostAffinityProviderList>
    </applicationRequestRouting>
</webFarms>
"@

$configXml.configuration.AppendChild($configXml.ImportNode($webFarmXml.webFarms, $true))
$configXml.Save($configPath)


问:
Next Panorama ID in street view
I have a develop for to get a panoramic photo with a specif longitude-latitude in Street View. With GoogleMaps API, I can get the route (see image) from point A to point B. But I need the next pano_id in that route. How can I get that?

I have this for now. Every black point is a step for the function DirectionDisplay, with the next code:

```<code>for (var i = 0; i < myroute.legs.length; i++) {
                    for (var j = 0; j < myroute.legs[i].steps.length; j++ ){
                      for (var k = 0; k < myroute.legs[i].steps[j].lat_lngs.length; k++ ){
                        var start = myroute.legs[i].steps[j].lat_lngs[k];
                        var coords = start.lat() + '|' + start.lng() ;
                        console.info('cooords',coords);
                    }
                  }
</code>```

I can get the longitude latitude of two points, but i need the longitude latitude of each 2 or 3 mts, (similar when you press the arrow in google street view). Like This Example

[3

EDIT:

I'm getting the Panorama ID with this code:

```<code>sv = new google.maps.StreetViewService();
sv.getPanorama({location: myLatLng, radius: 50}, processSVData);

function processSVData(info, status) {
$.ajax({
              type: 'POST',
              contentType: "application/json; charset=utf-8",
              url: "{{ url_for('download_tiles') }}",
              async: false,
              data: JSON.stringify({pano_id: info.location.pano}),
              success: function(response){
               }

   .... //get little images of panorama I later I build the panorama.
       //I get the panorama with the ID of the panorama.
}
</code>```

For now, I'm getting the Panorama photo in a specific longitude latitude. mylatlng is the variable with the longitude and latitude,

(I'm drawing the red lines manually)

EDIT:

For example: this route in GoogleMaps. The variable myroute.legs[i].steps[j].lat_lngs[k] have 3 longitude - latitude. But in StreetView, I can do 6 clics, from (Brodway,E 4th St) to (Brodway,W 3rd st)

thanks,

答:
Post this answer if someone needs this too.
The wrong it is not a proporty of Googmaps, is a property of StreetView.
StreetView have and object StreetViewPanorama. With that object is possible get the links (arrow with the next panorama ID). so you need to create a StreetViewPanorama objetc.</p>

```<code>var panorama = new StreetViewPanorama...;.
panorama.setPano('some panorama id');
var links = panorama.getLinks();
links[0].getPano(); //will be the next panorama y random direction, or the specified in the POV variable.
</code>```

Title: Next Panorama ID in street view

Body:
I have a develop for to get a panoramic photo with a specif longitude-latitude in Street View. With GoogleMaps API, I can get the route (see image) from point A to point B. But I need the next pano_id in that route. How can I get that?

I have this for now. Every black point is a step for the function DirectionDisplay, with the next code:

for (var i = 0; i < myroute.legs.length; i++) {
                    for (var j = 0; j < myroute.legs[i].steps.length; j++ ){
                      for (var k = 0; k < myroute.legs[i].steps[j].lat_lngs.length; k++ ){
                        var start = myroute.legs[i].steps[j].lat_lngs[k];
                        var coords = start.lat() + '|' + start.lng() ;
                        console.info('cooords',coords);
                    }
                  }

I can get the longitude latitude of two points, but i need the longitude latitude of each 2 or 3 mts, (similar when you press the arrow in google street view). Like This Example

[3

EDIT:

I'm getting the Panorama ID with this code:

sv = new google.maps.StreetViewService();
sv.getPanorama({location: myLatLng, radius: 50}, processSVData);

function processSVData(info, status) {
$.ajax({
              type: 'POST',
              contentType: "application/json; charset=utf-8",
              url: "{{ url_for('download_tiles') }}",
              async: false,
              data: JSON.stringify({pano_id: info.location.pano}),
              success: function(response){
               }

   .... //get little images of panorama I later I build the panorama.
       //I get the panorama with the ID of the panorama.
}

For now, I'm getting the Panorama photo in a specific longitude latitude. mylatlng is the variable with the longitude and latitude,

(I'm drawing the red lines manually)

EDIT:

For example: this route in GoogleMaps. The variable myroute.legs[i].steps[j].lat_lngs[k] have 3 longitude - latitude. But in StreetView, I can do 6 clics, from (Brodway,E 4th St) to (Brodway,W 3rd st)

thanks,

Body:
Post this answer if someone needs this too.
The wrong it is not a proporty of Googmaps, is a property of StreetView.
StreetView have and object StreetViewPanorama. With that object is possible get the links (arrow with the next panorama ID). so you need to create a StreetViewPanorama objetc.

var panorama = new StreetViewPanorama...;.
panorama.setPano('some panorama id');
var links = panorama.getLinks();
links[0].getPano(); //will be the next panorama y random direction, or the specified in the POV variable.


问:
Avoid gnome-terminal close after script execution?
I created a bash script that opens several gnome-terminals, connect to classroom computers via ssh and run a script.

How can I avoid that the gnome-terminal closes after the script is finished? Note that I also want to be able to enter further commands in the terminal.

Here is an example  of my code:

```<code>gnome-terminal -e "ssh root@<ip> cd /tmp && ls"
</code>```

答:
Finally this one works for me:</p>

```<code>gnome-terminal --working-directory=WORK_DIR -x bash -c "COMMAND; bash"
</code>```

Body:
I created a bash script that opens several gnome-terminals, connect to classroom computers via ssh and run a script.

How can I avoid that the gnome-terminal closes after the script is finished? Note that I also want to be able to enter further commands in the terminal.

Here is an example  of my code:

gnome-terminal -e "ssh root@<ip> cd /tmp && ls"

Body:
Finally this one works for me:

gnome-terminal --working-directory=WORK_DIR -x bash -c "COMMAND; bash"


问:
Selenium Chrome WebDriver is opening Setting as default tab asking to reset the setting
Selenium Chrome WebDriver is opening Setting as default tab asking to reset the setting.

答:
The same thing happened with Chrome Version 62.0.3202.94, when the browser automatically updated. It was easily fixed when I updated chromedriver in my automation framework.
Just download new version of chromedriver from: https://sites.google.com/a/chromium.org/chromedriver/downloads
and put it to your Drivers folder in your framework.</p>


问:
What is the advantage of using an INCLUDE column with a SQL Server index?
```<code>CREATE NONCLUSTERED INDEX index_name
    ON <object> ( column [ ASC | DESC ] [ ,...n ] )
    [ INCLUDE ( column_name [ ,...n ] ) ]
    [ WHERE <filter_predicate> ]
</code>```

<p>In the above syntax we will specify non-key columns in the INCLUDE. What is the advantage in specifying non-key columns? </p>

答:
Advantage of Include Index is to avoid size limit .

```<code>SELECT AddressLine1, AddressLine2, City, StateProvinceID, PostalCode
FROM Person.Address
WHERE PostalCode BETWEEN N'98000' and N'99999'
</code>```

Although you could define all columns as key columns, the key size would be 334 bytes.Only criteria we use here is Postalcode , Using Postalcode in the keycolumn and rest on non-key column will improve the performance and also the saves the size .

```<code>CREATE INDEX IX_Address_PostalCode
ON Person.Address (PostalCode)
INCLUDE (AddressLine1, AddressLine2, City, StateProvinceID);
</code>```

Body:
CREATE NONCLUSTERED INDEX index_name
    ON <object> ( column [ ASC | DESC ] [ ,...n ] )
    [ INCLUDE ( column_name [ ,...n ] ) ]
    [ WHERE <filter_predicate> ]

In the above syntax we will specify non-key columns in the INCLUDE. What is the advantage in specifying non-key columns?

Body:
Advantage of Include Index is to avoid size limit .

SELECT AddressLine1, AddressLine2, City, StateProvinceID, PostalCode
FROM Person.Address
WHERE PostalCode BETWEEN N'98000' and N'99999'

Although you could define all columns as key columns, the key size would be 334 bytes.Only criteria we use here is Postalcode , Using Postalcode in the keycolumn and rest on non-key column will improve the performance and also the saves the size .

CREATE INDEX IX_Address_PostalCode
ON Person.Address (PostalCode)
INCLUDE (AddressLine1, AddressLine2, City, StateProvinceID);


答:
At the beginning, there was Rx, version one. It was a language agnostic specification of reactive APIs that has implementations for Java, JavaScript, .NET. Then they improved it and we saw Rx 2. It has implementations for different languages as well. At the time of Rx 2 Spring team was working on Reactor — their own set of reactive APIs.

And then they all thought: why not make a joint effort and create one API to rule them all. That was how Reactive Commons was set up. A joint research effort for building highly optimized reactive streams compliant operators. Current implementors include RxJava2 and Reactor.

At the same time JDK developers realized that reactive stuff is great and worth including in Java. As it is usual in Java world the de facto standard become de jure. Remeber Hibernate and JPA, Joda Time and Java 8 Date/Time API? So what JDK develpers did is extracting the very core of reactive APIs, the most basic part, and making it a standard. That is how j.u.c.Flow was born.

Technically, j.u.c.Flow is much more simpler, it consists only of four simple interfaces, while other libraries provide dozens of classes and hundreds of operators.

I hope, this answers the question "what is the difference between them".

Why would someone choose j.u.c.Flow over Rx? Well, because now it is a standard!

Currently JDK ships with only one implementation of j.u.c.Flow: HTTP/2 API. It is actually an incubating API. But in future we might expect support of it from Reactor, RxJava 2 as well as from other libraries, like reactive DB drivers or even FS IO.

Title: Difference between RxJava API and the Java 9 Flow API

Body:
It seems on every iteration of Java for the last few major releases, there are consistently new ways to manage concurrent tasks.

In Java 9, we have the Flow API which resembles the Flowable API of RxJava but with Java 9 has a much simpler set of classes and interfaces.

Java 9

Has a Flow.Publisher, Flow.Subscriber, Flow.Processor, Flow.Subscription, and SubmissionPublisher, and that's about it.

RxJava

Has whole packages of Flow API-like classes, i.e. io.reactivex.flowables, io.reactivex.subscribers, io.reactivex.processors, io.reactivex.observers, and io.reactivex.observables which seem to do something similar.

What are the main differences between these two libraries? Why would someone use the Java 9 Flow library over the much more diverse RxJava library or vice versa?


问:
I am using the openpyxl library on python on a windows 10 computer and trying to load_workbook with whitespace
I am using the openpyxl library on python 3.5 on a windows 10 computer and trying to load_workbook() an pathname with white space.

I have looked it up online and can't seem to solve this myself. I have included some of my attempts below.

I must be missing something completely, because I can't find anyone else asking about this particular issue with openpyxl.

Any help would be very much appreciated.

My current work around would be to use python to check and possibly rename the file to remove the spaces, but that just seems entirely unnecessary and i might not always have the permissions to do that.

```<code>import openpyxl
from openpyxl import load_workbook
import os

docName = "space book.xlsx"
docNameWithExits = "space^ book.xlsm"
fullPathOfDocument =  "./" + docName
fullPathOfDocumentExtraPar = "'" + "./" + docName + "'"
fullOsPath =  os.path.join("." , docName)
docObject = open(fullPathOfDocument,"rb")

try:
    attempt1 = load_workbook(docName)
    print("worked")
except:
    print("didnt work")

try:
    attempt2 = load_workbook(fullPathOfDocument)
    print("worked")
except:
    print("didnt work")

try:
    attempt3 = load_workbook(fullPathOfDocumentExtraPar)
    print("worked")
except:
    print("didnt work")

try:
    attempt4 = load_workbook(docNameWithExits)
    print("worked")
except:
    print("didnt work")

try:
    attempt5 = load_workbook(fullOsPathvar)
    print("worked")
except:
    print("didnt work")

try:
    attempt6 = load_workbook(docObject)
    print("worked")
except:
    print("The computer has won")
</code>```

Thank you in advance for any help
Regards,
-Nex

答:
openpyxl.load_workbook() can read a path with Whitespace in it. In my fully reproducible example, there's whitespace in the workbook name and the folders.

I'm guessing that the problems occur if you are not preceding your strings with an "r".  The "r" will tell python to treat the given string as a raw string.

```<code>import os
from openpyxl import Workbook
from openpyxl import load_workbook

# Path to be created - please change to your desired folder location
path = r"C:\Users\doe_j\test\python\a path\with spaces"
wb_name = path + r"\space book.xlsx"

if os.path.isdir(path) != True:
    os.makedirs(path)
    print(path, "created!")
elif os.path.isdir(path) != False:
    print(path, "already exists!")

# making a workbook so this example is reproducible
wb = Workbook()
ws = wb.active

ws["A1"] = "Putting some text in"

wb.save(wb_name)

# loading that same workbook
wb = load_workbook(wb_name)
ws = wb.active

ws["A3"] = "Adding Some more text in"

wb.save(wb_name)
</code>```

This example was tested on windows 10, python 3.5 and openpyxl 2.4.7.

Body:
I am using the openpyxl library on python 3.5 on a windows 10 computer and trying to load_workbook() an pathname with white space.

I have looked it up online and can't seem to solve this myself. I have included some of my attempts below.

I must be missing something completely, because I can't find anyone else asking about this particular issue with openpyxl.

Any help would be very much appreciated.

My current work around would be to use python to check and possibly rename the file to remove the spaces, but that just seems entirely unnecessary and i might not always have the permissions to do that.

import openpyxl
from openpyxl import load_workbook
import os

docName = "space book.xlsx"
docNameWithExits = "space^ book.xlsm"
fullPathOfDocument =  "./" + docName
fullPathOfDocumentExtraPar = "'" + "./" + docName + "'"
fullOsPath =  os.path.join("." , docName)
docObject = open(fullPathOfDocument,"rb")

try:
    attempt1 = load_workbook(docName)
    print("worked")
except:
    print("didnt work")

try:
    attempt2 = load_workbook(fullPathOfDocument)
    print("worked")
except:
    print("didnt work")

try:
    attempt3 = load_workbook(fullPathOfDocumentExtraPar)
    print("worked")
except:
    print("didnt work")

try:
    attempt4 = load_workbook(docNameWithExits)
    print("worked")
except:
    print("didnt work")

try:
    attempt5 = load_workbook(fullOsPathvar)
    print("worked")
except:
    print("didnt work")

try:
    attempt6 = load_workbook(docObject)
    print("worked")
except:
    print("The computer has won")

Thank you in advance for any help
Regards,
-Nex

Body:
openpyxl.load_workbook() can read a path with Whitespace in it. In my fully reproducible example, there's whitespace in the workbook name and the folders.

I'm guessing that the problems occur if you are not preceding your strings with an "r".  The "r" will tell python to treat the given string as a raw string.

import os
from openpyxl import Workbook
from openpyxl import load_workbook

# Path to be created - please change to your desired folder location
path = r"C:\Users\doe_j\test\python\a path\with spaces"
wb_name = path + r"\space book.xlsx"

if os.path.isdir(path) != True:
    os.makedirs(path)
    print(path, "created!")
elif os.path.isdir(path) != False:
    print(path, "already exists!")

# making a workbook so this example is reproducible
wb = Workbook()
ws = wb.active

ws["A1"] = "Putting some text in"

wb.save(wb_name)

# loading that same workbook
wb = load_workbook(wb_name)
ws = wb.active

ws["A3"] = "Adding Some more text in"

wb.save(wb_name)

This example was tested on windows 10, python 3.5 and openpyxl 2.4.7.


问:
Access members of unkown template type of derived template class through pointer to base class C++
I need to have a map holding different value types. I achieved that using a derived template class Derived of type T derived from B  and declaring my map using a pointer to the base class Base like so:

```<code>class Base {
    public:
    ~Base(){}
};

template <class T>
class Derived: public Base {
     public:
     Derived(T value) {
          this->value = value;
     }
     T value;
 };

 std::map<std::string, std::shared_ptr<Base>> my_map;

 using KeyValuePair = std::pair<std::string, std::shared_ptr<Base>>;

 my_map.insert(KeyValuePair("foo1",std::make_shared<Derived<int>>(10)));
 my_map.insert(KeyValuePair("foo2",std::make_shared<Derived<double>>(20.0)));
 my_map.insert(KeyValuePair("foo3",std::make_shared<Derived<std::string>>("bla")));
</code>```

I now for example want to print the value of a map entry

```<code> for (auto const& x : my_map)
{
    std::cout << *x.get() << std::endl;
}
</code>```

However, I now have the problem that I cannot access the the members in the Derived class by casting x to Derived, because I don't know the type of the template parameter. So the following is not possible:

```<code>std::shared_ptr<Derived<?>> derived = std::dynamic_cast<Derived<?>>(x);
</code>```

I thought about having a virtual function in the Base class which returns the member, but I don't know the return type, so not an option.

I also don't want to specify several virtual functions for several return types, as the whole point of the code is to avoid copying code and having a "generic map"

However, I don't see another solution besides using some fancy boost magic by returning a streamable boost::any like the following, as this removes any information about the type.

```<code> using streamable_any = boost::type_erasure::any<boost::mpl::vector<
 boost::type_erasure::copy_constructible<>,
 boost::type_erasure::destructible<>,
 boost::type_erasure::ostreamable<>>>;
</code>```

What are the possibilities I have to achieve what I want? I suspect that I need to consider a design change.

答:
Specifically for printing, you can add a single virtual method easily enough:

```<code>class Base {
public:
  virtual ~Base() {}

  virtual std::ostream& print(std::ostream&) const = 0;
  friend std::ostream& operator<<(std::ostream& os, Base const &b) {
    return b.print(os);
  }
};

template <class T>
class Derived: public Base {
  T value;
public:
  Derived(T v) : value(v) {}

  std::ostream& print(std::ostream& os) const override {
      return os << value;
  }
};
</code>```

However, if you need more general access to the value, your options are essentially:

Extract value as Boost.any (by virtual function)

Enumerate all legal types for T, and return a Boost.variant<Ts> (again by virtual function)

Enumerate all legal types and write a Visitor with overloads for each. Then implement a simple virtual visit method in Base and Derived. Note that Derived<T>::apply(Visitor &v) { v.visit(value); } will fail to compile if T doesn't match any overload of visit, and also that you need to take care when the valid types of T have implicit conversions.

You can avoid coupling your code to a pre-defined list of legal Ts by writing a post-hoc visitor. This means manual dispatch, looking up the function to call using std::type_index as your key, and manual casting. It's ugly though.

Or (worst but most flexible) keep the streaming output and just re-parse the value from a stringstream. If you must do this, consider serializing to a well-defined format instead of (or as well as) just writing a pretty human-readable format.

Body:
I need to have a map holding different value types. I achieved that using a derived template class Derived of type T derived from B  and declaring my map using a pointer to the base class Base like so:

class Base {
    public:
    ~Base(){}
};

template <class T>
class Derived: public Base {
     public:
     Derived(T value) {
          this->value = value;
     }
     T value;
 };

 std::map<std::string, std::shared_ptr<Base>> my_map;

 using KeyValuePair = std::pair<std::string, std::shared_ptr<Base>>;

 my_map.insert(KeyValuePair("foo1",std::make_shared<Derived<int>>(10)));
 my_map.insert(KeyValuePair("foo2",std::make_shared<Derived<double>>(20.0)));
 my_map.insert(KeyValuePair("foo3",std::make_shared<Derived<std::string>>("bla")));

I now for example want to print the value of a map entry

 for (auto const& x : my_map)
{
    std::cout << *x.get() << std::endl;
}

However, I now have the problem that I cannot access the the members in the Derived class by casting x to Derived, because I don't know the type of the template parameter. So the following is not possible:

std::shared_ptr<Derived<?>> derived = std::dynamic_cast<Derived<?>>(x);

I thought about having a virtual function in the Base class which returns the member, but I don't know the return type, so not an option.

I also don't want to specify several virtual functions for several return types, as the whole point of the code is to avoid copying code and having a "generic map"

However, I don't see another solution besides using some fancy boost magic by returning a streamable boost::any like the following, as this removes any information about the type.

 using streamable_any = boost::type_erasure::any<boost::mpl::vector<
 boost::type_erasure::copy_constructible<>,
 boost::type_erasure::destructible<>,
 boost::type_erasure::ostreamable<>>>;

What are the possibilities I have to achieve what I want? I suspect that I need to consider a design change.

Body:
Specifically for printing, you can add a single virtual method easily enough:

class Base {
public:
  virtual ~Base() {}

  virtual std::ostream& print(std::ostream&) const = 0;
  friend std::ostream& operator<<(std::ostream& os, Base const &b) {
    return b.print(os);
  }
};

template <class T>
class Derived: public Base {
  T value;
public:
  Derived(T v) : value(v) {}

  std::ostream& print(std::ostream& os) const override {
      return os << value;
  }
};

However, if you need more general access to the value, your options are essentially:

Extract value as Boost.any (by virtual function)

Enumerate all legal types for T, and return a Boost.variant<Ts> (again by virtual function)

Enumerate all legal types and write a Visitor with overloads for each. Then implement a simple virtual visit method in Base and Derived. Note that Derived<T>::apply(Visitor &v) { v.visit(value); } will fail to compile if T doesn't match any overload of visit, and also that you need to take care when the valid types of T have implicit conversions.

You can avoid coupling your code to a pre-defined list of legal Ts by writing a post-hoc visitor. This means manual dispatch, looking up the function to call using std::type_index as your key, and manual casting. It's ugly though.

Or (worst but most flexible) keep the streaming output and just re-parse the value from a stringstream. If you must do this, consider serializing to a well-defined format instead of (or as well as) just writing a pretty human-readable format.


问:
Calling methods from PCL to android - Xamarin
How can I call method defined in my PCL project to Android project ?

I have a method DoWork() defined in my PCL and I want this method to continuously be run in a service defined in my android project as follows:

```<code>public class BroadcastService : Service
{
    IBinder mBinder;

    [return: GeneratedEnum]
    public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
    {

        Toast.MakeText(this, "BroadcastService is running ", ToastLength.Long).Show();

        Task.Run(() =>
        {
            var counter = new Counter();
            counter.DoWork().Wait();
        });

        base.OnStartCommand(intent, flags, startId);
        return StartCommandResult.Sticky;

    }
</code>```

The toast is appearing.
However, the DoWork() is not running. Can someone enlighten what is wrong please?

The full method signature for DoWork() :

```<code> private async void DoWork()
        {
       StartDetect();

            Device.StartTimer(TimeSpan.FromSeconds(20), () =>
                {
                    _foundTags = _truck.GetAvailableTrucks();

                    DoWork();

                });
        }
</code>```

答:
I think you can use a MessagingCenter. You can try something like this

public class BroadcastService : Service
{
    IBinder mBinder;

```<code>[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{

    Toast.MakeText(this, "BroadcastService is running ", ToastLength.Long).Show();

    Xamarin.Forms.MessagingCenter.Send<App>((App)Xamarin.Forms.Application.Current, "dowork");

    base.OnStartCommand(intent, flags, startId);
    return StartCommandResult.Sticky;

}
</code>```

and in your PCL project

```<code>    protected override void OnStart()
    {
        MessagingCenter.Subscribe<App>(this, "dowork", (sender) =>
        {
            // Do something here

        });
        // Handle when your app starts
    }
</code>```

Body:
How can I call method defined in my PCL project to Android project ?

I have a method DoWork() defined in my PCL and I want this method to continuously be run in a service defined in my android project as follows:

public class BroadcastService : Service
{
    IBinder mBinder;

    [return: GeneratedEnum]
    public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
    {

        Toast.MakeText(this, "BroadcastService is running ", ToastLength.Long).Show();

        Task.Run(() =>
        {
            var counter = new Counter();
            counter.DoWork().Wait();
        });

        base.OnStartCommand(intent, flags, startId);
        return StartCommandResult.Sticky;

    }

The toast is appearing.
However, the DoWork() is not running. Can someone enlighten what is wrong please?

The full method signature for DoWork() :

 private async void DoWork()
        {
       StartDetect();

            Device.StartTimer(TimeSpan.FromSeconds(20), () =>
                {
                    _foundTags = _truck.GetAvailableTrucks();

                    DoWork();

                });
        }

Body:
I think you can use a MessagingCenter. You can try something like this

public class BroadcastService : Service
{
    IBinder mBinder;

[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{

    Toast.MakeText(this, "BroadcastService is running ", ToastLength.Long).Show();

    Xamarin.Forms.MessagingCenter.Send<App>((App)Xamarin.Forms.Application.Current, "dowork");

    base.OnStartCommand(intent, flags, startId);
    return StartCommandResult.Sticky;

}

and in your PCL project

    protected override void OnStart()
    {
        MessagingCenter.Subscribe<App>(this, "dowork", (sender) =>
        {
            // Do something here

        });
        // Handle when your app starts
    }


问:
Override the jHipster JhiAlertErrorComponent http error listener
We have a front end jHipster application (v.4.8.0) which uses Angular 4. There is an alert-error-component.ts (JhiAlertErrorComponent) which includes an http error listener which intercepts all errors returned in Http responses throughout the application.

See here: https://github.com/jhipster/jhipster-sample-app-ng2/blob/master/src/main/webapp/app/shared/alert/alert-error.component.ts

This displays a little error box at the top of the window which is perfect in most cases but we now have some cases where we want to perform some custom behaviour on http errors.

Is there an elegant way to override the http error listener in this error component and instead handle the error locally for specific cases?

答:
I was able to solve this by using an HTTP header to distinguish requests where I want any HTTP error responses not to be handled by the JHipster alert error component.

This works by using a filter as described here:
automatically add header to every response

This filter is used to detect the chosen header on the request and put it on the response for any request coming through your server.

You can then check for this headers existence in the alert-error-component.ts and skip the error handling if it is present.


问:
AEM custom logs creation from scripts
we are automating the AEM configurations, we have a requirement for creating a custom log file. current Manual step followed is
login to AEM Felix console -> Sling -> log support ->Add new logger
parameters updated are log level, log file and logger.

is there a way to automate this log creation ? Please share your inputs.

Thanks in advance,

答:
You can do this by configuring OSGI content nodes or by creating OSGI config files.  For instance, I created an OSGI config node at this location:

```<code>/apps/cq/config.publish/org.apache.sling.commons.log.LogManager.factory.config-util.xml
</code>```

That file has contents such as this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="sling:OsgiConfig"
    org.apache.sling.commons.log.file="logs/util.log"
    org.apache.sling.commons.log.level="debug"
    org.apache.sling.commons.log.names="[com.myorg.commons.util.MyUtil,com.myorg.commons.util.OtherUtil]"
    org.apache.sling.commons.log.pattern="\{0,date,dd.MM.yyyy HH:mm:ss.SSS} *{4}* [{2}] {3} {5}"/>
</code>```

Similarly, you can also do this for

```<code>/apps/cq/config.publish/org.apache.sling.commons.log.LogManager.factory.writer-util.xml
</code>```

With contents such as

```<code><?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="sling:OsgiConfig"
    org.apache.sling.commons.log.file="logs/util.log"
    org.apache.sling.commons.log.file.buffered="{Boolean}false"
    org.apache.sling.commons.log.file.number="5"
    org.apache.sling.commons.log.file.size="20MB"/>
</code>```

See https://helpx.adobe.com/experience-manager/6-3/sites/deploying/using/configuring-osgi.html for more details on how these files can be made specific to run modes.

When you install the package containing these nodes, since they are jcr:primaryType of sling:OsgiConfig they will automatically be picked up and configured in your environment (per run mode matching).

Title: AEM custom logs creation from scripts

Body:
You can do this by configuring OSGI content nodes or by creating OSGI config files.  For instance, I created an OSGI config node at this location:

/apps/cq/config.publish/org.apache.sling.commons.log.LogManager.factory.config-util.xml

That file has contents such as this:

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="sling:OsgiConfig"
    org.apache.sling.commons.log.file="logs/util.log"
    org.apache.sling.commons.log.level="debug"
    org.apache.sling.commons.log.names="[com.myorg.commons.util.MyUtil,com.myorg.commons.util.OtherUtil]"
    org.apache.sling.commons.log.pattern="\{0,date,dd.MM.yyyy HH:mm:ss.SSS} *{4}* [{2}] {3} {5}"/>

Similarly, you can also do this for

/apps/cq/config.publish/org.apache.sling.commons.log.LogManager.factory.writer-util.xml

With contents such as

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="sling:OsgiConfig"
    org.apache.sling.commons.log.file="logs/util.log"
    org.apache.sling.commons.log.file.buffered="{Boolean}false"
    org.apache.sling.commons.log.file.number="5"
    org.apache.sling.commons.log.file.size="20MB"/>

See https://helpx.adobe.com/experience-manager/6-3/sites/deploying/using/configuring-osgi.html for more details on how these files can be made specific to run modes.

When you install the package containing these nodes, since they are jcr:primaryType of sling:OsgiConfig they will automatically be picked up and configured in your environment (per run mode matching).


问:
bootstrap push and pull
I'm creating a site with Bootstrap and I have a question. I would like to pull and push columns and to use some like "more" of the 12 columns, is it possible? On a Mobile version it would put a 3rd column on one of the next row. Maybe the image below would be helpful.

```<code>DESKTOP
---------------------------
|     1           --------|---------
| ----------      | 2     |        |
| |3       |      |       |        |
| ----------      |       |        |
---------------------------        |
                  |                |
                  ------------------
Reverse version
         ---------------------------
---------|--------    1            |
|        |       |      ---------- |
|2       |       |      |3       | |
|        |       |      ---------- |
|        ---------------------------
|                |
------------------
Mobile
---------------------------
|1  ------------------    |
|   | 2              |    |
|   |                |    |
|   |                |    |
---------------------------
    |                |
    ------------------
----------
| 3      |
----------
</code>```

I tried something like this but I don't know how I can do a reverse row. Reverse class doesn't work with div inside of a div, and that's why I want to put 1 and 2 columns on the regular columns next to each other and use pull and push, but the second column walks down. I don't know how export the 3rd column out of the row.

.webbg {
 height: 30vw;
 background-color: aqua;
 background-repeat: no-repeat;
 max-height: 75vw;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container-fluid my-5">
<div class="row">
 <div class="col-sm-12 col-md-8 offset-md-0 offset-lg-1 webbg" style="background-color: aqua;">
 <div class="col-3"><h3 class="text-uppercase"><strong>sometext</strong></h3></div>
 <div class="col-sm-12 offset-sm-0 col-md-12 col-lg-12 offset-md-4 offset-lg-4 offset-xl-7">
  <img src="http://www.tweaks.pl/wp-content/uploads/2015/10/aoc-u3477pqu.png" class="img-fluid">
 </div>
 </div>

</div>
</div></code>```

答:
If I understand your clarification you want Column A and Column B to collapse to each take 1/2 the .row on small devices, with Column C taking up the whole space below.  And (I assume) on larger screens they each take up an equal amount of space?

That being the case, this is basic Bootstrap Grid responsive design.  Things changed slightly in Bootstrap 4 as they flipped to Flexbox so you should definitely reorient yourself with Grid Syntax:

http://getbootstrap.com/docs/4.0/layout/grid/

To achieve the layout as described above you would use code similar to the following:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

A

B

C

```

The way the code above reads is as follows:

For A and B, use a '6 of 12' column for the smallest breakpoint.  For
  'medium' and greater use a '4 of 12' column.  For C use a full column
  for the smallest breakpoint.  For 'medium' and greater use a '4 of 12'
  column.

You can adjust as needed but if your intention is that on medium and greater every column displays in the same row the must add up to 12.

Title: bootstrap push and pull

Body:
I'm creating a site with Bootstrap and I have a question. I would like to pull and push columns and to use some like "more" of the 12 columns, is it possible? On a Mobile version it would put a 3rd column on one of the next row. Maybe the image below would be helpful.

DESKTOP
---------------------------
|     1           --------|---------
| ----------      | 2     |        |
| |3       |      |       |        |
| ----------      |       |        |
---------------------------        |
                  |                |
                  ------------------
Reverse version
         ---------------------------
---------|--------    1            |
|        |       |      ---------- |
|2       |       |      |3       | |
|        |       |      ---------- |
|        ---------------------------
|                |
------------------
Mobile
---------------------------
|1  ------------------    |
|   | 2              |    |
|   |                |    |
|   |                |    |
---------------------------
    |                |
    ------------------
----------
| 3      |
----------

I tried something like this but I don't know how I can do a reverse row. Reverse class doesn't work with div inside of a div, and that's why I want to put 1 and 2 columns on the regular columns next to each other and use pull and push, but the second column walks down. I don't know how export the 3rd column out of the row.

.webbg {
 height: 30vw;
 background-color: aqua;
 background-repeat: no-repeat;
 max-height: 75vw;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

sometext

Body:
If I understand your clarification you want Column A and Column B to collapse to each take 1/2 the .row on small devices, with Column C taking up the whole space below.  And (I assume) on larger screens they each take up an equal amount of space?

That being the case, this is basic Bootstrap Grid responsive design.  Things changed slightly in Bootstrap 4 as they flipped to Flexbox so you should definitely reorient yourself with Grid Syntax:

http://getbootstrap.com/docs/4.0/layout/grid/

To achieve the layout as described above you would use code similar to the following:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<div class="container">
  <div class="row text-center">
    <div class="col-6 col-md-4" style="background:#999">A</div>
    <div class="col-6 col-md-4" style="background:#777">B</div>
    <div class="col-12 col-md-4" style="background:#555">C</div>
  </div>
</div>

The way the code above reads is as follows:

For A and B, use a '6 of 12' column for the smallest breakpoint.  For
  'medium' and greater use a '4 of 12' column.  For C use a full column
  for the smallest breakpoint.  For 'medium' and greater use a '4 of 12'
  column.

You can adjust as needed but if your intention is that on medium and greater every column displays in the same row the must add up to 12.


问:
Pointer in for loop in c program
I have the following structure:

```<code>struct Matrix
{
    int     numOfRows;
    int     numOfColumns;
    double* values;
    int*    permutationVector;
}
</code>```

Also I have the following function:

```<code>void SetRowToZero(Matrix* m, int row)
{
    int rowBegin = row*(m->numOfColumns);
    for (int c = 0; c < (m->numOfColumns); c++)
    {
        m->values[rowBegin + c] = 0;
    }
}
</code>```

I wonder is there any performance slowdown during operation c < (m->numOfColumns)?
Is there any difference if i write function like this:

```<code>void SetRowToZero(Matrix* m, int row)
{
    // Unpacking structure
    int numOfColumns = m->numOfColumns;
    double* values = m->values;

    int rowBegin = row*(m->numOfColumns);

    for (int c = 0; c < numOfColumns; c++)
    {
        values[rowBegin + c] = 0;
    }
}
</code>```

And in general, should i even care about performace on such a small scale?

答:
There's no difference between these two pieces of code.  They do the same thing, with one using intermediate variables.

If it makes sense from a readability standpoint to use temporaries then use them, otherwise don't.

Title: Pointer in for loop in c program

Body:
I have the following structure:

struct Matrix
{
    int     numOfRows;
    int     numOfColumns;
    double* values;
    int*    permutationVector;
}

Also I have the following function:

void SetRowToZero(Matrix* m, int row)
{
    int rowBegin = row*(m->numOfColumns);
    for (int c = 0; c < (m->numOfColumns); c++)
    {
        m->values[rowBegin + c] = 0;
    }
}

I wonder is there any performance slowdown during operation c < (m->numOfColumns)?
Is there any difference if i write function like this:

void SetRowToZero(Matrix* m, int row)
{
    // Unpacking structure
    int numOfColumns = m->numOfColumns;
    double* values = m->values;

    int rowBegin = row*(m->numOfColumns);

    for (int c = 0; c < numOfColumns; c++)
    {
        values[rowBegin + c] = 0;
    }
}

And in general, should i even care about performace on such a small scale?


问:
Dropdown menu disappears when moving cursor from primary menu
I am working on a dropdown menu for a site with a fairly large header.  Inside of the header is a
 containing the primary menu, with each menu item revealing a dropdown.  The problem I am having is that the primary menu is shorter than the header, so there is a small space the cursor has to travel through where it is not hovering over the primary menu or the dropdown.  In this brief space, the dropdown menu disappears.  How can I keep this from happening?  I cannot move the dropdown up, or it overlaps with the header.  I also have been unable to change the height of the
 in an effective way.

The site is private, but I have created a jsfiddle displaying the problem I'm having: https://jsfiddle.net/x0hvdaqn/

Edit
I had made the fiddle with a div instead of a ul for simplicity's sake, but when I changed it to a ul it started working.  The actual menu I am building is made the same way, but does not work.  Why would this be the case?

New fiddle with ul instead of div: https://jsfiddle.net/tgqof8my/

答:
use this code. I hope, you need descreasing your margin in drop. Use this...

#wrapper {
  width: 100%;
  height: 75px;
  background-color: green;
  text-align: center;
}
#button {
  height: 40px;
  width: 25%;
  margin: auto;
  background-color: yellow;
  top: 25px;
  position: absolute;
}
#drop {
  display: none;
  background-color: red;
  margin-top: 20px;
}
#button:hover #drop {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div id="button">
  Primary Menu Item
    <div id="drop">
    Dropdown
    </div>
  </div>
  Header
</div></code>```

Body:
use this code. I hope, you need descreasing your margin in drop. Use this...

#wrapper {
  width: 100%;
  height: 75px;
  background-color: green;
  text-align: center;
}
#button {
  height: 40px;
  width: 25%;
  margin: auto;
  background-color: yellow;
  top: 25px;
  position: absolute;
}
#drop {
  display: none;
  background-color: red;
  margin-top: 20px;
}
#button:hover #drop {
  display: block;
}

<div id="wrapper">
  <div id="button">
  Primary Menu Item
    <div id="drop">
    Dropdown
    </div>
  </div>
  Header
</div>


问:
How convert an object to int
I want to convert an object to int type....
eg:
   Object obj=........;
   int count = Integer.parseInt((String) obj);

when i use above code ai got cast exception.

Anyone know how to cast object to int...?

答:
Use obj.hashCode(), to get an int that represents the object.  But what is your purpose?  The code you posted does not work - you try to cast the object to a string rather than calling toString(), but even then, unless the toString representation of the object is itself an integer, calling Integer.parseInt on it will throw an exception.

So what are you aiming at?

Title: How convert an object to int


问:
Postive/Negative Chart in Google Visualization API
I need to generate a chart like this one:

Specifically, I want to show both a positive value and a negative value for a time period (could be an hour, minute, etc.) and display it like this.

I could have sworn I saw something like this on the Google Visualization API Gallery the other day, but I can't find it now, and am not even sure what this kind of chart is called.

First, do you know what this kind of chart is called so I can possibly find documentation?  Second, is there any way to implement such a chart with the Google Visualization API?  If not, is there another common charting solution for web that I can achieve this with?

Thank you for your time.

答:
Use ColumnChart instead of BarChart:

```<code>var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
</code>```

https://jsfiddle.net/0rrar9oq/16

Body:
Use ColumnChart instead of BarChart:

var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));

https://jsfiddle.net/0rrar9oq/16