问:
Divide two lists of matrices where the ith matrix element in one list is divided by the ith matrix element in the second list
I have two lists of matrices. Here is an example of their structure:

```<code>list1<- list(structure(c(1, 2, 7, 1, 3, 0, 0, 0, 1, 4, 1, 3, 2, 3, 4,
6, 0, 0, 0, 3, 3), .Dim = c(7L, 3L), .Dimnames = list(c("lepA",
"lepB", "lepC", "lepD", "lepE", "lepF", "lepG"), NULL)), structure(c(1,
3, 7, 1, 3, 2, 3, 4, 6, 4, 1, 3, 3, 3), .Dim = c(7L, 2L), .Dimnames = list(
c("lepA", "lepB", "lepC", "lepD", "lepE", "lepF", "lepG"),
NULL)), structure(c(5, 8, 7, 1, 3, 3, 3), .Dim = c(7L, 1L
), .Dimnames = list(c("lepA", "lepB", "lepC", "lepD", "lepE",
"lepF", "lepG"), NULL)))

list2<-list(structure(c(6, 1, 51, 13, 15, 0, 0, 0, 6, 50, 13, 15, 6,
5, 5, 9, 0, 0, 0, 7, 5), .Dim = c(7L, 3L), .Dimnames = list(c("lepA",
"lepB", "lepC", "lepD", "lepE", "lepF", "lepG"), NULL)), structure(c(6,
7, 51, 13, 15, 6, 5, 5, 9, 50, 13, 15, 7, 5), .Dim = c(7L, 2L
), .Dimnames = list(c("lepA", "lepB", "lepC", "lepD", "lepE",
"lepF", "lepG"), NULL)), structure(c(11, 10, 51, 13, 15, 7, 5
), .Dim = c(7L, 1L), .Dimnames = list(c("lepA", "lepB", "lepC",
"lepD", "lepE", "lepF", "lepG"), NULL)))
</code>```

I need to divide each element of each matrix in a list with the corresponding element in the matching matrix in the second list. It's as though the two lists of matrices should be one list of arrays and the dividend is calculated for each array element. The result would be:

```<code>list<- list(list1[[1]]/list2[[1]], list1[[2]]/list2[[2]], list1[[3]]/list2[[3]])
</code>```

I tried:

```<code>list1/list2
</code>```

Body:
I have two lists of matrices. Here is an example of their structure:

list1<- list(structure(c(1, 2, 7, 1, 3, 0, 0, 0, 1, 4, 1, 3, 2, 3, 4,
6, 0, 0, 0, 3, 3), .Dim = c(7L, 3L), .Dimnames = list(c("lepA",
"lepB", "lepC", "lepD", "lepE", "lepF", "lepG"), NULL)), structure(c(1,
3, 7, 1, 3, 2, 3, 4, 6, 4, 1, 3, 3, 3), .Dim = c(7L, 2L), .Dimnames = list(
c("lepA", "lepB", "lepC", "lepD", "lepE", "lepF", "lepG"),
NULL)), structure(c(5, 8, 7, 1, 3, 3, 3), .Dim = c(7L, 1L
), .Dimnames = list(c("lepA", "lepB", "lepC", "lepD", "lepE",
"lepF", "lepG"), NULL)))

list2<-list(structure(c(6, 1, 51, 13, 15, 0, 0, 0, 6, 50, 13, 15, 6,
5, 5, 9, 0, 0, 0, 7, 5), .Dim = c(7L, 3L), .Dimnames = list(c("lepA",
"lepB", "lepC", "lepD", "lepE", "lepF", "lepG"), NULL)), structure(c(6,
7, 51, 13, 15, 6, 5, 5, 9, 50, 13, 15, 7, 5), .Dim = c(7L, 2L
), .Dimnames = list(c("lepA", "lepB", "lepC", "lepD", "lepE",
"lepF", "lepG"), NULL)), structure(c(11, 10, 51, 13, 15, 7, 5
), .Dim = c(7L, 1L), .Dimnames = list(c("lepA", "lepB", "lepC",
"lepD", "lepE", "lepF", "lepG"), NULL)))

I need to divide each element of each matrix in a list with the corresponding element in the matching matrix in the second list. It's as though the two lists of matrices should be one list of arrays and the dividend is calculated for each array element. The result would be:

list<- list(list1[[1]]/list2[[1]], list1[[2]]/list2[[2]], list1[[3]]/list2[[3]])

I tried:

list1/list2

Body:
Use Map :

Map(`/`, list1, list2)

#[[1]]
#           [,1]       [,2]      [,3]
#lepA 0.16666667        NaN 0.8000000
#lepB 2.00000000 0.16666667 0.6666667
#lepC 0.13725490 0.08000000       NaN
#lepD 0.07692308 0.07692308       NaN
#lepE 0.20000000 0.20000000       NaN
#lepF        NaN 0.33333333 0.4285714
#lepG        NaN 0.60000000 0.6000000

#[[2]]
#           [,1]       [,2]
#lepA 0.16666667 0.80000000
#lepB 0.42857143 0.66666667
#lepC 0.13725490 0.08000000
#lepD 0.07692308 0.07692308
#lepE 0.20000000 0.20000000
#lepF 0.33333333 0.42857143
#lepG 0.60000000 0.60000000

#[[3]]
#           [,1]
#lepA 0.45454545
#lepB 0.80000000
#lepC 0.13725490
#lepD 0.07692308
#lepE 0.20000000
#lepF 0.42857143
#lepG 0.60000000

Or map2 in purrr

purrr::map2(list1, list2, `/`)


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: How to do agg function on map column type in dataframe scala

Body:
col1    |     col2      |       col3    |          col4         |        col5    | col6|     col7          |
+-------+---------------+---------------+-----------------------+----------------+-----+-------------------+
|   1247|            PRM|        2010101|                   1254|         GUARNTR|    1|   [PRM -> 2010101]|
|   1246|            PRM|           null|                   1234|         GUARNTR|    3|           [PRM ->]|
|   1235|            PRM|               |                   1239|         CO_BORR|    1|          [PRM -> ]|
|   1249|            SEC|       20101010|                   1234|         GUARNTR|    1|  [SEC -> 20101010]|
|   1234|            PRM|           null|                   1234|            BORR|    1|      [PRM -> null]|
|   1248|            SEC|       20101010|                   1234|             chk|    1|  [SEC -> 20101010]|

I have a dataframe and col7 is of map datatype column. I want to do sum of this column based on a key values. for eg. I want sum of col7("PRM") with key PRM .

Body:
I hope this helps:

df.withColumn("prmSum",sum("col7.PRM").over(Window.partitionBy("col2"))).show

+----+----+-------+----+-------+----+----------------+-------+
|col1|col2|   col3|col4|   col5|col6|            col7| prmSum|
+----+----+-------+----+-------+----+----------------+-------+
|1249| SEC|2010101|1234|GUARNTR|   1|[SEC -> 2010101]|   null|
|1248| SEC|2010101|1234|    chk|   1|[SEC -> 2010101]|   null|
|1247| PRM|2010101|1254|GUARNTR|   1|[PRM -> 2010101]|2010101|
|1246| PRM|      0|1234|GUARNTR|   3|      [PRM -> 0]|2010101|
|1235| PRM|      0|1239|CO_BORR|   1|      [PRM -> 0]|2010101|
|1234| PRM|      0|1234|   BORR|   1|      [PRM -> 0]|2010101|
+----+----+-------+----+-------+----+----------------+-------+


问:
X is only available in IOS 9.0 o newer
During the development of the app with the plotter, it suddenly becomes impossible to build ios at all of a sudden. I will upload the related image below.

Other team members who do the same work have no problems.
Reinstallation of project ,xcode has already been attempted, and flutter clear , pod install has been attempted countless times. What can I do to fix this error?

Android builds normally.

I'm Korean and I'm not good at English, so I sent a question through a translator.

答:
self answer...
firebase Cache error...

```<code>cd ios
pod deintegrate
pod install
</code>```

firebase Cache all delete ->

Title: X is only available in IOS 9.0 o newer

Body:
self answer...
firebase Cache error...

cd ios
pod deintegrate
pod install

firebase Cache all delete ->


问:
Pandas drop_duplicates() not working after add a row to DataFrame when read from a csv file
My code like below:

```<code>indexing_file_path = 'indexing.csv'
if not os.path.exists(indexing_file_path):
    df = pd.DataFrame([['1111', '20200101', '20200101'],
                       ['1112', '20200101', '20200101'],
                       ['1113', '20200101', '20200101']],
                       columns = ['nname', 'nstart', 'nend'])
else:
    df = pd.read_csv(indexing_file_path, header = 0)

print(df)
df.loc[len(df)] = ['1113', '20200202', '20200303']
# append() method not working either
print(df)
df.drop_duplicates('nname', keep = 'last', inplace = True)
print(df)
df.to_csv(indexing_file_path, index = False)
</code>```

I want to keep the nname column unique in this file.

When the code run first time, it will save the records to csv file correctly, although the 1113 is not unique.

When the code run second time, it will save two 1113 rows to the csv file, because the DataFrame is created from a csv file.

After the third time run, it will always keep two 1113 rows.

Now I have a solution:

1, save to csv file with two 1113 row.

2, read the csv file again.

3, use drop_duplicates again.

4, save to csv file again.

Why the DataFrame created from a csv file is so different?

How can I save the unique row to csv file one time?

答:
I can answer my question now.

The reason is:

When DataFrame is created from a csv file, pandas recognize the nname column as integer

But, when I add 1113 row again, pandas recognize the new row nname as a string, so the integer 1113 is not equals the string 1113, pandas will keep two row.

The solution is:

Read csv file as string.

```<code>df = pd.read_csv(indexing_file_path, header=0, dtype=str)
</code>```

Body:
My code like below:

indexing_file_path = 'indexing.csv'
if not os.path.exists(indexing_file_path):
    df = pd.DataFrame([['1111', '20200101', '20200101'],
                       ['1112', '20200101', '20200101'],
                       ['1113', '20200101', '20200101']],
                       columns = ['nname', 'nstart', 'nend'])
else:
    df = pd.read_csv(indexing_file_path, header = 0)

print(df)
df.loc[len(df)] = ['1113', '20200202', '20200303']
# append() method not working either
print(df)
df.drop_duplicates('nname', keep = 'last', inplace = True)
print(df)
df.to_csv(indexing_file_path, index = False)

I want to keep the nname column unique in this file.

When the code run first time, it will save the records to csv file correctly, although the 1113 is not unique.

When the code run second time, it will save two 1113 rows to the csv file, because the DataFrame is created from a csv file.

After the third time run, it will always keep two 1113 rows.

Now I have a solution:

1, save to csv file with two 1113 row.

2, read the csv file again.

3, use drop_duplicates again.

4, save to csv file again.

Why the DataFrame created from a csv file is so different?

How can I save the unique row to csv file one time?

Body:
I can answer my question now.

The reason is:

When DataFrame is created from a csv file, pandas recognize the nname column as integer

But, when I add 1113 row again, pandas recognize the new row nname as a string, so the integer 1113 is not equals the string 1113, pandas will keep two row.

The solution is:

Read csv file as string.

df = pd.read_csv(indexing_file_path, header=0, dtype=str)


问:
How to find two points that form closest distance between two rectangles?
I'm trying to find algorithm that will find two points that represent closest distance between two rectangles. Like points C and J that form smallest distance on image below:

I'm trying to not reinvent the wheel here and use something that is already battletested like boost::geometry::distance, but it only return distance and not also the points.

答:
Not making things overly generic (by assuming floating point coordinates and cartesian coordinate system), here's an implementation of point-to-line-segment distance that returns the projected point as well as the distance:

```<code>struct DistancePoint {
    double distance;
    P projected_point;
};

template <typename Strategy = bg::strategy::distance::pythagoras<> >
DistancePoint point_to_segment(P const& p, P const& p1, P const& p2) {
    P v = p2, w = p;
    bg::subtract_point(v, p1);
    bg::subtract_point(w, p1);

    auto const c1 = bg::dot_product(w, v);
    if (c1 <= 0)  return { Strategy::apply(p, p1), p1 };

    auto const c2 = bg::dot_product(v, v);
    if (c2 <= c1) return { Strategy::apply(p, p2), p2 };

    P prj = p1;
    bg::multiply_value(v, c1/c2);
    bg::add_point(prj, v);

    return { Strategy::apply(p, prj), prj };
}
</code>```

Now you can use it with your geometries. I didn't want to satisfy all the criteria for the distance-strategy concept, so you can't use the above with boost::geometry::distance.

But since your input geometries have low point counts, you might get away with "brute-forcing" (without requiring the library internal closest_feature selection):

```<code>R a = gen_rect(),
  b = gen_rect();

// make sure a and b don't overlap (distance > 0)
while (!bg::disjoint(a,b)) { b = gen_rect(); }

std::cout
    << wkt(a) << "\n"
    << wkt(b) << "\n"
    << bg::distance(a, b) << " apart\n";

DistancePoint nearest;
P const* which = nullptr;

for (auto& [a,b] : { std::tie(a,b), std::tie(b,a) } ) {
    auto segments = boost::make_iterator_range(bg::segments_begin(a), bg::segments_end(a));
    auto points   = boost::make_iterator_range(bg::points_begin(b), bg::points_end(b));

    for (auto&& pq : segments) {
        for (auto&& r : points) {
            auto d = point_to_segment(r, *pq.first, *pq.second);

            if (!which || d.distance < nearest.distance) {
                which = &r;
                nearest = d;
            }
        }
    }
}

std::cout << wkt(which) << " at " << nearest.distance << " from " << wkt(nearest.projected_point) << "\n";
</code>```

DEMO

Live On Coliru

```<code>#include <boost/geometry.hpp>
#include <boost/geometry/util/range.hpp>
#include <boost/geometry/io/io.hpp>
#include <boost/geometry/algorithms/assign.hpp>
#include <boost/geometry/algorithms/convex_hull.hpp>
#include <boost/geometry/algorithms/point_on_surface.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/range/adaptors.hpp>
#include <iostream>
#include <fstream>

namespace bg = boost::geometry;
namespace bgm = boost::geometry::model;
using namespace boost::adaptors;
using bg::wkt;

using P = bgm::d2::point_xy<double>;
using B = bgm::box<P>;
using S = bgm::segment<P>;
using R = bgm::polygon<P>;

R gen_rect(); // generates a random rectangle

namespace {
    struct DistancePoint {
        double distance;
        P projected_point;
    };

    // after strategy::distance::projected_point<>
    template <typename Strategy = bg::strategy::distance::pythagoras<> >
    DistancePoint point_to_segment(P const& p, P const& p1, P const& p2) {
        P v = p2, w = p;
        bg::subtract_point(v, p1);
        bg::subtract_point(w, p1);

        auto const c1 = bg::dot_product(w, v);
        if (c1 <= 0)  return { Strategy::apply(p, p1), p1 };

        auto const c2 = bg::dot_product(v, v);
        if (c2 <= c1) return { Strategy::apply(p, p2), p2 };

        P prj = p1;
        bg::multiply_value(v, c1/c2);
        bg::add_point(prj, v);

        return { Strategy::apply(p, prj), prj };
    }
}

int main() {
    std::cout << std::setprecision(2);

    for (auto i = 0; i<10; ++i) {
        R a = gen_rect(),
          b = gen_rect();

        // make sure a and b don't overlap (distance > 0)
        while (!bg::disjoint(a,b)) { b = gen_rect(); }

        std::cout
            << wkt(a) << "\n"
            << wkt(b) << "\n"
            << bg::distance(a, b) << " apart\n";

        DistancePoint nearest;
        P const* which = nullptr;

        for (auto& [a,b] : { std::tie(a,b), std::tie(b,a) } ) {
            auto segments = boost::make_iterator_range(bg::segments_begin(a), bg::segments_end(a));
            auto points   = boost::make_iterator_range(bg::points_begin(b), bg::points_end(b));

            for (auto&& pq : segments) {
                for (auto&& r : points) {
                    auto d = point_to_segment(r, *pq.first, *pq.second);

                    if (!which || d.distance < nearest.distance) {
                        which = &r;
                        nearest = d;
                    }
                }
            }
        }

        std::cout << wkt(which) << " at " << nearest.distance << " from " << wkt(nearest.projected_point) << "\n";

        {
            std::ofstream svg("output" + std::to_string(i) + ".svg");
            boost::geometry::svg_mapper<P> mapper(svg, 400, 400, "style='fill-opacity:1;fill:rgb(255,255,255)'");
            mapper.add(a);
            mapper.add(b);
            S dline {*which, nearest.projected_point};
            mapper.add(dline);

            mapper.map(a, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2");
            mapper.map(b, "fill-opacity:0.5;fill:rgb(204,153,0);stroke:rgb(202,153,0);stroke-width:2");
            mapper.map(dline, "stroke-dasharray:1,1;stroke:rgb(255,0,0);stroke-width:1");
        }
    }
}

// details for generating the rectangles
#include <boost/geometry/strategies/transform/matrix_transformers.hpp>
#include <random>
std::mt19937 prng { std::random_device{}() };

static auto rand(double b, double e) {
    return std::uniform_real_distribution<double>(b, e)(prng);
}

R gen_rect() {
    B initial {{0, 0}, { rand(0.1, 1), rand(0.1, 1) } };
    R raw, rect; // todo rotate and stuff
    bg::assign(raw, initial);

    using namespace bg::strategy::transform;
    auto rot   = rand(-M_PI, +M_PI);
    auto scale = rand(1, 3);
    auto x     = rand(-5, 5),
         y     = rand(-5, 5);

    matrix_transformer<double, 2, 2> xfrm(
         scale* cos(rot), scale*sin(rot), x,
         scale*-sin(rot), scale*cos(rot), y,
                       0,              0, 1);

    bg::transform(raw, rect, xfrm);
    bg::correct(rect);
    return rect;
}
</code>```

This generates some randomized scenes like:

Body:
Not making things overly generic (by assuming floating point coordinates and cartesian coordinate system), here's an implementation of point-to-line-segment distance that returns the projected point as well as the distance:

struct DistancePoint {
    double distance;
    P projected_point;
};

template <typename Strategy = bg::strategy::distance::pythagoras<> >
DistancePoint point_to_segment(P const& p, P const& p1, P const& p2) {
    P v = p2, w = p;
    bg::subtract_point(v, p1);
    bg::subtract_point(w, p1);

    auto const c1 = bg::dot_product(w, v);
    if (c1 <= 0)  return { Strategy::apply(p, p1), p1 };

    auto const c2 = bg::dot_product(v, v);
    if (c2 <= c1) return { Strategy::apply(p, p2), p2 };

    P prj = p1;
    bg::multiply_value(v, c1/c2);
    bg::add_point(prj, v);

    return { Strategy::apply(p, prj), prj };
}

Now you can use it with your geometries. I didn't want to satisfy all the criteria for the distance-strategy concept, so you can't use the above with boost::geometry::distance.

But since your input geometries have low point counts, you might get away with "brute-forcing" (without requiring the library internal closest_feature selection):

R a = gen_rect(),
  b = gen_rect();

// make sure a and b don't overlap (distance > 0)
while (!bg::disjoint(a,b)) { b = gen_rect(); }

std::cout
    << wkt(a) << "\n"
    << wkt(b) << "\n"
    << bg::distance(a, b) << " apart\n";

DistancePoint nearest;
P const* which = nullptr;

for (auto& [a,b] : { std::tie(a,b), std::tie(b,a) } ) {
    auto segments = boost::make_iterator_range(bg::segments_begin(a), bg::segments_end(a));
    auto points   = boost::make_iterator_range(bg::points_begin(b), bg::points_end(b));

    for (auto&& pq : segments) {
        for (auto&& r : points) {
            auto d = point_to_segment(r, *pq.first, *pq.second);

            if (!which || d.distance < nearest.distance) {
                which = &r;
                nearest = d;
            }
        }
    }
}

std::cout << wkt(which) << " at " << nearest.distance << " from " << wkt(nearest.projected_point) << "\n";

DEMO

Live On Coliru

#include <boost/geometry.hpp>
#include <boost/geometry/util/range.hpp>
#include <boost/geometry/io/io.hpp>
#include <boost/geometry/algorithms/assign.hpp>
#include <boost/geometry/algorithms/convex_hull.hpp>
#include <boost/geometry/algorithms/point_on_surface.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/range/adaptors.hpp>
#include <iostream>
#include <fstream>

namespace bg = boost::geometry;
namespace bgm = boost::geometry::model;
using namespace boost::adaptors;
using bg::wkt;

using P = bgm::d2::point_xy<double>;
using B = bgm::box<P>;
using S = bgm::segment<P>;
using R = bgm::polygon<P>;

R gen_rect(); // generates a random rectangle

namespace {
    struct DistancePoint {
        double distance;
        P projected_point;
    };

    // after strategy::distance::projected_point<>
    template <typename Strategy = bg::strategy::distance::pythagoras<> >
    DistancePoint point_to_segment(P const& p, P const& p1, P const& p2) {
        P v = p2, w = p;
        bg::subtract_point(v, p1);
        bg::subtract_point(w, p1);

        auto const c1 = bg::dot_product(w, v);
        if (c1 <= 0)  return { Strategy::apply(p, p1), p1 };

        auto const c2 = bg::dot_product(v, v);
        if (c2 <= c1) return { Strategy::apply(p, p2), p2 };

        P prj = p1;
        bg::multiply_value(v, c1/c2);
        bg::add_point(prj, v);

        return { Strategy::apply(p, prj), prj };
    }
}

int main() {
    std::cout << std::setprecision(2);

    for (auto i = 0; i<10; ++i) {
        R a = gen_rect(),
          b = gen_rect();

        // make sure a and b don't overlap (distance > 0)
        while (!bg::disjoint(a,b)) { b = gen_rect(); }

        std::cout
            << wkt(a) << "\n"
            << wkt(b) << "\n"
            << bg::distance(a, b) << " apart\n";

        DistancePoint nearest;
        P const* which = nullptr;

        for (auto& [a,b] : { std::tie(a,b), std::tie(b,a) } ) {
            auto segments = boost::make_iterator_range(bg::segments_begin(a), bg::segments_end(a));
            auto points   = boost::make_iterator_range(bg::points_begin(b), bg::points_end(b));

            for (auto&& pq : segments) {
                for (auto&& r : points) {
                    auto d = point_to_segment(r, *pq.first, *pq.second);

                    if (!which || d.distance < nearest.distance) {
                        which = &r;
                        nearest = d;
                    }
                }
            }
        }

        std::cout << wkt(which) << " at " << nearest.distance << " from " << wkt(nearest.projected_point) << "\n";

        {
            std::ofstream svg("output" + std::to_string(i) + ".svg");
            boost::geometry::svg_mapper<P> mapper(svg, 400, 400, "style='fill-opacity:1;fill:rgb(255,255,255)'");
            mapper.add(a);
            mapper.add(b);
            S dline {*which, nearest.projected_point};
            mapper.add(dline);

            mapper.map(a, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2");
            mapper.map(b, "fill-opacity:0.5;fill:rgb(204,153,0);stroke:rgb(202,153,0);stroke-width:2");
            mapper.map(dline, "stroke-dasharray:1,1;stroke:rgb(255,0,0);stroke-width:1");
        }
    }
}

// details for generating the rectangles
#include <boost/geometry/strategies/transform/matrix_transformers.hpp>
#include <random>
std::mt19937 prng { std::random_device{}() };

static auto rand(double b, double e) {
    return std::uniform_real_distribution<double>(b, e)(prng);
}

R gen_rect() {
    B initial {{0, 0}, { rand(0.1, 1), rand(0.1, 1) } };
    R raw, rect; // todo rotate and stuff
    bg::assign(raw, initial);

    using namespace bg::strategy::transform;
    auto rot   = rand(-M_PI, +M_PI);
    auto scale = rand(1, 3);
    auto x     = rand(-5, 5),
         y     = rand(-5, 5);

    matrix_transformer<double, 2, 2> xfrm(
         scale* cos(rot), scale*sin(rot), x,
         scale*-sin(rot), scale*cos(rot), y,
                       0,              0, 1);

    bg::transform(raw, rect, xfrm);
    bg::correct(rect);
    return rect;
}

This generates some randomized scenes like:


问:
How do you get a file in C++?
So the teacher has posed this assignment:

You have been hired by the United Network Command for Law Enforcement, and you have been given files containing null cyphers you have to decrypt.

So for the first file given (as an example), every other letter is correct (ie: 'hielqlpo' is hello (assuming you start with the first letter).  My first question is, how do I read in a file?  The document is on my desktop in a folder and the file is named document01.cry.  I'm not sure the command I need to put that file into the program.

I'm also not overly sure how to grab a letter and skip a letter, but honestly I want to tinker with that before I post that question! So for now...my question is as stated in the title: How do you grab a file for reading in C++?

If it makes a difference (As I'm sure it does), I'm using Visual C++ 2008 Express Edition (because it's free and I like it! I've also attached what I have so far, please keep in mind it's -very- basic...and I added the getchar(); at the end so when it does run properly, the window stays open so I can see it (as Visual Express tends to close the window as soon as it's done running.)

The code so far:

```<code>#include<iostream>

using namespace std;

int main()
{
    while (! cin.eof())
    {
        int c = cin.get() ;
        cout.put(c) ;
    }
    getchar();
}
</code>```

PS: I realize that this code grabs and puts out every character. For now that's fine, once I can read in the file I think I can tinker with it from there.  I'm also poking at a book or two I have on C++ to see it anything pops up and screams "Pick me!" Thanks again!

EDIT:: Also curious, is there a way to input the file you want?
(I.e.:

```<code>char filename;
cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
cin >> filename;
cout << endl;
ifstream infile(filename, ios::in);
</code>```

This code doesn't work. It shoots back an error saying the char can't be converted to a const char *.  How can this problem be fixed?

EDIT 2:
Never mind about said part 2, I found it out! Thanks again for the assistance!

答:
To do file operations, you need the correct include:

```<code>#include <fstream>
</code>```

Then, in your main function, you can open a file stream:

```<code>ifstream inFile( "filename.txt", ios::in );
</code>```

or, for output:

```<code>ofstream outFile( "filename.txt", ios::out );
</code>```

You can then use inFile as you would use cin, and outFile as you would use cout. To close the file when you are done:

```<code>inFile.close();
outFile.close();
</code>```

OwnerDisplayName: Jeff

ContentLicense: CC BY-SA 2.5

Title: How do you get a file in C++?

Body:
So the teacher has posed this assignment:

You have been hired by the United Network Command for Law Enforcement, and you have been given files containing null cyphers you have to decrypt.

So for the first file given (as an example), every other letter is correct (ie: 'hielqlpo' is hello (assuming you start with the first letter).  My first question is, how do I read in a file?  The document is on my desktop in a folder and the file is named document01.cry.  I'm not sure the command I need to put that file into the program.

I'm also not overly sure how to grab a letter and skip a letter, but honestly I want to tinker with that before I post that question! So for now...my question is as stated in the title: How do you grab a file for reading in C++?

If it makes a difference (As I'm sure it does), I'm using Visual C++ 2008 Express Edition (because it's free and I like it! I've also attached what I have so far, please keep in mind it's -very- basic...and I added the getchar(); at the end so when it does run properly, the window stays open so I can see it (as Visual Express tends to close the window as soon as it's done running.)

The code so far:

#include<iostream>

using namespace std;

int main()
{
    while (! cin.eof())
    {
        int c = cin.get() ;
        cout.put(c) ;
    }
    getchar();
}

PS: I realize that this code grabs and puts out every character. For now that's fine, once I can read in the file I think I can tinker with it from there.  I'm also poking at a book or two I have on C++ to see it anything pops up and screams "Pick me!" Thanks again!

EDIT:: Also curious, is there a way to input the file you want?
(I.e.:

char filename;
cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
cin >> filename;
cout << endl;
ifstream infile(filename, ios::in);

This code doesn't work. It shoots back an error saying the char can't be converted to a const char *.  How can this problem be fixed?

EDIT 2:
Never mind about said part 2, I found it out! Thanks again for the assistance!

LastEditorDisplayName: EvilTeach

Body:
To do file operations, you need the correct include:

#include <fstream>

Then, in your main function, you can open a file stream:

ifstream inFile( "filename.txt", ios::in );

or, for output:

ofstream outFile( "filename.txt", ios::out );

You can then use inFile as you would use cin, and outFile as you would use cout. To close the file when you are done:

inFile.close();
outFile.close();

OwnerDisplayName: Colin


问:
jquery-ui retrieving selected in a buttonset (checkbox) - firefox issue
It's possible to retrieve the 'selected' buttons in a jquery ui buttonset build with checkboxes (to allow multiselect) with :

```<code>$('#format').buttonset();

$('#format').click(function() {
  var text = "";
  $('#format').find('label[aria-pressed|="true"]').each(function() {
      text += $(this).attr("for") + "-";
  });
  $('#selected').html(text);
});
</code>```

This is working fine in Chrome, IE, Safari but in Firefox the clicked checkbox is not taken into account. You can check this in jsFiddle.

答:
Try:

```<code>$('label.ui-state-active')
</code>```

See my updated jsFiddle http://jsfiddle.net/qLWNd/

ContentLicense: CC BY-SA 3.0

Body:
It's possible to retrieve the 'selected' buttons in a jquery ui buttonset build with checkboxes (to allow multiselect) with :

$('#format').buttonset();

$('#format').click(function() {
  var text = "";
  $('#format').find('label[aria-pressed|="true"]').each(function() {
      text += $(this).attr("for") + "-";
  });
  $('#selected').html(text);
});

This is working fine in Chrome, IE, Safari but in Firefox the clicked checkbox is not taken into account. You can check this in jsFiddle.

Body:
Try:

$('label.ui-state-active')

See my updated jsFiddle http://jsfiddle.net/qLWNd/


问:
How to open dropdown sub-menu from multi-navigation bar?
I am having trouble opening my dropdown sub-menu with CSS. I want the user to be able to open it when hovered over the corresponding  tag. I tried to make #lablinksDD open when hovered over #menuDD with #labLinksDD:hover #ddSbMenu How may I do that? I feel like I am missing something.

Code:

HTML

```<code><ul>
                    <li><a href="DD/Index.html" class="tpNavBtns">Digital Design (DD) ▾</a></li> <!--▴-->

                    <ul class="subMenu1" id="menuDD">
                        <li><a href="#" id="labLinksDD">Labs ▸</a></li> <!--◂-->

                            <ul class="drpDn-subMenu labSbMenu" id="ddSbMenu">
                                <li><a href="DD/Labs/Lab_01/LB1_WeiJianZhen_DD.html">DD Lab 1</a></li>
                                <li><a href="DD/Labs/Lab_02/LB2_WeiJianZhen_DD.html">DD Lab 2</a></li>
                                <li><a href="DD/Labs/Lab_03/Lab_3.html">DD Lab 3</a></li>
                                <!--more than 20 a tags inside lists-->
                            </ul>
</code>```

CSS

```<code>
.drpDn-subMenu {
    display: none;
    position: absolute;
    width: 200px;
    height: 500px;
    top: 0px;
    left: 164px;
    overflow-x: hidden;
    overflow-y: scroll;
    background-color: red;
    list-style-type: none;
    border-left: 1px solid rgba(120, 120, 120, 0.70);
    border-bottom: 1px solid rgba(120, 120, 120, 0.70);
}

.drpDn-subMenu a {
    display: inline-block;
    position: relative;
    padding: 20px 50px;
    width: 100%;
    height: auto;
    text-align: left;
}

#menuDD {
    top: 100%;
    left: 13.6%;
}

#menuWCP {
    top: 50px;
    left: 800px;
}

.labSbMenu {
    z-index: 3;
}

.prSbMenu {
    top: 56px;
    height: auto;
    background-color: antiquewhite;
}

</code>```

I'll also accept a Vanilla JavaScript version instead of a CSS one.

答:
If you change the id from the anchor to the list item or add different id or class to the list item then you can solve this with CSS general sibling selector (~) or adjacent sibling selector (+) without JS, see https://www.w3schools.com/css/css_combinators.asp:</p>

```<code>#labLinksDD:hover~#ddSbMenu {
    display: block;
}
</code>```

Body:
I am having trouble opening my dropdown sub-menu with CSS. I want the user to be able to open it when hovered over the corresponding  tag. I tried to make #lablinksDD open when hovered over #menuDD with #labLinksDD:hover #ddSbMenu How may I do that? I feel like I am missing something.

Code:

HTML

Digital Design (DD) ▾

Labs ▸

DD Lab 1

DD Lab 2

DD Lab 3

CSS

.drpDn-subMenu {
    display: none;
    position: absolute;
    width: 200px;
    height: 500px;
    top: 0px;
    left: 164px;
    overflow-x: hidden;
    overflow-y: scroll;
    background-color: red;
    list-style-type: none;
    border-left: 1px solid rgba(120, 120, 120, 0.70);
    border-bottom: 1px solid rgba(120, 120, 120, 0.70);
}

.drpDn-subMenu a {
    display: inline-block;
    position: relative;
    padding: 20px 50px;
    width: 100%;
    height: auto;
    text-align: left;
}

#menuDD {
    top: 100%;
    left: 13.6%;
}

#menuWCP {
    top: 50px;
    left: 800px;
}

.labSbMenu {
    z-index: 3;
}

.prSbMenu {
    top: 56px;
    height: auto;
    background-color: antiquewhite;
}

I'll also accept a Vanilla JavaScript version instead of a CSS one.

Body:
If you change the id from the anchor to the list item or add different id or class to the list item then you can solve this with CSS general sibling selector (~) or adjacent sibling selector (+) without JS, see https://www.w3schools.com/css/css_combinators.asp:

#labLinksDD:hover~#ddSbMenu {
    display: block;
}


问:
Android Navigation drawer transparent bug
I have an issue using the navigation drawer in combination with the AR-Fragment from googles arcore sdk, here's a screenshot:

When I change the current fragment it works as intended.
Code inside the onCreate-Method of the Activity:

```<code>drawerLayout = findViewById(R.id.activity_main);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();

navigationView = findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
drawerLayout.bringToFront();
navigationView.bringToFront();

arFragment = new ArSceneFragment();
getSupportFragmentManager().beginTransaction().replace(
                R.id.fragment_container, arFragment).commit();
</code>```

Hope you can help me:)
Thank you and best regards!

EDIT:
When I test using the emulator it works perfectly.

答:
try using

```<code>if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
   drawerLayout.openDrawer(Gravity.START);
} else {
   drawerLayout.closeDrawer(Gravity.END);
}
</code>```

when you open and close the drawer.

and i'm still suspecting the title bar.

Cuz i had a almost same problem before and it was about title bar.

Sometimes eventho you set the theme as NoActionBar in your layout xml,
the Manifest file doesn't automatically updates it. so you need to check it twice.

Body:
I have an issue using the navigation drawer in combination with the AR-Fragment from googles arcore sdk, here's a screenshot:

When I change the current fragment it works as intended.
Code inside the onCreate-Method of the Activity:

drawerLayout = findViewById(R.id.activity_main);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();

navigationView = findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
drawerLayout.bringToFront();
navigationView.bringToFront();

arFragment = new ArSceneFragment();
getSupportFragmentManager().beginTransaction().replace(
                R.id.fragment_container, arFragment).commit();

Hope you can help me:)
Thank you and best regards!

EDIT:
When I test using the emulator it works perfectly.

Body:
try using

if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
   drawerLayout.openDrawer(Gravity.START);
} else {
   drawerLayout.closeDrawer(Gravity.END);
}

when you open and close the drawer.

and i'm still suspecting the title bar.

Cuz i had a almost same problem before and it was about title bar.

Sometimes eventho you set the theme as NoActionBar in your layout xml,
the Manifest file doesn't automatically updates it. so you need to check it twice.


问:
.NET Core 3 dependency injection in custom validation
I want to make a custom validation attribute in .NET Core called CheckIfEmailExists. I want to make sure the user is not in my database already. So this is my create user view model:

```<code>public class CreateUserViewModel
{
    public readonly UserManager userManager;

    public CreateUserViewModel()
    {
    }

    public ExtendedProfile ExtendedProfile { get; set; }

    public User User { get; set; }

    public int SchemeId { get; set; }

    public SelectList Schemes { get; set; }

    [Required]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    [CheckIfEmailExists()]
    [Display(Name = "Email Address")]
    public string Email { get; set; }

    [DataType(DataType.EmailAddress)]
    [Display(Name = "Confirm Email Address")]
    public string ConfirmEmail { get; set; }

}
</code>```

Here is my custom validation:

```<code>public class CheckIfEmailExists : ValidationAttribute
{
    private readonly UserManager _userManager;

    public CheckIfEmailExists(UserManager userManager)
    {
        var _userManager = userManager;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var user = (User)validationContext.ObjectInstance;

        var result = _userManager.FindByEmailAsync(user.Email).Result;

        //do something

        return ValidationResult.Success;
    }
}
</code>```

I get an error when I add my custom validation on my email property, the error is that I must pass in the usermanager object to the custom class constructor.

Why doesn't my app just inject the object itself?

Is there a way I can create a user manager object in my custom class without coupling the classes?

Should I only access my database in my controller?

答:
The comment above from Nikki9696 helped me and now I know how to get my user manager and dbcontext in my custom validation attribute.</p>

```<code>public class IsEmailInDatabase : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var context = (DatabaseContext)validationContext.GetService(typeof(DatabaseContext));

        if (value == null)
        {
            return null;
        }
        else
        {
            var results = context.Users.AnyAsync(x => x.Email == value.ToString());

            if (results.Result)
            {
                return new ValidationResult("This email address already exists in our database");
            }

            return null;
        }
    }
}
</code>```

Body:
I want to make a custom validation attribute in .NET Core called CheckIfEmailExists. I want to make sure the user is not in my database already. So this is my create user view model:

public class CreateUserViewModel
{
    public readonly UserManager userManager;

    public CreateUserViewModel()
    {
    }

    public ExtendedProfile ExtendedProfile { get; set; }

    public User User { get; set; }

    public int SchemeId { get; set; }

    public SelectList Schemes { get; set; }

    [Required]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    [CheckIfEmailExists()]
    [Display(Name = "Email Address")]
    public string Email { get; set; }

    [DataType(DataType.EmailAddress)]
    [Display(Name = "Confirm Email Address")]
    public string ConfirmEmail { get; set; }

}

Here is my custom validation:

public class CheckIfEmailExists : ValidationAttribute
{
    private readonly UserManager _userManager;

    public CheckIfEmailExists(UserManager userManager)
    {
        var _userManager = userManager;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var user = (User)validationContext.ObjectInstance;

        var result = _userManager.FindByEmailAsync(user.Email).Result;

        //do something

        return ValidationResult.Success;
    }
}

I get an error when I add my custom validation on my email property, the error is that I must pass in the usermanager object to the custom class constructor.

Why doesn't my app just inject the object itself?

Is there a way I can create a user manager object in my custom class without coupling the classes?

Should I only access my database in my controller?

Body:
The comment above from Nikki9696 helped me and now I know how to get my user manager and dbcontext in my custom validation attribute.

public class IsEmailInDatabase : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var context = (DatabaseContext)validationContext.GetService(typeof(DatabaseContext));

        if (value == null)
        {
            return null;
        }
        else
        {
            var results = context.Users.AnyAsync(x => x.Email == value.ToString());

            if (results.Result)
            {
                return new ValidationResult("This email address already exists in our database");
            }

            return null;
        }
    }
}


问:
Typescript - Nested arrow function typing
I have this code for deferring the execution of a function

```<code>export type DeferredFunction<T> = () => T | PromiseLike<T>;

export class Deferrable<T> {
  protected df: DeferredFunction<T>;

  constructor(df: DeferredFunction<T>) {
    this.df = df;
  }

  public async execute(): Promise<T> {
    return this.df();
  }
}

export const defer = <T>(df: DeferredFunction<T>): Deferrable<T> => new Deferrable<T>(df);
</code>```

That works fine and I can run code like

```<code>await defer(() => someFunction('foo', 'bar')).execute();
</code>```

but I what I want to do is type DeferredFunction in a way that I can specify the inner function's signature but I can't get it working.  In generic cases the above works but when I want to limit the arguments such that they are specific to a certain type of function I don't have that kind of control.

For clarity, I want to be able to type the inner function's inputs like (as an example)

```<code>export type InnerDeferredFunction<T> = (a: string, b: number, c: SomeObjectType) => T | PromiseLike<T>
</code>```

Any help would be greatly appreciated!

答:
What "inner function" are you talking about?  Is it someFunction?  If so then the type of DeferredFunction<T> has no handle on it, since it's a function called by the implementation of DeferredFunction<T>.  There's no way in TypeScript to specify "a function whose implementation must call a function of type (x: string, y: number, z: boolean) => string".  Implementation details are not part of a function's call signature.

The only way I can imagine to begin to approach this would be for DeferredFunction<T> to accept as a parameter the inner function you want to call, along with the list of arguments to call it with.  This might not be what you're looking for, but it's the closest that the type system can represent.

Something like this:

```<code>export type InnerDeferredFunction<T, A extends any[]> = (...args: A) => T | PromiseLike<T>;
export type ZeroArgDeferredFunction<T> = InnerDeferredFunction<T, []>
</code>```

Here I'm keeping A generic but you can specify it to some hardcoded list of arguments.   I've renamed your DeferredFunction to ZeroArgDeferredFunction to be explicit that it doesn't need arguments.

But now Deferrable needs to know about T and A:

```<code>export class Deferrable<T, A extends any[]> {
  protected df: ZeroArgDeferredFunction<T>;

  constructor(df: InnerDeferredFunction<T, A>, ...args: A) {
    this.df = () => df(...args);
  }

  public async execute(): Promise<T> {
    return this.df();
  }
}
</code>```

And you can see that you have to construct one by passing it the inner function and its arguments, and the ZeroArgDeferredFunction is built inside the constructor and is not passed in.

There are different ways to define defer().  It could be a thin wrapper around new Deferrable the way you had it, or you could imagine splitting it up so that the args come first:

```<code>export const defer = <A extends any[]>(...args: A) => <T>(
  df: InnerDeferredFunction<T, A>): Deferrable<T, A> => new Deferrable<T, A>(df, ...args);
</code>```

And then you can test it like this:

```<code>function someFunction(x: string, y: string) {
  return (x + y).length;
}
function anotherFunction(x: number, y: number) {
  return (x * y).toFixed()
}

const deferFooBar = defer('foo', 'bar');
await deferFooBar(someFunction).execute(); // okay
await deferFooBar(anotherFunction); // error! string is not assignable to number
</code>```

Once you call deferFooBar('foo', 'bar'), the returned value will only accept functions that can be safely called with the arguments foo and 'bar'.  That means someFunction will be accepted and anotherFunction will be rejected.

Okay, hope that helps; good luck!

Playground link to code

Body:
I have this code for deferring the execution of a function

export type DeferredFunction<T> = () => T | PromiseLike<T>;

export class Deferrable<T> {
  protected df: DeferredFunction<T>;

  constructor(df: DeferredFunction<T>) {
    this.df = df;
  }

  public async execute(): Promise<T> {
    return this.df();
  }
}

export const defer = <T>(df: DeferredFunction<T>): Deferrable<T> => new Deferrable<T>(df);

That works fine and I can run code like

await defer(() => someFunction('foo', 'bar')).execute();

but I what I want to do is type DeferredFunction in a way that I can specify the inner function's signature but I can't get it working.  In generic cases the above works but when I want to limit the arguments such that they are specific to a certain type of function I don't have that kind of control.

For clarity, I want to be able to type the inner function's inputs like (as an example)

export type InnerDeferredFunction<T> = (a: string, b: number, c: SomeObjectType) => T | PromiseLike<T>

Any help would be greatly appreciated!

Body:
What "inner function" are you talking about?  Is it someFunction?  If so then the type of DeferredFunction<T> has no handle on it, since it's a function called by the implementation of DeferredFunction<T>.  There's no way in TypeScript to specify "a function whose implementation must call a function of type (x: string, y: number, z: boolean) => string".  Implementation details are not part of a function's call signature.

The only way I can imagine to begin to approach this would be for DeferredFunction<T> to accept as a parameter the inner function you want to call, along with the list of arguments to call it with.  This might not be what you're looking for, but it's the closest that the type system can represent.

Something like this:

export type InnerDeferredFunction<T, A extends any[]> = (...args: A) => T | PromiseLike<T>;
export type ZeroArgDeferredFunction<T> = InnerDeferredFunction<T, []>

Here I'm keeping A generic but you can specify it to some hardcoded list of arguments.   I've renamed your DeferredFunction to ZeroArgDeferredFunction to be explicit that it doesn't need arguments.

But now Deferrable needs to know about T and A:

export class Deferrable<T, A extends any[]> {
  protected df: ZeroArgDeferredFunction<T>;

  constructor(df: InnerDeferredFunction<T, A>, ...args: A) {
    this.df = () => df(...args);
  }

  public async execute(): Promise<T> {
    return this.df();
  }
}

And you can see that you have to construct one by passing it the inner function and its arguments, and the ZeroArgDeferredFunction is built inside the constructor and is not passed in.

There are different ways to define defer().  It could be a thin wrapper around new Deferrable the way you had it, or you could imagine splitting it up so that the args come first:

export const defer = <A extends any[]>(...args: A) => <T>(
  df: InnerDeferredFunction<T, A>): Deferrable<T, A> => new Deferrable<T, A>(df, ...args);

And then you can test it like this:

function someFunction(x: string, y: string) {
  return (x + y).length;
}
function anotherFunction(x: number, y: number) {
  return (x * y).toFixed()
}

const deferFooBar = defer('foo', 'bar');
await deferFooBar(someFunction).execute(); // okay
await deferFooBar(anotherFunction); // error! string is not assignable to number

Once you call deferFooBar('foo', 'bar'), the returned value will only accept functions that can be safely called with the arguments foo and 'bar'.  That means someFunction will be accepted and anotherFunction will be rejected.

Okay, hope that helps; good luck!

<a href="https://www.typescriptlang.org/play/#code/KYDwDg9gTgLgBDAnmYcCSA7DwoBFgBmOUwAJgGICuGAxjAJYQYA8AKgDRwCCcoMwGUgGc4AQwyIA2gF0AfHAC8cABQA6daKgBzIQC5uASkXzWcAD5wAClAgBbekOAAZegGtgbWQG4AUKEiwCMioAFo4EFza+ERQJBTUdIwsrPJKmNh4hMRkVLQMTGycMrI+fuDQ8DQANqJCItHEogBGVR4c3Lwg-IIi4lJycADePnBwYDb8dGRwpAT6YTaRWg2xOQn5yd6lozRMQjBQlHTQyrP66TgrcbmJBe1cspzqqpo6+lxGw6OjMAAWDqpZooVEYFPJZmoNNohAZfKMAL7bMaUFr0GhiISIWidYA0Sj8ZQGfTWOwONryL7fEgwShQDAIf5CQEEQlwuDwuA+RFlAKVPbwUhZKDA5g8PgCYRiCTFSEvaHvUHyTzKEYzOboLCXIXXdZJQrcWREuBXZqtfUPYxwbAAd2N2tNbU4D1OBCeUJ0sNKBF1TDgQjswBuG2UIH0+yg9AwWk4iDDB0jWk+quptPpIbgAGo4IgDKpWlG-r5Ed68kkpRA-jgg0kQ-oMJRbE0cDG6w2m1Ak6MU3SVCA4AAqbO5mAQcj0EBkQlc0q7DD7GZC8gQCAAIU0wMFMWUAHICMvt5xt01NNvPaJraJ6ALF8u11BlP7bIGfRhc6BcfjgKy4AB6H8+c9L2vGIl1XTRlHECtfirF9YV-H9eFiaAAEI-XjKM4AcK0KwxIR6C0DAHQQCArTbHAgA" rel="nofollow noreferrer">Playground link to code


问:
Coloring with a two color scale in HTML and JavaScript
I have an input element whose value is a number between 0 and 100. I am attempting to style the element via a two-color scale, taking its value as the input.

I am planning on making a simple gradient:

When the number is 100, the element's background color is green #00ff00

When the number is 0, it is red #ff0000

When the number is 50, it displays a yellow color #ffff00

The in-between values should be colored according to the scale.

I have tried using an if statement in JavaScript, but that fails to create a gradient, as there is a hard border between red, yellow, and green (sans gradient). See the code below:

var x = 0;

function color() {
    x = document.getElementById("color").value;
    console.log(x);

    if (x > 50) {
        document.getElementById('color').style.backgroundColor = "#00ff00";
    }
    else if (x == 50) {
        document.getElementById('color').style.backgroundColor = "#ffff00";
    }
    else {
        document.getElementById('color').style.backgroundColor = "#ff0000";
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="color();">Run</button>
<input type="number" id='color' value=50></input>
<!-- The input is not disabled for value debugging. --></code>```

Is there concise way to perform this task?

答:
I have found the optimal way to create a 2 color scale that uses vibrant, hexadecimal colors:

var colval = 0;
var R = 0;
var G = 0;
var B = 0;

function check() {

  c = document.getElementById("color");
  x = c.value;

  if (x > 50) {

    R = Math.round(-0.051 * x ** 2 + 2.55 * x + 255);
    G = 255;

  } else if (x < 50) {

    R = 255;
    G = Math.round(-0.051 * x ** 2 + 7.65 * x + 0);

  } else {

    R = 255;
    G = 255;

  }

  B = 0;

  colval = "#" + R.toString(16) + G.toString(16) + "00";
  c.style.background = colval;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<body>
  <input type="number" id="color" min="0" max="100" value="0" onkeyup="check()">

</body>

</html></code>```

Body:
I have an input element whose value is a number between 0 and 100. I am attempting to style the element via a two-color scale, taking its value as the input.

I am planning on making a simple gradient:

When the number is 100, the element's background color is green #00ff00

When the number is 0, it is red #ff0000

When the number is 50, it displays a yellow color #ffff00

The in-between values should be colored according to the scale.

I have tried using an if statement in JavaScript, but that fails to create a gradient, as there is a hard border between red, yellow, and green (sans gradient). See the code below:

var x = 0;

function color() {
    x = document.getElementById("color").value;
    console.log(x);

    if (x > 50) {
        document.getElementById('color').style.backgroundColor = "#00ff00";
    }
    else if (x == 50) {
        document.getElementById('color').style.backgroundColor = "#ffff00";
    }
    else {
        document.getElementById('color').style.backgroundColor = "#ff0000";
    }
}

<button onclick="color();">Run</button>
<input type="number" id='color' value=50></input>

Is there concise way to perform this task?

Body:
I have found the optimal way to create a 2 color scale that uses vibrant, hexadecimal colors:

var colval = 0;
var R = 0;
var G = 0;
var B = 0;

function check() {

  c = document.getElementById("color");
  x = c.value;

  if (x > 50) {

    R = Math.round(-0.051 * x ** 2 + 2.55 * x + 255);
    G = 255;

  } else if (x < 50) {

    R = 255;
    G = Math.round(-0.051 * x ** 2 + 7.65 * x + 0);

  } else {

    R = 255;
    G = 255;

  }

  B = 0;

  colval = "#" + R.toString(16) + G.toString(16) + "00";
  c.style.background = colval;
}

<html>

<body>
  <input type="number" id="color" min="0" max="100" value="0" onkeyup="check()">

</body>

</html>


问:
Error wrapping WebView within VStack: Unable to infer complex closure return type; add explicit type to disambiguate
I was trying to wrap my custom struct WebView within VStack but got this error:

Unable to infer complex closure return type; add explicit type to disambiguate

WebView is such a struct:

```<code>struct WebView: UIViewRepresentable {
    var request: URLRequest

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.load(request)
    }

}
</code>```

And this is part of my ContentView:

```<code>                        ZStack{
                            ScrollView{

                                VStack(spacing:0){
                                    ZStack{

                                        ZStack (alignment: .leading){...}.offset(y: self.expandedScreen_shown ? 0 : 0)
                                            .clipped()
                                            .background(Color.white)
                                            .foregroundColor(Color.green)
                                            .edgesIgnoringSafeArea(.top)
                                        VStack (alignment: .leading){...}.frame(height: self.maxHeight)
                                    .zIndex(1)

                                    WebView(request: URLRequest(url: URL(String: "google.com")))

                                    Rectangle()
                                        .fill(Color.white)
                                        .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)

                                }

                            }
                            .frame(width: self.expandedScreen_startPoint.width, height: self.expandedScreen_startPoint.height)
                            .background(Color.clear)
                            .cornerRadius(self.expandedScreen_shown ? 0 : 15 )
                            .animation(.easeInOut(duration: 0.3))
                            .offset(x: self.expandedScreen_startPoint.minX, y: self.expandedScreen_startPoint.minY)

                            // ScrollView ends

                            Button(action: {...}){...}.offset(x: (UIScreen.main.bounds.width/2) - 30, y: (-1 * UIScreen.main.bounds.height/2) + 60)
                        }
                            // ZStack ends
</code>```

As I have seen projects successfully wrap this WebView within a VStack, I cannot find where the problem is here. More generally, what is the difference between "complex closure return type" and "explicit type"?

Thanks in advance!

答:
Two things I noticed regarding your WebView.

1) String should be string, and

2) the URL should be unwrapped

try this:

```<code>WebView(request: URLRequest(url: URL(string: "https://google.com")!))
</code>```

Body:
I was trying to wrap my custom struct WebView within VStack but got this error:

Unable to infer complex closure return type; add explicit type to disambiguate

WebView is such a struct:

struct WebView: UIViewRepresentable {
    var request: URLRequest

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.load(request)
    }

}

And this is part of my ContentView:

                        ZStack{
                            ScrollView{

                                VStack(spacing:0){
                                    ZStack{

                                        ZStack (alignment: .leading){...}.offset(y: self.expandedScreen_shown ? 0 : 0)
                                            .clipped()
                                            .background(Color.white)
                                            .foregroundColor(Color.green)
                                            .edgesIgnoringSafeArea(.top)
                                        VStack (alignment: .leading){...}.frame(height: self.maxHeight)
                                    .zIndex(1)

                                    WebView(request: URLRequest(url: URL(String: "google.com")))

                                    Rectangle()
                                        .fill(Color.white)
                                        .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)

                                }

                            }
                            .frame(width: self.expandedScreen_startPoint.width, height: self.expandedScreen_startPoint.height)
                            .background(Color.clear)
                            .cornerRadius(self.expandedScreen_shown ? 0 : 15 )
                            .animation(.easeInOut(duration: 0.3))
                            .offset(x: self.expandedScreen_startPoint.minX, y: self.expandedScreen_startPoint.minY)

                            // ScrollView ends

                            Button(action: {...}){...}.offset(x: (UIScreen.main.bounds.width/2) - 30, y: (-1 * UIScreen.main.bounds.height/2) + 60)
                        }
                            // ZStack ends

As I have seen projects successfully wrap this WebView within a VStack, I cannot find where the problem is here. More generally, what is the difference between "complex closure return type" and "explicit type"?

Thanks in advance!

Body:
Two things I noticed regarding your WebView.

1) String should be string, and

2) the URL should be unwrapped

try this:

WebView(request: URLRequest(url: URL(string: "https://google.com")!))


问:
How to detect .o / .a / compiled object /executable c/c++ without extension? (to then issue 'what' on file to see what it was compiled with)
How can I detect if a file is a compiled object ( .o .a (library)) or executable, without the file extension?

I want to do this so that I can then issue the standard what command to see what .c / .h files were used to build the binary.

Presumably there would be some kind of header at the beginning of the file or some other pattern to look for (?)

Had a look around here and elsewhere a little already but the answers tend to be about MIME types and web development / handling of such files:

Indicate programming language in a file without extension

http://forums.devshed.com/c-programming-42/how-can-detect-filetype-for-files-without-extension-695199.html

http://cboard.cprogramming.com/c-programming/125865-how-can-detect-filetype-files-without-extension.html

答:
If  you're in Unix/Linux, the file command is useful for determining file type of files without relying on a file extension.

It looks at things like "is this a special device rather than a normal file", then looks for "magic numbers" which identify certain file format, etc.


问:
tomcat 405 error when deploying from jenkins to tomcat
I'm learning jenkins and I've been having hard time with jenkins deploying to tomcat using parameters, especially jenkins running on windows machine.
The issue is pretty much the same as the one asked before on stackoverflow, but I don't see the answer as a match as it's so broad. The issue was explained here

I have tomcat users permissions set as bellow

```<code><role rolename="tomcat"/>
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="manager" password="tomcat" roles="tomcat,manager-gui"/>
  <user username="jenkins" password="jenkins" roles="manager-script"/>
</code>```

and I'm trying deploy using the following curl command on windows 10 with curl

```<code>curl -u %tcuser%:%tcpass% -F filedata=target/**.war "http://localhost:8080/manager/text/deploy?path=/devops&update=true"
</code>```

I'm getting the following error in jenkins

```<code>C:\WINDOWS\system32\config\systemprofile\AppData\Local\Jenkins.[*******]\workspace\devops01>curl -u [*******]:[*******] -F filedata=target/**.war "http://localhost:8080/manager/text/deploy?path=/devops&update=true"
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100   908  100   752  100   156    752    156  0:00:01 --:--:--  0:00:01  7264
<!doctype html><html lang="en"><head><title>HTTP Status 405 â€“ Method Not Allowed</title><style type="text/css">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 405 â€“ Method Not Allowed</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Message</b> HTTP method POST is not supported by this URL</p><p><b>Description</b> The method received in the request-line is known by the origin server but not supported by the target resource.</p><hr class="line" /><h3>Apache Tomcat/8.5.54</h3></body></html>
C:\WINDOWS\system32\config\systemprofile\AppData\Local\Jenkins.[*******]\workspace\devops01>exit 0
</code>```

Can someone please help me ?

答:
curl -F issues a POST request (see the manual page). The Tomcat Manager's deploy command, however, only accepts GET or PUT requests -- which is why you got the Method Not Allowed Error (HTTP Status 405).

If you want to deploy your webapp by remote upload, you have to run curl with the -T command line option, e.g.:

```<code>curl -u %tcuser%:%tcpass% -T devops.war "http://localhost:8080/manager/text/deploy?path=/devops&update=true"
</code>```

This makes curl use the PUT method (instead of POST).

If you only want to deploy to localhost, you can also have Tomcat Manager deploy a WAR file from a local path as described here. Either way, you'll have to give an exact path to your WAR file. Wildcards as in target/**.war won't work.

EDIT: Some people have reported problems uploading files using curl -T on Windows. If you face these problems, too, then this workaround might help you.

Body:
I'm learning jenkins and I've been having hard time with jenkins deploying to tomcat using parameters, especially jenkins running on windows machine.
The issue is pretty much the same as the one asked before on stackoverflow, but I don't see the answer as a match as it's so broad. The issue was explained here

I have tomcat users permissions set as bellow

<role rolename="tomcat"/>
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="manager" password="tomcat" roles="tomcat,manager-gui"/>
  <user username="jenkins" password="jenkins" roles="manager-script"/>

and I'm trying deploy using the following curl command on windows 10 with curl

curl -u %tcuser%:%tcpass% -F filedata=target/**.war "http://localhost:8080/manager/text/deploy?path=/devops&update=true"

I'm getting the following error in jenkins

C:\WINDOWS\system32\config\systemprofile\AppData\Local\Jenkins.[*******]\workspace\devops01>curl -u [*******]:[*******] -F filedata=target/**.war "http://localhost:8080/manager/text/deploy?path=/devops&update=true"
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100   908  100   752  100   156    752    156  0:00:01 --:--:--  0:00:01  7264
<!doctype html><title>HTTP Status 405 â€“ Method Not Allowed</title>
HTTP Status 405 â€“ Method Not Allowed

Type Status Report

Message HTTP method POST is not supported by this URL

Description The method received in the request-line is known by the origin server but not supported by the target resource.

Apache Tomcat/8.5.54

C:\WINDOWS\system32\config\systemprofile\AppData\Local\Jenkins.[*******]\workspace\devops01>exit 0

Can someone please help me ?

Body:
curl -F issues a POST request (see the manual page). The Tomcat Manager's deploy command, however, only accepts GET or PUT requests -- which is why you got the Method Not Allowed Error (HTTP Status 405).

If you want to deploy your webapp by remote upload, you have to run curl with the -T command line option, e.g.:

curl -u %tcuser%:%tcpass% -T devops.war "http://localhost:8080/manager/text/deploy?path=/devops&update=true"

This makes curl use the PUT method (instead of POST).

If you only want to deploy to localhost, you can also have Tomcat Manager deploy a WAR file from a local path as described here. Either way, you'll have to give an exact path to your WAR file. Wildcards as in target/**.war won't work.

EDIT: Some people have reported problems uploading files using curl -T on Windows. If you face these problems, too, then this workaround might help you.


问:
React Js map function gives an "not a function" error
I'm trying to map through objects to display their values in my React JS project. It looks like I can't access values of the objects within objects using the map function, values simply are not displayed, or if I try to use (.split("/p")) it gives me an error saying "split is not a function".

Link to codesandbox

this is my code:

```<code>import React from "react";
import { studies } from "./studies";

import "./styles.css";

const Data = ({ title, text, number, numberdesc }) => {
  return (
    <>
      <div style={{ margin: "1rem" }}>{title}</div>
      <div style={{ margin: "1rem" }}>{text}</div>
      <div>{number}</div>
      <div>{numberdesc}</div>
    </>
  );
};

function App() {
  const appComponent = studies.map((post, i) => {
    console.log(studies);
    return (
      <Data
        key={i}
        number={studies[i].post.number}
        title={studies[i].post.title}
        text={studies[i].post.text
          .split("/p")
          .reduce((total, line) => [total, <br />, <br />, line])}
      />
    );
  });
  return <>{appComponent}</>;
}

export default App;
</code>```

and {studies} file:

```<code>export const studies = [
  {
    id: "first",
    text: "1st Post",
    post: {
      data: [
        { number: "100", numberdesc: "description1" },
        { number: "200", numberdesc: "description2" },
        { number: "300", numberdesc: "description3" }
      ],

      text: [
        {
          title: "Title1 from the 1st post",
          text: "Text1 from the 1st post."
        },
        {
          title: "Title2 from the 1st post",
          text: "Text2 from the 1st post."
        },
        {
          title: "Title3 from the 1st post",
          text: "Text3 from the 1st post"
        }
      ]
    }
  },
  {
    id: "second",
    text: "2nd Post",
    post: {
      data: [
        { number: "100", numberdesc: "description1" },
        { number: "200", numberdesc: "description2" },
        { number: "300", numberdesc: "description3" }
      ],

      text: [
        {
          title: "Title1 from the 2nd post",
          text: "Text1 from the 2nd post "
        },
        {
          title: "Title2 from the 2nd post",
          text: "Text2 /p from the 2nd post"
        },
        {
          title: "Title3 from the 2nd post",
          text: "Text3 from the 2nd post"
        }
      ]
    }
  }
];

</code>```

What I want to do is to access data and text values for each post, and display them in my Project. Any help and suggestion is greatly appreciated,

Thank you.

答:
I think you may be wanting to .map your array of content. For example:

```<code>text={studies[i].post.text.map(t => <p><strong>{t.title}</strong>: {t.text}</p>)}
</code>```

might replace the existing line that is breaking.

Body:
I'm trying to map through objects to display their values in my React JS project. It looks like I can't access values of the objects within objects using the map function, values simply are not displayed, or if I try to use (.split("/p")) it gives me an error saying "split is not a function".

Link to codesandbox

this is my code:

import React from "react";
import { studies } from "./studies";

import "./styles.css";

const Data = ({ title, text, number, numberdesc }) => {
  return (
    <>

{title}

{text}

{number}

{numberdesc}

    </>
  );
};

function App() {
  const appComponent = studies.map((post, i) => {
    console.log(studies);
    return (
      <Data
        key={i}
        number={studies[i].post.number}
        title={studies[i].post.title}
        text={studies[i].post.text
          .split("/p")
          .reduce((total, line) => [total,
,
, line])}
      />
    );
  });
  return <>{appComponent}</>;
}

export default App;

and {studies} file:

export const studies = [
  {
    id: "first",
    text: "1st Post",
    post: {
      data: [
        { number: "100", numberdesc: "description1" },
        { number: "200", numberdesc: "description2" },
        { number: "300", numberdesc: "description3" }
      ],

      text: [
        {
          title: "Title1 from the 1st post",
          text: "Text1 from the 1st post."
        },
        {
          title: "Title2 from the 1st post",
          text: "Text2 from the 1st post."
        },
        {
          title: "Title3 from the 1st post",
          text: "Text3 from the 1st post"
        }
      ]
    }
  },
  {
    id: "second",
    text: "2nd Post",
    post: {
      data: [
        { number: "100", numberdesc: "description1" },
        { number: "200", numberdesc: "description2" },
        { number: "300", numberdesc: "description3" }
      ],

      text: [
        {
          title: "Title1 from the 2nd post",
          text: "Text1 from the 2nd post "
        },
        {
          title: "Title2 from the 2nd post",
          text: "Text2 /p from the 2nd post"
        },
        {
          title: "Title3 from the 2nd post",
          text: "Text3 from the 2nd post"
        }
      ]
    }
  }
];

What I want to do is to access data and text values for each post, and display them in my Project. Any help and suggestion is greatly appreciated,

Thank you.

Body:
I think you may be wanting to .map your array of content. For example:

text={studies[i].post.text.map(t => <p><strong>{t.title}</strong>: {t.text}</p>)}

might replace the existing line that is breaking.


问:
WebDAV - Microsoft Excel 2016 not able to save back changes
I have a set up the ITHit WebDAV server on our company website which works great on Office 2007/10/13 with PowerPoint, Word and Excel. However I have recently updated to Office 2016 and I have found that Excel no longer works, however Word and PowerPoint work OK.

In Excel I get the error message below:

In Word and PowerPoint I get the dialog below which I can skip:

Is there a known issue with the ITHit WebDAV server in Excel 2016?

There are no exceptions thrown when I'm attached in Visual Studio 2015. Also when I've checked Fiddler I can see the last thing the WebDAV server try to do is lock the document which is seems to do without any exceptions. It locked and unlocks the document twice then on the lock where I try to save it then comes back with the error message in Excel (see pic 1).

The lock requests are shown below:

First Lock OK:

Unlock:

locks the document and stops:

The only think I can see that is different is a field in the Miscellaneous section of the header:

I've exhausted all options and I've got no idea why this is happening with just excel in office 2016.

Any help would be greatly appreciated.

答:
I know this post is old, but for anyone who's having the same issue here's the solution:

This error is caused because Excel requests the file a second time if the user selects "Enable Editing".
If the Server sends the file again (with code 200) instead of returning a 304 (Not Modified) Office seems to believe that somebody has changed the document even if this is not the case.

One quick solution is to use the ETag header and validate the If-None-Match in future requests to know what to return, whether 304 or 200.


问:
Returning a list and getting to the items in Hedgehog state machine
I have a model for a state machine that is

```<code>newtype State (v :: * -> *) = State (M.Map (Var UUID v) DataPerItem)
    deriving (Eq, Show)
</code>```

I then have a Command gen exec [Update update] with exec returning a list of UUID, i.e. it has type

```<code>exec :: action -> m [UUID]
</code>```

which in turns mean that update needs a type like this

```<code>update :: State v -> action -> Var [UUID] v -> State V
</code>```

AFAICS I need to, in order to actually update my model, turn that Var [UUID] v into [Var UUID v]. I've been staring at the functions in Hedgehog for a while now but nothing jumps out... or am I, once again, thinking about it all wrong? :)

答:
This can't work, but there's a good reason why.

Think of state machine testing as automatic writing a test programs, where each Var a Symbolic as a binding in the program.

So imagine I was testing a little buffer, with operations create :: Size -> Buf, put :: Buf -> Int -> IO () and get :: Buf -> IO Int.

I could hand roll a unit test.

```<code>test :: TestT IO ()
test = do
  buf <- create 3
  put buf 5
  put buf 10
  put buf 20
  retrieved <- get buf
  retrieved === Just 5
</code>```

with appropriate commands, hedgehog could also generate this exact test as

```<code>test :: TestT IO ()
test = do
  Var 1 = create 3
  Var 2 = put (Var 1) 5
  Var 3 = put (Var 1) 10
  Var 4 = put (Var 1) 20
  Var 5 = get (Var 1)
  Var 5 === Just 5
</code>```

So each execution is given a variable name.

When you way you want something like this:

```<code>splitNames :: Var [UUID] v -> [Var UUID v]
</code>```

What you're asking for is essentially each return from the execution list to be given its own variable name. The rest of the program could then use those variable names. The best way I can think to show this is:

```<code>test :: TestT IO ()
test = do
  Var 1 = returnSomeNumberOfItems
  Var 2 = Var 1 ! 0
  Var 3 = Var 1 ! 1
</code>```

Now the issue here is that we just don't know how long the list returned by returnSomeNumberOfItems is; we haven't run it yet; there's no way to do this safely.

Body:
I have a model for a state machine that is

newtype State (v :: * -> *) = State (M.Map (Var UUID v) DataPerItem)
    deriving (Eq, Show)

I then have a Command gen exec [Update update] with exec returning a list of UUID, i.e. it has type

exec :: action -> m [UUID]

which in turns mean that update needs a type like this

update :: State v -> action -> Var [UUID] v -> State V

AFAICS I need to, in order to actually update my model, turn that Var [UUID] v into [Var UUID v]. I've been staring at the functions in Hedgehog for a while now but nothing jumps out... or am I, once again, thinking about it all wrong? :)

Body:
This can't work, but there's a good reason why.

Think of state machine testing as automatic writing a test programs, where each Var a Symbolic as a binding in the program.

So imagine I was testing a little buffer, with operations create :: Size -> Buf, put :: Buf -> Int -> IO () and get :: Buf -> IO Int.

I could hand roll a unit test.

test :: TestT IO ()
test = do
  buf <- create 3
  put buf 5
  put buf 10
  put buf 20
  retrieved <- get buf
  retrieved === Just 5

with appropriate commands, hedgehog could also generate this exact test as

test :: TestT IO ()
test = do
  Var 1 = create 3
  Var 2 = put (Var 1) 5
  Var 3 = put (Var 1) 10
  Var 4 = put (Var 1) 20
  Var 5 = get (Var 1)
  Var 5 === Just 5

So each execution is given a variable name.

When you way you want something like this:

splitNames :: Var [UUID] v -> [Var UUID v]

What you're asking for is essentially each return from the execution list to be given its own variable name. The rest of the program could then use those variable names. The best way I can think to show this is:

test :: TestT IO ()
test = do
  Var 1 = returnSomeNumberOfItems
  Var 2 = Var 1 ! 0
  Var 3 = Var 1 ! 1

Now the issue here is that we just don't know how long the list returned by returnSomeNumberOfItems is; we haven't run it yet; there's no way to do this safely.


问:
Is it ideal to put data inside a private class? (C++)
For example, I have this class:

```<code>struct bankingFunctionality
{
private:
    class bankingData
    {
    public:
        int phoneNum, citizenNum, age, ID;
        string name, address;
        bankingData* next = nullptr;
    };

public:
    void input(bankingData*);
    void firstUser();
    void update(bankingData*);
};
</code>```

Is it ideal to put the data class in private to "protect" data? Since the only way, I can think of how to access it for input and output is to have functions like void input(...) in public. However, every time I want to call input I would need to create a new object and waste memory.

答:
If you're using this as a way to pass in arguments it's really wasteful and you should consider the traditional getX() and setX() approach for accessors and mutators. You can make these easy to use in a chain style if you return *this at the end of each.

As in:

```<code>class bankingData {
  int phoneNum, citizenNum, age, ID;
  string name, address;
  bankingData* next = nullptr;

  int getPhoneNum() const { return phoneNum; };
  bankingData& setPhoneNum(int n) { phoneNum = n; return *this; };

  const std::string& getName() const { return name; };
  bankingData& setName(const std::string& n) { name = n; return *this; };
};
</code>```

Where you can then do:

```<code>bankingData bd;

bd.setPhoneNum(111).setName(...);
</code>```

Body:
For example, I have this class:

struct bankingFunctionality
{
private:
    class bankingData
    {
    public:
        int phoneNum, citizenNum, age, ID;
        string name, address;
        bankingData* next = nullptr;
    };

public:
    void input(bankingData*);
    void firstUser();
    void update(bankingData*);
};

Is it ideal to put the data class in private to "protect" data? Since the only way, I can think of how to access it for input and output is to have functions like void input(...) in public. However, every time I want to call input I would need to create a new object and waste memory.

Body:
If you're using this as a way to pass in arguments it's really wasteful and you should consider the traditional getX() and setX() approach for accessors and mutators. You can make these easy to use in a chain style if you return *this at the end of each.

As in:

class bankingData {
  int phoneNum, citizenNum, age, ID;
  string name, address;
  bankingData* next = nullptr;

  int getPhoneNum() const { return phoneNum; };
  bankingData& setPhoneNum(int n) { phoneNum = n; return *this; };

  const std::string& getName() const { return name; };
  bankingData& setName(const std::string& n) { name = n; return *this; };
};

Where you can then do:

bankingData bd;

bd.setPhoneNum(111).setName(...);


问:
metaclass do not call __prepare__ when use type function
recently I want to convert Enum class to django's ChoicesText enum class dynamicly use code like below::

class DT(Enum):
  STRING = 'string'
  INT = 'int'

data_type = type('DataType', (django.models.enums.ChoicesText,), {tag:tag.value for tag in DT})
```

<p>it raises <code>AttributeError</code>exception:</p>

```File "/usr/local/lib/python3.6/site-packages/django/db/models/enums.py", line 13, in __new__
    for key in classdict._member_names:
AttributeError: 'dict' object has no attribute '_member_names'
```

<p>when debug with a toy script, I found a tricky thing is that, when use <code>type</code> as a function to create type, it will not call <code>__prepare__</code> like <code>class</code> statement. as below:</p>

<pre class="lang-py prettyprint-override"><code># metaprepare.py
class Meta1(type):
    @classmethod
    def __prepare__(mcs, name, bases):
        print('call prepare')
        return {}

    def __new__(mcs, name, bases, parameters):
        return super().__new__(mcs, name, bases, parameters)

class A(metaclass=Meta1):
    pass

type('C', (A, ), {})

</code>```

execute this script only one call prepare print.

$python metaprepare.py
$call prepare
```

it is porpose behavior or a bug?

答:
Yes, it is intentional.  When using type() to create a new class you are giving it everything it needs:

the name of the new class

any classes to inherit from

the namespace to use as the class body

That last one is important: when using the class statement Python will call __prepare__ to get the namespace to use, but when using type you are giving Python the namespace to use -- so it doesn't need to call __prepare__.

As far as your original plan, try something like:

```<code>data_type = django.models.enums.ChoicesText(
        'DataType',
        {tag:tag.value for tag in DT},
        )
</code>```

Body:
recently I want to convert Enum class to django's ChoicesText enum class dynamicly use code like below::

class DT(Enum):
  STRING = 'string'
  INT = 'int'

data_type = type('DataType', (django.models.enums.ChoicesText,), {tag:tag.value for tag in DT})

it raises AttributeErrorexception:

File "/usr/local/lib/python3.6/site-packages/django/db/models/enums.py", line 13, in __new__
    for key in classdict._member_names:
AttributeError: 'dict' object has no attribute '_member_names'

when debug with a toy script, I found a tricky thing is that, when use type as a function to create type, it will not call __prepare__ like class statement. as below:

# metaprepare.py
class Meta1(type):
    @classmethod
    def __prepare__(mcs, name, bases):
        print('call prepare')
        return {}

    def __new__(mcs, name, bases, parameters):
        return super().__new__(mcs, name, bases, parameters)

class A(metaclass=Meta1):
    pass

type('C', (A, ), {})

execute this script only one call prepare print.

$python metaprepare.py
$call prepare

it is porpose behavior or a bug?

Body:
Yes, it is intentional.  When using type() to create a new class you are giving it everything it needs:

the name of the new class

any classes to inherit from

the namespace to use as the class body

That last one is important: when using the class statement Python will call __prepare__ to get the namespace to use, but when using type you are giving Python the namespace to use -- so it doesn't need to call __prepare__.

As far as your original plan, try something like:

data_type = django.models.enums.ChoicesText(
        'DataType',
        {tag:tag.value for tag in DT},
        )


问:
using $regex in mongodb aggregation framework in $group

Consider the following example:

db.article.aggregate(
  { $group : {
      _id : "$author",
      docsPerAuthor : { $sum : 1 },
      viewsPerAuthor : { $sum : "$pageViews" }
  }}
);
```

<p>This groups by the author field and computes two fields.</p>

<p>I have values for $author = FirstName_LastName.
Now instead of grouping by $author, I want to group by all authors who share the same LastName.</p>

<p>I tried $regex to group by all matching strings after the '_'</p>

<pre class="lang-js prettyprint-override"><code>$author.match(/_[a-zA-Z0-9]+$/)

db.article.aggregate(
  { $group : {
      _id : "$author".match(/_[a-zA-Z0-9]+$/),
      docsPerAuthor : { $sum : 1 },
      viewsPerAuthor : { $sum : "$pageViews" }
  }}
);

also tried the following:

 db.article.aggregate(
  { $group : {
      _id : {$author: {$regex: /_[a-zA-Z0-9]+$/}},
      docsPerAuthor : { $sum : 1 },
      viewsPerAuthor : { $sum : "$pageViews" }
  }}
);
</code>```

答:
$group combining $addFields and $arrayElemAt works for me (version ≥ 3.4).

Say we have following data in collection faculty, database school:

```<code>{ "_id" : ObjectId("5ed5a59b1febc4c796a88e80"), "name" : "Harry_Potter" }
{ "_id" : ObjectId("5ed5a60e1febc4c796a88e81"), "name" : "Edison_Potter" }
{ "_id" : ObjectId("5ed5a6231febc4c796a88e82"), "name" : "Jack_Potter" }
{ "_id" : ObjectId("5ed5a62f1febc4c796a88e83"), "name" : "Alice_Walker" }
{ "_id" : ObjectId("5ed5a65f1febc4c796a88e84"), "name" : "Bob_Walker" }
{ "_id" : ObjectId("5ed5a6731febc4c796a88e85"), "name" : "Will_Smith" }
</code>```

Following can group each document by the last name:

```<code>db.faculty.aggregate([
  {
    $addFields: {
      lastName: {
        $arrayElemAt: [ { $split: ["$name", "_"] }, 1 ]
      }
    }
  },
  {
    $group: {
      _id: "$lastName",
      count: {$sum: 1}
    }
  }
])
</code>```

Running result is:

```<code>{ "_id" : "Potter", "count" : 3 }
{ "_id" : "Walker", "count" : 2 }
{ "_id" : "Smith", "count" : 1 }
</code>```

The trick I used is to add a field named lastName. Based on what you have for the name field, it can be split into an array by _. Last name is at index 1 and first name at index 0.

Reference

$addFields (aggregation)

$arrayElemAt (aggregation)

Body:
Consider the following example:

db.article.aggregate(
  { $group : {
      _id : "$author",
      docsPerAuthor : { $sum : 1 },
      viewsPerAuthor : { $sum : "$pageViews" }
  }}
);

This groups by the author field and computes two fields.

I have values for $author = FirstName_LastName.
Now instead of grouping by $author, I want to group by all authors who share the same LastName.

I tried $regex to group by all matching strings after the '_'

$author.match(/_[a-zA-Z0-9]+$/)

db.article.aggregate(
  { $group : {
      _id : "$author".match(/_[a-zA-Z0-9]+$/),
      docsPerAuthor : { $sum : 1 },
      viewsPerAuthor : { $sum : "$pageViews" }
  }}
);

also tried the following:

 db.article.aggregate(
  { $group : {
      _id : {$author: {$regex: /_[a-zA-Z0-9]+$/}},
      docsPerAuthor : { $sum : 1 },
      viewsPerAuthor : { $sum : "$pageViews" }
  }}
);

Body:
$group combining $addFields and $arrayElemAt works for me (version ≥ 3.4).

Say we have following data in collection faculty, database school:

{ "_id" : ObjectId("5ed5a59b1febc4c796a88e80"), "name" : "Harry_Potter" }
{ "_id" : ObjectId("5ed5a60e1febc4c796a88e81"), "name" : "Edison_Potter" }
{ "_id" : ObjectId("5ed5a6231febc4c796a88e82"), "name" : "Jack_Potter" }
{ "_id" : ObjectId("5ed5a62f1febc4c796a88e83"), "name" : "Alice_Walker" }
{ "_id" : ObjectId("5ed5a65f1febc4c796a88e84"), "name" : "Bob_Walker" }
{ "_id" : ObjectId("5ed5a6731febc4c796a88e85"), "name" : "Will_Smith" }

Following can group each document by the last name:

db.faculty.aggregate([
  {
    $addFields: {
      lastName: {
        $arrayElemAt: [ { $split: ["$name", "_"] }, 1 ]
      }
    }
  },
  {
    $group: {
      _id: "$lastName",
      count: {$sum: 1}
    }
  }
])

Running result is:

{ "_id" : "Potter", "count" : 3 }
{ "_id" : "Walker", "count" : 2 }
{ "_id" : "Smith", "count" : 1 }

The trick I used is to add a field named lastName. Based on what you have for the name field, it can be split into an array by _. Last name is at index 1 and first name at index 0.

Reference

$addFields (aggregation)

$arrayElemAt (aggregation)


问:
Call function of every instance of a class
I am developing a small game and need some help. To check for collisions I created a class Block to create different shoes of obstacles. Now I plan to use the colliderect method of pygame to check for collision.

Is there a way to call a method not only for one class instance (e.g. block_1.check() but calling it for every instance of class Block? For example: Block.check() so it checks for block_1, block_2, ..., etc?

答:
Since you are using pygame, I would recommend that you make the block class a subclass of pygame's Sprite class (see here). Then you can use sprite Groups (see here) to simplify performing operations on the groups of sprite (like updating, drawing, collision checking as well as killing sprites).

Collision checking can be done with pygame.sprite.collide_rect() (see here), pygame.sprite.spritecollideany() (see here), or pygame.sprite.groupcollide() (see here)

You can also use the sprite groups as iterator in for loops:

```<code>for enemy in enemy_sprite_group:
    do stuff with enemy sprites
</code>```

That is not quite what you asked since it is not a way to 'Call function on every instance of a class' but it is in the spirit of what you were trying to do since you are really asking about which was collision detection on your game objects.

Body:
Since you are using pygame, I would recommend that you make the block class a subclass of pygame's Sprite class (see here). Then you can use sprite Groups (see here) to simplify performing operations on the groups of sprite (like updating, drawing, collision checking as well as killing sprites).

Collision checking can be done with pygame.sprite.collide_rect() (see here), pygame.sprite.spritecollideany() (see here), or pygame.sprite.groupcollide() (see here)

You can also use the sprite groups as iterator in for loops:

for enemy in enemy_sprite_group:
    do stuff with enemy sprites

That is not quite what you asked since it is not a way to 'Call function on every instance of a class' but it is in the spirit of what you were trying to do since you are really asking about which was collision detection on your game objects.


问:
Unable to import org module to PySpark cluster
I am trying to import FPGrowth from org module but it throws an error while installing the org module. I also tried replacing org.apache.spark to pyspark, still doesn't work.

```<code>!pip install org
import org.apache.spark.ml.fpm.FPGrowth
</code>```

below is the error:

```<code>ERROR: Could not find a version that satisfies the requirement org (from versions: none)
ERROR: No matching distribution found for org
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-12-c730562e7076> in <module>
      1 get_ipython().system('pip install org')
----> 2 import org.apache.spark.ml.fpm.FPGrowth

ModuleNotFoundError: No module named 'org'
</code>```

答:
To import FPGrowth in PySpark you need to write:

```<code>from pyspark.ml.fpm import FPGrowth
</code>```

You can find additional instructions on how to use FPGrowth in Spark documentation.

Body:
I am trying to import FPGrowth from org module but it throws an error while installing the org module. I also tried replacing org.apache.spark to pyspark, still doesn't work.

!pip install org
import org.apache.spark.ml.fpm.FPGrowth

below is the error:

ERROR: Could not find a version that satisfies the requirement org (from versions: none)
ERROR: No matching distribution found for org
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-12-c730562e7076> in <module>
      1 get_ipython().system('pip install org')
----> 2 import org.apache.spark.ml.fpm.FPGrowth

ModuleNotFoundError: No module named 'org'

Body:
To import FPGrowth in PySpark you need to write:

from pyspark.ml.fpm import FPGrowth

You can find additional instructions on how to use FPGrowth in Spark documentation.


问:
PHP variable in Javascript
Consider this simple example;

```<code><?php $text = test; ?>

<script type="text/javascript" defer="defer">

var test;

test = "<?php echo $text; ?>"

$(document).ready(function(){
alert(test);
});

</script>
</code>```

This works fine. Creating the alert with the text from the php var. However, if I place;

```<code><?php $text = test; ?>
</code>```

below the script - it does not work. I've tried the defer function. What am I doing wrong?

Cheers

答:
If you place

```<code>  <?php $text = "test"; ?>
</code>```

below the JS code, the the variable $text is not defined yet, so you cannot echo it earlier (edit) in the script.

Title: PHP variable in Javascript

Body:
Consider this simple example;

<?php $text = test; ?>

This works fine. Creating the alert with the text from the php var. However, if I place;

<?php $text = test; ?>

below the script - it does not work. I've tried the defer function. What am I doing wrong?

Cheers

Body:
If you place

  <?php $text = "test"; ?>

below the JS code, the the variable $text is not defined yet, so you cannot echo it earlier (edit) in the script.


问:
Nginx Ingress: service "ingress-nginx-controller-admission" not found
We created a kubernetes cluster for a customer about one year ago with two environments; staging and production separated in namespaces. We are currently developing the next version of the application and need an environment for this development work, so we've created a beta environment in its own namespace.

This is a bare metal kubernetes cluster with MetalLB and and nginx-ingress. The nginx ingress controllers is installed with helm and the ingresses are created with the following manifest (namespaces are enforced by our deployment pipeline and are not visible in the manifest):

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: api-ingress
  annotations:
    #ingress.kubernetes.io/ssl-redirect: "true"
    #kubernetes.io/tls-acme: "true"
    #certmanager.k8s.io/issuer: "letsencrypt-staging"
    #certmanager.k8s.io/acme-challenge-type: http01
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/configuration-snippet: |
      more_set_headers "X-Robots-Tag: noindex, nofollow";
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-methods: "GET, OPTIONS"
    nginx.ingress.kubernetes.io/cors-allow-origin: "*"
    nginx.ingress.kubernetes.io/cors-allow-credentials: "true"
spec:
  tls:
    - hosts:
        - ${API_DOMAIN}
      secretName: api-cert
  rules:
    - host: ${API_DOMAIN}
      http:
        paths:
          - backend:
              serviceName: api
              servicePort: 80
</code>```

When applying the manifest kubernetes responds with the following error:

Error from server (InternalError): error when creating "STDIN": Internal error occurred: failed calling webhook "validate.nginx.ingress.kubernetes.io": Post https://ingress-nginx-controller-admission.ingress-nginx.svc:443/extensions/v1beta1/ingresses?timeout=30s: service "ingress-nginx-controller-admission" not found

I've attempted to update the apiVersion of the ingress manifest to networking.k8s.io/v1beta1 (this is the apiVersion the new nginx-ingress controllers are installed with via helm), but I'm getting the same error.

My initial suspicion is that this is related to a change in the nginx-ingress between the current installation and the installation from one year ago, even if the ingress controllers are separated by namespaces. But i cant find any services called ingress-nginx-controller-admission in any of my namespaces, so I'm clueless how to proceed.

答:
There is some issue with SSL cert it seems in the webhook.

Chaning failurePolicy: Fail to Ignore worked for me in the

kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-0.32.0/deploy/static/provider/baremetal/deploy.yaml

for more info check:

https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/

Body:
We created a kubernetes cluster for a customer about one year ago with two environments; staging and production separated in namespaces. We are currently developing the next version of the application and need an environment for this development work, so we've created a beta environment in its own namespace.

This is a bare metal kubernetes cluster with MetalLB and and nginx-ingress. The nginx ingress controllers is installed with helm and the ingresses are created with the following manifest (namespaces are enforced by our deployment pipeline and are not visible in the manifest):

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: api-ingress
  annotations:
    #ingress.kubernetes.io/ssl-redirect: "true"
    #kubernetes.io/tls-acme: "true"
    #certmanager.k8s.io/issuer: "letsencrypt-staging"
    #certmanager.k8s.io/acme-challenge-type: http01
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/configuration-snippet: |
      more_set_headers "X-Robots-Tag: noindex, nofollow";
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-methods: "GET, OPTIONS"
    nginx.ingress.kubernetes.io/cors-allow-origin: "*"
    nginx.ingress.kubernetes.io/cors-allow-credentials: "true"
spec:
  tls:
    - hosts:
        - ${API_DOMAIN}
      secretName: api-cert
  rules:
    - host: ${API_DOMAIN}
      http:
        paths:
          - backend:
              serviceName: api
              servicePort: 80

When applying the manifest kubernetes responds with the following error:

Error from server (InternalError): error when creating "STDIN": Internal error occurred: failed calling webhook "validate.nginx.ingress.kubernetes.io": Post https://ingress-nginx-controller-admission.ingress-nginx.svc:443/extensions/v1beta1/ingresses?timeout=30s: service "ingress-nginx-controller-admission" not found

I've attempted to update the apiVersion of the ingress manifest to networking.k8s.io/v1beta1 (this is the apiVersion the new nginx-ingress controllers are installed with via helm), but I'm getting the same error.

My initial suspicion is that this is related to a change in the nginx-ingress between the current installation and the installation from one year ago, even if the ingress controllers are separated by namespaces. But i cant find any services called ingress-nginx-controller-admission in any of my namespaces, so I'm clueless how to proceed.