问:
Java 8 stream: sum of units of same items
Is there a concise way to sum the units of the same type of items in a list with Java 8 streams? For example, suppose I have a list of three items:

```<code>{id: 10, units: 1}
{id: 20, units: 2}
{id: 10, units: 1}
</code>```

I like a summary stream like:

```<code>{id: 10, units 2}
{id: 20, units 2}
</code>```

which sums the units of items of the same id. Any ideas?

Here's Federico's solution (with Lombok):

```<code>import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class So44348207 {

    public static void main(String[] args) {
        List<Item> items = Arrays.asList(
            new Item(10,1), new Item(20,2), new Item(10, 1)
        );

        Map<Long, Integer> results = items.stream().collect(
            Collectors.toMap(
                Item::getId,
                Item::getUnits,
                Integer::sum
                )
            );

        results.forEach( (k,v) -> System.out.println(
            String.format("{id: %d, units: %d}", k,v))
        );
    }

    @Data
    @AllArgsContructor
    public static class Item {
        Long id;
        Integer units;
    }
}
</code>```

which correctly produces:

```<code>java So44348207
{id: 20, units: 2}
{id: 10, units: 2}
</code>```

答:
Assuming you have a class MyClass that encapsulates both fields and has getters for them, you could do it as follows:

```<code>Map<Long, Integer> result = list.stream()
    .collect(Collectors.toMap(
        MyClass::getId,
        MyClass::getUnits,
        Integer::sum));
</code>```

I'm also assuming that id is of type long or Long and units of type int or Integer.

Collectors.toMap creates a map whose keys are determined by its first argument, which is a function that maps an element of the stream to the key of the map. The second argument is a function that maps an element of the stream to the value of the map, and the third argument is an operator that merges two values when there are collisions on the key.

Body:
Is there a concise way to sum the units of the same type of items in a list with Java 8 streams? For example, suppose I have a list of three items:

{id: 10, units: 1}
{id: 20, units: 2}
{id: 10, units: 1}

I like a summary stream like:

{id: 10, units 2}
{id: 20, units 2}

which sums the units of items of the same id. Any ideas?

Here's Federico's solution (with Lombok):

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class So44348207 {

    public static void main(String[] args) {
        List<Item> items = Arrays.asList(
            new Item(10,1), new Item(20,2), new Item(10, 1)
        );

        Map<Long, Integer> results = items.stream().collect(
            Collectors.toMap(
                Item::getId,
                Item::getUnits,
                Integer::sum
                )
            );

        results.forEach( (k,v) -> System.out.println(
            String.format("{id: %d, units: %d}", k,v))
        );
    }

    @Data
    @AllArgsContructor
    public static class Item {
        Long id;
        Integer units;
    }
}

which correctly produces:

java So44348207
{id: 20, units: 2}
{id: 10, units: 2}

Body:
Assuming you have a class MyClass that encapsulates both fields and has getters for them, you could do it as follows:

Map<Long, Integer> result = list.stream()
    .collect(Collectors.toMap(
        MyClass::getId,
        MyClass::getUnits,
        Integer::sum));

I'm also assuming that id is of type long or Long and units of type int or Integer.

Collectors.toMap creates a map whose keys are determined by its first argument, which is a function that maps an element of the stream to the key of the map. The second argument is a function that maps an element of the stream to the value of the map, and the third argument is an operator that merges two values when there are collisions on the key.


来源: stackexchange

问:
Get 2 Divs in one box?
I was wondering how I would get 2 divs in one div

html {
  margin: auto;
  width: 960px;
  height: auto;
}

#navbar {
  height: 90px;
  background-color: #080808 !important;
  display: block;
}

.logo {
  padding-left: 31px;
  height: 90px !important;
  width: 90px !important;
}

.navitems li,
.navitems ul {
  list-style-type: none;
  display: inline-block;
}

.navitems {
  float: right;
}
```

<pre class="lang-html prettyprint-override"><code><div id="navbar">
  <div class="logo">
    <img src="images/logo.png" alt="" width="90px" height="90px">
  </div>
  <div class="navitems">
    <li>
      <ul>Home</ul>
      <ul>Contact Us</ul>
      <ul>About</ul>
    </li>
  </div>
</div>
</code>```

答:
If using float, the floating items must be placed before "regular" (non-floating) items in the DOM tree. In this instance, you would want to move your
 before
. Also, you might want to permutate your
 and
 tags.
 contains
s, not the other way around. ;)

ContentLicense: CC BY-SA 3.0

Title: Get 2 Divs in one box?

Body:
I was wondering how I would get 2 divs in one div

html {
  margin: auto;
  width: 960px;
  height: auto;
}

#navbar {
  height: 90px;
  background-color: #080808 !important;
  display: block;
}

.logo {
  padding-left: 31px;
  height: 90px !important;
  width: 90px !important;
}

.navitems li,
.navitems ul {
  list-style-type: none;
  display: inline-block;
}

.navitems {
  float: right;
}

Home

Contact Us

About

Body: If using float, the floating items must be placed before "regular" (non-floating) items in the DOM tree. In this instance, you would want to move your <div class="navitems"> before <div class="logo">. Also, you might want to permutate your <ul> and <li> tags. <ul> contains <li>s, not the other way around. ;)


问:
Spring netflix eureka, zuul vs Spring cloud data flow
I am new to the microservice world. Would like to know when to use Spring eureka, zuul vs spring data flow.

I am building a service which in turns will consume multiple granular services(aka micro service), aggregate all the data and returns aggregated data to the consumer. All the services will run in local intranet within company infrastructure. Also, I would like to load balance individual microservices.

What should be the choice of technology for microservices deployment?

I am using Spring 4.3, Spring boot, Rest, Spring data.

答:
I suggest this architecture:

Netflix Eureka : for Service discovery

Consul or Config Server : for saving configurations in environment base on 12 factors

Zuul : for Intelligent and programmable routing

Netflix Ribbon : for Client-Side Load Balancing

Zipkin : for tracing

Turbine : for metrics aggregation

Netflix Feign : for Declarative REST API implementation

Hysterix : for circuit breaker (one of the EIP patterns)

RabbitMQ (Spring-AMQP) or Kafka (Spring-Kafka and Kafka Stream) for having asynchronous communication style

Grafana + Prometheus + Prometheus-jmx-exporter for monitoring system

Docker : for virtualization and container base architecure

Docker Swarm or Kubernetes : for scalability, automation and Container Management

note : Prometheus is a time-series database (including monitoring features) you can also use InfluxDb or Graphite  instead of it.


问:
How can I center the loading div before load() with jQuery?
I have this code:

```<code>$("#result").html('<div class="loading">Loading results...</div>');
$("#result").load('<?php bloginfo('template_directory'); ?>/GetResults.php?' + $.cookie('nw-query'));
</code>```

It shows the loading div until the load is done. What I want to do here, I want the loading div exactly in the center of the page/document?

That's extra but could be nice - can I also fade the document until the load is done so that the loading div stands out?

Any jquery/css suggestions are welcome.

Thank you :)

答:
you could put a center div around your loading...</p>

```<code>$("#result").html('<div align="center" style="width:100%"><div class="loading">Loading results...</div></div>');
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this code:

$("#result").html('
Loading results...
');
$("#result").load('<?php bloginfo('template_directory'); ?>/GetResults.php?' + $.cookie('nw-query'));

It shows the loading div until the load is done. What I want to do here, I want the loading div exactly in the center of the page/document?

That's extra but could be nice - can I also fade the document until the load is done so that the loading div stands out?

Any jquery/css suggestions are welcome.

Thank you :)

Body:
you could put a center div around your loading...

$("#result").html('<div align="center" style="width:100%"><div class="loading">Loading results...</div></div>');


问:
Trouble reading ajax post response
I am working on a website and I am trying to connect JavaScript and php using ajax. I have a problem with reading ajax response.

I have one php script which has the following code:

```<code><?php
echo "1";
</code>```

And a function written in JavaScript ecma 6, which has the following code:

```<code>loginUser(username, password) {
        return new Promise((resolve, reject) => {

            var request = require('ajax-request');
            request.post(
                {
                    url: 'http://swiftservice.psoftwarestudio.com/Admin.php',
                    data: {
                        username: username,
                        password: password
                    },
                    headers: {}
                }
                , (data) => {
                    resolve(data);
                }
            );
        });
    }
</code>```

When I debug, the data is always null. I am very new at web programming especially whit ajax.
I hope someone can point me to the error, thanks.

答:
You need to parse the data you get back from your AJAX call into a JSON Object, as what you get is the String representation of it:

```<code>loginUser(username, password) {
        return new Promise((resolve, reject) => {

            var request = require('ajax-request');
            request.post(
                {
                    url: 'http://swiftservice.psoftwarestudio.com/Admin.php',
                    data: {
                        username: username,
                        password: password
                    },
                    headers: {}
                }
                , (data) => {
                    resolve(JSON.parse(data));
                }
            );
        });
    }
</code>```

Title: Trouble reading ajax post response

Body:
I am working on a website and I am trying to connect JavaScript and php using ajax. I have a problem with reading ajax response.

I have one php script which has the following code:

<?php
echo "1";

And a function written in JavaScript ecma 6, which has the following code:

loginUser(username, password) {
        return new Promise((resolve, reject) => {

            var request = require('ajax-request');
            request.post(
                {
                    url: 'http://swiftservice.psoftwarestudio.com/Admin.php',
                    data: {
                        username: username,
                        password: password
                    },
                    headers: {}
                }
                , (data) => {
                    resolve(data);
                }
            );
        });
    }

When I debug, the data is always null. I am very new at web programming especially whit ajax.
I hope someone can point me to the error, thanks.

Body:
You need to parse the data you get back from your AJAX call into a JSON Object, as what you get is the String representation of it:

loginUser(username, password) {
        return new Promise((resolve, reject) => {

            var request = require('ajax-request');
            request.post(
                {
                    url: 'http://swiftservice.psoftwarestudio.com/Admin.php',
                    data: {
                        username: username,
                        password: password
                    },
                    headers: {}
                }
                , (data) => {
                    resolve(JSON.parse(data));
                }
            );
        });
    }


问:
Confusion about Printing string arrays in C
This is probably a beginner question but it has been confusing me.  I understand that in c an array is itself a pointer to the first element of the array.  So consider the following example

```<code>char *words[LENGTH];
words[0] = "zero";
words[1] = "one";
words[2] = "two";
printf("%s\n",*words);
</code>```

What ends up printing is zero.  However, my understanding is that words is a pointer to the first element of the words array which is a char pointer => words is a pointer to a pointer to a char.  Therefore *words would be a pointer to char.  Therefore I would expect a memory address to be printed here and not an actual string.  What am I misunderstanding here?

答:
As @Stargateur replied you need to both use the %p flag and use the (void *).
Please note that it will show you the starting address of the first string ('zero') and the next code will go over all the strings and print their address (think of the 3 strings as a 2D (two dimensions) strings array having different lengths.</p>

```<code>#include <stdio.h>
#define LENGTH 3

int main(void)
{
    char *words[LENGTH];
    words[0] = "zero";
    words[1] = "one";
    words[2] = "two";

    int len = 0;
    while(len<(int)LENGTH)
    {
        printf("%s\n", words[len]);
        printf("%p\n", (void *)words[len]);
        len++;
    }
    printf("\n%p\n", (void *)*words); // prints the first address only (the 'zero' address)

    return 0;
}
</code>```

Body:
This is probably a beginner question but it has been confusing me.  I understand that in c an array is itself a pointer to the first element of the array.  So consider the following example

char *words[LENGTH];
words[0] = "zero";
words[1] = "one";
words[2] = "two";
printf("%s\n",*words);

What ends up printing is zero.  However, my understanding is that words is a pointer to the first element of the words array which is a char pointer => words is a pointer to a pointer to a char.  Therefore *words would be a pointer to char.  Therefore I would expect a memory address to be printed here and not an actual string.  What am I misunderstanding here?

Body:
As @Stargateur replied you need to both use the %p flag and use the (void *).
Please note that it will show you the starting address of the first string ('zero') and the next code will go over all the strings and print their address (think of the 3 strings as a 2D (two dimensions) strings array having different lengths.

#include <stdio.h>
#define LENGTH 3

int main(void)
{
    char *words[LENGTH];
    words[0] = "zero";
    words[1] = "one";
    words[2] = "two";

    int len = 0;
    while(len<(int)LENGTH)
    {
        printf("%s\n", words[len]);
        printf("%p\n", (void *)words[len]);
        len++;
    }
    printf("\n%p\n", (void *)*words); // prints the first address only (the 'zero' address)

    return 0;
}


问:
How to build 'function path' for any given Lua table?

Intro

Hello Lua programmers.

I don't have much experience in Lua programming language, it is still a new thing for me.

I've run into a problem with coding a recursive function that is supposed to build 'function path' for each function in (any) given Lua table.

Example

I've the following Lua table:

```<code>_G["foo_lua_bar_libs"] = {
    ["my cool lib A"] = {
        ["add"] = function(a, b) return a + b end,
        ["sub"] = function(a, b) return a - b end,
        ["mul"] = function(a, b) return a * b end,
        ["div"] = function(a, b) return a / b end
    },
    ["last?"] = function() return -1 end,
    ["my cool lib B"] = {
        ["B 1 hex"] = function() return 0xB1 end,
        ["B 2"] = function() return 0xB2 end,
        ["B utilib"] = {
            ["idk"] = function() return '1234567890' end,
            ["calc"] = function() return math.pi end,
            ["crash"] = function() print(string.rep(' ', math.huge)) end,
            ["first"] = function(x) return x or false end
        },
        ["main"] = {
            ["phys"] = {
                ["calc"] = function(c, s) return math.cos(c) * math.sin(s) end
            },
            ["internal"] = {
                -- no function in here
            },
            [""] = function() local _ = "i am unnamed" end,
            ["foo . bar"] = {
                ["foo"] = "bar" .. 0,
                --["bar"] = _G
            },
            ["math"] = {
                calc = function(x, y) return x * x + y * y end,
                pi = math.pi, -- not a function
                cos = math.cos,
                [math.sin] = math.random
            }
        }
    },
    [""] = {
        [false] = function() return true end,
        [.80] = function(n) return 0.01 * n * n end,
        ["i am a function in nameless lib"] = function() return 1234 end,
        i_am_totally_a_function = 'not a function',
        ["hi. i am a \"quoted!\" func."] = function() return "quoted", '!' end,
        ["\r\n"] = function() return "win" end
    },
    [ [[misc.lib]] ] = {
        ["..."] = function(...) return ... end,
        nothing = function() return nil end,
        ["nil"] = nil, -- not a function
        crash = function() while 0 do end end,
        ["end"] = function() end,
        [string] = " a string; not a function "
    }
}
</code>```

I need a recursive Lua function (lets call it BuildFunctionPath), which would build a function path for the given table, so that if I call BuildFunctionPath function:

```<code>local libs_function_path = BuildFunctionPath(_G.foo_lua_bar_libs, nil, { "_G", "foo_lua_bar_libs" })
</code>```

BuildFunctionPath function would return the following table to the libs_function_path variable:

```<code>{
    ["_G[\"foo_lua_bar_libs\"][\"last?\"]"] = function() return -1 end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib A\"][\"add\"]"] = function(a, b) return a + b end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib A\"][\"div\"]"] = function(a, b) return a / b end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib A\"][\"mul\"]"] = function(a, b) return a * b end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib A\"][\"sub\"]"] = function(a, b) return a - b end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"B 1 hex\"]"] = function() return 0xB1 end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"B 2\"]"] = function() return 0xB2 end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"B utilib\"][\"calc\"]"] = function() return math.pi end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"B utilib\"][\"crash\"]"] = function() print(string.rep(' ', math.huge)) end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"B utilib\"][\"first\"]"] = function(x) return x or false end
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"B utilib\"][\"idk\"]"] = function() return '1234567890' end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"main\"][\"\"]"] = function() local _ = "i am unnamed" end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"main\"][\"math\"][\"calc\"]"] = function(x, y) return x * x + y * y end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"main\"][\"math\"][\"cos\"]"] = math.cos,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"main\"][\"math\"][math.sin]"] = math.random,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"main\"][\"phys\"][\"calc\"]"] = function(c, s) return math.cos(c) * math.sin(s) end,
    ["_G[\"foo_lua_bar_libs\"][\"\"][false]"] = function() return true end,
    ["_G[\"foo_lua_bar_libs\"][\"\"][0.80]"] = function(n) return 0.01 * n * n end,
    ["_G[\"foo_lua_bar_libs\"][\"\"][\"\\r\\n\"]"] = function() return "win" end,
    ["_G[\"foo_lua_bar_libs\"][\"\"][\"hi. i am a \\\"quoted!\\\" func.\"]"] = function() return "quoted", '!' end,
    ["_G[\"foo_lua_bar_libs\"][\"\"][\"i am a function in nameless lib\"]"] = function() return 1234 end,
    ["_G[\"foo_lua_bar_libs\"][\"misc.lib\"][\"...\"]"] = function(...) return ... end,
    ["_G[\"foo_lua_bar_libs\"][\"misc.lib\"][\"crash\"]"] = function() while 0 do end,
    ["_G[\"foo_lua_bar_libs\"][\"misc.lib\"][\"end\"]"] = function() end,
    ["_G[\"foo_lua_bar_libs\"][\"misc.lib\"][\"nothing\"]"] = function() return nil end
}
</code>```

Here is the code I've got stuck at and I don't know how to finish the BuildFunctionPath function:

```<code>function BuildFunctionPath(tbl, done, path)
    -- Please help me with this function.
    local functionStore = {} -- Final return table
    if tbl == nil then tbl = _G end
    if done == nil then done = {} end
    if path == nil then path = { "_G" } end
    for key, value in pairs(tbl) do
        if type(value) == "table" and not done[value] then
            done[value] = true
            -- I am stuck...
            local pathIndex = #path + 1
            path[pathIndex] = key
            --print(string.format("%q", path)) -- Quoted/Escaped path string
            --BuildFunctionPath(value, done, path) -- Recursion....
            path[pathIndex] = nil
            done[value] = nil
        elseif type(value) == "function" then
            functionStore[path] = value
        end
    end
end
</code>```

If you are wondering why I need such function, it is so that I can know exactly in which particular table a given function is stored in.

Take a look at this screenshot: https://i.stack.imgur.com/Rh7Wr.png

So, if user enters "_G[\"print\"]" as path, it would return a _G.print function. Also, by creating inverse table of (_G) function path table, a user can then provide _G.print function and it would return "_G[\"print\"]" - the path string. Genius.

Please I need your help. Thanks for your time! :)

(Pardon my bad English.)

答:
```<code>local function BuildFunctionPath(tbl, done, path, functionStore)
   functionStore = functionStore or {} -- Final return table
   tbl = tbl or _G
   done = done or {}
   path = path or { "_G" }
   for key, value in pairs(tbl) do
      if type(value) == "table" and not done[value] or type(value) == "function" then
         -- convert key to string
         if type(key) == "string" then
            key = string.format("%q", key) -- Quoted/Escaped key
         else
            key = tostring(key)            -- for numbers and booleans
            -- Please note that you can't use a function as a key: [math.sin] = math.random
            -- There is no way in Lua to calculate the name of a function (such as "math.sin")
         end
         local pathIndex = #path + 1
         path[pathIndex] = key
         if type(value) ~= "function" then
            -- if the value is a table
            done[value] = true
            BuildFunctionPath(value, done, path, functionStore) -- Recursion....
            done[value] = nil
         else
            -- if the value is a function
            functionStore[path[1].."["..table.concat(path, "][", 2).."]"] = value
         end
         path[pathIndex] = nil
      end
   end
   return functionStore
end

local libs_function_path = BuildFunctionPath(_G.foo_lua_bar_libs, nil, { "_G", "foo_lua_bar_libs" }, nil)
</code>```

Body:
Intro

Hello Lua programmers.

I don't have much experience in Lua programming language, it is still a new thing for me.

I've run into a problem with coding a recursive function that is supposed to build 'function path' for each function in (any) given Lua table.

Example

I've the following Lua table:

_G["foo_lua_bar_libs"] = {
    ["my cool lib A"] = {
        ["add"] = function(a, b) return a + b end,
        ["sub"] = function(a, b) return a - b end,
        ["mul"] = function(a, b) return a * b end,
        ["div"] = function(a, b) return a / b end
    },
    ["last?"] = function() return -1 end,
    ["my cool lib B"] = {
        ["B 1 hex"] = function() return 0xB1 end,
        ["B 2"] = function() return 0xB2 end,
        ["B utilib"] = {
            ["idk"] = function() return '1234567890' end,
            ["calc"] = function() return math.pi end,
            ["crash"] = function() print(string.rep(' ', math.huge)) end,
            ["first"] = function(x) return x or false end
        },
        ["main"] = {
            ["phys"] = {
                ["calc"] = function(c, s) return math.cos(c) * math.sin(s) end
            },
            ["internal"] = {
                -- no function in here
            },
            [""] = function() local _ = "i am unnamed" end,
            ["foo . bar"] = {
                ["foo"] = "bar" .. 0,
                --["bar"] = _G
            },
            ["math"] = {
                calc = function(x, y) return x * x + y * y end,
                pi = math.pi, -- not a function
                cos = math.cos,
                [math.sin] = math.random
            }
        }
    },
    [""] = {
        [false] = function() return true end,
        [.80] = function(n) return 0.01 * n * n end,
        ["i am a function in nameless lib"] = function() return 1234 end,
        i_am_totally_a_function = 'not a function',
        ["hi. i am a \"quoted!\" func."] = function() return "quoted", '!' end,
        ["\r\n"] = function() return "win" end
    },
    [ [[misc.lib]] ] = {
        ["..."] = function(...) return ... end,
        nothing = function() return nil end,
        ["nil"] = nil, -- not a function
        crash = function() while 0 do end end,
        ["end"] = function() end,
        [string] = " a string; not a function "
    }
}

I need a recursive Lua function (lets call it BuildFunctionPath), which would build a function path for the given table, so that if I call BuildFunctionPath function:

local libs_function_path = BuildFunctionPath(_G.foo_lua_bar_libs, nil, { "_G", "foo_lua_bar_libs" })

BuildFunctionPath function would return the following table to the libs_function_path variable:

{
    ["_G[\"foo_lua_bar_libs\"][\"last?\"]"] = function() return -1 end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib A\"][\"add\"]"] = function(a, b) return a + b end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib A\"][\"div\"]"] = function(a, b) return a / b end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib A\"][\"mul\"]"] = function(a, b) return a * b end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib A\"][\"sub\"]"] = function(a, b) return a - b end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"B 1 hex\"]"] = function() return 0xB1 end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"B 2\"]"] = function() return 0xB2 end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"B utilib\"][\"calc\"]"] = function() return math.pi end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"B utilib\"][\"crash\"]"] = function() print(string.rep(' ', math.huge)) end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"B utilib\"][\"first\"]"] = function(x) return x or false end
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"B utilib\"][\"idk\"]"] = function() return '1234567890' end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"main\"][\"\"]"] = function() local _ = "i am unnamed" end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"main\"][\"math\"][\"calc\"]"] = function(x, y) return x * x + y * y end,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"main\"][\"math\"][\"cos\"]"] = math.cos,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"main\"][\"math\"][math.sin]"] = math.random,
    ["_G[\"foo_lua_bar_libs\"][\"my cool lib B\"][\"main\"][\"phys\"][\"calc\"]"] = function(c, s) return math.cos(c) * math.sin(s) end,
    ["_G[\"foo_lua_bar_libs\"][\"\"][false]"] = function() return true end,
    ["_G[\"foo_lua_bar_libs\"][\"\"][0.80]"] = function(n) return 0.01 * n * n end,
    ["_G[\"foo_lua_bar_libs\"][\"\"][\"\\r\\n\"]"] = function() return "win" end,
    ["_G[\"foo_lua_bar_libs\"][\"\"][\"hi. i am a \\\"quoted!\\\" func.\"]"] = function() return "quoted", '!' end,
    ["_G[\"foo_lua_bar_libs\"][\"\"][\"i am a function in nameless lib\"]"] = function() return 1234 end,
    ["_G[\"foo_lua_bar_libs\"][\"misc.lib\"][\"...\"]"] = function(...) return ... end,
    ["_G[\"foo_lua_bar_libs\"][\"misc.lib\"][\"crash\"]"] = function() while 0 do end,
    ["_G[\"foo_lua_bar_libs\"][\"misc.lib\"][\"end\"]"] = function() end,
    ["_G[\"foo_lua_bar_libs\"][\"misc.lib\"][\"nothing\"]"] = function() return nil end
}

Here is the code I've got stuck at and I don't know how to finish the BuildFunctionPath function:

function BuildFunctionPath(tbl, done, path)
    -- Please help me with this function.
    local functionStore = {} -- Final return table
    if tbl == nil then tbl = _G end
    if done == nil then done = {} end
    if path == nil then path = { "_G" } end
    for key, value in pairs(tbl) do
        if type(value) == "table" and not done[value] then
            done[value] = true
            -- I am stuck...
            local pathIndex = #path + 1
            path[pathIndex] = key
            --print(string.format("%q", path)) -- Quoted/Escaped path string
            --BuildFunctionPath(value, done, path) -- Recursion....
            path[pathIndex] = nil
            done[value] = nil
        elseif type(value) == "function" then
            functionStore[path] = value
        end
    end
end

If you are wondering why I need such function, it is so that I can know exactly in which particular table a given function is stored in.

Take a look at this screenshot: https://i.stack.imgur.com/Rh7Wr.png

So, if user enters "_G[\"print\"]" as path, it would return a _G.print function. Also, by creating inverse table of (_G) function path table, a user can then provide _G.print function and it would return "_G[\"print\"]" - the path string. Genius.

Please I need your help. Thanks for your time! :)

(Pardon my bad English.)


问:
Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object
I am getting this error:

```<code>Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
</code>```

This is my code:

```<code>var React = require('react')
var ReactDOM =  require('react-dom')
var Router = require('react-router')
var Route = Router.Route
var Link = Router.Link

var App = React.createClass({
  render() {
    return (
      <div>
        <h1>App</h1>
        <ul>
          <li><Link to="/about">About</Link></li>
        </ul>
      </div>
    )
  }
})

var About = require('./components/Home')
ReactDOM.render((
  <Router>
    <Route path="/" component={App}>
      <Route path="about" component={About} />
    </Route>
  </Router>
), document.body)
</code>```

My Home.jsx file:

```<code>var React = require('react');
var RaisedButton = require('material-ui/lib/raised-button');

var Home = React.createClass({
  render:function() {
    return (
        <RaisedButton label="Default" />
    );
  },
});

module.exports = Home;
</code>```

答:
Another possible solution, that worked for me:

Currently, react-router-redux is in beta and npm returns 4.x, but not 5.x. But the @types/react-router-redux returned 5.x. So there were undefined variables used.

Forcing NPM/Yarn to use 5.x solved it for me.

ContentLicense: CC BY-SA 4.0

Body:
I am getting this error:

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

This is my code:

var React = require('react')
var ReactDOM =  require('react-dom')
var Router = require('react-router')
var Route = Router.Route
var Link = Router.Link

var App = React.createClass({
  render() {
    return (

App

<Link to="/about">About</Link>

    )
  }
})

var About = require('./components/Home')
ReactDOM.render((
  <Router>
    <Route path="/" component={App}>
      <Route path="about" component={About} />
    </Route>
  </Router>
), document.body)

My Home.jsx file:

var React = require('react');
var RaisedButton = require('material-ui/lib/raised-button');

var Home = React.createClass({
  render:function() {
    return (
        <RaisedButton label="Default" />
    );
  },
});

module.exports = Home;


问:
How put custom icon to Visio Document for custom ribbon
I am trying to put custom icon to Visio Document for custom ribbon. When I using Excel I can use utility “Custom UI Editor for Microsoft Office”. For example, I can write next xml in utility and insert some picture:

Custom UI Editor

In Excel all working excellent.

But when I trying use this way in Visio, I don’t see picture on ribbon when I opening Visio-document.

After that I opening “Custom UI Editor for Microsoft Office” for Visio-document I also don’t see inserted picture that I inserted before.

Custom UI Editor after opening Visio-document

Can anyone help me out with my problem? Thank you.

答:
This is a known issue in Visio. Custom icons in .vsdx file simply do not work.

If you are really determined to have custom pictures, you should do it otherwise.
 Like via VBA macro, by writing a callback, i.e. instead of image specifying getImage pointing to some callback function to get the custom image. Or even by creating a full-blown extension.

Note - Microsoft-defined (idMso) images work fine.


问:
Type inference for overloaded function with enum params?
Is it possible to perform type inference using an overloaded function with an enum param? For example, say I'm trying to make a factory function whose return type depends on enum value:

enum Colors {
  Red,
  Green
};

abstract class Box { };
class RedBox extends Box { };
class GreenBox extends Box { };

class BoxFactory {
  static createBox(color: Colors.Red): RedBox;
  static createBox(color: Colors): Box {
    switch (color) {
      case Colors.Red:
        return new RedBox();
      case Colors.Green:
        return new GreenBox();
    }
  }
}

function makeMeABox(color: Colors) {
  // Argument of type 'Colors' is not assignable to parameter of type 'Colors.Red'
  return BoxFactory.createBox(color);
}
```

(playground)

If I generate a declarations file, the general overload doesn't even show up. However, things are fine if I remove the overload static createBox(color: Colors.Red): RedBox;.

答:
You are only missing one signature:

```<code>class BoxFactory {
  static createBox(color: Colors.Red): RedBox;
  static createBox(color: Colors): Box; // <--- THIS ONE
  static createBox(color: Colors): Box {
    switch (color) {
      case Colors.Red:
        return new RedBox();
      case Colors.Green:
        return new GreenBox();
    }
  }
}
</code>```

Then:

```<code>let a = BoxFactory.createBox(Colors.Red); // type of a is RedBox
let b = BoxFactory.createBox(Colors.Green); // type of b is Box
</code>```

(code in playground)

Body:
Is it possible to perform type inference using an overloaded function with an enum param? For example, say I'm trying to make a factory function whose return type depends on enum value:

enum Colors {
  Red,
  Green
};

abstract class Box { };
class RedBox extends Box { };
class GreenBox extends Box { };

class BoxFactory {
  static createBox(color: Colors.Red): RedBox;
  static createBox(color: Colors): Box {
    switch (color) {
      case Colors.Red:
        return new RedBox();
      case Colors.Green:
        return new GreenBox();
    }
  }
}

function makeMeABox(color: Colors) {
  // Argument of type 'Colors' is not assignable to parameter of type 'Colors.Red'
  return BoxFactory.createBox(color);
}

(<a href="http://www.typescriptlang.org/play/index.html#src=enum%20Colors%20%7B%0D%0A%20%20Red%2C%0D%0A%20%20Green%0D%0A%7D%3B%0D%0A%0D%0Aabstract%20class%20Box%20%7B%20%7D%3B%0D%0Aclass%20RedBox%20extends%20Box%20%7B%20%7D%3B%0D%0Aclass%20GreenBox%20extends%20Box%20%7B%20%7D%3B%0D%0A%0D%0Aclass%20BoxFactory%20%7B%0D%0A%20%20static%20createBox(color%3A%20Colors.Red)%3A%20RedBox%3B%0D%0A%20%20static%20createBox(color%3A%20Colors)%3A%20Box%20%7B%0D%0A%20%20%20%20switch%20(color)%20%7B%0D%0A%20%20%20%20%20%20case%20Colors.Red%3A%0D%0A%20%20%20%20%20%20%20%20return%20new%20RedBox()%3B%0D%0A%20%20%20%20%20%20case%20Colors.Green%3A%0D%0A%20%20%20%20%20%20%20%20return%20new%20GreenBox()%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%7D%20%0D%0A%7D%0D%0A%0D%0Afunction%20makeMeABox(color%3A%20Colors)%20%7B%0D%0A%20%20%2F%2F%20Argument%20of%20type%20'Colors'%20is%20not%20assignable%20to%20parameter%20of%20type%20'Colors.Red'%0D%0A%20%20return%20BoxFactory.createBox(color)%3B%0D%0A%7D" rel="nofollow noreferrer">playground)

If I generate a declarations file, the general overload doesn't even show up. However, things are fine if I remove the overload static createBox(color: Colors.Red): RedBox;.

Body:
You are only missing one signature:

class BoxFactory {
  static createBox(color: Colors.Red): RedBox;
  static createBox(color: Colors): Box; // <--- THIS ONE
  static createBox(color: Colors): Box {
    switch (color) {
      case Colors.Red:
        return new RedBox();
      case Colors.Green:
        return new GreenBox();
    }
  }
}

Then:

let a = BoxFactory.createBox(Colors.Red); // type of a is RedBox
let b = BoxFactory.createBox(Colors.Green); // type of b is Box

(<a href="http://www.typescriptlang.org/play/index.html#src=enum%20Colors%20%7B%0D%0A%20%20Red%2C%0D%0A%20%20Green%0D%0A%7D%3B%0D%0A%0D%0Aabstract%20class%20Box%20%7B%20%7D%3B%0D%0Aclass%20RedBox%20extends%20Box%20%7B%20%7D%3B%0D%0Aclass%20GreenBox%20extends%20Box%20%7B%20%7D%3B%0D%0A%0D%0Aclass%20BoxFactory%20%7B%0D%0A%20%20static%20createBox(color%3A%20Colors.Red)%3A%20RedBox%3B%0D%0A%20%20static%20createBox(color%3A%20Colors)%3A%20Box%3B%0D%0A%20%20static%20createBox(color%3A%20Colors)%3A%20Box%20%7B%0D%0A%20%20%20%20switch%20(color)%20%7B%0D%0A%20%20%20%20%20%20case%20Colors.Red%3A%0D%0A%20%20%20%20%20%20%20%20return%20new%20RedBox()%3B%0D%0A%20%20%20%20%20%20case%20Colors.Green%3A%0D%0A%20%20%20%20%20%20%20%20return%20new%20GreenBox()%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%7D%20%0D%0A%7D%0D%0A%0D%0Afunction%20makeMeABox(color%3A%20Colors)%20%7B%0D%0A%20%20return%20BoxFactory.createBox(color)%3B%0D%0A%7D%0D%0A%0D%0Alet%20a%20%3D%20BoxFactory.createBox(Colors.Red)%3B%20%2F%2F%20type%20of%20a%20is%20RedBox%0D%0Alet%20b%20%3D%20BoxFactory.createBox(Colors.Green)%3B%20%2F%2F%20type%20of%20b%20is%20Box" rel="nofollow noreferrer">code in playground)


问:
Admin SDK Chromeosdevices method
I'm using Google Scripts to maintain a list of Chrome devices on our domain.

I'm using the AdminDirectory.Chromeosdevices.list method to get all the information I require and write it to a sheet.

I am then trying to write a script to write information to the annotatedLocation and annotatedAssetId fields using the  Chromeosdevices.update method.

My problem: I receive a  phrase error using the following, from looking at the suggestion: update(resource, customerId, deviceId, optionalArgs) I don't seem to have a 'resource', I cannot seem to find any way to get this value.

Any suggestions as to how I can get the resource??

```<code>var options = {
  "annotatedAssetId": (data[i][13] == "") ? data[i][3] : data[i][13],
  "annotatedLocation": (data[i][14] == "") ? data[i][4] : data[i][14],
  "notes": (data[i][15] == "") ? data[i][7] : data[i][15],
  "orgUnitPath": (data[i][16] == "") ? data[i][15] : data[i][16]
}
 var device = AdminDirectory.Chromeosdevices.update(data[i][11],"my_customer", data[i][10], options)
</code>```

Thank you

答:
I think you're referring to this line:

In the request body, supply a Chromeosdevices resource with the
  following properties:

resource is referring to Chromeosdevices resource.

```<code>{
  "kind": "admin#directory#chromeosdevice",
  "etag": etag,
  "deviceId": string,
  "serialNumber": string,
  "status": string,
  "lastSync": datetime,
  "supportEndDate": datetime,
  "annotatedUser": string,
  "annotatedLocation": string,
  "annotatedAssetId": string,
  "notes": string,
  "model": string,
  "meid": string,
  "orderNumber": string,
  "willAutoRenew": boolean,
  "osVersion": string,
  "platformVersion": string,
  "firmwareVersion": string,
  "macAddress": string,
  "bootMode": string,
  "lastEnrollmentTime": datetime,
  "orgUnitPath": string,
  "recentUsers": [
    {
      "type": string,
      "email": string
    }
  ],
  "ethernetMacAddress": string,
  "activeTimeRanges": [
    {
      "date": date,
      "activeTime": integer
    }
  ]
}
</code>```

Click the link for more info.

Title: Admin SDK Chromeosdevices method

Body:
I'm using Google Scripts to maintain a list of Chrome devices on our domain.

I'm using the AdminDirectory.Chromeosdevices.list method to get all the information I require and write it to a sheet.

I am then trying to write a script to write information to the annotatedLocation and annotatedAssetId fields using the  Chromeosdevices.update method.

My problem: I receive a  phrase error using the following, from looking at the suggestion: update(resource, customerId, deviceId, optionalArgs) I don't seem to have a 'resource', I cannot seem to find any way to get this value.

Any suggestions as to how I can get the resource??

var options = {
  "annotatedAssetId": (data[i][13] == "") ? data[i][3] : data[i][13],
  "annotatedLocation": (data[i][14] == "") ? data[i][4] : data[i][14],
  "notes": (data[i][15] == "") ? data[i][7] : data[i][15],
  "orgUnitPath": (data[i][16] == "") ? data[i][15] : data[i][16]
}
 var device = AdminDirectory.Chromeosdevices.update(data[i][11],"my_customer", data[i][10], options)

Thank you

Body:
I think you're referring to this line:

In the request body, supply a Chromeosdevices resource with the
  following properties:

resource is referring to Chromeosdevices resource.

{
  "kind": "admin#directory#chromeosdevice",
  "etag": etag,
  "deviceId": string,
  "serialNumber": string,
  "status": string,
  "lastSync": datetime,
  "supportEndDate": datetime,
  "annotatedUser": string,
  "annotatedLocation": string,
  "annotatedAssetId": string,
  "notes": string,
  "model": string,
  "meid": string,
  "orderNumber": string,
  "willAutoRenew": boolean,
  "osVersion": string,
  "platformVersion": string,
  "firmwareVersion": string,
  "macAddress": string,
  "bootMode": string,
  "lastEnrollmentTime": datetime,
  "orgUnitPath": string,
  "recentUsers": [
    {
      "type": string,
      "email": string
    }
  ],
  "ethernetMacAddress": string,
  "activeTimeRanges": [
    {
      "date": date,
      "activeTime": integer
    }
  ]
}

Click the link for more info.


答:
I looked in the documentation of the ajax-request module and noticed that the callback takes 3 arguments: function(err, res, body) {.

Perhaps the required data is in the third?

Title: Trouble reading ajax post response


问:
Get the audio data from Google Assistant
As of now (is using api.ai) what I see is, I get the string format of what the user speaks.

I would like to access the raw audio file the user speaks to interact with Google Assistant using the api.ai platform.

Is there a way to get the audio file ?

[UPDATE]:

We are aiming to evaluate the quality of speech of the user hence we would need to run the algorithms on the audio.

答:
No, there is currently no way to get the audio content of what has been sent. </p>

<p>(However, the team is looking to understand the use cases of why you might want or need this feature, so you may want to elaborate on your question further.)</p>

Body:
No, there is currently no way to get the audio content of what has been sent.

(However, the team is looking to understand the use cases of why you might want or need this feature, so you may want to elaborate on your question further.)


问:
Why are result sets so large?
Why are result sets from data bases so large?  I typically get result sets that are around a million rows, each of which contains a couple of numerics, a varchar(75), a big int...whatever.  Probably not much more than 100 bytes per row.  And yet it takes up 6 GB!  Is this typical behavior?  My stack is Postgres + JDBC + Spring - I don't have any experience with other technologies.  </p>

答:
We're gonna need to see a Query to see why it's so big. Maybe you're not joining tables right.
(I wish I could comment that...)</p>

Title: Why are result sets so large?


问:
How to write success message of form in bootstrap modal?
SOLVED

Ok, I solved the problem with AJAX but I had to delete my WordPress because it didn't work with it so later I will upload back by individual directory. Luckily I don't need it for my index. The working code is by CodexWorld. I hope I help someone who is helpless.

I am searching for solution all day but I don't get relevant solution anywhere. Other similar questions here are old, maybe there are fresh solution.

So I am using Bootstrap the first time (files are on the themes of Wordpress). I started to build a contact form in Modal and if I hit submit the window closes, I get the e-mail, but the success-message only shows if I reopen it. I tried every solution I found on internet.

I am not familiar with javascript and jquery, I don't know how to use it.

In the footer I implemented:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</code>```

In index there is the form with Modal:

```<code> <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
    <form class="form-horizontal clearfix" id="contact-form" name="contact" role="form" method="post" action="index.php">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <h4 class="modal-title" id="myModalLabel">Küldj egy üzenetet</h4>
          </div>
          <div class="modal-body">

</div>

<div class="form-group">
    <label class="col-sm-2 control-label">Itt landol</label>
    <div class="col-sm-10">
      <input class="form-control" id="disabledInput" type="text" placeholder="hello@kanizsaipatricia.hu" disabled>
    </div>
  </div>

    <div class="form-group">
        <label for="name" class="col-sm-2 control-label">Név</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="name" name="name" placeholder="Minta János" value="<?php echo htmlspecialchars($_POST['name']); ?>">
            <?php echo "<p class='text-danger'>$errName</p>";?>
        </div>
    </div>
    <div class="form-group">
        <label for="email" class="col-sm-2 control-label">Email</label>
        <div class="col-sm-10">
            <input type="email" class="form-control" id="email" name="email" placeholder="valaki@email.hu" value="<?php echo htmlspecialchars($_POST['email']); ?>">
            <?php echo "<p class='text-danger'>$errEmail</p>";?>
        </div>
    </div>
    <div class="form-group">
        <label for="message" class="col-sm-2 control-label">Üzenet</label>
        <div class="col-sm-10">
            <textarea class="form-control" placeholder="Ide írd az üzenetet" rows="4" name="message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
            <?php echo "<p class='text-danger'>$errMessage</p>";?>
        </div>
    </div>
        </div>

                        <?php echo $result; ?>

      <div class="modal-footer">
        <button type="button" class="btn btn-cancel hvr-fade" data-dismiss="modal">Mégsem</button>
        <input type="submit" id="submit" name="submit" data-toggle="modal" data-target="#resultModal" value="Elküldöm" class="btn btn-info hvr-wobble-horizontal">
    </div>
</pop:form>
      </div>
    </div>
</code>```

The php code behind the form:

```<code>if (isset($_POST["submit"])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'Üzenetküldő űrlap';
    $to = 'hello@kanizsaipatricia.hu';
    $subject = 'Új üzenet formon keresztül';

    $body = "Feladó: $name\n E-Mail: $email\n Üzenet:\n $message";

    // Check if name has been entered
    if (!$_POST['name']) {
        $errName = 'Kérlek, add meg a neved!';
    }

    // Check if email has been entered and is valid
    if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errEmail = 'Nem érvényes e-mail cím!';
    }

    //Check if message has been entered
    if (!$_POST['message']) {
        $errMessage = 'Nem írtál üzenetet.';
    }

// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage) {
    if (mail ($to, $subject, $body, $from)) {
        $result='<div class="alert alert-success noshadow">Elküldve.</div>';
    } else {
        $result='<div class="alert alert-danger noshadow">Sajnálom, hiba lépett fel az üzenet küldése közben. Próbáld újra!</div>';
    }
}
}
</code>```

I'm open minded for any solution in any language! Please help!

答:
Ok, I solved the problem with ajax but I had to delete my WordPress because it didn't work with it so later I will upload back by individual directory. Luckily I don't need it for my index. Thanks to CodexWorld.

Bootstrap & jQuery Library

Bootstrap is used to create modal popup and design HTMl form, include the bootstrap and jQuery library first.

```<code>    <!-- Latest minified bootstrap css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<!-- Latest minified bootstrap js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</code>```

Bootstrap Modal Popup Form

```<code><!-- Button to trigger modal -->
<button class="btn btn-success btn-lg" data-toggle="modal" data-target="#modalForm">
    Open Contact Form
</button>

<!-- Modal -->
<div class="modal fade" id="modalForm" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">×</span>
                    <span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">Contact Form</h4>
            </div>

            <!-- Modal Body -->
            <div class="modal-body">
                <p class="statusMsg"></p>
                <form role="form">
                    <div class="form-group">
                        <label for="inputName">Name</label>
                        <input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
                    </div>
                    <div class="form-group">
                        <label for="inputEmail">Email</label>
                        <input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
                    </div>
                    <div class="form-group">
                        <label for="inputMessage">Message</label>
                        <textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
                    </div>
                </form>
            </div>

            <!-- Modal Footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button>
            </div>
        </div>
    </div>
</div>
</code>```

JavaScript Code: Validate and Submit Form

```<code><script>
function submitContactForm(){
    var reg = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
    var name = $('#inputName').val();
    var email = $('#inputEmail').val();
    var message = $('#inputMessage').val();
    if(name.trim() == '' ){
        alert('Please enter your name.');
        $('#inputName').focus();
        return false;
    }else if(email.trim() == '' ){
        alert('Please enter your email.');
        $('#inputEmail').focus();
        return false;
    }else if(email.trim() != '' && !reg.test(email)){
        alert('Please enter valid email.');
        $('#inputEmail').focus();
        return false;
    }else if(message.trim() == '' ){
        alert('Please enter your message.');
        $('#inputMessage').focus();
        return false;
    }else{
        $.ajax({
            type:'POST',
            url:'submit_form.php',
            data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message,
            beforeSend: function () {
                $('.submitBtn').attr("disabled","disabled");
                $('.modal-body').css('opacity', '.5');
            },
            success:function(msg){
                if(msg == 'ok'){
                    $('#inputName').val('');
                    $('#inputEmail').val('');
                    $('#inputMessage').val('');
                    $('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
                }else{
                    $('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
                }
                $('.submitBtn').removeAttr("disabled");
                $('.modal-body').css('opacity', '');
            }
        });
    }
}
</script>
</code>```

Send Contact Request Email (submit_form.php)

```<code><?php
if(isset($_POST['contactFrmSubmit']) && !empty($_POST['name']) && !empty($_POST['email']) && (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) && !empty($_POST['message'])){

    // Submitted form data
    $name   = $_POST['name'];
    $email  = $_POST['email'];
    $message= $_POST['message'];

    /*
     * Send email to admin
     */
    $to     = 'admin@example.com';
    $subject= 'Contact Request Submitted';

    $htmlContent = '
    <h4>Contact request has submitted at CodexWorld, details are given below.</h4>
    <table cellspacing="0" style="width: 300px; height: 200px;">
        <tr>
            <th>Name:</th><td>'.$name.'</td>
        </tr>
        <tr style="background-color: #e0e0e0;">
            <th>Email:</th><td>'.$email.'</td>
        </tr>
        <tr>
            <th>Message:</th><td>'.$message.'</td>
        </tr>
    </table>';

    // Set content-type header for sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

    // Additional headers
    $headers .= 'From: CodexWorld<sender@example.com>' . "\r\n";

    // Send email
    if(mail($to,$subject,$htmlContent,$headers)){
        $status = 'ok';
    }else{
        $status = 'err';
    }

    // Output status
    echo $status;die;
}
</code>```

Body:
SOLVED

Ok, I solved the problem with AJAX but I had to delete my WordPress because it didn't work with it so later I will upload back by individual directory. Luckily I don't need it for my index. The working code is by CodexWorld. I hope I help someone who is helpless.

I am searching for solution all day but I don't get relevant solution anywhere. Other similar questions here are old, maybe there are fresh solution.

So I am using Bootstrap the first time (files are on the themes of Wordpress). I started to build a contact form in Modal and if I hit submit the window closes, I get the e-mail, but the success-message only shows if I reopen it. I tried every solution I found on internet.

I am not familiar with javascript and jquery, I don't know how to use it.

In the footer I implemented:

In index there is the form with Modal:

    <form class="form-horizontal clearfix" id="contact-form" name="contact" role="form" method="post" action="index.php">

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Küldj egy üzenetet

    Itt landol

      <input class="form-control" id="disabledInput" type="text" placeholder="hello@kanizsaipatricia.hu" disabled>

        Név

            <input type="text" class="form-control" id="name" name="name" placeholder="Minta János" value="<?php echo htmlspecialchars($_POST['name']); ?>">
            <?php echo "
$errName
";?>

        Email

            <input type="email" class="form-control" id="email" name="email" placeholder="valaki@email.hu" value="<?php echo htmlspecialchars($_POST['email']); ?>">
            <?php echo "
$errEmail
";?>

        Üzenet

            <textarea class="form-control" placeholder="Ide írd az üzenetet" rows="4" name="message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
            <?php echo "
$errMessage
";?>

                        <?php echo $result; ?>

        <button type="button" class="btn btn-cancel hvr-fade" data-dismiss="modal">Mégsem</button>
        <input type="submit" id="submit" name="submit" data-toggle="modal" data-target="#resultModal" value="Elküldöm" class="btn btn-info hvr-wobble-horizontal">

</pop:form>

The php code behind the form:

if (isset($_POST["submit"])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'Üzenetküldő űrlap';
    $to = 'hello@kanizsaipatricia.hu';
    $subject = 'Új üzenet formon keresztül';

    $body = "Feladó: $name\n E-Mail: $email\n Üzenet:\n $message";

    // Check if name has been entered
    if (!$_POST['name']) {
        $errName = 'Kérlek, add meg a neved!';
    }

    // Check if email has been entered and is valid
    if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errEmail = 'Nem érvényes e-mail cím!';
    }

    //Check if message has been entered
    if (!$_POST['message']) {
        $errMessage = 'Nem írtál üzenetet.';
    }

// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage) {
    if (mail ($to, $subject, $body, $from)) {
        $result='
Elküldve.
';
    } else {
        $result='
Sajnálom, hiba lépett fel az üzenet küldése közben. Próbáld újra!
';
    }
}
}

I'm open minded for any solution in any language! Please help!

Body:
Ok, I solved the problem with ajax but I had to delete my WordPress because it didn't work with it so later I will upload back by individual directory. Luckily I don't need it for my index. Thanks to CodexWorld.

Bootstrap & jQuery Library

Bootstrap is used to create modal popup and design HTMl form, include the bootstrap and jQuery library first.

    <!-- Latest minified bootstrap css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<!-- Latest minified bootstrap js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Bootstrap Modal Popup Form

<!-- Button to trigger modal -->
<button class="btn btn-success btn-lg" data-toggle="modal" data-target="#modalForm">
    Open Contact Form
</button>

<!-- Modal -->
<div class="modal fade" id="modalForm" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                    <span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">Contact Form</h4>
            </div>

            <!-- Modal Body -->
            <div class="modal-body">
                <p class="statusMsg"></p>
                <form role="form">
                    <div class="form-group">
                        <label for="inputName">Name</label>
                        <input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
                    </div>
                    <div class="form-group">
                        <label for="inputEmail">Email</label>
                        <input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
                    </div>
                    <div class="form-group">
                        <label for="inputMessage">Message</label>
                        <textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
                    </div>
                </form>
            </div>

            <!-- Modal Footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button>
            </div>
        </div>
    </div>
</div>

JavaScript Code: Validate and Submit Form

<script>
function submitContactForm(){
    var reg = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
    var name = $('#inputName').val();
    var email = $('#inputEmail').val();
    var message = $('#inputMessage').val();
    if(name.trim() == '' ){
        alert('Please enter your name.');
        $('#inputName').focus();
        return false;
    }else if(email.trim() == '' ){
        alert('Please enter your email.');
        $('#inputEmail').focus();
        return false;
    }else if(email.trim() != '' && !reg.test(email)){
        alert('Please enter valid email.');
        $('#inputEmail').focus();
        return false;
    }else if(message.trim() == '' ){
        alert('Please enter your message.');
        $('#inputMessage').focus();
        return false;
    }else{
        $.ajax({
            type:'POST',
            url:'submit_form.php',
            data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message,
            beforeSend: function () {
                $('.submitBtn').attr("disabled","disabled");
                $('.modal-body').css('opacity', '.5');
            },
            success:function(msg){
                if(msg == 'ok'){
                    $('#inputName').val('');
                    $('#inputEmail').val('');
                    $('#inputMessage').val('');
                    $('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
                }else{
                    $('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
                }
                $('.submitBtn').removeAttr("disabled");
                $('.modal-body').css('opacity', '');
            }
        });
    }
}
</script>

Send Contact Request Email (submit_form.php)

<?php
if(isset($_POST['contactFrmSubmit']) && !empty($_POST['name']) && !empty($_POST['email']) && (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) && !empty($_POST['message'])){

    // Submitted form data
    $name   = $_POST['name'];
    $email  = $_POST['email'];
    $message= $_POST['message'];

    /*
     * Send email to admin
     */
    $to     = 'admin@example.com';
    $subject= 'Contact Request Submitted';

    $htmlContent = '
    <h4>Contact request has submitted at CodexWorld, details are given below.</h4>
    <table cellspacing="0" style="width: 300px; height: 200px;">
        <tr>
            <th>Name:</th><td>'.$name.'</td>
        </tr>
        <tr style="background-color: #e0e0e0;">
            <th>Email:</th><td>'.$email.'</td>
        </tr>
        <tr>
            <th>Message:</th><td>'.$message.'</td>
        </tr>
    </table>';

    // Set content-type header for sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

    // Additional headers
    $headers .= 'From: CodexWorld<sender@example.com>' . "\r\n";

    // Send email
    if(mail($to,$subject,$htmlContent,$headers)){
        $status = 'ok';
    }else{
        $status = 'err';
    }

    // Output status
    echo $status;die;
}


问:
Expected LdrDoDebuggerBreak(), got NtWaitForWorkViaWorkerFactory()
During a debugging workshop, one of the participants could not follow an example.

When running an executable under WinDbg 10.0.15603.137 on his Windows 10 machine, the debugger was breaking the first time at NtWaitForWorkViaWorkerFactory() instead of the initial breakpoint in LdrDoDebuggerBreak().

When trying to run the executable with g, it says that there's no debugee to run. What could the problem have been?

Here's what it looked like:

The source code of the application is trivial:

```<code>#include "stdafx.h"
#include <exception>

int _tmain(int /*argc*/, _TCHAR* /*argv*/[])
{
    throw std::exception();
}
</code>```

Note: I'll hardly be able to provide additional information, since I have no more access to the customer's PC and it doesn't happen on mine.

答:
It's not possible to say for sure what the problem was, but we can say what the problem could have been. Luckily that's what you asked.

I can't assign exact probabilities to this, but it's quite likely that an implicitly linked DLL failed loading. That's the major thing that happens before the initial breakpoint1.

Why did a DLL failed to load? Maybe some kind of resource problem, but - especially assuming you tried running a "fresh" machine after a restart - somewhat more likely is an extra DLL being loaded on the problematic machine. Maybe an AVRF DLL, maybe an AppInit DLL, maybe one of a hundred other ways to inject DLLs into unknowing and unwilling processes2.

As I said in my comment, the way to find out for sure would have been having WinDBG break on process creation rather than on the initial breakpoint, and start debugging from there.

The way to do this is to start NTSD/CDB with -xe cpr, setting this in WinDBG's Event Filters window (accessible through the Debug menu), or using sxe cpr and .restart in WinDBG, assuming you started the process in WinDBG (rather than attached to it), which is the best easiets and best in my opinion, but that's a matter of taste.

1 I think TLS callbacks for the main modules are also executed before the initial breakpoint, but what are the chances someone messes with the project configuration or the CRT LIBs to add a problematic TLS callback? (TLS callbacks of the implicitly linked DLLs are included in "DLL loading".)

2 But again, the more nefarious and clever tricks are less common and thus less likely.

Body:
During a debugging workshop, one of the participants could not follow an example.

When running an executable under WinDbg 10.0.15603.137 on his Windows 10 machine, the debugger was breaking the first time at NtWaitForWorkViaWorkerFactory() instead of the initial breakpoint in LdrDoDebuggerBreak().

When trying to run the executable with g, it says that there's no debugee to run. What could the problem have been?

Here's what it looked like:

The source code of the application is trivial:

#include "stdafx.h"
#include <exception>

int _tmain(int /*argc*/, _TCHAR* /*argv*/[])
{
    throw std::exception();
}

Note: I'll hardly be able to provide additional information, since I have no more access to the customer's PC and it doesn't happen on mine.


问:
Automatically stamping UserName of the User who created the a Sales record in the sales table
I want to create a ASP.NET MVC web application, which includes an Admin account and few user account, for registering and login I'm using Default Account Model and controller. Can anyone tell me how can I AutoStamp the username of the user who created the sales record also how can I view this in my index page.
For sales I have Sales Model which has

```<code>{
public ApplicationUser ApplicationUser { get; set; }
    public int Id { get; set; }
    public string Po { get; set; }
    public long So { get; set; }
}
</code>```

Thanks in advance.

答:
Store the username in the session.

```<code>Session["UserId"] = usernameThatLoggedIn
</code>```

Later you can access it with

```<code>Session["UserId"]
</code>```

If you are not inside a Controller you can access it via

```<code>HttpContext.Current.Session["UserId"]
</code>```

Body:
I want to create a ASP.NET MVC web application, which includes an Admin account and few user account, for registering and login I'm using Default Account Model and controller. Can anyone tell me how can I AutoStamp the username of the user who created the sales record also how can I view this in my index page.
For sales I have Sales Model which has

{
public ApplicationUser ApplicationUser { get; set; }
    public int Id { get; set; }
    public string Po { get; set; }
    public long So { get; set; }
}

Thanks in advance.

Body:
Store the username in the session.

Session["UserId"] = usernameThatLoggedIn

Later you can access it with

Session["UserId"]

If you are not inside a Controller you can access it via

HttpContext.Current.Session["UserId"]


问:
Unknown error using Swift 3 in xcode 8 - "Editor placeholder in source file"
I am creating a helper function to handle what happens when a register button is clicked. I am attempting to connect Firebase database and use the reference that I create to input the information that is inputed. I am getting the following two errors upon finishing the function...

```<code>"Editor placeholder in source file"
"Value of optional type 'String?' not unwrapped, did you mean '!' or '?'?"
</code>```

The first error is the one I am most concerned about, but all pointers would be appreciated.

Here is the function that I have created to handle the RegisterButtonClick action:

```<code>func handleRegisterClick(){
        guard let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text else{
            print("Form is not valid...")
            return
        }

        FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user: FIRUser?, error) in
            if error != nil{
                print(error ?? "user was not created... something went wrong")
                return
            }
            // else... succesfully authernticated user

            var ref: FIRDatabaseReference!
            ref = FIRDatabase.database().reference()

            let values = ["name": name, "email": email]

            ref.updateChildValues(values, withCompletionBlock: { (err, ref) in
                if err != nil{
                    print(err ?? "Child values could not be updated... something went wrong")
                    return
                }
                print("Saved user successfully into the Firebase DB")
            })
        })
        print("Register Button was pressed.")
    }
</code>```

Up above is where the error is being called. The following block of code shows where this function is being called:

```<code>lazy var loginRegisterButton: UIButton = {
        let button = UIButton(type: .system)
        button.backgroundColor = UIColor(r: 80, g: 101, b: 161)
        button.setTitle("Register", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)

        button.addTarget(self, action: #selector(handleRegisterClick), for: .touchUpInside)

        // this next step is needed or else the constraints set later on will not work
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()
</code>```

Any help fixing the first error would be extremely helpful. I just don't understand what the error is stating. Very new to iOS development, therefore apologies on any unclarity.

答:
Xcode inserts placeholders in your code when using autocomplete. You should replace them with your own values. That first error means you left one of those placeholders in your code. It should look visually different, with a rounded "pill-like" background of a different color. Find it and replace it or remove it.

The second error means you have an optional String (String?) that you have to unwrap using ! or ? to turn it into a non-optional String.

Body:
I am creating a helper function to handle what happens when a register button is clicked. I am attempting to connect Firebase database and use the reference that I create to input the information that is inputed. I am getting the following two errors upon finishing the function...

"Editor placeholder in source file"
"Value of optional type 'String?' not unwrapped, did you mean '!' or '?'?"

The first error is the one I am most concerned about, but all pointers would be appreciated.

Here is the function that I have created to handle the RegisterButtonClick action:

func handleRegisterClick(){
        guard let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text else{
            print("Form is not valid...")
            return
        }

        FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user: FIRUser?, error) in
            if error != nil{
                print(error ?? "user was not created... something went wrong")
                return
            }
            // else... succesfully authernticated user

            var ref: FIRDatabaseReference!
            ref = FIRDatabase.database().reference()

            let values = ["name": name, "email": email]

            ref.updateChildValues(values, withCompletionBlock: { (err, ref) in
                if err != nil{
                    print(err ?? "Child values could not be updated... something went wrong")
                    return
                }
                print("Saved user successfully into the Firebase DB")
            })
        })
        print("Register Button was pressed.")
    }

Up above is where the error is being called. The following block of code shows where this function is being called:

lazy var loginRegisterButton: UIButton = {
        let button = UIButton(type: .system)
        button.backgroundColor = UIColor(r: 80, g: 101, b: 161)
        button.setTitle("Register", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)

        button.addTarget(self, action: #selector(handleRegisterClick), for: .touchUpInside)

        // this next step is needed or else the constraints set later on will not work
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

Any help fixing the first error would be extremely helpful. I just don't understand what the error is stating. Very new to iOS development, therefore apologies on any unclarity.


问:
Is there a way to style a TextView to uppercase all of its letters?
I would like to be able to assign a xml attribute or style to a TextView that will make whatever text it has in ALL CAPITAL LETTERS.

The attributes android:inputType="textCapCharacters" and android:capitalize="characters" do nothing and look like they are for user inputed text, not a TextView.

I would like to do this so I can separate the style from the content.  I know I could do this programmically but again I want keep style out of the content and the code.

答:
I though that was a pretty reasonable request but it looks like you cant do it at this time. What a Total Failure. lol

Update

You can now use
textAllCaps
 to force all caps.


问:
I need a way to run Haskell code without any install on a Mac
I enjoy developing in Haskell, but am presently confronted with a challenge. At my place of education, I don't have administrative rights on my account. I want to debug/test while there. I need a way to run Haskell code without installing haskell-platform or ghci or anything else requiring of an administrative level of privilege. For instance, a web site which will run haskell code (abeit limited to not include file access of course) or a java utility (or standalone .app, though java is preferred due to the nature of the "parental controls"), or something else I haven't thought of. Source or compiled Java, Flash, and source code in Ruby or Python are preferred to native code. This is on Mac OS X 10.6, for reference.

答:
You just need to install homebrew, which you can do without root rights if you do so in your home directory. You can then brew install cabal-install
which will automatically install cabal and ghc, or brew install stack to install stack.


问:
How to set a recursive steps counter using MySQL data in PHP
So, I'm creating a mini strategy game for fun, and stumbled upon an issue I can't really sort out.

I thought it would be easy, but seems I was wrong, or maybe the solution is right under my nose, but I'm looking for another view on my problem.

I have a database with a list of Territories recorded on a Map. Each of these territories hold a list of adjacent territories.

```<code>ID | name  | adjacent     | faction

1  | Name1 | 2;7;10;24    | 5
2  | Name2 | 1;3;7;8      | 4
3  | Name3 | 2;4;5;8      | 8
</code>```

adjacent being a list of IDs separated by semi-colon

My goal is to find the shortest route to a territory from all territories held by a certain faction. The distance is calculated by the amount of steps required to reach the territory.

This way, I can quickly get the distance and apply modifiers in this regard.

For instance, in the data snippet above:

Territory 1 is at 0 distance from 2, since they're adjacent.

Territory 1 is at 1 distance from 3, since 3 is adjacent to 2 (and 2 is adjacent to 1).

Territory 1 is at 2 distance from 4, since 4 is adjacent to 3, which is adjacent to 2.

Currently, my code looks like this;

```<code>function getProximity($connexion, $faction, $terrain)
{
    $query = "SELECT id, adjacent FROM worldmap WHERE faction = ".$faction;
    $result = mysqli_query($connexion, $query);

    $proximity = 10;
    while ($row = mysqli_fetch_row($result))
    {
        $adjacent = explode(";", $row[1]);
        if (in_array($terrain, $adjacent))
        {
            //territory is adjacent, stop looking
            return 0;
        }
        else
        {
            //if not directly adjacent, seek through the list
            foreach($adjacent as $adj)
            {
                $prox = getSubProximity($connexion, array($row[0]), $adj, $terrain, 1);
                if ($prox < $proximity)
                {
                    $proximity = $prox;
                }
            }
        }
    }

    return $proximity;
}

function getSubProximity($connexion, $from, $terrain, $terrain2, $proximity)
{
    //Attempt to break weird loops... not succesful...
    if ($proximity > 10)
    {
        return $proximity;
    }
    $query = "SELECT id, adjacent FROM worldmap WHERE id = ".$terrain;
    $result = mysqli_query($connexion, $query);

    while ($row = mysqli_fetch_row($result))
    {
        $adjacent = explode(";", $row[1]);
        if (in_array($terrain2, $adjacent))
        {
            //territory is adjacent, stop looping
            return $proximity;
        }
        else
        {
            foreach($adjacent as $adj)
            {
                //check if we've been through there
                if (!in_array($adj, $from))
                {
                    array_push($from, $terrain);
                    $prox = getSubProximity($connexion, $from, $adj, $terrain2, $proximity+1);
                    if ($prox < $proximity)
                    {
                        $proximity = $prox;
                    }
                }
            }
        }
    }
}
</code>```

Thanks for the help, and feel free if you have other ways to get the same result; the database structure isn't static and fully under my control.

答:
Some things I would suggest:

MySql is not so strong in working with self-referencing/hierarchical data, so against the usual answer ("do it in SQL"), perform the logic in PHP.

Since the total data set is relatively small, read all the territories' data in memory with one query, and then leave the database out of it.

Perform a non-recursive, breadth first search. This way you only need to visit any world territory at most once.

Keep a list of territories that you have already visited, to avoid endless looping in circles, and use an associative array for this so you get fast key lookup (instead of inefficient in_array). It is not enough to just keep note of a $from territory.

Here is the outline of such code:

```<code>// This function returns the whole data set in a nice data structure
function getProximityData($connexion) {
    $query = "SELECT id, adjacent, faction FROM worldmap";
    $result = mysqli_query($connexion, $query);
    while ($row = mysqli_fetch_row($result)) {
        $territories[$row[0]] = [
            "adjacent" => explode(";", $row[1]),
            "faction" => $row[2]
        ];
    }
    return $territories;
}

function getProximity($territories, $faction, $terrain) {
    // mark this terrain as visited
    $visited[$terrain] = 1;
    // Create queue for breadth first search
    $queue = [$terrain];
    $steps = 0;
    while (count($queue)) {
        $next = [];
        foreach($queue as $terrain) {
            if ($territories[$terrain]["faction"] === $faction) {
                // Territory belongs to the faction, stop looking
                return $steps;
            }
            // collect list of unvisited neighbours of this terrain
            foreach($territories[$terrain]["adjacent"] as $adj) {
                if (!isset($visited[$adj])) { // not yet visited
                    $next[] = $adj;
                    $visited[$adj] = 1;
                }
            }
        }
        $queue = $next;
        $steps++;
    }
    // Should never get here: it would mean territories are disconnected
}

// Load the world map:
$territories = getProximityData($connexion);

// Example use:
$steps = getProximity($territories, 5, 4); // distance of faction 5 to territory 4.
</code>```

Note that 0 will be returned for a territory (last argument) that is owned by the given faction (second argument). For a territory that is adjacent to the faction you'll get 1, ...etc.

Body:
So, I'm creating a mini strategy game for fun, and stumbled upon an issue I can't really sort out.

I thought it would be easy, but seems I was wrong, or maybe the solution is right under my nose, but I'm looking for another view on my problem.

I have a database with a list of Territories recorded on a Map. Each of these territories hold a list of adjacent territories.

ID | name  | adjacent     | faction

1  | Name1 | 2;7;10;24    | 5
2  | Name2 | 1;3;7;8      | 4
3  | Name3 | 2;4;5;8      | 8

adjacent being a list of IDs separated by semi-colon

My goal is to find the shortest route to a territory from all territories held by a certain faction. The distance is calculated by the amount of steps required to reach the territory.

This way, I can quickly get the distance and apply modifiers in this regard.

For instance, in the data snippet above:

Territory 1 is at 0 distance from 2, since they're adjacent.

Territory 1 is at 1 distance from 3, since 3 is adjacent to 2 (and 2 is adjacent to 1).

Territory 1 is at 2 distance from 4, since 4 is adjacent to 3, which is adjacent to 2.

Currently, my code looks like this;

function getProximity($connexion, $faction, $terrain)
{
    $query = "SELECT id, adjacent FROM worldmap WHERE faction = ".$faction;
    $result = mysqli_query($connexion, $query);

    $proximity = 10;
    while ($row = mysqli_fetch_row($result))
    {
        $adjacent = explode(";", $row[1]);
        if (in_array($terrain, $adjacent))
        {
            //territory is adjacent, stop looking
            return 0;
        }
        else
        {
            //if not directly adjacent, seek through the list
            foreach($adjacent as $adj)
            {
                $prox = getSubProximity($connexion, array($row[0]), $adj, $terrain, 1);
                if ($prox < $proximity)
                {
                    $proximity = $prox;
                }
            }
        }
    }

    return $proximity;
}

function getSubProximity($connexion, $from, $terrain, $terrain2, $proximity)
{
    //Attempt to break weird loops... not succesful...
    if ($proximity > 10)
    {
        return $proximity;
    }
    $query = "SELECT id, adjacent FROM worldmap WHERE id = ".$terrain;
    $result = mysqli_query($connexion, $query);

    while ($row = mysqli_fetch_row($result))
    {
        $adjacent = explode(";", $row[1]);
        if (in_array($terrain2, $adjacent))
        {
            //territory is adjacent, stop looping
            return $proximity;
        }
        else
        {
            foreach($adjacent as $adj)
            {
                //check if we've been through there
                if (!in_array($adj, $from))
                {
                    array_push($from, $terrain);
                    $prox = getSubProximity($connexion, $from, $adj, $terrain2, $proximity+1);
                    if ($prox < $proximity)
                    {
                        $proximity = $prox;
                    }
                }
            }
        }
    }
}

Thanks for the help, and feel free if you have other ways to get the same result; the database structure isn't static and fully under my control.

Body:
Some things I would suggest:

MySql is not so strong in working with self-referencing/hierarchical data, so against the usual answer ("do it in SQL"), perform the logic in PHP.

Since the total data set is relatively small, read all the territories' data in memory with one query, and then leave the database out of it.

Perform a non-recursive, breadth first search. This way you only need to visit any world territory at most once.

Keep a list of territories that you have already visited, to avoid endless looping in circles, and use an associative array for this so you get fast key lookup (instead of inefficient in_array). It is not enough to just keep note of a $from territory.

Here is the outline of such code:

// This function returns the whole data set in a nice data structure
function getProximityData($connexion) {
    $query = "SELECT id, adjacent, faction FROM worldmap";
    $result = mysqli_query($connexion, $query);
    while ($row = mysqli_fetch_row($result)) {
        $territories[$row[0]] = [
            "adjacent" => explode(";", $row[1]),
            "faction" => $row[2]
        ];
    }
    return $territories;
}

function getProximity($territories, $faction, $terrain) {
    // mark this terrain as visited
    $visited[$terrain] = 1;
    // Create queue for breadth first search
    $queue = [$terrain];
    $steps = 0;
    while (count($queue)) {
        $next = [];
        foreach($queue as $terrain) {
            if ($territories[$terrain]["faction"] === $faction) {
                // Territory belongs to the faction, stop looking
                return $steps;
            }
            // collect list of unvisited neighbours of this terrain
            foreach($territories[$terrain]["adjacent"] as $adj) {
                if (!isset($visited[$adj])) { // not yet visited
                    $next[] = $adj;
                    $visited[$adj] = 1;
                }
            }
        }
        $queue = $next;
        $steps++;
    }
    // Should never get here: it would mean territories are disconnected
}

// Load the world map:
$territories = getProximityData($connexion);

// Example use:
$steps = getProximity($territories, 5, 4); // distance of faction 5 to territory 4.

Note that 0 will be returned for a territory (last argument) that is owned by the given faction (second argument). For a territory that is adjacent to the faction you'll get 1, ...etc.


问:
How can I center the loading div before load() with jQuery?
I have this code:

```<code>$("#result").html('<div class="loading">Loading results...</div>');
$("#result").load('<?php bloginfo('template_directory'); ?>/GetResults.php?' + $.cookie('nw-query'));
</code>```

It shows the loading div until the load is done. What I want to do here, I want the loading div exactly in the center of the page/document?

That's extra but could be nice - can I also fade the document until the load is done so that the loading div stands out?

Any jquery/css suggestions are welcome.

Thank you :)

答: If understand you question correctly: You need to figure out how to center the loading div both horizontally and vertically? If so, I would take a look at the answers to this question: Practical solution to center vertically and horizontally in HTML that works in FF, IE6 and IE7.</p>

Body:
I have this code:

$("#result").html('
Loading results...
');
$("#result").load('<?php bloginfo('template_directory'); ?>/GetResults.php?' + $.cookie('nw-query'));

It shows the loading div until the load is done. What I want to do here, I want the loading div exactly in the center of the page/document?

That's extra but could be nice - can I also fade the document until the load is done so that the loading div stands out?

Any jquery/css suggestions are welcome.

Thank you :)


问:
database triggers firebase function to download images from URL and save it to storage
I want to download the image and save it to storage when my database is updated with the 'photo_url' field

```<code>exports.saveToStorage = functions.database.ref(`/images/${itemImageRef}`)
.onWrite(event => {
  const filePath = event.data.val();
  const filename = filePath.split('/').pop();

  var download = request.get(filePath).on('error', (err) => {
    console.log(err)
  })
  .pipe(fs.createWriteStream(filename));

  download.on('finish', () => {
    const bucket = gcs.bucket('id.appspot.com');
    const storagePath = `images/${filename}`;

    return bucket.upload(download, { destination: storagePath })
    .then(() => {
      console.log('success upload');
    });
  });
});
</code>```

it logs "Error: EROFS: read-only file system, open 'image.jpg' at Error (native)." I suppose I cannot retrieve the file saved by createWriteStream?
So how should I download images from the web?

答:
with the post suggested by @Jobsamuel, the code now works:

```<code>exports.saveToStorage = functions.database.ref(`/images/${itemImageRef}`)
.onWrite(event => {

  const filePath = event.data.val();
  const filename = filePath.split('/').pop();

  const bucket = gcs.bucket('id.appspot.com');
  const remoteWriteStream = bucket.file(filename).createWriteStream({
    metadata: { contentType: 'image/jpeg' }
  });

  request(filePath).pipe(remoteWriteStream)
  .on('error', (err) => console.log(err))
  .on('finish', () => console.log('success save image'));

});
</code>```

By pipe the request result directly to the bucket, it solves the problem by skipping the step writing to a local file, which I suspect is the reason my original code fails. Also, don't forget to set contentType for images.

Body:
I want to download the image and save it to storage when my database is updated with the 'photo_url' field

exports.saveToStorage = functions.database.ref(`/images/${itemImageRef}`)
.onWrite(event => {
  const filePath = event.data.val();
  const filename = filePath.split('/').pop();

  var download = request.get(filePath).on('error', (err) => {
    console.log(err)
  })
  .pipe(fs.createWriteStream(filename));

  download.on('finish', () => {
    const bucket = gcs.bucket('id.appspot.com');
    const storagePath = `images/${filename}`;

    return bucket.upload(download, { destination: storagePath })
    .then(() => {
      console.log('success upload');
    });
  });
});

it logs "Error: EROFS: read-only file system, open 'image.jpg' at Error (native)." I suppose I cannot retrieve the file saved by createWriteStream?
So how should I download images from the web?

Body:
with the post suggested by @Jobsamuel, the code now works:

exports.saveToStorage = functions.database.ref(`/images/${itemImageRef}`)
.onWrite(event => {

  const filePath = event.data.val();
  const filename = filePath.split('/').pop();

  const bucket = gcs.bucket('id.appspot.com');
  const remoteWriteStream = bucket.file(filename).createWriteStream({
    metadata: { contentType: 'image/jpeg' }
  });

  request(filePath).pipe(remoteWriteStream)
  .on('error', (err) => console.log(err))
  .on('finish', () => console.log('success save image'));

});

By pipe the request result directly to the bucket, it solves the problem by skipping the step writing to a local file, which I suspect is the reason my original code fails. Also, don't forget to set contentType for images.


问:
RGB-Depth Datasets for Images and Videos
I'm looking for RGB-D (D is depth) datasets of images and videos for object detection and recognition tasks similar to the ones provided by PASCAL VOC or ILSVRC (but augmented with depth data).</p>

答: A great list of RGBD datasets can be found here : http://www0.cs.ucl.ac.uk/staff/M.Firman/RGBDdatasets/</p>