问:
Why is boost::recursive_wrapper not working in this case
I have the following three rules:

```<code>unary_expression =
    ( '(' > expression > ')' )
    | int_;

operator_expression =
    unary_expression >> *(operators > expression);

expression =
    ( '(' > expression > ')' )
    | operator_expression;
</code>```

Obviously this is recursive, so I use boost::recursive_wrapper and created the following AST:

```<code>struct expression;
using unary_expression_node = boost::variant<boost::recursive_wrapper<expression>, int>;

struct unary_expression
{
  unary_expression_node m_unary_expression;
};

enum operators { op_eq, op_ne };
struct expression;
struct operator_expression
{
  unary_expression first;
  using second_type = std::vector<std::pair<operators, expression>>;
  second_type second;
};

using expression_node =
boost::variant<boost::recursive_wrapper<expression>, operator_expression>;

struct expression
{
  expression_node m_expression;
};
</code>```

This compiles (see full example below), but when the code attempts to construct an expression object the constructor gets into an infinite loop of calling these three constructors:

```<code>#11 0x0000000000466066 in ast::expression::expression ...
#12 0x00000000004682e0 in boost::recursive_wrapper<ast::expression>::recursive_wrapper ...
#13 0x000000000046718d in boost::variant<boost::recursive_wrapper<ast::expression>, ast::operator_expression>::variant
...
</code>```

Thus, Creating an expression creates a boost::variant<boost::recursive_wrapper<ast::expression>, ast::operator_expression> (aka, an expression_node) which creates a boost::recursive_wrapper<ast::expression> which creates an expression which creates... and so on.

How can I solve this?

Here is a full example that compiles, but segfaults when the stack runs full:

```<code>#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <iostream>
#include <string>
#include <vector>

namespace ast {

struct expression;
using unary_expression_node = boost::variant<boost::recursive_wrapper<expression>, int>;

struct unary_expression
{
  unary_expression_node m_unary_expression;
};

enum operators { op_eq, op_ne };
struct expression;
struct operator_expression
{
  unary_expression first;
  using second_type = std::vector<std::pair<operators, expression>>;
  second_type second;
};

using expression_node = boost::variant<boost::recursive_wrapper<expression>, operator_expression>;

struct expression
{
  expression_node m_expression;
};

std::ostream& operator<<(std::ostream& os, expression const& expression)
{
  return os << expression.m_expression;
}

std::ostream& operator<<(std::ostream& os, unary_expression const& unary_expression)
{
  return os << unary_expression.m_unary_expression;
}

std::ostream& operator<<(std::ostream& os, operator_expression const& operator_expression)
{
  os << operator_expression.first;
  for (auto& l : operator_expression.second)
  {
    os << ' ' << l.first << ' ' << l.second;
  }
  return os;
}

} // namespace ast

BOOST_FUSION_ADAPT_STRUCT(
  ast::expression,
  (ast::expression_node, m_expression)
)

BOOST_FUSION_ADAPT_STRUCT(
  ast::unary_expression,
  (ast::unary_expression_node, m_unary_expression)
)

BOOST_FUSION_ADAPT_STRUCT(
  ast::operator_expression,
  (ast::unary_expression, first),
  (ast::operator_expression::second_type, second)
)

namespace client
{

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

template <typename Iterator>
class expression_grammar : public qi::grammar<Iterator, ast::expression(), qi::space_type>
{
 private:
  qi::symbols<char, ast::operators> operators;
  qi::rule<Iterator, ast::unary_expression(), qi::space_type> unary_expression;
  qi::rule<Iterator, ast::operator_expression(), qi::space_type> operator_expression;
  qi::rule<Iterator, ast::expression(), qi::space_type> expression;

 public:
  expression_grammar() : expression_grammar::base_type(expression, "expression_grammar")
  {
    using qi::double_;
    using qi::char_;
    using qi::int_;

    operators.add
        ("==", ast::op_eq)
        ("!=", ast::op_ne)
    ;

    unary_expression =
        ( '(' > expression > ')' )
        | int_;

    operator_expression =
        unary_expression >> *(operators > expression);

    expression =
        ( '(' > expression > ')' )
        | operator_expression;
  }
};

} // namespace client

int main()
{
  std::string const input{"1 == 1 != 0"};
  using iterator_type = std::string::const_iterator;
  using expression_grammar = client::expression_grammar<iterator_type>;
  namespace qi = boost::spirit::qi;

  expression_grammar program;
  iterator_type iter{input.begin()};
  iterator_type const end{input.end()};
  ast::expression out;
  bool r = qi::phrase_parse(iter, end, program, qi::space, out);

  if (!r || iter != end)
  {
    std::cerr << "Parsing failed." << std::endl;
    return 1;
  }
  std::cout << "Parsed: " << out << std::endl;
}
</code>```

EDIT:

I tried simplifying things to just two rules (and two 'ast's):

```<code>struct expression;
using unary_expression = boost::variant<boost::recursive_wrapper<expression>, int>;

enum operators { op_eq, op_ne };
struct expression
{
  unary_expression first;
  using second_type = std::vector<std::pair<operators, expression>>;
  second_type second;
};

BOOST_FUSION_ADAPT_STRUCT(
  ast::expression,
  (ast::unary_expression, first),
  (ast::expression::second_type, second)
)

[...]

  unary_expression =
    ( '(' > expression > ')' )
    | int_;

  expression =
    unary_expression >> *(operators > expression);
</code>```

but also this result in an infinite loop.

```<code>#18 0x00000000004646f2 in ast::expression::expression
#19 0x00000000004669ac in boost::recursive_wrapper<ast::expression>::recursive_wrapper
#20 0x0000000000465821 in boost::variant<boost::recursive_wrapper<ast::expression>, int>::variant
...
</code>```

答:
Variants default-construct to their first element type.

This indeed directly leads to an infinite loop. (Demo)

The way to solve it is to make the default variant element not re-entrant or to make it lazily constructed. In this case, you can simply re-arrange to make int the first element.

Better yet, there doesn't seem to be a need to reflect the operator precedence hieararchy (as it is expressed in the rules) in the resultant tree, so why not simplify to:

```<code>struct unary_expression;
struct binary_expression;

enum operators { op_eq, op_ne };

using expression = boost::variant<
    int,
    boost::recursive_wrapper<unary_expression>,
    boost::recursive_wrapper<binary_expression>
>;

struct unary_expression {
    expression expr;
};

struct binary_expression {
    expression                                    first;
    std::vector<std::pair<operators, expression>> other;
};
</code>```

This no longer crashes and seems a bit simpler in adaptation and usage.

Simplified Full Demo

This full demo uses that AST, but adds a true unary expression. A few style things have been fixed:

don't expose the skipper unless you intend for the caller to change it

make the parser const

show unparsed trailing data (or instead assert >> qi::eoi)

Note: I might have changed the precedence rules (specifically, associativity of binary operators). I'm not sure which version you require.

Live On Coliru

```<code>//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <iostream>
#include <string>
#include <vector>

namespace ast {
    struct unary_expression;
    struct binary_expression;

    enum operators { op_eq, op_ne };

    using expression = boost::variant<
        int,
        boost::recursive_wrapper<unary_expression>,
        boost::recursive_wrapper<binary_expression>
    >;

    struct unary_expression {
        bool negated = false;
        expression expr;
    };

    struct binary_expression {
        expression                                    first;
        std::vector<std::pair<operators, expression>> other;
    };

}

BOOST_FUSION_ADAPT_STRUCT(ast::unary_expression, negated, expr)
BOOST_FUSION_ADAPT_STRUCT(ast::binary_expression, first, other)

namespace ast {
    static inline std::ostream& operator<<(std::ostream& os, operators op) { return os << (op==op_eq?"==":"!="); }
    static inline std::ostream& operator<<(std::ostream& os, binary_expression const& e) {
        os << e.first;
        for (auto& oe : e.other)
            os << " " << oe.first << " " << oe.second;
        return os;
    }
    static inline std::ostream& operator<<(std::ostream& os, unary_expression const& e) {
        return os << (e.negated?"!":"") << "(" << e.expr << ")";
    }
}

namespace client
{
    namespace qi = boost::spirit::qi;

    template <typename Iterator>
    class expression_grammar : public qi::grammar<Iterator, ast::expression()> {
      private:
        qi::symbols<char, ast::operators> operators;
        qi::rule<Iterator, ast::expression()> start;

        qi::rule<Iterator, ast::expression(),        qi::space_type> simple_expression;
        qi::rule<Iterator, ast::unary_expression(),  qi::space_type> unary_expression;
        qi::rule<Iterator, ast::binary_expression(), qi::space_type> binary_expression;
        qi::rule<Iterator, ast::expression(),        qi::space_type> expression;

      public:
        expression_grammar() : expression_grammar::base_type(start, "expression") {
            using namespace qi;

            operators.add
                ("==", ast::op_eq)
                ("!=", ast::op_ne)
                ;

            simple_expression =
                ( '(' > expression > ')' )
                | int_;

            unary_expression =
                matches['!'] >> simple_expression;

            binary_expression =
                unary_expression >> *(operators > expression);

            expression = binary_expression;

            start = skip(space) [ expression ];

            BOOST_SPIRIT_DEBUG_NODES((expression)(binary_expression)(unary_expression)(simple_expression))
        }
    };

} // namespace client

int main() {
    using It = std::string::const_iterator;
    client::expression_grammar<It> const program;

    std::string const input{"1 == !(1 != 0)"};
    It iter = input.begin(), end = input.end();
    ast::expression out;

    if (parse(iter, end, program, out)) {
        std::cout << "Parsed: " << out << std::endl;
    } else {
        std::cerr << "Parsing failed." << std::endl;
        return 1;
    }

    if (iter != end) {
        std::cout << "Remaining unparsed input: '" << std::string(iter, end) << "'\n";
    }
}
</code>```

Prints

```<code>Parsed: (1) == !((1) != (0))
</code>```

Body:
I have the following three rules:

unary_expression =
    ( '(' > expression > ')' )
    | int_;

operator_expression =
    unary_expression >> *(operators > expression);

expression =
    ( '(' > expression > ')' )
    | operator_expression;

Obviously this is recursive, so I use boost::recursive_wrapper and created the following AST:

struct expression;
using unary_expression_node = boost::variant<boost::recursive_wrapper<expression>, int>;

struct unary_expression
{
  unary_expression_node m_unary_expression;
};

enum operators { op_eq, op_ne };
struct expression;
struct operator_expression
{
  unary_expression first;
  using second_type = std::vector<std::pair<operators, expression>>;
  second_type second;
};

using expression_node =
boost::variant<boost::recursive_wrapper<expression>, operator_expression>;

struct expression
{
  expression_node m_expression;
};

This compiles (see full example below), but when the code attempts to construct an expression object the constructor gets into an infinite loop of calling these three constructors:

#11 0x0000000000466066 in ast::expression::expression ...
#12 0x00000000004682e0 in boost::recursive_wrapper<ast::expression>::recursive_wrapper ...
#13 0x000000000046718d in boost::variant<boost::recursive_wrapper<ast::expression>, ast::operator_expression>::variant
...

Thus, Creating an expression creates a boost::variant<boost::recursive_wrapper<ast::expression>, ast::operator_expression> (aka, an expression_node) which creates a boost::recursive_wrapper<ast::expression> which creates an expression which creates... and so on.

How can I solve this?

Here is a full example that compiles, but segfaults when the stack runs full:

#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <iostream>
#include <string>
#include <vector>

namespace ast {

struct expression;
using unary_expression_node = boost::variant<boost::recursive_wrapper<expression>, int>;

struct unary_expression
{
  unary_expression_node m_unary_expression;
};

enum operators { op_eq, op_ne };
struct expression;
struct operator_expression
{
  unary_expression first;
  using second_type = std::vector<std::pair<operators, expression>>;
  second_type second;
};

using expression_node = boost::variant<boost::recursive_wrapper<expression>, operator_expression>;

struct expression
{
  expression_node m_expression;
};

std::ostream& operator<<(std::ostream& os, expression const& expression)
{
  return os << expression.m_expression;
}

std::ostream& operator<<(std::ostream& os, unary_expression const& unary_expression)
{
  return os << unary_expression.m_unary_expression;
}

std::ostream& operator<<(std::ostream& os, operator_expression const& operator_expression)
{
  os << operator_expression.first;
  for (auto& l : operator_expression.second)
  {
    os << ' ' << l.first << ' ' << l.second;
  }
  return os;
}

} // namespace ast

BOOST_FUSION_ADAPT_STRUCT(
  ast::expression,
  (ast::expression_node, m_expression)
)

BOOST_FUSION_ADAPT_STRUCT(
  ast::unary_expression,
  (ast::unary_expression_node, m_unary_expression)
)

BOOST_FUSION_ADAPT_STRUCT(
  ast::operator_expression,
  (ast::unary_expression, first),
  (ast::operator_expression::second_type, second)
)

namespace client
{

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

template <typename Iterator>
class expression_grammar : public qi::grammar<Iterator, ast::expression(), qi::space_type>
{
 private:
  qi::symbols<char, ast::operators> operators;
  qi::rule<Iterator, ast::unary_expression(), qi::space_type> unary_expression;
  qi::rule<Iterator, ast::operator_expression(), qi::space_type> operator_expression;
  qi::rule<Iterator, ast::expression(), qi::space_type> expression;

 public:
  expression_grammar() : expression_grammar::base_type(expression, "expression_grammar")
  {
    using qi::double_;
    using qi::char_;
    using qi::int_;

    operators.add
        ("==", ast::op_eq)
        ("!=", ast::op_ne)
    ;

    unary_expression =
        ( '(' > expression > ')' )
        | int_;

    operator_expression =
        unary_expression >> *(operators > expression);

    expression =
        ( '(' > expression > ')' )
        | operator_expression;
  }
};

} // namespace client

int main()
{
  std::string const input{"1 == 1 != 0"};
  using iterator_type = std::string::const_iterator;
  using expression_grammar = client::expression_grammar<iterator_type>;
  namespace qi = boost::spirit::qi;

  expression_grammar program;
  iterator_type iter{input.begin()};
  iterator_type const end{input.end()};
  ast::expression out;
  bool r = qi::phrase_parse(iter, end, program, qi::space, out);

  if (!r || iter != end)
  {
    std::cerr << "Parsing failed." << std::endl;
    return 1;
  }
  std::cout << "Parsed: " << out << std::endl;
}

EDIT:

I tried simplifying things to just two rules (and two 'ast's):

struct expression;
using unary_expression = boost::variant<boost::recursive_wrapper<expression>, int>;

enum operators { op_eq, op_ne };
struct expression
{
  unary_expression first;
  using second_type = std::vector<std::pair<operators, expression>>;
  second_type second;
};

BOOST_FUSION_ADAPT_STRUCT(
  ast::expression,
  (ast::unary_expression, first),
  (ast::expression::second_type, second)
)

[...]

  unary_expression =
    ( '(' > expression > ')' )
    | int_;

  expression =
    unary_expression >> *(operators > expression);

but also this result in an infinite loop.

#18 0x00000000004646f2 in ast::expression::expression
#19 0x00000000004669ac in boost::recursive_wrapper<ast::expression>::recursive_wrapper
#20 0x0000000000465821 in boost::variant<boost::recursive_wrapper<ast::expression>, int>::variant
...

Body:
Variants default-construct to their first element type.

This indeed directly leads to an infinite loop. (Demo)

The way to solve it is to make the default variant element not re-entrant or to make it lazily constructed. In this case, you can simply re-arrange to make int the first element.

Better yet, there doesn't seem to be a need to reflect the operator precedence hieararchy (as it is expressed in the rules) in the resultant tree, so why not simplify to:

struct unary_expression;
struct binary_expression;

enum operators { op_eq, op_ne };

using expression = boost::variant<
    int,
    boost::recursive_wrapper<unary_expression>,
    boost::recursive_wrapper<binary_expression>
>;

struct unary_expression {
    expression expr;
};

struct binary_expression {
    expression                                    first;
    std::vector<std::pair<operators, expression>> other;
};

This no longer crashes and seems a bit simpler in adaptation and usage.

Simplified Full Demo

This full demo uses that AST, but adds a true unary expression. A few style things have been fixed:

don't expose the skipper unless you intend for the caller to change it

make the parser const

show unparsed trailing data (or instead assert >> qi::eoi)

Note: I might have changed the precedence rules (specifically, associativity of binary operators). I'm not sure which version you require.

Live On Coliru

//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <iostream>
#include <string>
#include <vector>

namespace ast {
    struct unary_expression;
    struct binary_expression;

    enum operators { op_eq, op_ne };

    using expression = boost::variant<
        int,
        boost::recursive_wrapper<unary_expression>,
        boost::recursive_wrapper<binary_expression>
    >;

    struct unary_expression {
        bool negated = false;
        expression expr;
    };

    struct binary_expression {
        expression                                    first;
        std::vector<std::pair<operators, expression>> other;
    };

}

BOOST_FUSION_ADAPT_STRUCT(ast::unary_expression, negated, expr)
BOOST_FUSION_ADAPT_STRUCT(ast::binary_expression, first, other)

namespace ast {
    static inline std::ostream& operator<<(std::ostream& os, operators op) { return os << (op==op_eq?"==":"!="); }
    static inline std::ostream& operator<<(std::ostream& os, binary_expression const& e) {
        os << e.first;
        for (auto& oe : e.other)
            os << " " << oe.first << " " << oe.second;
        return os;
    }
    static inline std::ostream& operator<<(std::ostream& os, unary_expression const& e) {
        return os << (e.negated?"!":"") << "(" << e.expr << ")";
    }
}

namespace client
{
    namespace qi = boost::spirit::qi;

    template <typename Iterator>
    class expression_grammar : public qi::grammar<Iterator, ast::expression()> {
      private:
        qi::symbols<char, ast::operators> operators;
        qi::rule<Iterator, ast::expression()> start;

        qi::rule<Iterator, ast::expression(),        qi::space_type> simple_expression;
        qi::rule<Iterator, ast::unary_expression(),  qi::space_type> unary_expression;
        qi::rule<Iterator, ast::binary_expression(), qi::space_type> binary_expression;
        qi::rule<Iterator, ast::expression(),        qi::space_type> expression;

      public:
        expression_grammar() : expression_grammar::base_type(start, "expression") {
            using namespace qi;

            operators.add
                ("==", ast::op_eq)
                ("!=", ast::op_ne)
                ;

            simple_expression =
                ( '(' > expression > ')' )
                | int_;

            unary_expression =
                matches['!'] >> simple_expression;

            binary_expression =
                unary_expression >> *(operators > expression);

            expression = binary_expression;

            start = skip(space) [ expression ];

            BOOST_SPIRIT_DEBUG_NODES((expression)(binary_expression)(unary_expression)(simple_expression))
        }
    };

} // namespace client

int main() {
    using It = std::string::const_iterator;
    client::expression_grammar<It> const program;

    std::string const input{"1 == !(1 != 0)"};
    It iter = input.begin(), end = input.end();
    ast::expression out;

    if (parse(iter, end, program, out)) {
        std::cout << "Parsed: " << out << std::endl;
    } else {
        std::cerr << "Parsing failed." << std::endl;
        return 1;
    }

    if (iter != end) {
        std::cout << "Remaining unparsed input: '" << std::string(iter, end) << "'\n";
    }
}

Prints

Parsed: (1) == !((1) != (0))


来源: stackexchange

问:
Use iPhone 6/6s/7 Plus' Native Resolution
I'm creating an app that uses pixel-art style graphics, and I'd like to avoid the "Plus-class" iPhones' downscaling from 1242x2208 to 1080x1920 in order to avoid resampling artifacts. I know iOS bypasses the scaling when it plays full screen video. Private APIs are fine (not targeting the App Store) and I'm using OpenGL with GLKView to render, if that's relevant.</p>

答:
```<code>glkView.contentScaleFactor = UIScreen.main.nativeScale
</code>```

See the answers to this question for more information.

ContentLicense: CC BY-SA 3.0

Body:
glkView.contentScaleFactor = UIScreen.main.nativeScale

See the answers to this question for more information.


问:
How to access second "td" using BeautifulSoup
I have an html document that I am trying to scrape. I have gotten to the "table" part of the document, but I cannot seem to access the "td" that I want. Here is an image of a part of the document looks like:

This is some of my code:

```<code>prePostBody.find("table", {"class": "tborder"}).find("tr", {"valign": "top"}).find("td")
print(prePostBody)
</code>```

When I run my code, I get this:

```<code><td class="alt2" style="border: 1px solid #D1D1E1; border-top: 0px; border-bottom: 0px" width="175">
<div id="postmenu_2012213">
</code>```

So my code is working, and it is finding the "td" with class="alt2", but I want to be able to access the class="alt1" portion of the table. How would I do that?

答:
Why don't you try:</p>

```<code>prePostBody.find("table", {"class": "tborder"}).find("tr", {"valign": "top"}).find("td", {"class": "alt1"})
print(prePostBody)
</code>```

Body:
I have an html document that I am trying to scrape. I have gotten to the "table" part of the document, but I cannot seem to access the "td" that I want. Here is an image of a part of the document looks like:

This is some of my code:

prePostBody.find("table", {"class": "tborder"}).find("tr", {"valign": "top"}).find("td")
print(prePostBody)

When I run my code, I get this:

So my code is working, and it is finding the "td" with class="alt2", but I want to be able to access the class="alt1" portion of the table. How would I do that?

Body:
Why don't you try:

prePostBody.find("table", {"class": "tborder"}).find("tr", {"valign": "top"}).find("td", {"class": "alt1"})
print(prePostBody)


问:
ServiceNow- How add user to a grup from excel file
I have a excel file with the below info :

User name--|--Group Name--|--User id

User 1-------|---   Group 1------|------1

User 2-------|---group 2--------|------2

User 3-------|---group 3--------|------3

all the listed "users"  and "group" are present in the user table and group table, ex(User1, user2, user3 are there in sys_user table and group1, group2 , group3 are present in sys_user_group)

i just want to add the user to the corresponding group mention in the excel.

Can anyone suggest how to automate this in service now by any means because the excel file contains larger no of data and manually it is not possible.

答:
You can use an Import Set and add records to the sys_user_grmember table.

There are two fields to set on the insert

Group - sys_id of the group

User - sys_id of the user

Update @Joey mentioned the Transform Set that is part of an overall Import Set, take a look at the details for your version. For example, Istanbul https://docs.servicenow.com/bundle/istanbul-servicenow-platform/page/script/server-scripting/task/t_CreateATransformMap.html

Essentially this is used by the Import Set to map the spreadsheet to the fields in ServiceNow.

In your case it's slightly more involved since you'll need to get the sys_id for the user and the group, while it sounds like you have the usernames and the group names. Using the Script section of the Transform Map should work in your case.

Something along the code below would be a general idea. However I haven't tested this whatsoever and you'd need to test thoroughly in a development environment to get it working.

Here source.u_user_name and source.u_group_name are the fields from your loaded data in the Import Set

```<code>(function runTransformScript(source, map, log, target /*undefined onStart*/ ) {
    // get the user
    var usr = new GlideRecord('sys_user');
    usr.get('user_name',source.u_user_name.toString());

    // get the group
    var grp = new GlideRecord('sys_group');
    grp.get('name',source.u_group_name.toString());

    // insert group membership
    var grMember = new GlideRecord('sys_user_grmember');
    grMember.initialize();
    grMember.user = usr.sys_id;
    grMember.group = grp.sys_id;
    grMember.insert();

})(source, map, log, target);
</code>```

Body:
You can use an Import Set and add records to the sys_user_grmember table.

There are two fields to set on the insert

Group - sys_id of the group

User - sys_id of the user

Update @Joey mentioned the Transform Set that is part of an overall Import Set, take a look at the details for your version. For example, Istanbul https://docs.servicenow.com/bundle/istanbul-servicenow-platform/page/script/server-scripting/task/t_CreateATransformMap.html

Essentially this is used by the Import Set to map the spreadsheet to the fields in ServiceNow.

In your case it's slightly more involved since you'll need to get the sys_id for the user and the group, while it sounds like you have the usernames and the group names. Using the Script section of the Transform Map should work in your case.

Something along the code below would be a general idea. However I haven't tested this whatsoever and you'd need to test thoroughly in a development environment to get it working.

Here source.u_user_name and source.u_group_name are the fields from your loaded data in the Import Set

(function runTransformScript(source, map, log, target /*undefined onStart*/ ) {
    // get the user
    var usr = new GlideRecord('sys_user');
    usr.get('user_name',source.u_user_name.toString());

    // get the group
    var grp = new GlideRecord('sys_group');
    grp.get('name',source.u_group_name.toString());

    // insert group membership
    var grMember = new GlideRecord('sys_user_grmember');
    grMember.initialize();
    grMember.user = usr.sys_id;
    grMember.group = grp.sys_id;
    grMember.insert();

})(source, map, log, target);


问:
make loop read clearer
within my while loop I am doing a test, but it seems really redundant and I think there may be a better solution to implement this such as a "case" structure possibly? If anyone can recommend how to cut down on the redundancy that would be wonderful, thanks! Basically, how can I restructure this loop to be better?

the loop:

```<code> if [ "$cursor" -eq "1" ]
    then
        Links="Links: $(ls -ld / | cut -d" " -f2)"
        Owner="Owner: $(ls -ld / | cut -d" " -f3)"
        Group="Group: $(ls -ld / | cut -d" " -f4)"
        Size="Size: $(ls -ld / | cut -d" " -f5)"
        Modified="Modified: $(ls -ld / | cut -d" " -f6-8)"
        echo "$Links  $Owner  $Group  $Size  $Modified"
    elif [ "$cursor" -eq "2" ]
    then
        Links="Links: $(ls -ld /home | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld /home | cut -d" " -f3)"
                    Group="Group: $(ls -ld /home | cut -d" " -f4)"
                    Size="Size: $(ls -ld /home | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld /home | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
        elif [ "$cursor" -eq "3" ]
    then
        Links="Links: $(ls -ld ~ | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld ~ | cut -d" " -f3)"
                    Group="Group: $(ls -ld ~ | cut -d" " -f4)"
                    Size="Size: $(ls -ld ~ | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld ~ | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
    else
        temp=`expr $cursor - 1`
        curDir=${currentdir[$temp]}
        Links="Links: $(ls -ld $curDir | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld $curDir | cut -d" " -f3)"
                    Group="Group: $(ls -ld $curDir | cut -d" " -f4)"
                    Size="Size: $(ls -ld $curDir | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld $curDir | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
fi
</code>```

答:
```<code>#!/bin/bash
cursor="$1"
case "$cursor" in
    1) curDir="/"
    ;;
    2) curDir="/home"
    ;;
    3) curDir="${HOME}"
    ;;
    *) curDir=${currentdir[$temp]}
    ;;
esac

Links="Links: $(ls -ld $curDir | cut -d" " -f2)"
Owner="Owner: $(ls -ld $curDir | cut -d" " -f3)"
Group="Group: $(ls -ld $curDir | cut -d" " -f4)"
Size="Size: $(ls -ld $curDir | cut -d" " -f5)"
Modified="Modified: $(ls -ld $curDir | cut -d" " -f6-8)"
echo "$Links  $Owner  $Group  $Size  $Modified"
</code>```

Title: make loop read clearer

Body:
within my while loop I am doing a test, but it seems really redundant and I think there may be a better solution to implement this such as a "case" structure possibly? If anyone can recommend how to cut down on the redundancy that would be wonderful, thanks! Basically, how can I restructure this loop to be better?

the loop:

 if [ "$cursor" -eq "1" ]
    then
        Links="Links: $(ls -ld / | cut -d" " -f2)"
        Owner="Owner: $(ls -ld / | cut -d" " -f3)"
        Group="Group: $(ls -ld / | cut -d" " -f4)"
        Size="Size: $(ls -ld / | cut -d" " -f5)"
        Modified="Modified: $(ls -ld / | cut -d" " -f6-8)"
        echo "$Links  $Owner  $Group  $Size  $Modified"
    elif [ "$cursor" -eq "2" ]
    then
        Links="Links: $(ls -ld /home | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld /home | cut -d" " -f3)"
                    Group="Group: $(ls -ld /home | cut -d" " -f4)"
                    Size="Size: $(ls -ld /home | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld /home | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
        elif [ "$cursor" -eq "3" ]
    then
        Links="Links: $(ls -ld ~ | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld ~ | cut -d" " -f3)"
                    Group="Group: $(ls -ld ~ | cut -d" " -f4)"
                    Size="Size: $(ls -ld ~ | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld ~ | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
    else
        temp=`expr $cursor - 1`
        curDir=${currentdir[$temp]}
        Links="Links: $(ls -ld $curDir | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld $curDir | cut -d" " -f3)"
                    Group="Group: $(ls -ld $curDir | cut -d" " -f4)"
                    Size="Size: $(ls -ld $curDir | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld $curDir | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
fi


问:
Select MAX value inside a JOIN and JOIN inside another SELECT
I have two tables:

table a:

```<code>PersonID | name | age | gender
-------- | ---- | --- | ------
20       | John | 45  | Male
30       | Ann  | 50  | Female
</code>```

table b:

```<code>ValueID | PersonID | Column1
------- | -------- | -------
1       | 20       | 654321
2       | 20       | 345653
3       | 30       | 756756
4       | 30       | 142857
</code>```

I need to get all values from table 'a' and for each one a corresponding Column1 with a.PersonID = b.PersonID and with the MAX ValueID.

The expected result in this example would be the following:

```<code> PersonID | name | age | gender | Column1
 -------- | ---- | --- | ------   -------
 20       | John | 45  | Male   | 345653
 30       | Ann  | 50  | Female | 142857
</code>```

I tried this and doesn't work.

```<code>SELECT ps.*,
(SELECT Column1 FROM b ef
JOIN (SELECT MAX(ValueID) AS id FROM b
  WHERE PersonID = ps.PersonID) max ON ef.PersonID = max.id ) AS Column1
FROM a ps
</code>```

I guess ps.PersonID in WHERE clause ef.PersonID = ps.PersonID is not recognized.

I appreciate very much your help.

答:
Try This.. presumably the valueid is unique/ identity seeded</p>

```<code>SELECT ps.*,
(SELECT Column1 FROM b
where b.valueId =(SELECT MAX(ValueID) FROM b as x
  WHERE x.PersonID = ps.PersonID)
) AS Column1
FROM a ps
</code>```

Body:
I have two tables:

table a:

PersonID | name | age | gender
-------- | ---- | --- | ------
20       | John | 45  | Male
30       | Ann  | 50  | Female

table b:

ValueID | PersonID | Column1
------- | -------- | -------
1       | 20       | 654321
2       | 20       | 345653
3       | 30       | 756756
4       | 30       | 142857

I need to get all values from table 'a' and for each one a corresponding Column1 with a.PersonID = b.PersonID and with the MAX ValueID.

The expected result in this example would be the following:

 PersonID | name | age | gender | Column1
 -------- | ---- | --- | ------   -------
 20       | John | 45  | Male   | 345653
 30       | Ann  | 50  | Female | 142857

I tried this and doesn't work.

SELECT ps.*,
(SELECT Column1 FROM b ef
JOIN (SELECT MAX(ValueID) AS id FROM b
  WHERE PersonID = ps.PersonID) max ON ef.PersonID = max.id ) AS Column1
FROM a ps

I guess ps.PersonID in WHERE clause ef.PersonID = ps.PersonID is not recognized.

I appreciate very much your help.

Body:
Try This.. presumably the valueid is unique/ identity seeded

SELECT ps.*,
(SELECT Column1 FROM b
where b.valueId =(SELECT MAX(ValueID) FROM b as x
  WHERE x.PersonID = ps.PersonID)
) AS Column1
FROM a ps


问:
Custom memo or text selection in Delphi Firemonkey for mobile?
Is it possible to create a custom memo in firemonkey to implement things like syntax highlighting?

I wrote my own component on a Frame but it doesnt support mobile text selecting on android... Is there any way to create a custom memo or implement the native text selection into my own component on a TFrame?

What i mean is this:

Hold touch to select text, selected text gets hovered with blue background and on top the toolbar comes down.

答:
There is one full native android TMemo with the design you post available for Delphi. You can find the source code here: https://svn.code.sf.net/p/alcinoe/code/ (i gave the link because the code is too big to be post on SO)

You can also download the demo apk to see it in action:
https://svn.code.sf.net/p/alcinoe/code/demos/ALFmxControls/Android/Release/ALFmxControls/bin/ALFmxControls.apk

ContentLicense: CC BY-SA 4.0


问:
Reading and writing the same file simultaneosly with c++
I'm trying to read and write a file as I loop through its lines. At each line, I will do an evaluation to determine if I want to write it into the file or skip it and move onto the next line. This is a basically a skeleton of what I have so far.

```<code>void readFile(char* fileName)
{
    char line[1024];
    fstream file("test.file", ios::in | ios::out);

    if(file.is_open())
    {
        while(file.getline(line,MAX_BUFFER))
        {

            //evaluation

            file.seekg(file.tellp());
            file << line;
            file.seekp(file.tellg());
        }
    }
}
</code>```

As I'm reading in the lines, I seem to be having issues with the starting index of the string copied into the line variable. For example, I may be expecting the string in the line variable to be "000/123/FH/" but it actually goes in as "123/FH/". I suspect that I have an issue with file.seekg(file.tellp()) and file.seekp(file.tellg()) but I am not sure what it is.

答:
It is not clear from your code [1] and problem description what is in the file and why you expect "000/123/FH/", but I can state that the getline function is a buffered input, and you don't have code to access the buffer.  In general, it is not recommended to use buffered and unbuffered i/o together because it requires deep knowledge of the buffer mechanism and then relies on that mechanism not to change as libraries are upgraded.

You appear to want to do byte or character[2] level manipulation.  For small files, you should read the entire file into memory, manipulate it, and then overwrite the original, requiring an open, read, close, open, write, close sequence.  For large files you will need to use fread and/or some of the other lower level C library functions.

The best way to do this, since you are using C++, is to create your own class that handles reading up to and including a line separator [3] into one of the off-the-shelf circular buffers (that use malloc or a plug-in allocator as in the case of STL-like containers) or a circular buffer you develop as a template over a statically allocated array of bytes (if you want high speed an low resource utilization).  The size will need to be at least as large as the longest line in the later case. [4]

Either way, you would want to add to the class to open the file in binary mode and expose the desired methods to do the line level manipulations to an arbitrary line.  Some say (and I personally agree) that taking advantage of Bjarne Stroustrup's class encapsulation in C++ is that classes are easier to test carefully.  Such a line manipulation class would encapsulate the random access C functions and unbuffered i/o and leave open the opportunity to maximize speed, while allowing for plug-and-play usage in systems and applications.

Notes

[1] The seeking of the current position is just testing the functions and does not yet, in the current state of the code, re-position the current file pointer.

[2] Note that there is a difference between character and byte level manipulations in today's computing environment where utf-8 or some other unicode standard is now more common than ASCII in many domains, especially that of the web.

[3] Note that line separators are dependent on the operating system, its version, and sometimes settings.

[4] The advantage of circular buffers in terms of speed is that you can read more than one line using fread at a time and use fast iteration to find the next end of line.

Body:
I'm trying to read and write a file as I loop through its lines. At each line, I will do an evaluation to determine if I want to write it into the file or skip it and move onto the next line. This is a basically a skeleton of what I have so far.

void readFile(char* fileName)
{
    char line[1024];
    fstream file("test.file", ios::in | ios::out);

    if(file.is_open())
    {
        while(file.getline(line,MAX_BUFFER))
        {

            //evaluation

            file.seekg(file.tellp());
            file << line;
            file.seekp(file.tellg());
        }
    }
}

As I'm reading in the lines, I seem to be having issues with the starting index of the string copied into the line variable. For example, I may be expecting the string in the line variable to be "000/123/FH/" but it actually goes in as "123/FH/". I suspect that I have an issue with file.seekg(file.tellp()) and file.seekp(file.tellg()) but I am not sure what it is.


问:
Go back to the actual previous page regardless of a form post error
I have a page with a form. On this page there is also "go back to previous page" link, which uses the following JavaScript:

```<code>window.history.go(-1)
</code>```

When the form is posted and there is a validation error, the website returns the user to the same form page. However, clicking on this link in case of a form validation error gets the user to the form page before its submission, not the actual, different previous page.

How can I get the user back to the actual previous page by ONLY using JavaScript? Please note that there could be multiple times of form submission with errors.

答: You could store the "actual" previous page in a hidden form field on initial load and send this along with the form, then in your "go back to previous page" link js you could access that data.</p>

Body:
I have a page with a form. On this page there is also "go back to previous page" link, which uses the following JavaScript:

window.history.go(-1)

When the form is posted and there is a validation error, the website returns the user to the same form page. However, clicking on this link in case of a form validation error gets the user to the form page before its submission, not the actual, different previous page.

How can I get the user back to the actual previous page by ONLY using JavaScript? Please note that there could be multiple times of form submission with errors.


问:
Help with converting bool to integer
I keep getting an error saying "Cannot implicitly covert type bool to int" I cannot figure out what to do with this. I get the error on: DisplayIndex = columns[i].Visible,

Code:

```<code>    private void SaveColumnOrder()
    {
        if (dgPortStatus.CanUserReorderColumns == true)
        {
            List<ColumnOrderItem> columnOrder = new List<ColumnOrderItem>();
            DataGridViewColumnCollection columns = this.Columns;
            for (int i = 0; i < columns.Count; i++)
            {
                columnOrder.Add(new ColumnOrderItem
                {
                    ColumnIndex = i,
                    DisplayIndex = columns[i].Visible,
                    Width = columns[i].Width
                });

            }

            portalDataGridViewSetting.Default.ColumnOrder[this.Name] = columnOrder;
            portalDataGridViewSetting.Default.Save();
        }
    }
</code>```

Code:

```<code> public sealed class ColumnOrderItem
    {
        public int DisplayIndex { get; set; }
        public int Width { get; set; }
        public bool Visible  { get; set; }
        public int ColumnIndex { get; set; }
    }
</code>```

答:
Try

```<code>DisplayIndex = columns[i].Visible ? 1 : 0
</code>```

However, more likely, you mean

```<code>DisplayIndex = columns[i].DisplayIndex
</code>```

ContentLicense: CC BY-SA 2.5

Title: Help with converting bool to integer

Body:
I keep getting an error saying "Cannot implicitly covert type bool to int" I cannot figure out what to do with this. I get the error on: DisplayIndex = columns[i].Visible,

Code:

    private void SaveColumnOrder()
    {
        if (dgPortStatus.CanUserReorderColumns == true)
        {
            List<ColumnOrderItem> columnOrder = new List<ColumnOrderItem>();
            DataGridViewColumnCollection columns = this.Columns;
            for (int i = 0; i < columns.Count; i++)
            {
                columnOrder.Add(new ColumnOrderItem
                {
                    ColumnIndex = i,
                    DisplayIndex = columns[i].Visible,
                    Width = columns[i].Width
                });

            }

            portalDataGridViewSetting.Default.ColumnOrder[this.Name] = columnOrder;
            portalDataGridViewSetting.Default.Save();
        }
    }

Code:

 public sealed class ColumnOrderItem
    {
        public int DisplayIndex { get; set; }
        public int Width { get; set; }
        public bool Visible  { get; set; }
        public int ColumnIndex { get; set; }
    }

Body:
Try

DisplayIndex = columns[i].Visible ? 1 : 0

However, more likely, you mean

DisplayIndex = columns[i].DisplayIndex


问:
dots in lineChart dont hide DC.js d3-tip
I'm working with a DC.js lineChart, I added a tooltip with d3-tip, but when I activate it, the points in the lineChart do not disappear, as in the image.

What can I be doing wrong with the d3-tip?

答:
It's easier for folks to answer your question if you include a reproducible example and the relevant code in your question.

Did you namespace your events? You probably want mouseover and mouseout to be handled by both the line chart and d3.tip.

So using the quick usage d3.tip code,

```<code>  .on('mouseover', tip.show)
  .on('mouseout', tip.hide)
</code>```

should probably be

```<code>  .on('mouseover.tip', tip.show)
  .on('mouseout.tip', tip.hide)
</code>```

This way dc.lineChart will not lose its own mouseout events.

Example fiddle: http://jsfiddle.net/gordonwoodhull/8z15xboq/6/

Body:
It's easier for folks to answer your question if you include a reproducible example and the relevant code in your question.

Did you namespace your events? You probably want mouseover and mouseout to be handled by both the line chart and d3.tip.

So using the quick usage d3.tip code,

  .on('mouseover', tip.show)
  .on('mouseout', tip.hide)

should probably be

  .on('mouseover.tip', tip.show)
  .on('mouseout.tip', tip.hide)

This way dc.lineChart will not lose its own mouseout events.

Example fiddle: http://jsfiddle.net/gordonwoodhull/8z15xboq/6/


问:
Pandas Stack() Unanticipated Result
The pandas stack() operation is producing some unanticipated results in practice that I am unable to replicate with a small working example. I'm curious if others have run into this behavior and if there is a likely explanation for the root cause. First, a small reproducible example that demonstrates what I am trying to do:

```<code>data = {'kpiOne': [1,1,1,1,1,2,2,2,2,2],
'kpiTwo': [3,3,3,3,3,4,4,4,4,4],
'kpiThree': [5,5,5,5,5,6,6,6,6,6],
'PrePost': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', ]}
dfr = pd.DataFrame(data)
dfr = dfr.groupby('PrePost').describe()
dfr = dfr.stack(0) #this is where my problem is in practice, but works fine in this example
dfr
</code>```

Here is the code that I am using with the actual data in case there is anything relevant here:

```<code>kpiSum = dfr[(dfr.filter_any == False) & (dfr.version == 'After')].groupby('waveTwoExp')[kpi].describe()
kpiSum = kpiSum#.stack(0)
kpiSum
</code>```

The output looks like this before (comment symbol in place) I stack(0):
[Before stacking][1]
  [1]: https://i.stack.imgur.com/cMTAK.png

The output looks like this when I remove the comment symbol and stack(0):
[After stacking][2]
  [2]: https://i.stack.imgur.com/whXZ7.png

If you look closely you'll notice that the values have been incorrectly stacked. The mean for the KPI, 'uarl' before stacking is correct - 765. After stacking, the mean for the KPI 'uarl' is from the next level 0 column, 'alCost', or 797484. I cannot figure out why this shift is occuring.

What makes this very strange is that:

My reproducible example does not exhibit this behavior and more
importantly:

My code to stack(0) worked fine before I upgraded to Jupyter 5.0

Please let me know if my question is clear! Anyone else running into this behavior?

Thanks!

Kris

答:
Let's try upgrading or downgrading a version.

This appears to be a bug related to MultiIndex/Reshaping differences between Pandas versions.

Title: Pandas Stack() Unanticipated Result

Body:
The pandas stack() operation is producing some unanticipated results in practice that I am unable to replicate with a small working example. I'm curious if others have run into this behavior and if there is a likely explanation for the root cause. First, a small reproducible example that demonstrates what I am trying to do:

data = {'kpiOne': [1,1,1,1,1,2,2,2,2,2],
'kpiTwo': [3,3,3,3,3,4,4,4,4,4],
'kpiThree': [5,5,5,5,5,6,6,6,6,6],
'PrePost': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', ]}
dfr = pd.DataFrame(data)
dfr = dfr.groupby('PrePost').describe()
dfr = dfr.stack(0) #this is where my problem is in practice, but works fine in this example
dfr

Here is the code that I am using with the actual data in case there is anything relevant here:

kpiSum = dfr[(dfr.filter_any == False) & (dfr.version == 'After')].groupby('waveTwoExp')[kpi].describe()
kpiSum = kpiSum#.stack(0)
kpiSum

The output looks like this before (comment symbol in place) I stack(0):
[Before stacking][1]
  [1]: https://i.stack.imgur.com/cMTAK.png

The output looks like this when I remove the comment symbol and stack(0):
[After stacking][2]
  [2]: https://i.stack.imgur.com/whXZ7.png

If you look closely you'll notice that the values have been incorrectly stacked. The mean for the KPI, 'uarl' before stacking is correct - 765. After stacking, the mean for the KPI 'uarl' is from the next level 0 column, 'alCost', or 797484. I cannot figure out why this shift is occuring.

What makes this very strange is that:

My reproducible example does not exhibit this behavior and more
importantly:

My code to stack(0) worked fine before I upgraded to Jupyter 5.0

Please let me know if my question is clear! Anyone else running into this behavior?

Thanks!

Kris


问:
Powershell and Excel sheet automation
I am trying to make an automated process with powershell to import the csv that I have, and to automate the report that I generate on a monthly basis. I am just starting and here is what I have.

```<code>$excel = New-Object -ComObject excel.application
$wb = $excel.Workbooks.Open("U:\Local Group Members.csv")
$excel.visible=$true
$excel.DisplayAlerts = $false
$sheet =$book.worksheets.items(1)
$sheet.name = 'Local Group Memb'
$sheet.Activate() | Out-Null
$sheet.Rows.Item(1).Font.Bold = $true
$wb.Save()
$excel.Quit()
</code>```

I just tried this, and it gives me this error.Error I receive

How do I bold the first Row?

答:
I think you were on the right track, you just need to add:

```<code>$wb.Save()
$excel.Quit()
</code>```

I would also recommend just bolding the first Row, unless that is too much.

```<code>$sheet.Rows.Item(1).Font.Bold = $true
</code>```

Title: Powershell and Excel sheet automation

Body:
I am trying to make an automated process with powershell to import the csv that I have, and to automate the report that I generate on a monthly basis. I am just starting and here is what I have.

$excel = New-Object -ComObject excel.application
$wb = $excel.Workbooks.Open("U:\Local Group Members.csv")
$excel.visible=$true
$excel.DisplayAlerts = $false
$sheet =$book.worksheets.items(1)
$sheet.name = 'Local Group Memb'
$sheet.Activate() | Out-Null
$sheet.Rows.Item(1).Font.Bold = $true
$wb.Save()
$excel.Quit()

I just tried this, and it gives me this error.Error I receive

How do I bold the first Row?

Body:
I think you were on the right track, you just need to add:

$wb.Save()
$excel.Quit()

I would also recommend just bolding the first Row, unless that is too much.

$sheet.Rows.Item(1).Font.Bold = $true


问:
moving file from one location to another without knowing file name
One of my executable process produces two files. I want to move one file that is produced to shared drive. I am writing an automatic process to move the file from one location to shared drive. The only issue is file name changes every time the executable is run so I don't have the exact filename with me. I only have the extension, .xls. I have only one .xls file in my directory.

I tried doing this

```<code>File.Copy(@"*.xls", @"\\serv44\Application\testing\name\test2\*.xls", true);
</code>```

It threw an error saying Invalid name. After moving the file to shared drive. I want to delete the .xls file.

```<code>File.Delete("*.xls");
</code>```

any help will be appreciated

答:
This should give you that file name:</p>

```<code>var fileName = Directory.GetFiles(yourDirectory, "*.xls").ToList().FirstOrDefault();
</code>```

Body:
One of my executable process produces two files. I want to move one file that is produced to shared drive. I am writing an automatic process to move the file from one location to shared drive. The only issue is file name changes every time the executable is run so I don't have the exact filename with me. I only have the extension, .xls. I have only one .xls file in my directory.

I tried doing this

File.Copy(@"*.xls", @"\\serv44\Application\testing\name\test2\*.xls", true);

It threw an error saying Invalid name. After moving the file to shared drive. I want to delete the .xls file.

File.Delete("*.xls");

any help will be appreciated

Body:
This should give you that file name:

var fileName = Directory.GetFiles(yourDirectory, "*.xls").ToList().FirstOrDefault();


答:
Try this:</p>

```<code>SELECT ps.*,
  (SELECT Column1
   FROM b ef
   JOIN (SELECT MAX(ValueID) AS id FROM b
   WHERE PersonID = ps.PersonID) max ON ef.PersonID = max.id ) AS Column1
FROM a ps
</code>```

Title: Select MAX value inside a JOIN and JOIN inside another SELECT

Body:
Try this:

SELECT ps.*,
  (SELECT Column1
   FROM b ef
   JOIN (SELECT MAX(ValueID) AS id FROM b
   WHERE PersonID = ps.PersonID) max ON ef.PersonID = max.id ) AS Column1
FROM a ps


问:
Creating product label with Amazon MWS API
I can't seem to find the answer to this, I want to be able to add an item to a inbound shipment and then print the label, I have found the info below

http://docs.developer.amazonservices.com/en_UK/fba_guide/FBAGuide_LabelItems1x1.html

Point 2 says "Use the FulfillmentNetworkSKU returned in Step 1 to create a label for your item"

But I can't any call to use FulfillmentNetworkSKU to generate the label.

Anyone any idea's ?

Thanks

Darren

答:
It looks like they have left those specific instructions out.  Currently we use Seller Central to create our shipment plans, but eventually will use MWS.  Is it maybe GetUniquePackageLabels that you call?

In any event, I would contact MWS support and ask this question.  They will come back to you pretty quickly with an answer.


问:
Make links based on textboxes
How can I have something like a search bar, but instead of searching, it appends the text box contents to an address.

For example say I type in "hello", I'd like to have a button bellow which links to "https://example.com/hello".

答:
It can be something as simple as below, you get the value of the text on a button click, and then when you have clicked the button you append the value of the text box to the end of a domain which can be whatever you want it to be

To redirect on the button click you can add...

window.location.replace(url) where the p.innerText is.

var search = document.querySelector('#search');
var button = document.querySelector('#search-btn');
var p = document.querySelector('p');
var url;

button.addEventListener('click', function() {
  url = 'exampledomain.com/' + search.value;

  p.innerText = url;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="search" />
<button id="search-btn">Search</button>
<p></p></code>```

Title: Make links based on textboxes

Body:
It can be something as simple as below, you get the value of the text on a button click, and then when you have clicked the button you append the value of the text box to the end of a domain which can be whatever you want it to be

To redirect on the button click you can add...

window.location.replace(url) where the p.innerText is.

var search = document.querySelector('#search');
var button = document.querySelector('#search-btn');
var p = document.querySelector('p');
var url;

button.addEventListener('click', function() {
  url = 'exampledomain.com/' + search.value;

  p.innerText = url;
});

<input type="text" id="search" />
<button id="search-btn">Search</button>
<p></p>


问:
Reusing ViewModels for API in ASP.NET MVC?
I want to create an API for a large ASP.NET MVC application. This application uses strongly typed viewmodels for all its views. The most important job for the API will be to enable the website's functionality on other platforms such as iPhone's Objective C.

Now the idea has been from the start to reuse the ViewModels and existing controller actions for the API, in such a way that the viewmodels are returned as JSON or Ajax results by the controller instead of the view.

But there has been some discussion about this, because viewmodels have a lot of composite information that does not always seem useful for an API. For example, a typical API function could be GetRanking(). The viewmodel belonging to the Ranking() action actually has more data, such as the name of the current user and maybe some explanation about the ranking.

So the question is, what would be the best way to approach this: write separate actions for the api and return serialized domain objects, or reuse the current actions and viewmodels, and just ignore the unneeded data?

答:
Or third option: create a set of service models. Long-term, the big win in making separate ViewModels tends to be the view and the entities can change independently. Services also have a few unique dimensions -- such as versioning -- that you might not need to account for elsewhere. In any case, service almost always deserves a model in and of it's own.

Now, you can often argue that the ViewModels could descend from/make use of the service models for the data transfer side of their role. Especially for updates which tends to be a bit ui agnostic.


问:
Aggregate data in one column based on values in another column
I know there is an easy way to do this...but, I can't figure it out.

I have a dataframe in my R script that looks something like this:

```<code>A      B    C
1.2    4    8
2.3    4    9
2.3    6    0
1.2    3    3
3.4    2    1
1.2    5    1
</code>```

Note that A, B, and C are column names. And I'm trying to get variables like this:

```<code>sum1 <- [the sum of all B values such that A is 1.2]
num1 <- [the number of times A is 1.2]
</code>```

Any easy way to do this?
I basically want to end up with a data frame that looks like this:

```<code>    A     num     totalB
   1.2    3       12
   etc    etc     etc
</code>```

Where "num" is the number of times that particular A value appeared, and "totalB" is the sum of the B values given the A value.

Body:
I know there is an easy way to do this...but, I can't figure it out.

I have a dataframe in my R script that looks something like this:

A      B    C
1.2    4    8
2.3    4    9
2.3    6    0
1.2    3    3
3.4    2    1
1.2    5    1

Note that A, B, and C are column names. And I'm trying to get variables like this:

sum1 <- [the sum of all B values such that A is 1.2]
num1 <- [the number of times A is 1.2]

Any easy way to do this?
I basically want to end up with a data frame that looks like this:

    A     num     totalB
   1.2    3       12
   etc    etc     etc

Where "num" is the number of times that particular A value appeared, and "totalB" is the sum of the B values given the A value.

Body:
In dplyr:

library(tidyverse)
A <- c(1.2, 2.3, 2.3, 1.2, 3.4, 1.2)
B <- c(4, 4, 6, 3, 2, 5)
C <- c(8, 9, 0, 3, 1, 1)

df <- data_frame(A, B, C)

df %>%
    group_by(A) %>%
    summarise(num = n(),
              totalB = sum(B))


问:
I have made a mistake, but I can't seem to find what it is. I have tried researching on many platforms. What is wrong?
I am an 8th grader that likes coding. I wanted to try out this code, but it is not working. What is wrong with it?</p>

```<code><!DOCTYPE html>
<html>
<body>

<p>Click the button to find out the truth.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var t = document.createTextNode("Coding is fun! ");
    document.body.appendChild(t);
}
</script>

</body>
</html>
</code>```

答:
The code works as expected. It adds the text when clicking the button.

Have you blocked javascript? Maybe try an other browser.

Body:
I am an 8th grader that likes coding. I wanted to try out this code, but it is not working. What is wrong with it?

<!DOCTYPE html>

Click the button to find out the truth.

<button onclick="myFunction()">Try it</button>


问:
Align nav-items to right side in bootstrap-4
I just switched to bootstrap 4 and reworking all my html and scss to work with it and I cant seem to find how to put a group of nav-items on the right side of the navbar. This is my navbar code:

```<code><nav class="navbar navbar-full navbar-dark bg-primary">
        <button class="navbar-toggler hidden-md-up" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"></button>
        <%= link_to "Living Recipe", recipes_path(sort_attribut: "popularity", sort_order: :desc), class: "navbar-brand" %>
        <div class="collapse navbar-toggleable-sm" id="navbarResponsive">
            <ul class="nav navbar-nav float-md-left">
                <li class="nav-item">
                    <%= form_tag(recipes_path, :method => "get", id: "search-form", class: "form-inline") do %>
                            <%= text_field_tag :search, params[:search], placeholder: "Search Recipes", class: "form-control col-md-8" %>
                    <% end %>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="http://example.com" id="responsiveNavbarDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Browse</a>
                    <div class="dropdown-menu" aria-labelledby="responsiveNavbarDropdown">
                        <%= link_to "Popular", recipes_path(sort_attribute: "popularity", sort_order: :desc), class: "dropdown-item" %>
                        <%= link_to "Newest", recipes_path(sort_attribute: "created_at", sort_order: :desc), class: "dropdown-item" %>
                        <%= link_to "Most Updated", recipes_path(sort_attribute: "most_active", sort_order: :desc), class: "dropdown-item" %>
                        <%= link_to "Most Saved", recipes_path(sort_attribute: "save_count", sort_order: :desc), class: "dropdown-item" %>
                    </div>
                </li>
            </ul>
            <ul class="nav navbar-nav float-md-right">
                <% if user_signed_in? %>
                    <li class="dropdown">
                        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <%= current_user.displayname.present? ? "D-ring" : current_user.firstname %>
                        </a>
                        <div class="dropdown-menu" aria-labelledby="responsiveNavbarDropdown">
                            <%= link_to "Profile", user_path(current_user.id), class: "dropdown-item" %>
                            <%= link_to "Recipe Box", user_saved_recipes_path(current_user.id), class: "dropdown-item" %>
                            <%= link_to "Add Recipe", new_recipe_path, class: "dropdown-item" %>
                            <%= link_to "Submitted Recipes", user_path(current_user.id), class: "dropdown-item" %>
                            <%= link_to "Sign Out", destroy_user_session_path, :method => :delete, class: "dropdown-item" %>
                        </div>
                    </li>
                <% else %>
                    <li class="nav-item">
                        <%= link_to "Create Account", '', data: {:'toggle' => 'modal', :'target' => '#signupModal'}, class: "nav-link" %>
                    </li>
                    <li class="nav-item">
                        <%= link_to "Login", '', data: {:'toggle' => 'modal', :'target' => '#loginModal'}, class: "nav-link" %>
                    </li>
                <% end %>
            </ul>
        </div>
    </nav>
</code>```

And this is the screenshot of what it looks like

答:
In my case, I was looking for a solution that allows one of the navbar items to be right aligned. In order to do this, you must add style="width:100%;" to the
 and then add the ml-auto class to your navbar item.

Body:
I just switched to bootstrap 4 and reworking all my html and scss to work with it and I cant seem to find how to put a group of nav-items on the right side of the navbar. This is my navbar code:

        <button class="navbar-toggler hidden-md-up" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"></button>
        <%= link_to "Living Recipe", recipes_path(sort_attribut: "popularity", sort_order: :desc), class: "navbar-brand" %>

                    <%= form_tag(recipes_path, :method => "get", id: "search-form", class: "form-inline") do %>
                            <%= text_field_tag :search, params[:search], placeholder: "Search Recipes", class: "form-control col-md-8" %>
                    <% end %>

                    Browse

                        <%= link_to "Popular", recipes_path(sort_attribute: "popularity", sort_order: :desc), class: "dropdown-item" %>
                        <%= link_to "Newest", recipes_path(sort_attribute: "created_at", sort_order: :desc), class: "dropdown-item" %>
                        <%= link_to "Most Updated", recipes_path(sort_attribute: "most_active", sort_order: :desc), class: "dropdown-item" %>
                        <%= link_to "Most Saved", recipes_path(sort_attribute: "save_count", sort_order: :desc), class: "dropdown-item" %>

                <% if user_signed_in? %>

                            <%= current_user.displayname.present? ? "D-ring" : current_user.firstname %>

                            <%= link_to "Profile", user_path(current_user.id), class: "dropdown-item" %>
                            <%= link_to "Recipe Box", user_saved_recipes_path(current_user.id), class: "dropdown-item" %>
                            <%= link_to "Add Recipe", new_recipe_path, class: "dropdown-item" %>
                            <%= link_to "Submitted Recipes", user_path(current_user.id), class: "dropdown-item" %>
                            <%= link_to "Sign Out", destroy_user_session_path, :method => :delete, class: "dropdown-item" %>

                <% else %>

                        <%= link_to "Create Account", '', data: {:'toggle' => 'modal', :'target' => '#signupModal'}, class: "nav-link" %>

                        <%= link_to "Login", '', data: {:'toggle' => 'modal', :'target' => '#loginModal'}, class: "nav-link" %>

                <% end %>

And this is the screenshot of what it looks like

Body: In my case, I was looking for a solution that allows one of the navbar items to be right aligned. In order to do this, you must add style="width:100%;" to the <ul class="navbar-nav"> and then add the ml-auto class to your navbar item.


问:
virtualenv command is not found in Mac OS
I installed virtualenv using the command sudo pip install virtualenv and the installation is successful. Later, when I type virtualenv, I get the error message as following,  -bash: virtualenv: command not found

The virtualenv is installed in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages. I see the similar questions in the forum with no definitive answers.

Python is in the location /usr/local/bin/python and I have version 2.7.9. I get the following using ls -l command,

Why do I see the virtualenv is not found and how to solve the issue ?

UPDATE:

I use the command

ln -s /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/virtualenv.py /usr/local/bin/virtualenv.py to put the virtualenv.py

inside the /usr/local/bin folder. Previously, I only did the same for the virtualenv file. Now, when I put the command virtualenv in the terminal, I get

-bash: /usr/local/bin/virtualenv: Permission denied.

I later use

sudo ln -s /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/virtualenv.py /usr/local/bin/virtualenv.py

and the say message keep showing. which virtualenv still returns nothing.

答:
You are created the symbolic link to the wrong file. As far as I know virtualenv is installed to /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv, (you can change the numbers for your Python version) so the command for creating the symbolic link should be:

```<code>ln -s /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv /usr/local/bin/virtualenv
</code>```

Body:
You are created the symbolic link to the wrong file. As far as I know virtualenv is installed to /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv, (you can change the numbers for your Python version) so the command for creating the symbolic link should be:

ln -s /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv /usr/local/bin/virtualenv


问:
IdentityServer3 - redirect to ADFS if client is on intranet
We have a portal (mvc rdp) that is used by both internal users (employees) and external users (customers).  We would like IdentityServer3 to automatically detect if the authentication request is done from within the corporate network, and redirect to ADFS. The local login should be shown if the user-agent is calling from the internet.

In short, we don't want to have buttons for the external idp as we want the IdSrv to automatically redirect to ADFS if client is on the internal network to provide true single sign on for our domain bound users.

If the portal was only used by internal users, then we would just configure the client to only use a particular identity provider but this portal is also used by external customers and those users are not stored in our AD ;)

I've looked at overriding PreAuthenticateAsync and using Dns.Dns.GetHostName() but that is related to the machine that IdentityServer is running on and not the client machine.

In an mvc controller, we would just use Request.UserHostName but this is not available in IdentityServer3 UserService.

答:
I think you can get the client's IP address from the OwinContext; something like this:</p>

```<code>public class UserService : UserServiceBase
{
    OwinContext ctx;
    public UserService(OwinEnvironmentService owinEnv)
    {
        ctx = new OwinContext(owinEnv.Environment);
    }

    public override Task PreAuthenticateAsync(PreAuthenticationContext context)
    {
        // The IP Address of the remote client
        var ipAddress = ctx.Environment["server.RemoteIpAddress"].ToString();

        if (BelongsToOurNetwork(ipAddress))
            context.SignInMessage.IdP = "OurADFS";
        else
            context.SignInMessage.IdP = "idsrv"; // local login

        return Task.FromResult(0);
    }
}
</code>```

Body:
I think you can get the client's IP address from the OwinContext; something like this:

public class UserService : UserServiceBase
{
    OwinContext ctx;
    public UserService(OwinEnvironmentService owinEnv)
    {
        ctx = new OwinContext(owinEnv.Environment);
    }

    public override Task PreAuthenticateAsync(PreAuthenticationContext context)
    {
        // The IP Address of the remote client
        var ipAddress = ctx.Environment["server.RemoteIpAddress"].ToString();

        if (BelongsToOurNetwork(ipAddress))
            context.SignInMessage.IdP = "OurADFS";
        else
            context.SignInMessage.IdP = "idsrv"; // local login

        return Task.FromResult(0);
    }
}


问:
What is crtbegin.o and crtbegin_dynamic.o?
When debugging a link error (undefined reference to _dso_handle) using the Android x86 toolchain, I noticed it's statically linking crtbegin_dynamic.o. What is the purpose of this file? There is another similar crtbegin.o in the toolchain install directory that contains the missing symbol (_dso_handle). What is the difference between crtbegin.o and crtbegin_dynamic.o?

答: C++ has global constructors and destructors. crtbegin.o and crtend.o deal with calling those constructors and destructors. The variants of crtbegin.o such as crtbeginS.o do the same thing for other types of executables such as static executables and shared libraries.</p>


问:
Oracle Sql Developer I Can Not Edit
A record does not allow me to edit it. How can I edit the script by typing?

image

答:
You can't edit a record form select statement because this statement is read only.

If you want to update the record you have tow options:

Update statement.

UPDATE [TABLE_NAME]
SET [COLUMN_NAME] = [VALUE]
WHERE
CONDITION1 AND CONDETION2;

Select the table by click on it from table table at the left then click on data table from top of the table then filter to find the requested record then update the record and click on commit.

Title: Oracle Sql Developer I Can Not Edit


问:
Javascript - Convert object properties to variables inside function scope
This is what i want to achieve:

```<code>let scope = { property: "value" };
function fun()
{
  //That's how I can get my variables:
  console.log(this.property);

  //And that's how I want to get them
  console.log(property);
}
fun.call(scope);
</code>```

But of course the bind() function doesn't work like that. My idea was to do it this way:

```<code>let scope = { property: "value" }
function fun(scope)
{
  for (let p in scope)
  {
    if (scope.hasOwnProperty(p))
      window[p] = scope[p];
  }
  // Now it works
  console.log(property);
}
fun(scope);
</code>```

Unfortunately by doing this variables are declared in the global scope and the Garbage Collector won't free them up after function execution. So I would have to also add something like this at the end of my function:

```<code>for (let p in scope)
{
  if (scope.hasOwnProperty(p))
    delete window[p];
}
</code>```

But as we all know delete operator is pretty heavy, so I would like to omit using it.
That's why I'm looking for a way to convert object properties into variables in function scope.

PS: I can't use destructuring assignment because I don't know names of object properties.

答:
Other than using the window object you have the option of using eval:

```<code>let scope = { property: "value" }
function fun(scope)
{
  for (let p in scope)
  {
    if (scope.hasOwnProperty(p))
      eval("var " + p + " = scope[p];");
  }
  console.log(property);
}
fun(scope);
</code>```

See also: How do i declare and use dynamic variables in javascript?

Body:
This is what i want to achieve:

let scope = { property: "value" };
function fun()
{
  //That's how I can get my variables:
  console.log(this.property);

  //And that's how I want to get them
  console.log(property);
}
fun.call(scope);

But of course the bind() function doesn't work like that. My idea was to do it this way:

let scope = { property: "value" }
function fun(scope)
{
  for (let p in scope)
  {
    if (scope.hasOwnProperty(p))
      window[p] = scope[p];
  }
  // Now it works
  console.log(property);
}
fun(scope);

Unfortunately by doing this variables are declared in the global scope and the Garbage Collector won't free them up after function execution. So I would have to also add something like this at the end of my function:

for (let p in scope)
{
  if (scope.hasOwnProperty(p))
    delete window[p];
}

But as we all know delete operator is pretty heavy, so I would like to omit using it.
That's why I'm looking for a way to convert object properties into variables in function scope.

PS: I can't use destructuring assignment because I don't know names of object properties.

Body:
Other than using the window object you have the option of using eval:

let scope = { property: "value" }
function fun(scope)
{
  for (let p in scope)
  {
    if (scope.hasOwnProperty(p))
      eval("var " + p + " = scope[p];");
  }
  console.log(property);
}
fun(scope);

See also: How do i declare and use dynamic variables in javascript?


问:
Use jasmine to test Express.js
I am learning Node.js and Express framework. I am a big fan of jasmine. So I want to use jasmine whenever I can, however, I can't find a good way testing Express with jasmine. For example, how should I test a route in app.js?

If I have this route in app.js:

```<code>app.get('/', function(req, res) {
  ...
});
</code>```

How can I use jasmine to test it?

答:
Since Jasmine 2 it is very simple to use Jasmine in a Node.js environment. To test express apps with it, I recommend to use Jasmine in combination with supertest.

Here is how such a test looks like:

project/spec/ServerSpec.json

```<code>const request = require('supertest');
const app = require('../app');

describe('Server', () => {
  describe('REST API v1', () => {
    it('returns a JSON payload', (done) => {
      request(app)
        .get('/rest/service/v1/categories')
        .expect(200)
        .expect('Content-Type', 'application/json; charset=utf-8')
        .end((error) => (error) ? done.fail(error) : done());
    });
  });
});
</code>```

Some prerequisites:

Install Jasmine v2 as dev dependency in your project: npm i -D jasmine@2

Install supertest v3 as dev dependency in your project: npm i -D supertest@3

Create an initial Jasmine configuration using jasmine init (Note: You need to install Jasmine globally first if you haven't done already to run this command)

Create a specification ending on "Spec.js" (like ServerSpec.js)

Here is how a Jasmine configuration looks like:

project/spec/support/jasmine.json

```<code>{
  "helpers": [
    "helpers/**/*.js"
  ],
  "random": false,
  "spec_dir": "spec",
  "spec_files": [
    "**/*[sS]pec.js"
  ],
  "stopSpecOnExpectationFailure": false
}
</code>```

To run your specifications (test suites) simply add this to your npm scripts and execute npm test (or just npm t):

```<code>  "scripts": {
    "test": "jasmine"
  },
</code>```

Title: Use jasmine to test Express.js

Body:
I am learning Node.js and Express framework. I am a big fan of jasmine. So I want to use jasmine whenever I can, however, I can't find a good way testing Express with jasmine. For example, how should I test a route in app.js?

If I have this route in app.js:

app.get('/', function(req, res) {
  ...
});

How can I use jasmine to test it?

Body:
Since Jasmine 2 it is very simple to use Jasmine in a Node.js environment. To test express apps with it, I recommend to use Jasmine in combination with supertest.

Here is how such a test looks like:

project/spec/ServerSpec.json

const request = require('supertest');
const app = require('../app');

describe('Server', () => {
  describe('REST API v1', () => {
    it('returns a JSON payload', (done) => {
      request(app)
        .get('/rest/service/v1/categories')
        .expect(200)
        .expect('Content-Type', 'application/json; charset=utf-8')
        .end((error) => (error) ? done.fail(error) : done());
    });
  });
});

Some prerequisites:

Install Jasmine v2 as dev dependency in your project: npm i -D jasmine@2

Install supertest v3 as dev dependency in your project: npm i -D supertest@3

Create an initial Jasmine configuration using jasmine init (Note: You need to install Jasmine globally first if you haven't done already to run this command)

Create a specification ending on "Spec.js" (like ServerSpec.js)

Here is how a Jasmine configuration looks like:

project/spec/support/jasmine.json

{
  "helpers": [
    "helpers/**/*.js"
  ],
  "random": false,
  "spec_dir": "spec",
  "spec_files": [
    "**/*[sS]pec.js"
  ],
  "stopSpecOnExpectationFailure": false
}

To run your specifications (test suites) simply add this to your npm scripts and execute npm test (or just npm t):

  "scripts": {
    "test": "jasmine"
  },


问:
Extract substrings from a list into a list in Python
I have a Python list like:

```<code>['user@gmail.com', 'someone@hotmail.com'...]
</code>```

And I want to extract only the strings after @ into another list directly, such as:

```<code>mylist = ['gmail.com', 'hotmail.com'...]
</code>```

Is it possible? split() doesn't seem to be working with lists.

This is my try:

```<code>for x in range(len(mylist)):
  mylist[x].split("@",1)[1]
</code>```

But it didn't give me a list of the output.

答:
That's my solution with nested for loops:</p>

```<code>myl = ['user@gmail.com', 'someone@hotmail.com'...]
results = []
for element in myl:
    for x in element:
        if x == '@':
            x =  element.index('@')
            results.append(element[x+1:])
</code>```

Body:
I have a Python list like:

['user@gmail.com', 'someone@hotmail.com'...]

And I want to extract only the strings after @ into another list directly, such as:

mylist = ['gmail.com', 'hotmail.com'...]

Is it possible? split() doesn't seem to be working with lists.

This is my try:

for x in range(len(mylist)):
  mylist[x].split("@",1)[1]

But it didn't give me a list of the output.

Body:
That's my solution with nested for loops:

myl = ['user@gmail.com', 'someone@hotmail.com'...]
results = []
for element in myl:
    for x in element:
        if x == '@':
            x =  element.index('@')
            results.append(element[x+1:])


问:
Snakebite HDFS touchz not working
I want to use snakebite to check if a file exist in hdfs directory, and create if it doesnt exist. I'm following the documentation on touchz here and using it like this:

```<code>def createFile(client):
    if client.test("/user/test/sample.txt", exists=True):
        print "file exists"
    else:
        print "file not exist, create file"
        print client.touchz(["/user/test/sample.txt"])

client = Client(remote_host, 8020, use_trash=False)
createFile(client)
</code>```

But when I go to check, I dont see sample.txt in remote_host:/user/test/
But I see the file when I used hadoop fs -touchz remote_host:/user/test/sample.txt

How to use snakebite's touchz ?

答:
snakebite's touchz yields a generator that doesn't do anything until you iterate over the values.

So you either have to iterate over the return value of touchz or call list() on it.

Title: Snakebite HDFS touchz not working

Body:
I want to use snakebite to check if a file exist in hdfs directory, and create if it doesnt exist. I'm following the documentation on touchz here and using it like this:

def createFile(client):
    if client.test("/user/test/sample.txt", exists=True):
        print "file exists"
    else:
        print "file not exist, create file"
        print client.touchz(["/user/test/sample.txt"])

client = Client(remote_host, 8020, use_trash=False)
createFile(client)

But when I go to check, I dont see sample.txt in remote_host:/user/test/
But I see the file when I used hadoop fs -touchz remote_host:/user/test/sample.txt

How to use snakebite's touchz ?


问:
facebook open graph count shares using PHP SDK
As from Facebook documentation I can get the count of shares for a web page calling the following url https://graph.facebook.com/?id=http://www.google.it, the returned data are the following:

```<code>{
   "share": {
      "comment_count": 0,
      "share_count": 636734
   },
   "og_object": {
      "id": "389545309239",
      "title": "Google",
      "type": "website",
      "updated_time": "2017-06-08T10:05:50+0000"
   },
   "id": "http://www.google.it"
}
</code>```

I want to get the same data using the PHP SDK using the following code:

```<code>//require the Facebook PHP SDK

$client_id="my app id";
$client_secret="my secret key";
$default_access_token = file_get_contents( "https://graph.facebook.com/oauth/access_token?client_id=$client_id&client_secret=$client_secret&grant_type=client_credentials");

$OGResponse = new Facebook\Authentication\AccessToken($default_access_token);

$access_token = json_decode($OGResponse)->access_token;

$fb = new Facebook\Facebook([
    'app_id' => $client_id, // Replace {app-id} with your app id
    'app_secret' => $client_secret,
    'default_access_token' => $access_token,
]);

$helper = $fb->getRedirectLoginHelper();

$request = new \Facebook\FacebookRequest(
    $fb->getApp(),
    $access_token,
    'GET',
    '/',
    array(
        'id' => 'http://www.google.it',
    )
);

$response = $fb->getClient()->sendRequest($request);

//$response = $request->execute();
$graphObject = $response->getGraphObject();
</code>```

Accessing the $graphObject I can retrieve the same data except the ones in "share" key, that are what I'm interested.

If I use the GRAPH API Explorer, I get the same info using the PHP SDK:

```<code>{
  "og_object": {
  "id": "389545309239",
  "title": "Google",
  "type": "website",
  "updated_time": "2017-06-08T10:05:50+0000"
},
"id": "http://www.google.it"
}
</code>```

Is there any way to get the "shares" using the PHP SDK?

答:
try this
graph api explorer v2.8

but you cannot get share field with graph api v2.9 because share field is deprecated for versions v2.9 and higher,or you can use engagement field like this graph api explorer v2.9

for PHP SDK:

```<code>$request = new \Facebook\FacebookRequest(
    $fb->getApp(),
    $access_token,
    'GET',
    '/',
    array(
        'id'     => 'http://www.google.it',
        'fields' => 'engagement,og_object',
    )
);
</code>```

then you will get something like this

```<code>{
  "engagement": {
    "reaction_count": 207037,
    "comment_count": 125335,
    "share_count": 304362,
    "comment_plugin_count": 0
  },
  "og_object": {
    "id": "389545309239",
    "title": "Google",
    "type": "website",
    "updated_time": "2017-06-08T15:58:56+0000"
  },
  "id": "http://www.google.it"
}
</code>```

Body:
As from Facebook documentation I can get the count of shares for a web page calling the following url https://graph.facebook.com/?id=http://www.google.it, the returned data are the following:

{
   "share": {
      "comment_count": 0,
      "share_count": 636734
   },
   "og_object": {
      "id": "389545309239",
      "title": "Google",
      "type": "website",
      "updated_time": "2017-06-08T10:05:50+0000"
   },
   "id": "http://www.google.it"
}

I want to get the same data using the PHP SDK using the following code:

//require the Facebook PHP SDK

$client_id="my app id";
$client_secret="my secret key";
$default_access_token = file_get_contents( "https://graph.facebook.com/oauth/access_token?client_id=$client_id&client_secret=$client_secret&grant_type=client_credentials");

$OGResponse = new Facebook\Authentication\AccessToken($default_access_token);

$access_token = json_decode($OGResponse)->access_token;

$fb = new Facebook\Facebook([
    'app_id' => $client_id, // Replace {app-id} with your app id
    'app_secret' => $client_secret,
    'default_access_token' => $access_token,
]);

$helper = $fb->getRedirectLoginHelper();

$request = new \Facebook\FacebookRequest(
    $fb->getApp(),
    $access_token,
    'GET',
    '/',
    array(
        'id' => 'http://www.google.it',
    )
);

$response = $fb->getClient()->sendRequest($request);

//$response = $request->execute();
$graphObject = $response->getGraphObject();

Accessing the $graphObject I can retrieve the same data except the ones in "share" key, that are what I'm interested.

If I use the GRAPH API Explorer, I get the same info using the PHP SDK:

{
  "og_object": {
  "id": "389545309239",
  "title": "Google",
  "type": "website",
  "updated_time": "2017-06-08T10:05:50+0000"
},
"id": "http://www.google.it"
}

Is there any way to get the "shares" using the PHP SDK?

Body:
try this
graph api explorer v2.8

but you cannot get share field with graph api v2.9 because share field is deprecated for versions v2.9 and higher,or you can use engagement field like this graph api explorer v2.9

for PHP SDK:

$request = new \Facebook\FacebookRequest(
    $fb->getApp(),
    $access_token,
    'GET',
    '/',
    array(
        'id'     => 'http://www.google.it',
        'fields' => 'engagement,og_object',
    )
);

then you will get something like this

{
  "engagement": {
    "reaction_count": 207037,
    "comment_count": 125335,
    "share_count": 304362,
    "comment_plugin_count": 0
  },
  "og_object": {
    "id": "389545309239",
    "title": "Google",
    "type": "website",
    "updated_time": "2017-06-08T15:58:56+0000"
  },
  "id": "http://www.google.it"
}


问:
Detect ongoing write operation on a networkstream
Imagine a server application is connected via TCP to some client device. The user of the server decides to send some message to the client device with NetworkStream.BeginWrite, but due to a slow connection or some other unknown factor, the server calls BeginWrite, but BeginWrite has not yet finished its write and performed its callback. In the meantime, the user decides to disconnect the client device in the main thread, causing an ObjectDisposedException to be immediately thrown in the callback due to the underlying connection no longer being available.

Here's a pseudo example of what I mean:

```<code>/// bad pseudo of possible code happening in main server thread
while(!quit){
    if( command has been inputted) {
          switch (command) {
               case send:
                    string m = getAStringFromGUI();
                    Send(m);
               break;
               case disconnect:
                    ClientDevice.Close();
               break;
          }
    }
}

private void Send(string msg){
    NetworkStream stream;

    byte[ ] packetBuffer = Encoding.ASCII.GetBytes(msg);
    stream = clientDevice.GetStream();
    stream.BeginWrite(packetBuffer, 0, packetBuffer.Length, new AsyncCallback(StreamWriteCompleteCallback), stream);
}
private void StreamWriteCompleteCallback(IAsyncResult ar) {
    try {
        NetworkStream stream = (NetworkStream)ar.AsyncState;
        stream.EndWrite(ar);
    }
    catch (ObjectDisposedException) {
        // client device was disconnected by the server before write completed
    }
}
</code>```

If a disconnect command is entered fast enough after the send command, the exception will be thrown. Obviously in this simple example, you could block until the write is complete, but what if you wanted to have the writes to occur asynchronously but still prevent disconnect commands from executing until any write commands have completed (or timed out)? I believe you could keep track of all the BeginWrite calls with waithandles, and utilize those to ensure writes complete before disconnecting, but that seems like a lot of work. Is there any way to know whether any thread is attempting to write to a given network stream?

答:
You need to track manually the request, but it's more easy than you think, a simple concurrent dictionary would be enough for this:

```<code>//This class will store ongoing requests and also will be used as the async parameter
public class ExecutingRequest
{
    public Guid Id { get; set; }
    public NetworkStream Stream { get; set; }
}

//Somewhere in your server class
ConcurrentDictionary<Guid, ExecutingRequest> pendingRequests = new ConcurrentDictionary<Guid, ExecutingRequest>();

private void Send(string msg)
{
    NetworkStream stream;

    byte[ ] packetBuffer = Encoding.ASCII.GetBytes(msg);
    stream = clientDevice.GetStream();
    var request = new ExecutingRequest{ Stream = stream, Id = Guid.NewGuid() };
    pendingRequests.AddOrUpdate(request.Id, request, (a,b) => request);
    stream.BeginWrite(packetBuffer, 0, packetBuffer.Length, new AsyncCallback(StreamWriteCompleteCallback), request);
}

private void StreamWriteCompleteCallback(IAsyncResult ar)
{
    try {
        ExecutingRequest req = (ExecutingRequest)ar.AsyncState;
        pendingRequests.TryRemove(req.Id, out ExecutingRequest dummy);
        req.stream.EndWrite(ar);
    }
    catch (ObjectDisposedException)
    {
        // client device was disconnected by the server before write completed
    }
}
</code>```

Then, you can check if there is any request running by checking the length of the dictionary.

Body:
Imagine a server application is connected via TCP to some client device. The user of the server decides to send some message to the client device with NetworkStream.BeginWrite, but due to a slow connection or some other unknown factor, the server calls BeginWrite, but BeginWrite has not yet finished its write and performed its callback. In the meantime, the user decides to disconnect the client device in the main thread, causing an ObjectDisposedException to be immediately thrown in the callback due to the underlying connection no longer being available.

Here's a pseudo example of what I mean:

/// bad pseudo of possible code happening in main server thread
while(!quit){
    if( command has been inputted) {
          switch (command) {
               case send:
                    string m = getAStringFromGUI();
                    Send(m);
               break;
               case disconnect:
                    ClientDevice.Close();
               break;
          }
    }
}

private void Send(string msg){
    NetworkStream stream;

    byte[ ] packetBuffer = Encoding.ASCII.GetBytes(msg);
    stream = clientDevice.GetStream();
    stream.BeginWrite(packetBuffer, 0, packetBuffer.Length, new AsyncCallback(StreamWriteCompleteCallback), stream);
}
private void StreamWriteCompleteCallback(IAsyncResult ar) {
    try {
        NetworkStream stream = (NetworkStream)ar.AsyncState;
        stream.EndWrite(ar);
    }
    catch (ObjectDisposedException) {
        // client device was disconnected by the server before write completed
    }
}

If a disconnect command is entered fast enough after the send command, the exception will be thrown. Obviously in this simple example, you could block until the write is complete, but what if you wanted to have the writes to occur asynchronously but still prevent disconnect commands from executing until any write commands have completed (or timed out)? I believe you could keep track of all the BeginWrite calls with waithandles, and utilize those to ensure writes complete before disconnecting, but that seems like a lot of work. Is there any way to know whether any thread is attempting to write to a given network stream?

Body:
You need to track manually the request, but it's more easy than you think, a simple concurrent dictionary would be enough for this:

//This class will store ongoing requests and also will be used as the async parameter
public class ExecutingRequest
{
    public Guid Id { get; set; }
    public NetworkStream Stream { get; set; }
}

//Somewhere in your server class
ConcurrentDictionary<Guid, ExecutingRequest> pendingRequests = new ConcurrentDictionary<Guid, ExecutingRequest>();

private void Send(string msg)
{
    NetworkStream stream;

    byte[ ] packetBuffer = Encoding.ASCII.GetBytes(msg);
    stream = clientDevice.GetStream();
    var request = new ExecutingRequest{ Stream = stream, Id = Guid.NewGuid() };
    pendingRequests.AddOrUpdate(request.Id, request, (a,b) => request);
    stream.BeginWrite(packetBuffer, 0, packetBuffer.Length, new AsyncCallback(StreamWriteCompleteCallback), request);
}

private void StreamWriteCompleteCallback(IAsyncResult ar)
{
    try {
        ExecutingRequest req = (ExecutingRequest)ar.AsyncState;
        pendingRequests.TryRemove(req.Id, out ExecutingRequest dummy);
        req.stream.EndWrite(ar);
    }
    catch (ObjectDisposedException)
    {
        // client device was disconnected by the server before write completed
    }
}

Then, you can check if there is any request running by checking the length of the dictionary.


问:
how to replace locked dll (was inuse)
I have a dll loaded into LSASS. I need to replace it on reboot.

There is an old utility called inuse from win2k reskit. It does not seem to work anymore (I am on windows 7)

Anybody know the right way to do it now?

答:
Movefile from Sysinternals should do the trick :)

http://technet.microsoft.com/en-us/sysinternals/bb897556

Title: how to replace locked dll (was inuse)


问:
How can i get all my user files using Forge Data Management API?
We need to get all the root hubs, projects and folders for a user with Forge Data Management API, just like we do with Dropbox API:

Dropbox API Reference

Does anybody from Autodesk know how to get all items from the users, without having to enter all folders, projects and hubs?

Best,

答:
You'll need to recursively list files on all subfolders, this is not natively implemented. This .NET sample implements it on the UI tree, see the tree controller class.

That's an interesting feature from the Dropbox SDK, but more like a SDK feature, not the API.