问:
Linq ToDictionary returns an anonymous type
I want to call a method that returns an anonymous type.  I need to know what the Type of this anonymous type is because I am returning it in a method.  Is it called "dynamic"?  When I debug, the watch window says the type is <>f__AnonymousType0.

Here is my code:

```<code>// this doesn't compile
public static Dictionary<int,dynamic> GetRuleNamesDictionary()
{
    List<ResponseRoutingRule> rules = GetResponseRoutingRules();
    var q = (rules.Select(r => new {r.ResponseRoutingRuleId, r.RuleName}));

    var dict1 = q.ToDictionary(d => d.ResponseRoutingRuleId);
    var dict = q.ToDictionary(d => d.ResponseRoutingRuleId, d => d.RuleName);
    return dict;
}

public static List<ResponseRoutingRule> GetResponseRoutingRules()
{
   ....
}

public class ResponseRoutingRule
{
    public int ResponseRoutingRuleId { get; set; }
    ....
    public string RuleName { get; set; }
    ...
}
</code>```

答:
Well, you actually seem to be returning a Dictionary<int, string>. The type of dict's values isn't an anonymous type; it's a plain old string. In fact, there doesn't seem to be any need for anonymous types or dynamic here.

Are you sure this isn't what you really want?

```<code>public static Dictionary<int, string> GetRuleNamesDictionary()
{
    return GetResponseRoutingRules()
            .ToDictionary(r => r.ResponseRoutingRuleId, r => r.RuleName);
}
</code>```

If not, please let us know why.

If you really want to stick with dynamic, you could of course cast as appropriate:

```<code>public static Dictionary<int, dynamic> GetRuleNamesDictionary()
{
    return GetResponseRoutingRules()
            .ToDictionary(r => r.ResponseRoutingRuleId, r => (dynamic) r.RuleName);
}
</code>```

Body:
I want to call a method that returns an anonymous type.  I need to know what the Type of this anonymous type is because I am returning it in a method.  Is it called "dynamic"?  When I debug, the watch window says the type is <>f__AnonymousType0.

Here is my code:

// this doesn't compile
public static Dictionary<int,dynamic> GetRuleNamesDictionary()
{
    List<ResponseRoutingRule> rules = GetResponseRoutingRules();
    var q = (rules.Select(r => new {r.ResponseRoutingRuleId, r.RuleName}));

    var dict1 = q.ToDictionary(d => d.ResponseRoutingRuleId);
    var dict = q.ToDictionary(d => d.ResponseRoutingRuleId, d => d.RuleName);
    return dict;
}

public static List<ResponseRoutingRule> GetResponseRoutingRules()
{
   ....
}

public class ResponseRoutingRule
{
    public int ResponseRoutingRuleId { get; set; }
    ....
    public string RuleName { get; set; }
    ...
}

Body:
Well, you actually seem to be returning a Dictionary<int, string>. The type of dict's values isn't an anonymous type; it's a plain old string. In fact, there doesn't seem to be any need for anonymous types or dynamic here.

Are you sure this isn't what you really want?

public static Dictionary<int, string> GetRuleNamesDictionary()
{
    return GetResponseRoutingRules()
            .ToDictionary(r => r.ResponseRoutingRuleId, r => r.RuleName);
}

If not, please let us know why.

If you really want to stick with dynamic, you could of course cast as appropriate:

public static Dictionary<int, dynamic> GetRuleNamesDictionary()
{
    return GetResponseRoutingRules()
            .ToDictionary(r => r.ResponseRoutingRuleId, r => (dynamic) r.RuleName);
}


来源: stackexchange

问:
How to find ASCII value of a character in wtx
In a string, I want to replace all the characters between ASCII value of 0-32 and 127-255 to spaces. I have been breaking my head for 4 days and but not able to find the solution.</p>

答:
There is no shortcut for replacing ranges, but you can use the SUBSTITUTE function to replace each individual character.

```<code>=SUBSTITUTE(string,
SYMBOL(0), " ",
SYMBOL(1), " ",
// etc.
SYMBOL(254), " ",
SYMBOL(255), " ")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
There is no shortcut for replacing ranges, but you can use the SUBSTITUTE function to replace each individual character.

=SUBSTITUTE(string,
SYMBOL(0), " ",
SYMBOL(1), " ",
// etc.
SYMBOL(254), " ",
SYMBOL(255), " ")


问:
Boost regex to capture all repeated patterns
I have a simple text file with the following contents:

```<code>VALUE "foo"
ANOTHERVALUE "bar"
YETANOTHERVALUE "barbar"
</code>```

The values in column 1 are known.

I want to capture everything in column 1 and in column 2.

My solution involves manually writing all the possible values of column 1 (which is known), into the regex string but obviously this is not ideal practice since I am basically repeating code and this does not allow the ordering to be flexible:

```<code>const char* re =
     "^[[:space:]]*"
     "(VALUE)[[:space:]]*\"(.*)\"[[:space:]]*"
     "(ANOTHERVALUE)[[:space:]]*\"(.*)\"[[:space:]]*"
     "(YETANOTHERVALUE)[[:space:]]*\"(.*)\"[[:space:]]*";
</code>```

答:
I would use a little Spirit Parser here:

Reading Into A Map

Live On Coliru

```<code>#include <boost/fusion/adapted/std_pair.hpp> // reading maps
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>

#include <iostream>
#include <fstream>
#include <map>

auto read_config_map(std::istream& stream) {
    std::map<std::string, std::string> settings;

    boost::spirit::istream_iterator f(stream >> std::noskipws), l;
    using namespace boost::spirit::x3;

    auto key_ = lexeme [ +upper ];
    auto value_ = lexeme [ '"' >> *~char_('"') >> '"' ];

    if (!phrase_parse(f, l, -(key_ >> value_) % eol >> eoi, blank, settings))
        throw std::invalid_argument("cannot parse config map");

    return settings;
}

auto read_config_map(std::string const& fname) {
    std::ifstream stream(fname);
    return read_config_map(stream);
}

int main() {
    for (auto&& entry : read_config_map(std::cin))
        std::cout << "Key:'" << entry.first << "' Value:'" << entry.second << "'\n";
}
</code>```

Prints:

```<code>Key:'ANOTHERVALUE' Value:'bar'
Key:'VALUE' Value:'foo'
Key:'YETANOTHERVALUE' Value:'barbar'
</code>```

Body:
I have a simple text file with the following contents:

VALUE "foo"
ANOTHERVALUE "bar"
YETANOTHERVALUE "barbar"

The values in column 1 are known.

I want to capture everything in column 1 and in column 2.

My solution involves manually writing all the possible values of column 1 (which is known), into the regex string but obviously this is not ideal practice since I am basically repeating code and this does not allow the ordering to be flexible:

const char* re =
     "^[[:space:]]*"
     "(VALUE)[[:space:]]*\"(.*)\"[[:space:]]*"
     "(ANOTHERVALUE)[[:space:]]*\"(.*)\"[[:space:]]*"
     "(YETANOTHERVALUE)[[:space:]]*\"(.*)\"[[:space:]]*";

Body:
I would use a little Spirit Parser here:

Reading Into A Map

Live On Coliru

#include <boost/fusion/adapted/std_pair.hpp> // reading maps
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>

#include <iostream>
#include <fstream>
#include <map>

auto read_config_map(std::istream& stream) {
    std::map<std::string, std::string> settings;

    boost::spirit::istream_iterator f(stream >> std::noskipws), l;
    using namespace boost::spirit::x3;

    auto key_ = lexeme [ +upper ];
    auto value_ = lexeme [ '"' >> *~char_('"') >> '"' ];

    if (!phrase_parse(f, l, -(key_ >> value_) % eol >> eoi, blank, settings))
        throw std::invalid_argument("cannot parse config map");

    return settings;
}

auto read_config_map(std::string const& fname) {
    std::ifstream stream(fname);
    return read_config_map(stream);
}

int main() {
    for (auto&& entry : read_config_map(std::cin))
        std::cout << "Key:'" << entry.first << "' Value:'" << entry.second << "'\n";
}

Prints:

Key:'ANOTHERVALUE' Value:'bar'
Key:'VALUE' Value:'foo'
Key:'YETANOTHERVALUE' Value:'barbar'


问:
How can you read just the first word of every line of file using python?
What's the most efficient way to read just the first word of every line in a large text file? Should I use split? Is there a more efficient way? Can I just read one word and discard the line and go to the next line?
Right now I'm using this:

```<code>for line in f:
    dct[line.split(None, 1)[0]] = dct.get(line.split(None, 1)[0], 0) + 1
</code>```

答:
Try:

```<code>with open('file.txt','r') as f:
    for line in f:
        print(line.split(' ')[0])
</code>```

Where file.txt is the file you want to read. You can also use:

```<code>f = open('file.txt', 'r')
for line in f:
        print(line.split(' ')[0])
</code>```

f.readline() returns the line

.split(' ') creates a list with each word as an element

[0] selects the 0th element

Putting that as I put it maximizes efficiency by not losing time assigning values to variables. Although it is not too much.

Body:
What's the most efficient way to read just the first word of every line in a large text file? Should I use split? Is there a more efficient way? Can I just read one word and discard the line and go to the next line?
Right now I'm using this:

for line in f:
    dct[line.split(None, 1)[0]] = dct.get(line.split(None, 1)[0], 0) + 1

Body:
Try:

with open('file.txt','r') as f:
    for line in f:
        print(line.split(' ')[0])

Where file.txt is the file you want to read. You can also use:

f = open('file.txt', 'r')
for line in f:
        print(line.split(' ')[0])

f.readline() returns the line

.split(' ') creates a list with each word as an element

[0] selects the 0th element

Putting that as I put it maximizes efficiency by not losing time assigning values to variables. Although it is not too much.


问:
How do you test code without uploading to the web server?
(This is a high level software development question)

I'm running a web app.  In the past, to test new features, I have uploaded under a subdirectory such as test/.  This generally broke all the URLs, so I'd have to redo the URLs in the test code. Then I'd have to rename all the URLs when I pushed it to the main site.  I'm sure there's a better way but don't know what people usually do.

Do you install a web server on your laptop?  I could always buy a cheap computer and run it as a test web server, I suppose.

Eventually I'd like to have a version control system with a friend also coding, so maybe we'd both need to install Apache and MySQL on our laptops?  That way we don't interfere with each other when testing new code.

答:
You and your friend can install a WAMP/LAMP stack on each of your laptops. If you need a version control system, you can both use SVN or Git.

Structure your folders so they replicate the production server's directory structure. That way you don't have to rewrite URLs when deployment time comes. Virtual hosts will help you a lot.

OwnerDisplayName: anon

ContentLicense: CC BY-SA 2.5


问:
How do I bind different component instantations (in testbench) to different architectures in VHDL?
I create a multiplexer called mux21_generic.vhdl. It is a Nx1 mux. I define two architectures, one behavioral, the other structural.

The structural architecture uses a small 2x1 mux in the following way:

```<code>architecture structural of MUX21_GENERIC is

component MUX21 is
    Port (  A:      In      std_logic;
            B:      In      std_logic;
            S:      In      std_logic;
            Y:      Out     std_logic);
end component MUX21;

begin  -- structural

    create_mux:
        for i in 0 to N-1 generate
        begin
            MUX21_i : MUX21 port map(A=>A(i), B=>B(i), S=>SEL, Y=>Y(i));
        end generate create_mux;

end structural;
</code>```

These are the configurations:

```<code>-- CONFIGURATIONS --

-- (1) CFG_MUX21_GEN_BEHAVIORAL

configuration CFG_MUX21_GEN_BEHAVIORAL of MUX21_GENERIC is
    for behavioral
    end for;
end CFG_MUX21_GEN_BEHAVIORAL;

-- (2) CFG_MUX21_GEN_STRUCTURAL

configuration CFG_MUX21_GEN_STRUCTURAL of MUX21_GENERIC is
    for structural
        for create_mux
            for all : MUX21
                use configuration WORK.CFG_MUX21_STRUCTURAL;
            end for;
        end for;
     end for;
end CFG_MUX21_GEN_STRUCTURAL;
</code>```

The compilation works well, so I don't think the problem is in the above configurations.

I guess the problem is in the testbench.

The following code represents how I instantiate, in the "TEST" architecture of the testbench, both the behavioral and the structural mux:

```<code>U1 : MUX21_GENERIC
Generic Map (NBIT, 7 ns)
Port Map ( A1, B1, S1, output_beh); -- it should be behavioral

U2 : MUX21_GENERIC
Generic Map (NBIT)
Port Map ( A1, B1, S1, output_str); -- it should be structural
</code>```

and this is the configuration that I wrote in the testbench:

```<code>configuration MUX21GENTEST of TB_MUX21_GENERIC is
   for TEST

      for U1: MUX21_GENERIC
          use configuration WORK.CFG_MUX21_GEN_BEHAVIORAL;
      end for;

      for U2: MUX21_GENERIC
          use configuration WORK.CFG_MUX21_GEN_STRUCTURAL;
      end for;

    end for;
end MUX21GENTEST;
</code>```

Now the problem is that when I start the simulation with modelsim, It instantiates both the component with the structural architecture. Modelsim image

I notice that if I exchange the position between the two architectures in the mux21_generic.vhdl file, modelsim uses the behavioral instead of the structural arch. Should it be a configuration problem?

答:
You don't provide a Minimal, Complete and Verifiable example.

Your configurations are overly complex.

In your testbench configuration you could:

```<code>configuration MUX21GENTEST of TB_MUX21_GENERIC is
   for TEST

      for U1: MUX21_GENERIC
          use entity WORK.MUX21_GENERIC(behavioral);
      end for;

      for U2: MUX21_GENERIC
          use entity WORK.MUX21_GENERIC(structural);
      end for;

    end for;
end MUX21GENTEST;
</code>```

Without relying on superfluous configurations. There's a concept in VHDL called binding indication where the default binding indication can be supplanted by a configuration specification (which can be found configuration declarations or as block declarative items).

When your configuration declaration(s) appear to ignore specific binding indications and use the default it's because they aren't applicable. (The component binding indication is invalid).

Using configuration specifications in your testbench without a configuration declaration entails providing them as architecture declarative items.

Without an MCVe providing an answer entails a certain amount of risk due to uncertainty from lack of visibility and the inability to test a solution without replicating your work.

Body:
I create a multiplexer called mux21_generic.vhdl. It is a Nx1 mux. I define two architectures, one behavioral, the other structural.

The structural architecture uses a small 2x1 mux in the following way:

architecture structural of MUX21_GENERIC is

component MUX21 is
    Port (  A:      In      std_logic;
            B:      In      std_logic;
            S:      In      std_logic;
            Y:      Out     std_logic);
end component MUX21;

begin  -- structural

    create_mux:
        for i in 0 to N-1 generate
        begin
            MUX21_i : MUX21 port map(A=>A(i), B=>B(i), S=>SEL, Y=>Y(i));
        end generate create_mux;

end structural;

These are the configurations:

-- CONFIGURATIONS --

-- (1) CFG_MUX21_GEN_BEHAVIORAL

configuration CFG_MUX21_GEN_BEHAVIORAL of MUX21_GENERIC is
    for behavioral
    end for;
end CFG_MUX21_GEN_BEHAVIORAL;

-- (2) CFG_MUX21_GEN_STRUCTURAL

configuration CFG_MUX21_GEN_STRUCTURAL of MUX21_GENERIC is
    for structural
        for create_mux
            for all : MUX21
                use configuration WORK.CFG_MUX21_STRUCTURAL;
            end for;
        end for;
     end for;
end CFG_MUX21_GEN_STRUCTURAL;

The compilation works well, so I don't think the problem is in the above configurations.

I guess the problem is in the testbench.

The following code represents how I instantiate, in the "TEST" architecture of the testbench, both the behavioral and the structural mux:

U1 : MUX21_GENERIC
Generic Map (NBIT, 7 ns)
Port Map ( A1, B1, S1, output_beh); -- it should be behavioral

U2 : MUX21_GENERIC
Generic Map (NBIT)
Port Map ( A1, B1, S1, output_str); -- it should be structural

and this is the configuration that I wrote in the testbench:

configuration MUX21GENTEST of TB_MUX21_GENERIC is
   for TEST

      for U1: MUX21_GENERIC
          use configuration WORK.CFG_MUX21_GEN_BEHAVIORAL;
      end for;

      for U2: MUX21_GENERIC
          use configuration WORK.CFG_MUX21_GEN_STRUCTURAL;
      end for;

    end for;
end MUX21GENTEST;

Now the problem is that when I start the simulation with modelsim, It instantiates both the component with the structural architecture. Modelsim image

I notice that if I exchange the position between the two architectures in the mux21_generic.vhdl file, modelsim uses the behavioral instead of the structural arch. Should it be a configuration problem?

Body:
You don't provide a Minimal, Complete and Verifiable example.

Your configurations are overly complex.

In your testbench configuration you could:

configuration MUX21GENTEST of TB_MUX21_GENERIC is
   for TEST

      for U1: MUX21_GENERIC
          use entity WORK.MUX21_GENERIC(behavioral);
      end for;

      for U2: MUX21_GENERIC
          use entity WORK.MUX21_GENERIC(structural);
      end for;

    end for;
end MUX21GENTEST;

Without relying on superfluous configurations. There's a concept in VHDL called binding indication where the default binding indication can be supplanted by a configuration specification (which can be found configuration declarations or as block declarative items).

When your configuration declaration(s) appear to ignore specific binding indications and use the default it's because they aren't applicable. (The component binding indication is invalid).

Using configuration specifications in your testbench without a configuration declaration entails providing them as architecture declarative items.

Without an MCVe providing an answer entails a certain amount of risk due to uncertainty from lack of visibility and the inability to test a solution without replicating your work.


问:
jQuery - How to call a callback with getjson
I have the following callback:

```<code>var getData = function (callback) {

    var id = $("#Id").val();

    if (id.length === 0)
       return;

   $.getJSON('api/data' + '?id=' + id)
    .done(function (data) {
        callback(data);
    }).fail(function (jqXHR, textStatus, err) {
        return;
    });

}
</code>```

I'm trying to call it as follows:

```<code>var id = 123;
getData(function () {
     //TO DO: check if id exist in data
     console.log(data);
});
</code>```

But I get reference error: data is not defined. How do I get the data returned by the ajax request. I'm not too familiar with callbacks so bear with me as I'm still trying to get to grips with them.

答:
When you do callback(data), you are simply calling the function you passed in to getData. You passed it one argument during the call, which means the function you passed in must have one argument present so that you can access it. Simply do:

```<code>getData(function (data) {
        console.log(data);
});
</code>```

For a better understanding of what callbacks are and what's really going on, let's rewrite it to a simpler form.

```<code>function getData(callback) {

    var id = $("#Id").val();

    if (id.length === 0)
       return;

   $.getJSON('api/data' + '?id=' + id)
    .done(function (data) {
        // 2. All that getData is doing is call that function using the
        //    reference you sent when it's done. Like any other function
        //    you can pass it arguments.
        getDataCallback(data);
    }).fail(function (jqXHR, textStatus, err) {
        return;
    });

}

function getDataCallback(message){
  // 3. Like any other function, to access the arguments passed, you need
  //    to name your arguments.
  console.log(message);
}

var id = 123;

// 1. All you are doing really is pass a reference to a function to getData
getData(getDataCallback);
</code>```

Where your code failed is at console.log. It tried to access data which is not defined anywhere, even on the outer scopes. That's equivalent to removing message from the arguments of getDataCallback.

Body:
I have the following callback:

var getData = function (callback) {

    var id = $("#Id").val();

    if (id.length === 0)
       return;

   $.getJSON('api/data' + '?id=' + id)
    .done(function (data) {
        callback(data);
    }).fail(function (jqXHR, textStatus, err) {
        return;
    });

}

I'm trying to call it as follows:

var id = 123;
getData(function () {
     //TO DO: check if id exist in data
     console.log(data);
});

But I get reference error: data is not defined. How do I get the data returned by the ajax request. I'm not too familiar with callbacks so bear with me as I'm still trying to get to grips with them.

Body:
When you do callback(data), you are simply calling the function you passed in to getData. You passed it one argument during the call, which means the function you passed in must have one argument present so that you can access it. Simply do:

getData(function (data) {
        console.log(data);
});

For a better understanding of what callbacks are and what's really going on, let's rewrite it to a simpler form.

function getData(callback) {

    var id = $("#Id").val();

    if (id.length === 0)
       return;

   $.getJSON('api/data' + '?id=' + id)
    .done(function (data) {
        // 2. All that getData is doing is call that function using the
        //    reference you sent when it's done. Like any other function
        //    you can pass it arguments.
        getDataCallback(data);
    }).fail(function (jqXHR, textStatus, err) {
        return;
    });

}

function getDataCallback(message){
  // 3. Like any other function, to access the arguments passed, you need
  //    to name your arguments.
  console.log(message);
}

var id = 123;

// 1. All you are doing really is pass a reference to a function to getData
getData(getDataCallback);

Where your code failed is at console.log. It tried to access data which is not defined anywhere, even on the outer scopes. That's equivalent to removing message from the arguments of getDataCallback.


问:
Python Selenium how to move mouse on element. which shows drop-down menu
link http://www.babylegs.com

My code:

```<code>class TestClassMy(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()

    def test1(self):
        driver = self.driver
        driver.get('http://www.babylegs.com')
        driver.maximize_window()
        element_to_select = driver.find_element_by_xpath(".//*[@id='nav']/ol/li[5]/a") #d.send_keys(Keys.NULL)

        actions = ActionChains(driver)
        element_to_select.click_and_hold(element_to_select).perform()

    def tearDown(self):
        self.driver.close()

if __name__ == '__main__':
    unittest.main()
</code>```

答:
Use the ActionChains like:

```<code>actions.move_to_element(element_to_select).perform()
</code>```

Then you can do what you need. This is how you'll work with dropdown menus, by finding the elements, then performing a chain to essentially moves the mouse into the right places.

Then, once the menu (and submenus) have been exposed, you can click on them (as you see, you cannot click on things not visible.

In your case, to select something from the "Socks" menu:

```<code>e1 = driver.find_element_by_xpath('//*[@id="nav"]/ol/li[5]/a')
e2 = e1.find_element_by_xpath('../ul/li[1]/a')
actions.move_to_element(e1).move_to_element(e2).perform()
e2.click()
</code>```

Body:
link http://www.babylegs.com

My code:

class TestClassMy(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()

    def test1(self):
        driver = self.driver
        driver.get('http://www.babylegs.com')
        driver.maximize_window()
        element_to_select = driver.find_element_by_xpath(".//*[@id='nav']/ol/li[5]/a") #d.send_keys(Keys.NULL)

        actions = ActionChains(driver)
        element_to_select.click_and_hold(element_to_select).perform()

    def tearDown(self):
        self.driver.close()

if __name__ == '__main__':
    unittest.main()

Body:
Use the ActionChains like:

actions.move_to_element(element_to_select).perform()

Then you can do what you need. This is how you'll work with dropdown menus, by finding the elements, then performing a chain to essentially moves the mouse into the right places.

Then, once the menu (and submenus) have been exposed, you can click on them (as you see, you cannot click on things not visible.

In your case, to select something from the "Socks" menu:

e1 = driver.find_element_by_xpath('//*[@id="nav"]/ol/li[5]/a')
e2 = e1.find_element_by_xpath('../ul/li[1]/a')
actions.move_to_element(e1).move_to_element(e2).perform()
e2.click()


问:
How to run java program inside another java program
I want to know how can I run a another java console application (jar1) inside another java application (jar2) also I want to be able to see jar1 outputs and insert my own inputs from jar2.

Let me explain more. there is a program called spigot (see more in www.spigotmc.org): Spigot is CLI java program for running a minecraft server
and you have to run it with launch flags in a bat file in windows server like:
java -Xmx 1024m -Xms 1024Xms spigot.jar1. Now I want to make a program which let me to running this on my own graphical design not in a console.

How can I pass arguments to an existing command window?

答: Run a new program with ProcessBuilder. You cannot modify arguments in any already running program, so terminate them first.


问:
Is there way to convert mask image into UIBezierPath in iOS
I wanted to show animations on parts of image like a coloring apps. I achieved this with masking but that is heavy on performance.

I'm looking a way to convert a mask into UIBezierPath so I can add animations on layers on UIView instead of UIView object every-time.

I'm trying to following the exact same method of
MagicWand for Mac
but it has lot of Cocoa classes. Anyone can suggest me the solution of converting mask or image to UIBezierPath object according to iOS classes or any tutorial to find the clue?

Thanks in advance.

答:
Please have a look at PocketSVG if you are ok with using SVGs for the images. You'd get an array of bezier paths for a given svg. You could add each of these paths as separate CAShapeLayer objects and add any animations to their path and fill color as intended using CABasicAnimation.

Hope it answers your question.


问:
Xively Personal - was working but now data does not change
I'd appreciate any help that you might offer with debugging my AirPi based weather station that uploads data to my Xively Personal account. The station has been working and uploading for several months. I checked the Xively graphs and noticed that they had flat-lined. I checked the weather station and it was working as before, other than the status of the Python command that posts he data was coming back as failed.

I changed nothing so am really confused as to why something that worked flawlessly for months suddenly stopped and since that date has refused to work again.

Does anyone have any ideas what I might do to rectify this situation? Many thanks in advance for your attention.

Ian.

答:
It is probably failing as your weather station software is unable to verify the certificate provided by the server.

I experienced the same today, seems the last time the data had been successfully uploaded was about 2 weeks ago.

I'm using curl and for the time being, I solved it by using the "-k" switch (meaning curl will still allow to establish the connection).


答:
To maximize efficiency use

```<code>line.split(" ",1)[0]
</code>```

Split on first occurrence therefore saves time

Title: How can you read just the first word of every line of file using python?

Body:
To maximize efficiency use

line.split(" ",1)[0]

Split on first occurrence therefore saves time


问:
Django follow primary key JSON
I relatively new to Django, but im trying to return the complete JSON document for the following data model.

```<code>class Wheels(models.Model):
   w_name = models.CharField(max_length=255)
   w_weight = models.IntegerField(default=200)
   w_size = models.CharField(max_length=200)
   w_durability = models.IntegerField(default=45)

   def __str__(self):
    return self.w_name

class Chassis(models.Model):
    c_owner = models.CharField(max_length=255)
    c_year = models.IntegerField(default=1900)
    c_model = models.CharField(max_length=255)
    c_wheels = models.ForeignKey(Wheels)
    c_weight = models.IntegerField(default=20)

    def __str__(self):
      return self.c_model`
</code>```

Right now the code returns just:

```<code>{
"id": 1,
"c_owner": "Mike",
"c_year": 1969,
"c_model": "Chevy",
"c_weight": 3500,
"c_wheels": 1
}
</code>```

But instead of the 1 for wheels i would like it to follow the wheels table

Views:

```<code>class ChassisList(ModelViewSet):
   queryset = Chassis.objects.all()
   serializer_class = ChassisSerializer

class WheelsList(ModelViewSet):
   queryset = Wheels.objects.all()
   serializer_class = WheelSerializer
</code>```

Serializers:

```<code>class WheelSerializer(serializers.ModelSerializer):
   class Meta:
    model = Wheels
    fields = ('__all__')

class ChassisSerializer(serializers.ModelSerializer):
   class Meta:
    model = Chassis
    fields = ('__all__')
</code>```

答:
Simple solution:</p>

```<code>class ChassisSerializer(serializers.ModelSerializer):
   class Meta:
    model = Chassis
    fields = ('__all__')
    depth = 1
</code>```

Title: Django follow primary key JSON

Body:
I relatively new to Django, but im trying to return the complete JSON document for the following data model.

class Wheels(models.Model):
   w_name = models.CharField(max_length=255)
   w_weight = models.IntegerField(default=200)
   w_size = models.CharField(max_length=200)
   w_durability = models.IntegerField(default=45)

   def __str__(self):
    return self.w_name

class Chassis(models.Model):
    c_owner = models.CharField(max_length=255)
    c_year = models.IntegerField(default=1900)
    c_model = models.CharField(max_length=255)
    c_wheels = models.ForeignKey(Wheels)
    c_weight = models.IntegerField(default=20)

    def __str__(self):
      return self.c_model`

Right now the code returns just:

{
"id": 1,
"c_owner": "Mike",
"c_year": 1969,
"c_model": "Chevy",
"c_weight": 3500,
"c_wheels": 1
}

But instead of the 1 for wheels i would like it to follow the wheels table

Views:

class ChassisList(ModelViewSet):
   queryset = Chassis.objects.all()
   serializer_class = ChassisSerializer

class WheelsList(ModelViewSet):
   queryset = Wheels.objects.all()
   serializer_class = WheelSerializer

Serializers:

class WheelSerializer(serializers.ModelSerializer):
   class Meta:
    model = Wheels
    fields = ('__all__')

class ChassisSerializer(serializers.ModelSerializer):
   class Meta:
    model = Chassis
    fields = ('__all__')

Body:
Simple solution:

class ChassisSerializer(serializers.ModelSerializer):
   class Meta:
    model = Chassis
    fields = ('__all__')
    depth = 1


问:
.net / c# test wanted for a non techical MD
Dear all i am looking for an half finished .net application to test my .net c# applicants.

As I come from a differnt coding background, it is difficult for me to assess people skills hence a great test would do a good job!

Regarding checking candidates' test performance, I can ask a friend, no problem !

Does a practical test exist out there? Would I need to pay for it?

答:
To create a suitable C# program for this purpose, it would help to know exactly you're trying to measure:

Knowledge or skills (or both)?

Desktop, web, or server?

Basic, intermediate, or advanced?

Development or maintenance?

With or without database knowledge?

Error-handling and reliability?

Performance?

Security?

UI?

Algorithms?

Testing?

Base class library knowledge?

.......

OwnerDisplayName: frank publisher

LastEditorDisplayName: Tom Anderson

OwnerDisplayName: RoadWarrior


问:
What is hook1 in an ActiveX INF file?
Currently I've seen hooks created for activeX installer archives in an INF file that use "hook1" and "hook" (to the left of the = sign). I'm confused about the differences in the two. Here is an example:

```<code>[version]
signature="$CHICAGO$"
AdvancedINF=2.0
[Setup Hooks]
hook1=hook1

[hook1]
run=msiexec.exe /i "%EXTRACT_DIR%\ccScanning_msi.msi" /qn
</code>```

Shouldn't it read "hook=hook1"? Is the "hook1" to the left simply a user-defined name with no real usefulness or meaning? How am I supposed to read and understand this syntax/structure?

答: have you looked at the official documentation about this? it's available here: Using Hooks</p>

Title: What is hook1 in an ActiveX INF file?

Body:
Currently I've seen hooks created for activeX installer archives in an INF file that use "hook1" and "hook" (to the left of the = sign). I'm confused about the differences in the two. Here is an example:

[version]
signature="$CHICAGO$"
AdvancedINF=2.0
[Setup Hooks]
hook1=hook1

[hook1]
run=msiexec.exe /i "%EXTRACT_DIR%\ccScanning_msi.msi" /qn

Shouldn't it read "hook=hook1"? Is the "hook1" to the left simply a user-defined name with no real usefulness or meaning? How am I supposed to read and understand this syntax/structure?


问:
Javascript Loop for same commands
I am trying to figure out how to loop this instead of 6 seperate versions of this. It's obviously redundant code. I would have no issues doing this in PHP.

I would like to keep this purely JS.

```<code>    function p1Name() {
    document.getElementById('p1_name_1').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_2').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_3').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_4').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_5').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_6').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_7').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
}
</code>```

This same function gets repeated 6 times.
p1, p2, p3, p4, p5, p6

答:
You just have to construct the names of your elements (p(x)_name_(i)). Since you want to call the function 6 times (for p1...p6) you should pass that as an argument (px) to the function:

```<code>function pName(px) {
    for (var i = 1; i <= 7; i++) {
        document.getElementById(px + '_name_' + i).innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    }
}
</code>```

You would then call this function for each p1...p6 (which depending on your circumstances you'll probably also going to want to do in a loop). I'm going to leave that one to you since you can use the same concept as the one in the function above.

Title: Javascript Loop for same commands

Body:
I am trying to figure out how to loop this instead of 6 seperate versions of this. It's obviously redundant code. I would have no issues doing this in PHP.

I would like to keep this purely JS.

    function p1Name() {
    document.getElementById('p1_name_1').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_2').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_3').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_4').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_5').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_6').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    document.getElementById('p1_name_7').innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
}

This same function gets repeated 6 times.
p1, p2, p3, p4, p5, p6

Body:
You just have to construct the names of your elements (p(x)_name_(i)). Since you want to call the function 6 times (for p1...p6) you should pass that as an argument (px) to the function:

function pName(px) {
    for (var i = 1; i <= 7; i++) {
        document.getElementById(px + '_name_' + i).innerHTML = (scorecard.p1[scorecard.p1.selectedIndex].text);
    }
}

You would then call this function for each p1...p6 (which depending on your circumstances you'll probably also going to want to do in a loop). I'm going to leave that one to you since you can use the same concept as the one in the function above.


问:
Which libraries should be linked to this VTK example?
I want to compile this example in vtk, which includes the following include files:

```<code>#include <vtkSmartPointer.h>
#include <vtkObjectFactory.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkActor.h>
// headers needed for this example
#include <vtkImageViewer2.h>
#include <vtkDICOMImageReader.h>
#include <vtkInteractorStyleImage.h>
#include <vtkActor2D.h>
#include <vtkTextProperty.h>
#include <vtkTextMapper.h>
// needed to easily convert int to std::string
#include <sstream>
</code>```

Originally it should be compiled with a CMakeLists.txt-file which looks like:

```<code>cmake_minimum_required(VERSION 2.8)

PROJECT(ReadDICOMSeries)

find_package(VTK REQUIRED)
include(${VTK_USE_FILE})

add_executable(ReadDICOMSeries MACOSX_BUNDLE ReadDICOMSeries)

if(VTK_LIBRARIES)
  target_link_libraries(ReadDICOMSeries ${VTK_LIBRARIES})
else()
  target_link_libraries(ReadDICOMSeries vtkHybrid vtkWidgets)
endif()
</code>```

The problem is: When I simply copy this code and compile it, I get a lot of reference errors (for example: Undefined reference to 'vtkDICOMImageReader::SetDirectoryName(char const*)'). This leads me to the assumption that I should link some libraries to it. Unfortunately the CMakeLists-file does not tell me which libraries. How do I find that out?

答:
I managed to figure this out without using CMake directly or having to dig into each individual lib.

find a header file or C/CPP file that defines the object that's giving you linker pain.

Do a find-in-files of the *.cmake files that came with VTK, searching for that filename.  So in your case, look for vtkDICOMImageReader.

I found vtkDICOMImageReader in vtkIOKit.cmake, so a decent guess might be libvtkio.

In my case, I was hunting for vtkDataSetAttributes, and this method successfully determined it was in vtkFiltering.lib.

If you've already got Cmake set up then doing it correctly might be easier, but I didn't want "set up vtk" to turn into "set up cmake so I can set up vtk" and then into "set up some other thing so I can set up cmake so I can set up vtk".

Body:
I want to compile this example in vtk, which includes the following include files:

#include <vtkSmartPointer.h>
#include <vtkObjectFactory.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkActor.h>
// headers needed for this example
#include <vtkImageViewer2.h>
#include <vtkDICOMImageReader.h>
#include <vtkInteractorStyleImage.h>
#include <vtkActor2D.h>
#include <vtkTextProperty.h>
#include <vtkTextMapper.h>
// needed to easily convert int to std::string
#include <sstream>

Originally it should be compiled with a CMakeLists.txt-file which looks like:

cmake_minimum_required(VERSION 2.8)

PROJECT(ReadDICOMSeries)

find_package(VTK REQUIRED)
include(${VTK_USE_FILE})

add_executable(ReadDICOMSeries MACOSX_BUNDLE ReadDICOMSeries)

if(VTK_LIBRARIES)
  target_link_libraries(ReadDICOMSeries ${VTK_LIBRARIES})
else()
  target_link_libraries(ReadDICOMSeries vtkHybrid vtkWidgets)
endif()

The problem is: When I simply copy this code and compile it, I get a lot of reference errors (for example: Undefined reference to 'vtkDICOMImageReader::SetDirectoryName(char const*)'). This leads me to the assumption that I should link some libraries to it. Unfortunately the CMakeLists-file does not tell me which libraries. How do I find that out?


问:
Converting a foldl into fold1
I am using the following fold to get the final monotonically decreasing sequence of a list.

```<code>foldl (\acc x -> if x<=(last acc) then acc ++ [x] else [x]) [(-1)] a
</code>```

So [9,5,3,6,2,1]  would return [6,2,1]
However, with foldl I needed to supply a start for the fold namely [(-1)].  I was trying to turn into to a foldl1 to be able to handle any range of integers as well as any Ord a like so:

```<code>foldl1 (\acc x -> if x<=(last acc) then acc ++ [x] else [x]) a
</code>```

But I get there error:

```<code>cannot construct infinite type: a ~ [a]
in the second argument of (<=) namely last acc
</code>```

I was under the impression that foldl1 was basically :

```<code>foldl (function) [head a] a
</code>```

But I guess this isn't so?  How would you go about making this fold generic for any Ord type?

答:
The type of foldl1 is:

```<code>Foldable t => (a -> a -> a) -> t a -> a
</code>```

Your function argument,

```<code>\acc x -> if x<=(last acc) then acc ++ [x] else [x]
</code>```

has type:

```<code>(Ord a) => [a] -> a -> [a]
</code>```

When Haskell's typechecker tries typechecking your function, it'll try unifying the type a -> a -> a (the type of the first argument of foldl1) with the type [a] -> a -> [a] (the type of your function).

To unify these types would require unifying a with [a], which would lead to the infinite type a ~ [a] ~ [[a]] ~ [[[a]]]... and so on.

The reason this works while using foldl is that the type of foldl is:

Foldable t => (b -> a -> b) -> b -> t a -> b

So [a] gets unified with b and a gets unified with the other a, leading to no problem at all.

foldl1 is limited in that it can only take functions which deal with only one type, or, in other terms,  the accumulator needs to be the same type as the input list (for instance, when folding a list of Ints, foldl1 can only return an Int, while foldl can use arbitrary accumulators. So you can't do this using foldl1).

With regards to making this generic for all Ord values, one possible solution is to make a new typeclass for values which state their own "least-bound" value, which would then be used by your function. You can't make this function as it is generic on all Ord values because not all Ord values have sequence least bounds you can use.

```<code>class LowerBounded a where
    lowerBound :: a

instance LowerBounded Int where
    lowerBound = -1

finalDecreasingSequence :: (Ord a, LowerBounded a) => [a] -> [a]
finalDecreasingSequence = foldl buildSequence lowerBound
  where buildSequence acc x
    | x <= (last acc) = acc ++ [x]
    | otherwise       = [x]
</code>```

You might also want to read a bit about how Haskell does its type inference, as it helps a lot in figuring out errors like the one you got.

Title: Converting a foldl into fold1

Body:
I am using the following fold to get the final monotonically decreasing sequence of a list.

foldl (\acc x -> if x<=(last acc) then acc ++ [x] else [x]) [(-1)] a

So [9,5,3,6,2,1]  would return [6,2,1]
However, with foldl I needed to supply a start for the fold namely [(-1)].  I was trying to turn into to a foldl1 to be able to handle any range of integers as well as any Ord a like so:

foldl1 (\acc x -> if x<=(last acc) then acc ++ [x] else [x]) a

But I get there error:

cannot construct infinite type: a ~ [a]
in the second argument of (<=) namely last acc

I was under the impression that foldl1 was basically :

foldl (function) [head a] a

But I guess this isn't so?  How would you go about making this fold generic for any Ord type?

Body:
The type of foldl1 is:

Foldable t => (a -> a -> a) -> t a -> a

Your function argument,

\acc x -> if x<=(last acc) then acc ++ [x] else [x]

has type:

(Ord a) => [a] -> a -> [a]

When Haskell's typechecker tries typechecking your function, it'll try unifying the type a -> a -> a (the type of the first argument of foldl1) with the type [a] -> a -> [a] (the type of your function).

To unify these types would require unifying a with [a], which would lead to the infinite type a ~ [a] ~ [[a]] ~ [[[a]]]... and so on.

The reason this works while using foldl is that the type of foldl is:

Foldable t => (b -> a -> b) -> b -> t a -> b

So [a] gets unified with b and a gets unified with the other a, leading to no problem at all.

foldl1 is limited in that it can only take functions which deal with only one type, or, in other terms,  the accumulator needs to be the same type as the input list (for instance, when folding a list of Ints, foldl1 can only return an Int, while foldl can use arbitrary accumulators. So you can't do this using foldl1).

With regards to making this generic for all Ord values, one possible solution is to make a new typeclass for values which state their own "least-bound" value, which would then be used by your function. You can't make this function as it is generic on all Ord values because not all Ord values have sequence least bounds you can use.

class LowerBounded a where
    lowerBound :: a

instance LowerBounded Int where
    lowerBound = -1

finalDecreasingSequence :: (Ord a, LowerBounded a) => [a] -> [a]
finalDecreasingSequence = foldl buildSequence lowerBound
  where buildSequence acc x
    | x <= (last acc) = acc ++ [x]
    | otherwise       = [x]

You might also want to read a bit about how Haskell does its type inference, as it helps a lot in figuring out errors like the one you got.


问:
Rails is not installing any gem
Whenever i try to install any gem and bundle install it it gives me:

following bundle instructions to bundle update rails(which i shouldn't do it suppose) i get:
<img src="https://i.stack.imgur.com/Hlh5K.png" alt="bundle update rails">

答: I think you just have to run bundle update

Title: Rails is not installing any gem


问:
How to extract images from pdf using Java (not using pdfbox)
I've being researching on how to extract images from a big (> 300MB) PDF file. I'm using pdfbox but for some particular reason that I can't figure out, some pages are not correctly extracted.

I'm using the PDFToImage class of pdfbox as base for my code.

So, do you know another library that may help me to do this? I know that iText may be used, but I read that it can't be used for commercial products.

I've installed the packages xpdf and xpdf-utils, and the utility called pdfimages is working perfect. But I need to solve this problem from Java and it should be portable.

答: Have you tried icepdf or JPedal (both pure java)?</p>


问:
tensorboard can't find event files
I tried to use tensorboard to visualize a image classifier using DNN. I'm very sure that the directory path is correct, however no data is shown.
When I tried
tensorboard --inspect --logdir='PATH/'
returns: No event files found within logdir 'PATH/'

I'm thinking of there must be something wrong with my coding.

Graph

```<code>batch_size = 500

graph = tf.Graph()
with graph.as_default():

  # Input data. For the training data, we use a placeholder that will be fed
  # at run time with a training minibatch.
  with tf.name_scope('train_input'):
    tf_train_dataset = tf.placeholder(tf.float32,
                                      shape=(batch_size, image_size * image_size),
                                      name = 'train_x_input')

    tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels),
                                     name = 'train_y_input')
  with tf.name_scope('validation_input'):
    tf_valid_dataset = tf.constant(valid_dataset, name = 'valid_x_input')
    tf_test_dataset = tf.constant(test_dataset, name = 'valid_y_input')

  # Variables.
  with tf.name_scope('layer'):
    with tf.name_scope('weights'):
        weights = tf.Variable(
            tf.truncated_normal([image_size * image_size, num_labels]),
            name = 'W')
        variable_summaries(weights)
    with tf.name_scope('biases'):
        biases = tf.Variable(tf.zeros([num_labels]), name = 'B')
        variable_summaries(biases)
  # Training computation.
  with tf.name_scope('Wx_plus_b'):
    logits = tf.matmul(tf_train_dataset, weights) + biases
    tf.summary.histogram('logits', logits)
  with tf.name_scope('loss'):
    loss = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits),
        name = 'loss')
    tf.summary.histogram('loss', loss)
    tf.summary.scalar('loss_scalar', loss)

  # Optimizer.
  with tf.name_scope('optimizer'):
    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  valid_prediction = tf.nn.softmax(tf.matmul(tf_valid_dataset, weights) + biases)
  test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)
</code>```

Run

```<code>num_steps = 1001
t1 = time.time()
with tf.Session(graph=graph) as session:
  merged = tf.summary.merge_all()
  writer = tf.summary.FileWriter('C:/Users/Dr_Chenxy/Documents/pylogs', session.graph)
  tf.global_variables_initializer().run()
  print("Initialized")
  for step in range(num_steps):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)  # 1*128 % (200000 - 128)
    # Generate a minibatch.
    batch_data = train_dataset[offset:(offset + batch_size), :]   # choose training set for this iteration
    batch_labels = train_labels[offset:(offset + batch_size), :]  # choose labels for this iteration
    # Prepare a dictionary telling the session where to feed the minibatch.
    # The key of the dictionary is the placeholder node of the graph to be fed,
    # and the value is the numpy array to feed to it.
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 100 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % accuracy(
        valid_prediction.eval(), valid_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))
t2 = time.time()
print('Running time', t2-t1, 'seconds')
</code>```

答:
Solved. For anyone who is bad at command line as me, the problem is that in command line, don't use quote ('') to label your directory.
Say your data is at 'X:\X\file.x'
Go in command line to X:\ first.
Then type:
tensorboard --logdir=X/
NOT
tensorboard --logdir='.X/'

Title: tensorboard can't find event files

Body:
I tried to use tensorboard to visualize a image classifier using DNN. I'm very sure that the directory path is correct, however no data is shown.
When I tried
tensorboard --inspect --logdir='PATH/'
returns: No event files found within logdir 'PATH/'

I'm thinking of there must be something wrong with my coding.

Graph

batch_size = 500

graph = tf.Graph()
with graph.as_default():

  # Input data. For the training data, we use a placeholder that will be fed
  # at run time with a training minibatch.
  with tf.name_scope('train_input'):
    tf_train_dataset = tf.placeholder(tf.float32,
                                      shape=(batch_size, image_size * image_size),
                                      name = 'train_x_input')

    tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels),
                                     name = 'train_y_input')
  with tf.name_scope('validation_input'):
    tf_valid_dataset = tf.constant(valid_dataset, name = 'valid_x_input')
    tf_test_dataset = tf.constant(test_dataset, name = 'valid_y_input')

  # Variables.
  with tf.name_scope('layer'):
    with tf.name_scope('weights'):
        weights = tf.Variable(
            tf.truncated_normal([image_size * image_size, num_labels]),
            name = 'W')
        variable_summaries(weights)
    with tf.name_scope('biases'):
        biases = tf.Variable(tf.zeros([num_labels]), name = 'B')
        variable_summaries(biases)
  # Training computation.
  with tf.name_scope('Wx_plus_b'):
    logits = tf.matmul(tf_train_dataset, weights) + biases
    tf.summary.histogram('logits', logits)
  with tf.name_scope('loss'):
    loss = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits),
        name = 'loss')
    tf.summary.histogram('loss', loss)
    tf.summary.scalar('loss_scalar', loss)

  # Optimizer.
  with tf.name_scope('optimizer'):
    optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  valid_prediction = tf.nn.softmax(tf.matmul(tf_valid_dataset, weights) + biases)
  test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)

Run

num_steps = 1001
t1 = time.time()
with tf.Session(graph=graph) as session:
  merged = tf.summary.merge_all()
  writer = tf.summary.FileWriter('C:/Users/Dr_Chenxy/Documents/pylogs', session.graph)
  tf.global_variables_initializer().run()
  print("Initialized")
  for step in range(num_steps):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)  # 1*128 % (200000 - 128)
    # Generate a minibatch.
    batch_data = train_dataset[offset:(offset + batch_size), :]   # choose training set for this iteration
    batch_labels = train_labels[offset:(offset + batch_size), :]  # choose labels for this iteration
    # Prepare a dictionary telling the session where to feed the minibatch.
    # The key of the dictionary is the placeholder node of the graph to be fed,
    # and the value is the numpy array to feed to it.
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 100 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % accuracy(
        valid_prediction.eval(), valid_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))
t2 = time.time()
print('Running time', t2-t1, 'seconds')


问:
how can I implement adaptive mergesort on hadoop clustering using mapreduce
I want to implement adaptive merge sort on hadoop multinode clustering so that the run time reduces. But as far I did study map does sorting and grouping itself. I mean The map output is the input of reduce and the output of map we get is sorted (if I m not wrong). So how can I implement Adaptive merge sort? I mean is it possible? </p>

答:
In map reduce program if you want to apply your on sorting logic on map output so that reducer will get data in some sorted order you need to do following things

Choose your composite key

Set sort comparator class

Set grouping comparator class

Set partition class

For example if you have dataset like as below

UserID,ApplicationId,Datetime

And if you want to sort the row on basis of userid and Datetime

First you need to create a composite key class which consist of userid and datetime

Secondly you need to write sort comparator class in which you need to write your sorting logic

Thirdly you need to write grouping comparator class in which you want to compare value of keys on basis of one of the key not on basis of both the keys, like in this example we just want to group the record with userid only.

Fourthly you need to create partition class where you need to write logic to send the data of same userid to same reducer.

Last you need to set all classes under job instance

```<code>job.setSortComparatorClass(YourSortComparator.class);
job.setGroupingComparatorClass(YourGroupingComparator.class);
job.setPartitionerClass(YourPartitioner.class);
</code>```

Body:
In map reduce program if you want to apply your on sorting logic on map output so that reducer will get data in some sorted order you need to do following things

Choose your composite key

Set sort comparator class

Set grouping comparator class

Set partition class

For example if you have dataset like as below

UserID,ApplicationId,Datetime

And if you want to sort the row on basis of userid and Datetime

First you need to create a composite key class which consist of userid and datetime

Secondly you need to write sort comparator class in which you need to write your sorting logic

Thirdly you need to write grouping comparator class in which you want to compare value of keys on basis of one of the key not on basis of both the keys, like in this example we just want to group the record with userid only.

Fourthly you need to create partition class where you need to write logic to send the data of same userid to same reducer.

Last you need to set all classes under job instance

job.setSortComparatorClass(YourSortComparator.class);
job.setGroupingComparatorClass(YourGroupingComparator.class);
job.setPartitionerClass(YourPartitioner.class);


问:
Angular Queue Action From Directive To Service
I'm trying to get better understanding of how to code in Angular properly and am writing my own custom module to better understand how things are supposed to work.

I have an HTML markup consisting of images and a directive i.e.

```<code><img ng-if="!post.tooBig" mydirective resize="0" ng-src="/img/@{{post.Content}}">
</code>```

My directive is here:

```<code>.directive('mydirective', [
           '$animate','$mediaStack',
  function($animate,$mediaStack) {
  return {
    restrict: 'A',
    compile: function(tElement, tAttrs) {
        return loader;
    }
  };

    function loader(scope, element, attrs) {
      var source = attrs.ngSrc;
      var tooLoadBig = parseInt(attrs.resize);
      if(tooLoadBig){
        var bigImage = new Image();
        bigImage.src = source.replace("small.",".");
      }
      }
}])
</code>```

The idea is this: if the image has small appended to its filename, I know it is a thumbnail. I want to load it's big version (same file without the appended small) in the background so it is ready for a lightbox.

This works fine as is, but the problem is because I'm doing all the work in the compile, when I set bigImage.src = source.replace("small.","."); it fires off right away, and if I have many small images on the page, it causes the page to slow down because of all the loading that is going on.

I want to therefore use $q to make it so that it will load one image at a time.

So move

```<code> var bigImage = new Image();
 bigImage.src = source.replace("small.",".");
</code>```

Into a promise. Is it best practice to do this in the directive? My understanding is it wouldn't make sense to do so and that I should use a service, but I'm not sure how to do that. I could play around with it more but I was hoping someone with more experience could instruct me as to best-practices for something like this and a code sample of a similar workflow, thank you.

Edits:

Directive:

```<code>.directive('mydirective', [
           '$animate','$mediaStack',
  function($animate,$mediaStack) {
  return {
    restrict: 'A',
    compile: function(tElement, tAttrs) {
        return loader;
    }
  };

    function loader(scope, element, attrs) {
      var source = attrs.ngSrc;
      var tooLoadBig = parseInt(attrs.resize);
      if(tooLoadBig){
        /*var bigImage = new Image();
        bigImage.src = source.replace("small.",".");*/
        $mediaStack.load(source);
      }
      }
}])
</code>```

My service:

```<code>.factory('$mediaStack', [
             '$animate', '$timeout', '$document', '$compile', '$rootScope',
             '$q',
             '$injector',
    function($animate ,  $timeout ,  $document ,  $compile ,  $rootScope ,
              $q,
              $injector) {
      var OPENED_MEDIA_CLASS = 'media-open';
      var theImages = [];
      $mediaStack = {};
      $mediaStack.load = function(source){
          theImages.push(source);
      };
      $mediaStack.loadRequest   = function(theImages) {

                          deferred.resolve(function(){
                          var bigImage = new Image();
                          bigImage.src = theImages[0].replace("small.",".");
                          });
                          return deferred.promise;
                        }

                        /*var promise = asyncGreet('Robin Hood');
                        promise.then(function(greeting) {
                          alert('Success: ' + greeting);
                        }, function(reason) {
                          alert('Failed: ' + reason);
                        }, function(update) {
                          alert('Got notification: ' + update);
                        });*/
                        //above from docs
      }
      return $mediaStack;
    }])
</code>```

This works in that it gets the image urls into an array in the service, so I have all the images in the array, how do I use $q properly based off that array. I got started but most of the $mediaStack.loadRequest is based off the $q documentation, I'm not sure how to use it effectively in this case.

EDIT 2:

My service as is:

```<code>    .factory('$mediaStack', [
                 '$animate', '$timeout', '$document', '$compile', '$rootScope',
                 '$q',
                 '$injector',
        function($animate ,  $timeout ,  $document ,  $compile ,  $rootScope ,
                  $q,
                  $injector) {
           var OPENED_MEDIA_CLASS = 'media-open';
      var theImages = [];
      var theLoadedImages = [];
      var thePromises = [];
      var loading = false;
      $mediaStack = {};
      $mediaStack.load = function(source){
          theImages.push(source);
          var mainDeferred = $q.defer();
         if(loading)
         {
             thePromises.push(mainDeferred.promise);
             console.log(thePromises);
             $mediaStack.myRaceFn(thePromises).then(function() {
             console.log("Fire!");
             loading=true;
            $mediaStack.loadRequest(theImages[0]).then(function(bigImage){
          console.log(bigImage);
            theImages.shift();
            theLoadedImages.push(bigImage);
            loading = false;
          mainDeferred.resolve();
        });
      });
         }
         if(!loading)
         {
            loading = true;
            $mediaStack.loadRequest(theImages[0]).then(function(bigImage){
            console.log(bigImage);
            theImages.shift();
            theLoadedImages.push(bigImage);
            loading = false;
            mainDeferred.resolve();
            });

         }
           }
      $mediaStack.loadRequest = function(source){
                          var deferred = $q.defer();
                          var bigImage = new Image();
                          bigImage.src = source.replace("small.",".");
                          bigImage.onload = function() {
                          deferred.resolve(bigImage);
                          }
                           return deferred.promise;
      }
      //.race implementation in old angular
      $mediaStack.myRaceFn = function (promises){
   return $q(function(resolve, reject) {
     promises.forEach(function(promise) {
       console.log(promise);
       promise.then(resolve, reject);
     });
   });
}
//.race implementation in old angular
      return $mediaStack;
        }])
</code>```

I'm very close, I see an array of promises but I never get to the point of being able to fire them again, so I have 10 images, and I get an array of 9 promises. How do I fire them?

I expected it would happen around here:

```<code>$mediaStack.myRaceFn(thePromises).then(function() {
console.log("Fire!");
loading=true;
$mediaStack.loadRequest(theImages[0]).then(function(bigImage){
</code>```

But I never get that console.log().

Instead I get console messages in $mediaStack.myRaceFn() showing me each promise (9 at the end) but they just sit there? I'm missing something.

I think I may be resolving mainDeferred too early...

答:
Marking Oskar as accepted because it basically allowed me to figure out a solution.

Here is what I actually implemented, however:

```<code>    .factory('$mediaStack', [
             '$animate', '$timeout', '$document', '$compile', '$rootScope',
             '$q',
             '$injector',
    function($animate ,  $timeout ,  $document ,  $compile ,  $rootScope ,
              $q,
              $injector) {
      var OPENED_MEDIA_CLASS = 'media-open';
      var theImages = [];
      var theLoadedImages = [];
      var thePromises = [];
      var loading = false;
      $mediaStack = {};
      $mediaStack.load = function(source){
          if(source)
          {
          theImages.push(source);
          }
          var mainDeferred = $q.defer();
         if(loading)
         {
             thePromises.push(mainDeferred.promise);
             console.log(thePromises);
             $mediaStack.myRaceFn(thePromises).then(function() {
             console.log("Fire!");
             loading=true;
            $mediaStack.loadRequest(theImages[0]).then(function(bigImage){
          console.log(bigImage);
            theImages.shift();
            theLoadedImages.push(bigImage);
            loading = false;
          //mainDeferred.resolve();
        });
      });
         }
         if(!loading)
         {
            loading = true;
            $mediaStack.loadRequest(theImages[0]).then(function(bigImage){
            console.log(bigImage);
            theImages.shift();
            theLoadedImages.push(bigImage);
            loading = false;
            if(theImages.length>0)
            {
            $mediaStack.load();
            };
            });

         }
           }
      $mediaStack.loadRequest = function(source){
                          var deferred = $q.defer();
                          var bigImage = new Image();
                          bigImage.src = source.replace("small.",".");
                          bigImage.onload = function() {
                          deferred.resolve(bigImage);
                          }
                           return deferred.promise;
      }
      //.race implementation in old angular
      $mediaStack.myRaceFn = function (promises){
   return $q(function(resolve, reject) {
     promises.forEach(function(promise) {
       console.log(promise);
       promise.then(resolve, reject);
     });
   });
}
//.race implementation in old angular
      return $mediaStack;
    }])
</code>```

Body:
I'm trying to get better understanding of how to code in Angular properly and am writing my own custom module to better understand how things are supposed to work.

I have an HTML markup consisting of images and a directive i.e.

My directive is here:

.directive('mydirective', [
           '$animate','$mediaStack',
  function($animate,$mediaStack) {
  return {
    restrict: 'A',
    compile: function(tElement, tAttrs) {
        return loader;
    }
  };

    function loader(scope, element, attrs) {
      var source = attrs.ngSrc;
      var tooLoadBig = parseInt(attrs.resize);
      if(tooLoadBig){
        var bigImage = new Image();
        bigImage.src = source.replace("small.",".");
      }
      }
}])

The idea is this: if the image has small appended to its filename, I know it is a thumbnail. I want to load it's big version (same file without the appended small) in the background so it is ready for a lightbox.

This works fine as is, but the problem is because I'm doing all the work in the compile, when I set bigImage.src = source.replace("small.","."); it fires off right away, and if I have many small images on the page, it causes the page to slow down because of all the loading that is going on.

I want to therefore use $q to make it so that it will load one image at a time.

So move

 var bigImage = new Image();
 bigImage.src = source.replace("small.",".");

Into a promise. Is it best practice to do this in the directive? My understanding is it wouldn't make sense to do so and that I should use a service, but I'm not sure how to do that. I could play around with it more but I was hoping someone with more experience could instruct me as to best-practices for something like this and a code sample of a similar workflow, thank you.

Edits:

Directive:

.directive('mydirective', [
           '$animate','$mediaStack',
  function($animate,$mediaStack) {
  return {
    restrict: 'A',
    compile: function(tElement, tAttrs) {
        return loader;
    }
  };

    function loader(scope, element, attrs) {
      var source = attrs.ngSrc;
      var tooLoadBig = parseInt(attrs.resize);
      if(tooLoadBig){
        /*var bigImage = new Image();
        bigImage.src = source.replace("small.",".");*/
        $mediaStack.load(source);
      }
      }
}])

My service:

.factory('$mediaStack', [
             '$animate', '$timeout', '$document', '$compile', '$rootScope',
             '$q',
             '$injector',
    function($animate ,  $timeout ,  $document ,  $compile ,  $rootScope ,
              $q,
              $injector) {
      var OPENED_MEDIA_CLASS = 'media-open';
      var theImages = [];
      $mediaStack = {};
      $mediaStack.load = function(source){
          theImages.push(source);
      };
      $mediaStack.loadRequest   = function(theImages) {

                          deferred.resolve(function(){
                          var bigImage = new Image();
                          bigImage.src = theImages[0].replace("small.",".");
                          });
                          return deferred.promise;
                        }

                        /*var promise = asyncGreet('Robin Hood');
                        promise.then(function(greeting) {
                          alert('Success: ' + greeting);
                        }, function(reason) {
                          alert('Failed: ' + reason);
                        }, function(update) {
                          alert('Got notification: ' + update);
                        });*/
                        //above from docs
      }
      return $mediaStack;
    }])

This works in that it gets the image urls into an array in the service, so I have all the images in the array, how do I use $q properly based off that array. I got started but most of the $mediaStack.loadRequest is based off the $q documentation, I'm not sure how to use it effectively in this case.

EDIT 2:

My service as is:

    .factory('$mediaStack', [
                 '$animate', '$timeout', '$document', '$compile', '$rootScope',
                 '$q',
                 '$injector',
        function($animate ,  $timeout ,  $document ,  $compile ,  $rootScope ,
                  $q,
                  $injector) {
           var OPENED_MEDIA_CLASS = 'media-open';
      var theImages = [];
      var theLoadedImages = [];
      var thePromises = [];
      var loading = false;
      $mediaStack = {};
      $mediaStack.load = function(source){
          theImages.push(source);
          var mainDeferred = $q.defer();
         if(loading)
         {
             thePromises.push(mainDeferred.promise);
             console.log(thePromises);
             $mediaStack.myRaceFn(thePromises).then(function() {
             console.log("Fire!");
             loading=true;
            $mediaStack.loadRequest(theImages[0]).then(function(bigImage){
          console.log(bigImage);
            theImages.shift();
            theLoadedImages.push(bigImage);
            loading = false;
          mainDeferred.resolve();
        });
      });
         }
         if(!loading)
         {
            loading = true;
            $mediaStack.loadRequest(theImages[0]).then(function(bigImage){
            console.log(bigImage);
            theImages.shift();
            theLoadedImages.push(bigImage);
            loading = false;
            mainDeferred.resolve();
            });

         }
           }
      $mediaStack.loadRequest = function(source){
                          var deferred = $q.defer();
                          var bigImage = new Image();
                          bigImage.src = source.replace("small.",".");
                          bigImage.onload = function() {
                          deferred.resolve(bigImage);
                          }
                           return deferred.promise;
      }
      //.race implementation in old angular
      $mediaStack.myRaceFn = function (promises){
   return $q(function(resolve, reject) {
     promises.forEach(function(promise) {
       console.log(promise);
       promise.then(resolve, reject);
     });
   });
}
//.race implementation in old angular
      return $mediaStack;
        }])

I'm very close, I see an array of promises but I never get to the point of being able to fire them again, so I have 10 images, and I get an array of 9 promises. How do I fire them?

I expected it would happen around here:

$mediaStack.myRaceFn(thePromises).then(function() {
console.log("Fire!");
loading=true;
$mediaStack.loadRequest(theImages[0]).then(function(bigImage){

But I never get that console.log().

Instead I get console messages in $mediaStack.myRaceFn() showing me each promise (9 at the end) but they just sit there? I'm missing something.

I think I may be resolving mainDeferred too early...

Body:
Marking Oskar as accepted because it basically allowed me to figure out a solution.

Here is what I actually implemented, however:

    .factory('$mediaStack', [
             '$animate', '$timeout', '$document', '$compile', '$rootScope',
             '$q',
             '$injector',
    function($animate ,  $timeout ,  $document ,  $compile ,  $rootScope ,
              $q,
              $injector) {
      var OPENED_MEDIA_CLASS = 'media-open';
      var theImages = [];
      var theLoadedImages = [];
      var thePromises = [];
      var loading = false;
      $mediaStack = {};
      $mediaStack.load = function(source){
          if(source)
          {
          theImages.push(source);
          }
          var mainDeferred = $q.defer();
         if(loading)
         {
             thePromises.push(mainDeferred.promise);
             console.log(thePromises);
             $mediaStack.myRaceFn(thePromises).then(function() {
             console.log("Fire!");
             loading=true;
            $mediaStack.loadRequest(theImages[0]).then(function(bigImage){
          console.log(bigImage);
            theImages.shift();
            theLoadedImages.push(bigImage);
            loading = false;
          //mainDeferred.resolve();
        });
      });
         }
         if(!loading)
         {
            loading = true;
            $mediaStack.loadRequest(theImages[0]).then(function(bigImage){
            console.log(bigImage);
            theImages.shift();
            theLoadedImages.push(bigImage);
            loading = false;
            if(theImages.length>0)
            {
            $mediaStack.load();
            };
            });

         }
           }
      $mediaStack.loadRequest = function(source){
                          var deferred = $q.defer();
                          var bigImage = new Image();
                          bigImage.src = source.replace("small.",".");
                          bigImage.onload = function() {
                          deferred.resolve(bigImage);
                          }
                           return deferred.promise;
      }
      //.race implementation in old angular
      $mediaStack.myRaceFn = function (promises){
   return $q(function(resolve, reject) {
     promises.forEach(function(promise) {
       console.log(promise);
       promise.then(resolve, reject);
     });
   });
}
//.race implementation in old angular
      return $mediaStack;
    }])


问:
jQuery not working in MVC partialview after moving the JavaScript code to separate file and reference the file in a script tag cause problems
I am new to web development and I am using .net core MVC with VS2017, and trying to load several partial views inside a div (section1 and section2) using ajax and javascript.

My index page:

    Setup Programs

```
</div>
</div>
</p>

<p>When I include the javascript code inside the chtml it run perfectly, but when I remove the jQuery code and put it inside <code>site.js</code>, it didn't work </p>

<p>My site.js code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () {

    $("#Sform").submit(function (e) {
        e.preventDefault();
        var urlsx = $('#UrlsX').val();
        var urls = $('#Urls').val();

        $.ajax({
            url: urls,
            type: "POST",
            dataType: "html",
            data: $('#Sform').serialize(),
            success: function (data, textStatus, xhr) {
                $('#Section2').html(data);
                $("#Section1").load(urlsx)
            },
            error: function (xhr, textStatus, errorThrown) {
                $("#Section2").html(xhr.responseText);
            }
        });
    });

    $('.section1').click(function (e) {
        e.preventDefault();
        $("#Section1").show();
        $('#' + $(this).data("target")).load($(this).attr("href"));
    });

    $('.section2').click(function (e) {
        e.preventDefault();
        $("#Section1").show();
        $("#Section2").show();
        $('#' + $(this).data("target")).load($(this).attr("href"));
    });

});</code>```

the simple way to solve this issue is to include the script tag

```<code><script src="~/js/site.js"></script>
</code>```

at each partial view to load the JavaScript code after the DOM load and to be able to find the required objects, accounting to this post and also this post

Mmy problem is that the JavaScript code make the page load time too long after few clicks and it themes that the code is looping inside my C# action several times and making the page load time unaccepted.

Also the second partial view do not recognize the code and load in a new page rather than being rendered in the Section2 div.

The site.js file is referanced in the _Layout.cshtml:

```<code> <environment names="Development">
    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
    <script src="~/js/site.js"></script>@*asp-append-version="true"*@
</environment>
</code>```

The first patial view that load in section one is as follwoing :

@foreach (var p in Model)
{

        @p.ProgName

            Edit
            || Delete

}

    cancel

```

First : is it better to keep the JavaScript code inside the chtml view page ?\

Second : any idea how to come over this issue, in case i decided to move the JavaScript code into a separate file ?

答:
Is best to keep the jquery code in a separate file and include that file in your view.

If your page loading time is big, why you don't load the partials when you click the button instead of loading them all at once and keeping them hidden?

Also you are requesting the same partials multiple times?

Body:
I am new to web development and I am using .net core MVC with VS2017, and trying to load several partial views inside a div (section1 and section2) using ajax and javascript.

My index page:

    Setup Programs

When I include the javascript code inside the chtml it run perfectly, but when I remove the jQuery code and put it inside site.js, it didn't work

My site.js code:

$(document).ready(function () {

    $("#Sform").submit(function (e) {
        e.preventDefault();
        var urlsx = $('#UrlsX').val();
        var urls = $('#Urls').val();

        $.ajax({
            url: urls,
            type: "POST",
            dataType: "html",
            data: $('#Sform').serialize(),
            success: function (data, textStatus, xhr) {
                $('#Section2').html(data);
                $("#Section1").load(urlsx)
            },
            error: function (xhr, textStatus, errorThrown) {
                $("#Section2").html(xhr.responseText);
            }
        });
    });

    $('.section1').click(function (e) {
        e.preventDefault();
        $("#Section1").show();
        $('#' + $(this).data("target")).load($(this).attr("href"));
    });

    $('.section2').click(function (e) {
        e.preventDefault();
        $("#Section1").show();
        $("#Section2").show();
        $('#' + $(this).data("target")).load($(this).attr("href"));
    });

});

the simple way to solve this issue is to include the script tag

at each partial view to load the JavaScript code after the DOM load and to be able to find the required objects, accounting to this post and also this post

Mmy problem is that the JavaScript code make the page load time too long after few clicks and it themes that the code is looping inside my C# action several times and making the page load time unaccepted.

Also the second partial view do not recognize the code and load in a new page rather than being rendered in the Section2 div.

The site.js file is referanced in the _Layout.cshtml:

 <environment names="Development">

    @*asp-append-version="true"*@
</environment>

The first patial view that load in section one is as follwoing :

@foreach (var p in Model)
{

        @p.ProgName

            Edit
            || Delete

}

    cancel

First : is it better to keep the JavaScript code inside the chtml view page ?\

Second : any idea how to come over this issue, in case i decided to move the JavaScript code into a separate file ?


问:
How do you go about batch processing poorly formatted text files?
People complain a lot about XML but, when compared to EDI and some of the proprietary file formats I've dealt with in my career, I think XML is bliss.  The work I did on importing data files from Automotive Comparative Raters, each with it's own creative and nightmarish file format, still gives me nightmares.

That being said I'm curious how other programmers approach automated parsing of poorly formatted text files.  Do you have a language preference?  Are there any automation tools that you find invaluable?  How do you make your code reusable?

答:
A solution I learned about quite recently is using a standalone lexer. You get to use structured regular expressions and you avoid the constraints of a full blown parser generator.

Here are some examples with ocamllex (the lexer generator provided with OCaml):

an ocamllex tutorial with some examples.

processing of genbank loosely formatted text files (other link which better illustrates the point but hindered by a javascript dialog).

Obviously lexer generators are also available in other languages if using OCaml is an issue for you.


问:
how to put Firebase RecyclerView inside another RecyclerView
basically i am having an application like a homework reminder

the user can insert a list of subjects and in each subject a list of homeworks

i know its the worst practice and i cant put recyclerview inside another one

but i need that in my application as subjects cannot be counted+other things

i inserted it in firebase database successfuly like that

that is subject_item.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/simple_round"
android:padding="10dp"
android:layout_margin="10dp">
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Subject: "/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2"/>
</LinearLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="2dp"
    android:weightSum="6">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Teacher:"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="2"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/recyclerview_illness_item_list">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</code>```

and that is homework_item.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/simple_round"
android:padding="10dp"
android:layout_margin="10dp">
<LinearLayout
    android:layout_width="match_parent"
    android:padding="2dp"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="title:"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:orientation="horizontal">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="description:"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="deadline:"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>
</code>```

and for only one recyclerview i do it like that

```<code>adapter = new FirebaseRecyclerAdapter<Test, TestViewHolder>(Test.class, R.layout.test_main_body_item, TestViewHolder.class, reference.child("subjects/98794656")) {
        @Override
        protected void populateViewHolder(TestViewHolder viewHolder, Test model, int position) {
            viewHolder.title.setText(model.getTitle());
            viewHolder.description.setText(model.getDescription());
        }
    };
</code>```

so how can i do for a recycler view insider another recyclerview ??

thanks

答:
What you want to do is detect what is clicked and navigate to another activity  to show the list of data that also contains right?

But before that you need an EXTRA_KEY bundle to tell your new activity that it needs to receive something from his parent. e.g: "Hey, i am sending you a package, extract it and use it wisely in your environment."

Now to create that EXTRA BUNDLE is simple. Just write this in your local variable .

The activity you want navigate to, put this there:

```<code>public static final String EXTRA_NAME = "cheese_name";
public static final String EXTRA_POST_KEY = ""; `

Intent intent = getIntent();
final String cheeseName = intent.getStringExtra(EXTRA_NAME);`
</code>```

Get the database reference key for the post also:

```<code>            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Launch PostDetailActivity
                    Intent intent = new Intent(getActivity(),   CheeseDetailActivity.class);

  //How you are sending something to another activity

intent.putExtra(CheeseDetailActivity.EXTRA_POST_KEY, postKey);
                    startActivity(intent);
                }
            });

    }
};
</code>```

You referenced to a child ("test").

```<code>adapter = new FirebaseRecyclerAdapter<Test, TestViewHolder>(Test.class, R.layout.test_main_body_item, TestViewHolder.class, reference.child("test")) {
    @Override
    protected void populateViewHolder(TestViewHolder viewHolder, Test model, int position) {

    final DatabaseReference postRef = getRef(position);

            // Set click listener for the whole post view
            final String postKey = postRef.getKey();

        viewHolder.title.setText(model.getTitle());
        viewHolder.description.setText(model.getDescription());
    }
};
</code>```

Body:
basically i am having an application like a homework reminder

the user can insert a list of subjects and in each subject a list of homeworks

i know its the worst practice and i cant put recyclerview inside another one

but i need that in my application as subjects cannot be counted+other things

i inserted it in firebase database successfuly like that

that is subject_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/simple_round"
android:padding="10dp"
android:layout_margin="10dp">
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Subject: "/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2"/>
</LinearLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="2dp"
    android:weightSum="6">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Teacher:"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="2"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/recyclerview_illness_item_list">
</android.support.v7.widget.RecyclerView>
</LinearLayout>

and that is homework_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/simple_round"
android:padding="10dp"
android:layout_margin="10dp">
<LinearLayout
    android:layout_width="match_parent"
    android:padding="2dp"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="title:"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:orientation="horizontal">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="description:"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="deadline:"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

and for only one recyclerview i do it like that

adapter = new FirebaseRecyclerAdapter<Test, TestViewHolder>(Test.class, R.layout.test_main_body_item, TestViewHolder.class, reference.child("subjects/98794656")) {
        @Override
        protected void populateViewHolder(TestViewHolder viewHolder, Test model, int position) {
            viewHolder.title.setText(model.getTitle());
            viewHolder.description.setText(model.getDescription());
        }
    };

so how can i do for a recycler view insider another recyclerview ??

thanks

Body:
What you want to do is detect what is clicked and navigate to another activity  to show the list of data that also contains right?

But before that you need an EXTRA_KEY bundle to tell your new activity that it needs to receive something from his parent. e.g: "Hey, i am sending you a package, extract it and use it wisely in your environment."

Now to create that EXTRA BUNDLE is simple. Just write this in your local variable .

The activity you want navigate to, put this there:

public static final String EXTRA_NAME = "cheese_name";
public static final String EXTRA_POST_KEY = ""; `

Intent intent = getIntent();
final String cheeseName = intent.getStringExtra(EXTRA_NAME);`

Get the database reference key for the post also:

            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Launch PostDetailActivity
                    Intent intent = new Intent(getActivity(),   CheeseDetailActivity.class);

  //How you are sending something to another activity

intent.putExtra(CheeseDetailActivity.EXTRA_POST_KEY, postKey);
                    startActivity(intent);
                }
            });

    }
};

You referenced to a child ("test").

adapter = new FirebaseRecyclerAdapter<Test, TestViewHolder>(Test.class, R.layout.test_main_body_item, TestViewHolder.class, reference.child("test")) {
    @Override
    protected void populateViewHolder(TestViewHolder viewHolder, Test model, int position) {

    final DatabaseReference postRef = getRef(position);

            // Set click listener for the whole post view
            final String postKey = postRef.getKey();

        viewHolder.title.setText(model.getTitle());
        viewHolder.description.setText(model.getDescription());
    }
};


问:
$exists query in mongodb c-api
I am trying to implement the following mongodb query in C

db.test.find({"timestamp": {"$exists":true}});

I thought it would be something like

```<code>bson query, existspart;
mongo_cursor cursor;
int i;

bson_init(&existspart);
bson_append_string ( &existspart, "$exists", "false" );
bson_finish(&existspart);
bson_init(&query);
bson_append_bson ( &query, "timestamp", &existspart );
bson_finish(&query);

mongo_cursor_init(&cursor, conn, "mydb.test");
mongo_cursor_set_query(&cursor, &query );
while( mongo_cursor_next( &cursor ) == MONGO_OK )
{
    // blabla
}
</code>```

But it does not work. What I am doing wrong?

答:
I used a slightly different syntax:</p>

```<code>bson_t* existspart = BCON_NEW("$exists", BCON_BOOL(true));
bson_t *query = bson_new();
BSON_APPEND_DOCUMENT(query, "timestamp", existspart);

mongoc_cursor_t* cursor = MongoInterface::Instance().Find("db_name", query);

const bson_t *doc;
while (mongoc_cursor_next (cursor, &doc))
{
  // Do stuff...
}

bson_destroy (existspart);
bson_destroy (query);
</code>```

Title: $exists query in mongodb c-api

Body:
I am trying to implement the following mongodb query in C

db.test.find({"timestamp": {"$exists":true}});

I thought it would be something like

bson query, existspart;
mongo_cursor cursor;
int i;

bson_init(&existspart);
bson_append_string ( &existspart, "$exists", "false" );
bson_finish(&existspart);
bson_init(&query);
bson_append_bson ( &query, "timestamp", &existspart );
bson_finish(&query);

mongo_cursor_init(&cursor, conn, "mydb.test");
mongo_cursor_set_query(&cursor, &query );
while( mongo_cursor_next( &cursor ) == MONGO_OK )
{
    // blabla
}

But it does not work. What I am doing wrong?

Body:
I used a slightly different syntax:

bson_t* existspart = BCON_NEW("$exists", BCON_BOOL(true));
bson_t *query = bson_new();
BSON_APPEND_DOCUMENT(query, "timestamp", existspart);

mongoc_cursor_t* cursor = MongoInterface::Instance().Find("db_name", query);

const bson_t *doc;
while (mongoc_cursor_next (cursor, &doc))
{
  // Do stuff...
}

bson_destroy (existspart);
bson_destroy (query);


问:
Can you upload changes, to Google Drive, only?
Similarly to GIT, is it possible to upload changes to a file, only, instead of uploading the entire new file?

I wish to do this within C#.

I've tried searching for a solution, but haven't had luck.

答: No you can't. The only exception is if it's a spreadsheet you can update individual cells using the Sheets API.</p>


问:
TypeScript returns `":" expected` in Ionic 2 app
I get a TypeScript error with this code in Angular 2 / Ionic 2:

```<code>constructor(){...}

    initializeApp() {
        this.platform.ready().then(() => {
        this.geolocation.getCurrentPosition().then((resp) => {
                // resp.coords.latitude
                // resp.coords.longitude
                this.storageService.set("geolocation", {resp.coords.latitude, resp.coords.longitude} );
            }).catch((error) => {
              console.log('Error getting location', error);
            });
});
    }
</code>```

error:

```<code>Typescript Error
':' expected.
src/app/app.component.ts
    // resp.coords.longitude
    this.storageService.set("geolocation", {resp.coords.latitude, resp.coords.longitude} );
</code>```

on the "." after "resp".

I am new to TypeScript, should I declare something here ?

答:
You should either save your data as an array or as an object:

array

```<code>[resp.coords.latitude, resp.coords.longitude]
</code>```

object

```<code>{latitude: resp.coords.latitude, longitude: resp.coords.longitude}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I get a TypeScript error with this code in Angular 2 / Ionic 2:

constructor(){...}

    initializeApp() {
        this.platform.ready().then(() => {
        this.geolocation.getCurrentPosition().then((resp) => {
                // resp.coords.latitude
                // resp.coords.longitude
                this.storageService.set("geolocation", {resp.coords.latitude, resp.coords.longitude} );
            }).catch((error) => {
              console.log('Error getting location', error);
            });
});
    }

error:

Typescript Error
':' expected.
src/app/app.component.ts
    // resp.coords.longitude
    this.storageService.set("geolocation", {resp.coords.latitude, resp.coords.longitude} );

on the "." after "resp".

I am new to TypeScript, should I declare something here ?

Body:
You should either save your data as an array or as an object:

array

[resp.coords.latitude, resp.coords.longitude]

object

{latitude: resp.coords.latitude, longitude: resp.coords.longitude}