Title: How do I select and print the : values and , values

Body:
How do I select and print the   :  separated values and the, separated values in pandas. Example, I want, from ( Fridge:200:1,1,1,...1) the 200 values to be printed separately and the printed sum of the 1s after the final : from the"

Fridge:200:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
Washer:500:0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0
Oven:2150:0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0
Microwave:1000:0,0,0,0,0,0,0,0,0.5,0,0,0,0,0,0,0,0,0.5,0,0,0.5,0,0,0
Aircon:2000:0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0
TV:60:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
TV:60:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
TV:60:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
Console:140:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
Console:140:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1

Body:
IIUC, This might help you:

'''
Fridge:200:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
Washer:500:0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0
Oven:2150:0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0
Microwave:1000:0,0,0,0,0,0,0,0,0.5,0,0,0,0,0,0,0,0,0.5,0,0,0.5,0,0,0
Aircon:2000:0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0
TV:60:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
TV:60:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
TV:60:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
Console:140:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
Console:140:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
'''

import pandas as pd

# for your case, if you are reading the data from csv,
# use the separator as ":" just like below
df = pd.read_clipboard(sep=":", header=None)

df[3]=df[2].str.split(',',expand=True).astype(float).sum(axis=1)

print(df)

Output:

           0     1                                                  2     3
0     Fridge   200    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1  24.0
1     Washer   500    0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0   3.0
2       Oven  2150    0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0   2.0
3  Microwave  1000  0,0,0,0,0,0,0,0,0.5,0,0,0,0,0,0,0,0,0.5,0,0,0....   1.5
4     Aircon  2000    0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0  12.0
5         TV    60    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1  24.0
6         TV    60    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1  24.0
7         TV    60    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1  24.0
8    Console   140    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1  24.0
9    Console   140    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1  24.0


来源: stackexchange

问:
How can hackers abuse javascript's eval() for cross-site attacks?
I am setting up a website that lets users solve coding puzzles/assignments. I have a reactJS component set up so that it accepts user inputted javascript and it seems to work. However, I have read the following:

"Eval makes hacking easier. Injection hacks can be a problem, particularly with cross-site attacks)."

Just to be clear: I am evalling the inserted JS clientside, to ensure that no code can mess with my server.

So how then can a user cause any harm? What's there to 'hack'? if a user is only executing JS clientside then any malicious actions will be executed in the context of his or her pc and browser window right? And that person is able to do that in the first place.

Thanks in advance!

答:
You are assuming that any code processed by the client originates from the client in the form on strings entered into input fields and that may not be the case.

The primary reason why eval() and innerHTML are security risks is because the strings that you pass to them may be sent to the client from a non-verified source.

Of course, if you are going to always be the one providing the input string to eval() then there is (one would think) no danger, but all JavaScript code in a web page is client-side code and that client-side code is always part of an HTTP Request/Response conversation. It's the response that we're concerned about here.

ContentLicense: CC BY-SA 4.0


问:
assignment operator overloading in c++
I have used the following code for assignment operator overloading:

```<code>SimpleCircle SimpleCircle::operator=(const SimpleCircle & rhs)
{
     if(this == &rhs)
        return *this;
     itsRadius = rhs.getRadius();
     return *this;
}
</code>```

My Copy Constructor is this:

```<code>SimpleCircle::SimpleCircle(const SimpleCircle & rhs)
{
    itsRadius = rhs.getRadius();
}
</code>```

In the above operator overloading code, copy constructor is called as there is a new object is being created; hence I used the below code:

```<code>SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    if(this == &rhs)
       return *this;
    itsRadius = rhs.getRadius();
    return *this;
}
</code>```

Its working perfectly and the copy constructor problem is avoided, but is there any unknown issues (to me) regarding this ?

答:
```<code>#include<iostream>

using namespace std;

class employee
{
    int idnum;
    double salary;
    public:
        employee(){}

        employee(int a,int b)
        {
            idnum=a;
            salary=b;
        }

        void dis()
        {
            cout<<"1st emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl<<endl;
        }

        void operator=(employee &emp)
        {
            idnum=emp.idnum;
            salary=emp.salary;
        }

        void show()
        {
            cout<<"2nd emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl;
        }
};

main()
{
    int a;
    double b;

    cout<<"enter id num and salary"<<endl;
    cin>>a>>b;
    employee e1(a,b);
    e1.dis();
    employee e2;
    e2=e1;
    e2.show();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: assignment operator overloading in c++

Body:
I have used the following code for assignment operator overloading:

SimpleCircle SimpleCircle::operator=(const SimpleCircle & rhs)
{
     if(this == &rhs)
        return *this;
     itsRadius = rhs.getRadius();
     return *this;
}

My Copy Constructor is this:

SimpleCircle::SimpleCircle(const SimpleCircle & rhs)
{
    itsRadius = rhs.getRadius();
}

In the above operator overloading code, copy constructor is called as there is a new object is being created; hence I used the below code:

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    if(this == &rhs)
       return *this;
    itsRadius = rhs.getRadius();
    return *this;
}

Its working perfectly and the copy constructor problem is avoided, but is there any unknown issues (to me) regarding this ?


问:
C++ const char with .begin() and .end()
So I have a program that looks something like this:

```<code>const char *Argv[] = {"stuff", "stuff1", "stuff3"};

bool pass = xxxxx::yyyyy(Argv.begin(), Argv.end(), Tri);
</code>```

I think this is illegal because const char * is not a user-defined type. However, I am not sure how to fix this. Would I need to change the first line or the second? Or both?

答:
Just for completeness, and to show the c++ way, you could change the first line to:

```<code>std::array<std::string_view, 3> Argv {"stuff", "stuff1", "stuff3"};
</code>```

and then the second line:

```<code>bool pass = xxxxx::yyyyy(Argv.begin(), Argv.end(), Tri);
</code>```

will work just fine.

Title: C++ const char with .begin() and .end()

Body:
So I have a program that looks something like this:

const char *Argv[] = {"stuff", "stuff1", "stuff3"};

bool pass = xxxxx::yyyyy(Argv.begin(), Argv.end(), Tri);

I think this is illegal because const char * is not a user-defined type. However, I am not sure how to fix this. Would I need to change the first line or the second? Or both?

Body:
Just for completeness, and to show the c++ way, you could change the first line to:

std::array<std::string_view, 3> Argv {"stuff", "stuff1", "stuff3"};

and then the second line:

bool pass = xxxxx::yyyyy(Argv.begin(), Argv.end(), Tri);

will work just fine.


问:
DLL load failed: The specified module could not be found when doing "from mpi4py import MPI"
I am trying to use Mpi4py 1.3 with python 2.7 on Windows 7 64bits. I downloaded the installable version from here which includes OpenMPI 1.6.3 so in the installed directory (*/Python27\Lib\site-packages\mpi4py\lib) following libraries exist: libmpi.lib, libmpi_cxx.lib, libopen-pal.lib, and libopen-rte.lib. Now in my codes when trying to import it:

```<code>from mpi4py import MPI
</code>```

It returns following error:

ImportError: DLL load failed: The specified module could not be found.

I tried to copy a bove lib files alongside the */Python27\Lib\site-packages\mpi4py\MPI.pyd and even to Windows/System32, but it didn't work. I appreciate your help on what DLL is missing and how to fix the  error?

答:
I tried the following and it worked.

Uninstalling OpenMPI

Uninstalling mpi4py

Installing Microsoft MPI

Re-installing mpi4py with pip so that a wheel gets installed

Source: https://groups.google.com/d/msg/mpi4py/VA7Aihi64R0/jnxAT2HtCgAJ

Body:
I am trying to use Mpi4py 1.3 with python 2.7 on Windows 7 64bits. I downloaded the installable version from here which includes OpenMPI 1.6.3 so in the installed directory (*/Python27\Lib\site-packages\mpi4py\lib) following libraries exist: libmpi.lib, libmpi_cxx.lib, libopen-pal.lib, and libopen-rte.lib. Now in my codes when trying to import it:

from mpi4py import MPI

It returns following error:

ImportError: DLL load failed: The specified module could not be found.

I tried to copy a bove lib files alongside the */Python27\Lib\site-packages\mpi4py\MPI.pyd and even to Windows/System32, but it didn't work. I appreciate your help on what DLL is missing and how to fix the  error?


问:
Does Embarcadero RAD Studio XE license allow use on multiple machines?
In the past the Borland "no nonsense" license allowed one developer to do multiple installs.

I'm tempted to upgrade to Embarcadero RAD Studio XE, professional edition, but am worried about licensing restrictions, and whether it will allow me to work in the same way as before.

I downloaded a 30 day trial, and that will only allow one install, so I'm a bit concerned the upgrade would enforce a similar restriction.

I use a small and a large laptop and a PC and would like to install RAD Studio on all 3, as well as in VMs. I've posted a question asking about this on the vendor website, but there's no response yet, and I wonder if people could answer from their own experience please?

I'd also be interested to know if the upgrade will only run if there is an existing installation of an earlier product on the same machine.

答:
Yes, you can legally install Rad Studio on more than one machine, as long as you are the only user.  I'm specifically talking about the named user license.

Check the section titled "Installing the product on multiple machines" here.


问:
django urls.py: two modules with similar paths
I have two modules in my django app, let's say cats and dogs, and I want to have urls like this:

/fluffy/meow.html  - Fluffy is a cat's name

/fluffy/eat.html

/jackie/bark.html  - Jackie is a dog

/jackie/eat.html   - same name as in cats module

There will be a lot of different cats and dogs, but it's guaranteed, that cat and dog can't have the same name.

If I make urls.py like this:

urlpatterns += [
    path('<slug:cat_name>/', include('cats.urls')),
    path('<slug:dog_name>/', include('dogs.urls')),
]
```

<p>request <code>/jackie/eat.html</code> wil be caught by <code>cats</code>
module, but there's no cat with name jackie, so it will give 404 error. Is it possible to make django check another url path instead of getting 404 error? </p>

<hr>

<p>I know, that I can use this <code>urls.py</code></p>

<pre class="lang-py prettyprint-override"><code>urlpatterns += [
    path('cats/<slug:cat_name>/', include('cats.urls')),
    path('dogs/<slug:dog_name>/', include('dogs.urls')),
]
</code>```

But I don't want it

there's about 1000 cats' names, and it's not frequently changing, so i can hardcode cat's names in huge re_path, but I hope that there's a better solution

```<code>urlpatterns += [
    re_path(r'^(?P<cat_name>fluffy|simon|thomas|etc..)/$', include('cats.urls')),
    path('<slug:dog_name>/', include('dogs.urls')),
]
</code>```

答:
No. Change your logic instead of hard cording urls and searching in Urls.
First categorized your cats and dogs urls then search in db to show them into urls. </p>

Body:
I have two modules in my django app, let's say cats and dogs, and I want to have urls like this:

/fluffy/meow.html  - Fluffy is a cat's name

/fluffy/eat.html

/jackie/bark.html  - Jackie is a dog

/jackie/eat.html   - same name as in cats module

There will be a lot of different cats and dogs, but it's guaranteed, that cat and dog can't have the same name.

If I make urls.py like this:

urlpatterns += [
    path('<slug:cat_name>/', include('cats.urls')),
    path('<slug:dog_name>/', include('dogs.urls')),
]

request /jackie/eat.html wil be caught by cats
module, but there's no cat with name jackie, so it will give 404 error. Is it possible to make django check another url path instead of getting 404 error?

I know, that I can use this urls.py

urlpatterns += [
    path('cats/<slug:cat_name>/', include('cats.urls')),
    path('dogs/<slug:dog_name>/', include('dogs.urls')),
]

But I don't want it

there's about 1000 cats' names, and it's not frequently changing, so i can hardcode cat's names in huge re_path, but I hope that there's a better solution

urlpatterns += [
    re_path(r'^(?P<cat_name>fluffy|simon|thomas|etc..)/$', include('cats.urls')),
    path('<slug:dog_name>/', include('dogs.urls')),
]


问:
How to Assign a TBitmap to a TPath.Data
I would like to fill a TPath.Data from a TBitmap.

Delphi FMX provides a FillPath on a Bitmap Canvas:-
http://docwiki.embarcadero.com/CodeExamples/Rio/en/FMXTCanvasFillFunctions_(Delphi)

Image1.Bitmap.Canvas.FillPath(path, 200);

But I'm looking fill the Path Data from the Bitmap.

Any code examples?
tia

答:
You mean how do you fill an enclosed TPath with a bitmap instead of a solid color. You change the Fill property to a Bitmap:</p>

```<code>path1.Fill.Bitmap:=mybitmap;
path1.Fill.Kind:=TBrushKind.Bitmap;
</code>```

Title: How to Assign a TBitmap to a TPath.Data

Body:
You mean how do you fill an enclosed TPath with a bitmap instead of a solid color. You change the Fill property to a Bitmap:

path1.Fill.Bitmap:=mybitmap;
path1.Fill.Kind:=TBrushKind.Bitmap;


问:
Entity class defines non-transient non-serializable instance field price
Below little bit of code showing SONAR bug like :Class com.sample.Submit defines non-transient non-serializable instance field price. How can we get rid from this issue.

Code

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class Submit implements Serializable {

    /**
     * serialVersionUID of type long.
     */
    private static final long serialVersionUID = 0L;

    @JsonProperty("billCode")
    private String billCode;

    @JsonProperty("displayName")
    private String displayName;

    @JsonProperty("visible")
    private Boolean visible;

    @JsonProperty("price")
    private Price price;

    public Boolean getVisible() {
        return visible;
    }

    public void setVisible(Boolean visible) {
        this.visible = visible;
    }

    public String getBillCode() {
        return billCode;
    }

    public void setBillCode(String billCode) {
        this.billCode = billCode;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public Price getPrice() {
        return price;
    }

    public void setPrice(Price price) {
        this.price = price;
    }

}
</code>```

答:
If you actually need the class to be serializable, then every one of its instance members, like Price, needs to be serializable as well.

Consider if you actually need this Submit class to be serializable though. If you are not doing anything that requires storing this or copying it across a network (like putting it in the HTTP session, or saving it on a file system, or putting it in a queue), you may not need the class to be serializable at all, in which the best course to take is to delete the implements Serializable from the Submit class.

(Be aware that making the class serializable has nothing to do with using it to generate JSON.)

Body:
Below little bit of code showing SONAR bug like :Class com.sample.Submit defines non-transient non-serializable instance field price. How can we get rid from this issue.

Code

@JsonIgnoreProperties(ignoreUnknown = true)
public class Submit implements Serializable {

    /**
     * serialVersionUID of type long.
     */
    private static final long serialVersionUID = 0L;

    @JsonProperty("billCode")
    private String billCode;

    @JsonProperty("displayName")
    private String displayName;

    @JsonProperty("visible")
    private Boolean visible;

    @JsonProperty("price")
    private Price price;

    public Boolean getVisible() {
        return visible;
    }

    public void setVisible(Boolean visible) {
        this.visible = visible;
    }

    public String getBillCode() {
        return billCode;
    }

    public void setBillCode(String billCode) {
        this.billCode = billCode;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public Price getPrice() {
        return price;
    }

    public void setPrice(Price price) {
        this.price = price;
    }

}


问:
Printing only when it is not an empty string
Assume that

```<code>type house = {first_name: string; last_name: string; nb_windows: int; nb_doors: int; nb_cars: int; nb_rooms: int};;
house1 = {first_name="John"; last_name="Doe; nb_windows = 10; nb_doors = 50; nb_cars = 3; nb_rooms= 10};;
</code>```

I want to print each element of record house1.

```<code>Full Name : John Doe
Number of windows : 10
Number of doors : 50
Number of cars : 3
Number of rooms : 10
</code>```

A way I have define the function is

```<code>let test (lch: house) =
    begin
      print_string ("Full Name : " ^ lch.first_name ^ " " ^ lch.last_name "\n");
      print_string ("Number of windows : " ^ string_of_int lch.nb_windows ^ "\n");
      print_string ("Number of doors : " ^ string_of_int lch.nb_doors ^ "\n");
      print_string ("Number of car : " ^ string_of_int lch.nb_cars ^ "\n");
      print_string ("Number of rooms : " ^ string_of_int lch.nb_rooms ^ "\n\n");
    end;;

test house1;;
</code>```

However, that function is very limited. For instance, if I define

```<code>house2 = {first_name=""; last_name="" nb_windows=10; nb_doors = 50; nb_cars = 3; nb_rooms= 10}
</code>```

In that example, I don't want to print Full Name if first_name and last_name are emptied strings.

How can I modify the test function so that the line test house2;; will display only

```<code>Number of windows : 10
Number of doors : 50
Number of cars : 3
Number of rooms : 10
</code>```

instead of

```<code>Full Name :
Number of windows : 10
Number of doors : 50
Number of cars : 3
Number of rooms : 10
</code>```

Be aware that I have to use only the functional paradigm, so no while or for loops.

Beginning of an answer

I think I can use something like

```<code>let print_data x y = match x with
      | "" -> ()
      | x -> print_string y;;
</code>```

but I don't know how to move on

答:
Your function print_data tests one string to determine whether to print another string. You can use this function if you pass lch.first_name ^ lch.last_name as the test string, and your desired output string as the second string.

Specifically, replace this line:

```<code>  print_string ("Full Name : " ^ lch.first_name ^ " " ^ lch.last_name "\n");
</code>```

With this instead:

```<code>print_data (lch.first_name ^ lch.last_name)
    ("Full Name : " ^ lch.first_name ^ " " ^ lch.last_name "\n");
</code>```

For what it's worth, this is just programming and doesn't have much to do with OCaml in particular (IMHO).

As some unsolicited advice: if your problem is that you can't look at print_data and figure out how it works, the thing to do is to go through an OCaml tutorial or two until you can understand the language more easily. This will be faster than asking individual questions here on StackOverflow.

Update

Here's a function that formats only the non-null strings that it is given:

```<code>let concat_non_null strings =
    String.concat " " (List.filter ((<>) "") strings)
</code>```

To print the name:

```<code>match concat_non_null [lch.first_name; lch.last_name] with
| "" -> ()
| s -> print_endline ("Full_name: " ^ s)
</code>```

You could argue that this generalizes fairly well to more names--when there's also a middle name, say.

Body:
Assume that

type house = {first_name: string; last_name: string; nb_windows: int; nb_doors: int; nb_cars: int; nb_rooms: int};;
house1 = {first_name="John"; last_name="Doe; nb_windows = 10; nb_doors = 50; nb_cars = 3; nb_rooms= 10};;

I want to print each element of record house1.

Full Name : John Doe
Number of windows : 10
Number of doors : 50
Number of cars : 3
Number of rooms : 10

A way I have define the function is

let test (lch: house) =
    begin
      print_string ("Full Name : " ^ lch.first_name ^ " " ^ lch.last_name "\n");
      print_string ("Number of windows : " ^ string_of_int lch.nb_windows ^ "\n");
      print_string ("Number of doors : " ^ string_of_int lch.nb_doors ^ "\n");
      print_string ("Number of car : " ^ string_of_int lch.nb_cars ^ "\n");
      print_string ("Number of rooms : " ^ string_of_int lch.nb_rooms ^ "\n\n");
    end;;

test house1;;

However, that function is very limited. For instance, if I define

house2 = {first_name=""; last_name="" nb_windows=10; nb_doors = 50; nb_cars = 3; nb_rooms= 10}

In that example, I don't want to print Full Name if first_name and last_name are emptied strings.

How can I modify the test function so that the line test house2;; will display only

Number of windows : 10
Number of doors : 50
Number of cars : 3
Number of rooms : 10

instead of

Full Name :
Number of windows : 10
Number of doors : 50
Number of cars : 3
Number of rooms : 10

Be aware that I have to use only the functional paradigm, so no while or for loops.

Beginning of an answer

I think I can use something like

let print_data x y = match x with
      | "" -> ()
      | x -> print_string y;;

but I don't know how to move on

Body:
Your function print_data tests one string to determine whether to print another string. You can use this function if you pass lch.first_name ^ lch.last_name as the test string, and your desired output string as the second string.

Specifically, replace this line:

  print_string ("Full Name : " ^ lch.first_name ^ " " ^ lch.last_name "\n");

With this instead:

print_data (lch.first_name ^ lch.last_name)
    ("Full Name : " ^ lch.first_name ^ " " ^ lch.last_name "\n");

For what it's worth, this is just programming and doesn't have much to do with OCaml in particular (IMHO).

As some unsolicited advice: if your problem is that you can't look at print_data and figure out how it works, the thing to do is to go through an OCaml tutorial or two until you can understand the language more easily. This will be faster than asking individual questions here on StackOverflow.

Update

Here's a function that formats only the non-null strings that it is given:

let concat_non_null strings =
    String.concat " " (List.filter ((<>) "") strings)

To print the name:

match concat_non_null [lch.first_name; lch.last_name] with
| "" -> ()
| s -> print_endline ("Full_name: " ^ s)

You could argue that this generalizes fairly well to more names--when there's also a middle name, say.


问:
Unable to create DI for retrofit with Koin, android?
I am trying to have DI for creating a retrofit instance with KOIN
this is the module

```<code>val networkModule = module {
factory { provideRetrofit(get()) }
single { provideNetworkApi(get()) }
}

fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
    .baseUrl(NetworkConstant.BASE_URL)
    .addConverterFactory(MoshiConverterFactory.create())
    .client(OkHttpClient.Builder().build())
    .build()

}

fun provideNetworkApi(retrofit: Retrofit): NetworkCall =
retrofit.create(NetworkCall::class.java)
</code>```

In the application class

```<code>class BaseApp :Application() {

override fun onCreate() {
    super.onCreate()
    startKoin {
        androidLogger()
        androidContext(this@BaseApp)
        modules(listOf(prefModule,networkModule))
    }
}
}
</code>```

The compiler is showing error on provideRetrofit(get()

```<code>Too many arguments for public fun provideRetrofit():
</code>```

I was able to create DI for another class

```<code>val prefModule = module {
single { AppPreference(androidContext()) }
}
</code>```

Can someone point me whats wrong here?

答:
Would it be acceptable skip separation of Retrofit instance (what's benefit?) and simply combine it in the goal of creating your NetworkCall?

Here is an example of what I mean:

```<code>val appModule = module {
    single {
        val httpInterceptor = HttpLoggingInterceptor()
        httpInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)

        Retrofit.Builder()
            .client(
                OkHttpClient.Builder()
                    .addInterceptor(httpInterceptor).build()
            )
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("https://postman-echo.com/")
            .build()
            .create(PostmanEcho::class.java)
    }

    single {
        PostmanEchoRepository(get(), get())
    }
....
</code>```

My PostmanEchoRepository is using equivalent of your NetworkCall as first param.

Details: https://github.com/oradkovsky/weird-data-input/blob/master/app/src/main/java/com/ror/weirddatainput/di/AppModule.kt

Body:
I am trying to have DI for creating a retrofit instance with KOIN
this is the module

val networkModule = module {
factory { provideRetrofit(get()) }
single { provideNetworkApi(get()) }
}

fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
    .baseUrl(NetworkConstant.BASE_URL)
    .addConverterFactory(MoshiConverterFactory.create())
    .client(OkHttpClient.Builder().build())
    .build()

}

fun provideNetworkApi(retrofit: Retrofit): NetworkCall =
retrofit.create(NetworkCall::class.java)

In the application class

class BaseApp :Application() {

override fun onCreate() {
    super.onCreate()
    startKoin {
        androidLogger()
        androidContext(this@BaseApp)
        modules(listOf(prefModule,networkModule))
    }
}
}

The compiler is showing error on provideRetrofit(get()

Too many arguments for public fun provideRetrofit():

I was able to create DI for another class

val prefModule = module {
single { AppPreference(androidContext()) }
}

Can someone point me whats wrong here?

Body:
Would it be acceptable skip separation of Retrofit instance (what's benefit?) and simply combine it in the goal of creating your NetworkCall?

Here is an example of what I mean:

val appModule = module {
    single {
        val httpInterceptor = HttpLoggingInterceptor()
        httpInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)

        Retrofit.Builder()
            .client(
                OkHttpClient.Builder()
                    .addInterceptor(httpInterceptor).build()
            )
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("https://postman-echo.com/")
            .build()
            .create(PostmanEcho::class.java)
    }

    single {
        PostmanEchoRepository(get(), get())
    }
....

My PostmanEchoRepository is using equivalent of your NetworkCall as first param.

Details: https://github.com/oradkovsky/weird-data-input/blob/master/app/src/main/java/com/ror/weirddatainput/di/AppModule.kt


问:
A way to backup data(databases, collections, documents) in mongodb
do you know any tool to backup data in mongodb? Like mysqldump in mongodb

thank you in advance!

答: Take a look also into this one my questions about how to do daily backups and restore data from backup.</p>


问:
Proportion request sql
There is a table of accidents and output the share of accidents number 2 to all accidents I wrote this code, but I can not make it work:

```<code>select ((select count("ID") from "DTP" where "REASON"=2)/count("REASON"))
from "DTP"
group by "ID"
</code>```

答:
Something like this (not tested):

```<code>select id, count(case reason when 2 then 1 end)/count(*) as proportion
from   your_table
--     where  ...  (if you need to filter, for example by date)
group  by id
;
</code>```

count(*) counts all the rows in a group (that is, all the rows for each separate id). The case expression returns 1 when the reason is 2 and it returns null otherwise; count counts only non-null values, so it will count the rows where the reason is 2.

Title: Proportion request sql

Body:
There is a table of accidents and output the share of accidents number 2 to all accidents I wrote this code, but I can not make it work:

select ((select count("ID") from "DTP" where "REASON"=2)/count("REASON"))
from "DTP"
group by "ID"

Body:
Something like this (not tested):

select id, count(case reason when 2 then 1 end)/count(*) as proportion
from   your_table
--     where  ...  (if you need to filter, for example by date)
group  by id
;

count(*) counts all the rows in a group (that is, all the rows for each separate id). The case expression returns 1 when the reason is 2 and it returns null otherwise; count counts only non-null values, so it will count the rows where the reason is 2.


问:
How to exit an async method early that wraps an awaitable method?
My class is wrapping TcpListener and I'm trying to update it to use modern async language.

It throws up the question what to do if a method should exit early. If this is the old code:

```<code>    public void Connect()
    {
        if (tcp != null)
          tcp.Connect(config.IPAddress, config.Port);
    }
</code>```

Then I start with something like this:

```<code>    public Task ConnectAsync()
    {
        if (tcp != null)
          { ???? }
        return tcp.ConnectAsync(config.IPAddress, config.Port);
    }
</code>```

But in the condition tcp==null what should I return? Is there some "null awaitable"?

I also am unsure if my method should be designated async or not in this case where I am wrapping another method - I am sure I do not want to await the called method. This compiles but I do not think it is right:

```<code>    public async Task ConnectAsync()
    {
        if (tcp != null)
            return;

        await tcp.ConnectAsync(config.IPAddress, config.Port);
    }
</code>```

答:
You can return a completed task:

```<code>public Task ConnectAsync()
{
    if (tcp == null)
    {
        return Task.CompletedTask;
    }
    return tcp.ConnectAsync(config.IPAddress, config.Port);
}
</code>```

Task.CompletedTask is also a singleton instance, so there is no additional overhead if this method is called regularly.

You could also write your method as async and return nothing at all:

```<code>public async Task ConnectAsync()
{
    if (tcp != null)
    {
        await tcp.ConnectAsync(config.IPAddress, config.Port);
    }
}
</code>```

Body:
My class is wrapping TcpListener and I'm trying to update it to use modern async language.

It throws up the question what to do if a method should exit early. If this is the old code:

    public void Connect()
    {
        if (tcp != null)
          tcp.Connect(config.IPAddress, config.Port);
    }

Then I start with something like this:

    public Task ConnectAsync()
    {
        if (tcp != null)
          { ???? }
        return tcp.ConnectAsync(config.IPAddress, config.Port);
    }

But in the condition tcp==null what should I return? Is there some "null awaitable"?

I also am unsure if my method should be designated async or not in this case where I am wrapping another method - I am sure I do not want to await the called method. This compiles but I do not think it is right:

    public async Task ConnectAsync()
    {
        if (tcp != null)
            return;

        await tcp.ConnectAsync(config.IPAddress, config.Port);
    }

Body:
You can return a completed task:

public Task ConnectAsync()
{
    if (tcp == null)
    {
        return Task.CompletedTask;
    }
    return tcp.ConnectAsync(config.IPAddress, config.Port);
}

Task.CompletedTask is also a singleton instance, so there is no additional overhead if this method is called regularly.

You could also write your method as async and return nothing at all:

public async Task ConnectAsync()
{
    if (tcp != null)
    {
        await tcp.ConnectAsync(config.IPAddress, config.Port);
    }
}


问:
Format 2 dates in 1 cell
I'm displaying 2 dates in 1 cell and I want to change the format of the 2 dates. I could do it with only one date but when it comes to 2 I struggle. here is a screenshot of my ag-grid:

I tried to create new function dateFormatterr which takes 2 parameters and use it in columnDefs but it didn't work. Here is my code:

```<code>import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Grid, GridApi } from 'ag-grid-community';
import { AgGridAngular } from 'ag-grid-angular';
import { DealsService } from './services/deals.service';
import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
  title = 'app';
  gridOptions = {
    rowHeight: 70
  }
  columnDefs = [{
      headerName: "Block \n Deal",
      cellRenderer: function(params) {
        return params.data.BLOCKID + '<br/>' + params.data.DEALID
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Class \n Type',
      cellRenderer: function(params) {
        return params.data.DEALCLASS + '<br/>' + params.data.DEALTYPE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Trade \n Start',
      cellRenderer: function(params) {
        return params.data.TRADEDATE + '<br/>' + params.data.STARTDATE
      },
      valueFormatter: this.dateFormatterr('TRADEDATE', 'STARTDATE'),
      width: 150,
      resizable: true,
      filter: true,
    },
    {
      headerName: 'Folder \n Cpty',
      cellRenderer: function(params) {
        return params.data.FOLDERSHORTNAME + '<br/>' + params.data.CPTYSHORTNAME
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'ShortName \n Name',
      cellRenderer: function(params) {
        return params.data.INSTRSHORTNAME + '<br/>' + params.data.INSTRNAME
      },
      width: 150,
      resizable: true,
      filter: true,
    },
    {
      headerName: 'Quantity \n Settl.Amt',
      cellRenderer: function(params) {
        return params.data.QUANTITY + '<br/>' + params.data.SETTLEAMT
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Rate \n Fees',
      cellRenderer: function(params) {
        return params.data.FLOATINGRATESSHORTNAME + '<br/>' + params.data.RENTSPREADFIXEDRATE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Category \n Status',
      cellRenderer: function(params) {
        return params.data.DEALCAT + '<br/>' + params.data.WORKFLOWSTATE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'End',
      field: 'ENDDATE',
      valueFormatter: this.dateFormatter,
      width: 140,
      resizable: true,
      filter: true
    },
  ];
  rowData: any;
  constructor(private service: DealsService) {}
  dateFormatter(params) {
    return moment(params.value).format('DD/MM/YYYY');
  }
  dateFormatterr(params1, params2) {
    return moment(params1.value + params2.value).format('DD/MM/YYYY');
  }
  ngOnInit() {
    this.service.getDealsList().subscribe(data => {
      this.rowData = data;
    });
  }
}
</code>```

I hope to get your help.

答:
You can achieve this using a custom cell renderer component for Trade Start column.

Create an ag-grid custom cell render component implementing ICellRendererAngularComp

Add the DateCellRendererComponent as the cellRendererFramework in column definition of Trade Start column

Register the custom cell render component in your app module.

date-cell-renderer.component.html

```<code><p>{{trDate}} <br />{{strtDate}}</p>
</code>```

date-cell-renderer.component.ts

```<code>    import { Component } from '@angular/core';
    import { ICellRendererAngularComp } from 'ag-grid-angular';
    import * as moment from 'moment';

    @Component({
       selector: 'app-comment-cell-renderer',
       templateUrl: './comment-cell-renderer.component.html',
       styleUrls: ['./comment-cell-renderer.component.scss']
    })
    export class DateCellRendererComponent implements ICellRendererAngularComp {
       params: any;
       trDate: string;
       strtDate: string;

       refresh(params: any): boolean {
            return false;
       }

       agInit(params: any): void {
            this.params = params;
            this.trDate = moment(params.data.TRADEDATE).format('DD/MM/YYYY');
            this.strtDate = moment(params.data.STARTDATE).format('DD/MM/YYYY');
       }

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

app.component.ts

```<code>columnDefs = [
    {
      headerName: 'Trade \n Start',
      cellRendererFramework: DateCellRendererComponent,
      width: 150,
      resizable: true,
      filter: true,
    }
];
</code>```

app.module.ts

```<code>import { AgGridModule } from 'ag-grid-angular';

@NgModule({
  imports: [
    AgGridModule.withComponents(
      [ DateCellRendererComponent]
    )
  ]
})
</code>```

Title: Format 2 dates in 1 cell

Body:
I'm displaying 2 dates in 1 cell and I want to change the format of the 2 dates. I could do it with only one date but when it comes to 2 I struggle. here is a screenshot of my ag-grid:

I tried to create new function dateFormatterr which takes 2 parameters and use it in columnDefs but it didn't work. Here is my code:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Grid, GridApi } from 'ag-grid-community';
import { AgGridAngular } from 'ag-grid-angular';
import { DealsService } from './services/deals.service';
import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
  title = 'app';
  gridOptions = {
    rowHeight: 70
  }
  columnDefs = [{
      headerName: "Block \n Deal",
      cellRenderer: function(params) {
        return params.data.BLOCKID + '
' + params.data.DEALID
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Class \n Type',
      cellRenderer: function(params) {
        return params.data.DEALCLASS + '
' + params.data.DEALTYPE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Trade \n Start',
      cellRenderer: function(params) {
        return params.data.TRADEDATE + '
' + params.data.STARTDATE
      },
      valueFormatter: this.dateFormatterr('TRADEDATE', 'STARTDATE'),
      width: 150,
      resizable: true,
      filter: true,
    },
    {
      headerName: 'Folder \n Cpty',
      cellRenderer: function(params) {
        return params.data.FOLDERSHORTNAME + '
' + params.data.CPTYSHORTNAME
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'ShortName \n Name',
      cellRenderer: function(params) {
        return params.data.INSTRSHORTNAME + '
' + params.data.INSTRNAME
      },
      width: 150,
      resizable: true,
      filter: true,
    },
    {
      headerName: 'Quantity \n Settl.Amt',
      cellRenderer: function(params) {
        return params.data.QUANTITY + '
' + params.data.SETTLEAMT
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Rate \n Fees',
      cellRenderer: function(params) {
        return params.data.FLOATINGRATESSHORTNAME + '
' + params.data.RENTSPREADFIXEDRATE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Category \n Status',
      cellRenderer: function(params) {
        return params.data.DEALCAT + '
' + params.data.WORKFLOWSTATE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'End',
      field: 'ENDDATE',
      valueFormatter: this.dateFormatter,
      width: 140,
      resizable: true,
      filter: true
    },
  ];
  rowData: any;
  constructor(private service: DealsService) {}
  dateFormatter(params) {
    return moment(params.value).format('DD/MM/YYYY');
  }
  dateFormatterr(params1, params2) {
    return moment(params1.value + params2.value).format('DD/MM/YYYY');
  }
  ngOnInit() {
    this.service.getDealsList().subscribe(data => {
      this.rowData = data;
    });
  }
}

I hope to get your help.

Body:
You can achieve this using a custom cell renderer component for Trade Start column.

Create an ag-grid custom cell render component implementing ICellRendererAngularComp

Add the DateCellRendererComponent as the cellRendererFramework in column definition of Trade Start column

Register the custom cell render component in your app module.

date-cell-renderer.component.html

<p>{{trDate}} <br />{{strtDate}}</p>

date-cell-renderer.component.ts

    import { Component } from '@angular/core';
    import { ICellRendererAngularComp } from 'ag-grid-angular';
    import * as moment from 'moment';

    @Component({
       selector: 'app-comment-cell-renderer',
       templateUrl: './comment-cell-renderer.component.html',
       styleUrls: ['./comment-cell-renderer.component.scss']
    })
    export class DateCellRendererComponent implements ICellRendererAngularComp {
       params: any;
       trDate: string;
       strtDate: string;

       refresh(params: any): boolean {
            return false;
       }

       agInit(params: any): void {
            this.params = params;
            this.trDate = moment(params.data.TRADEDATE).format('DD/MM/YYYY');
            this.strtDate = moment(params.data.STARTDATE).format('DD/MM/YYYY');
       }

       constructor() { }
   }

app.component.ts

columnDefs = [
    {
      headerName: 'Trade \n Start',
      cellRendererFramework: DateCellRendererComponent,
      width: 150,
      resizable: true,
      filter: true,
    }
];

app.module.ts

import { AgGridModule } from 'ag-grid-angular';

@NgModule({
  imports: [
    AgGridModule.withComponents(
      [ DateCellRendererComponent]
    )
  ]
})


问:
Domain Specific Language resources
I was just listening to some older .Net Rocks! episodes, and I found #329 on DSLs to be interesting. My problem is that I can't find any good online resources for people trying to learn this technology. I get the basics of the creating new designers, but the MS docs on the T4 engine used by the DSL tools and then how to integrate the templates with the DSL models are lacking.

Does anyone know of some good introductory resources for the MS DSL tools?

答:
Martin Fowler is writing a book on DSLs. You can read his work so far here http://www.martinfowler.com/dslwip/

I also went to a good presentation by Jay Fields (His slides are here).

ContentLicense: CC BY-SA 2.5

Title: Domain Specific Language resources

LastEditorDisplayName: Jeff Atwood

OwnerDisplayName: John Nolan


问:
Is my reputation system secure?
BOUNTY: To get bounty either show me how to play the system, or explain why you think it's impossible to play it.

I'm developing a reputation system for a site that allows you to start your own blog of sorts, and to comment and have favorites etc.

I aim for a very short ruleset that is easy to understand for the users and can't be "played". Note: when I write "answers", I mean answers to comments, which is
the equivalent of Stack Overflow's comments to answers.

To create an account you need one Mojo. Without it you can only answer other people's comments.

When you have an account, you get one Mojo a day.

Each day you can only post as many posts and comments as you have Mojo. You can answer as many comments as you like. You don't lose Mojo when you post.

You can give one Mojo to someone who has less, but only once to each person.

Alternatively, you can burn one Mojo to take one Mojo away from someone who has less, but only once.

You can't have your Mojo back.

The site is supposed to be invite-only, but non-members can answer member's comments, and maybe they'll be able to start their own blogs too, I'm not sure yet. The idea is for a system based mainly on seniority, where power can be transferred between users only in a very limited manner so basically there's no way to inflate your reputation (Mojo only flows down.)

Giving and taking Mojo is supposed to be an act on the level of marking someone as a friend or as an enemy.

I don't want Mojo itself to be a motivator for people to be part of the community. I want them to use it to influence how other people behave on site. By burning someone with your Mojo you effectively limit how much they can post on the site. By giving someone Mojo you allow them to express more.

I'm also planning to add ways to get extra Mojo, like "Post of the Day" or "Favorite Blog of the Week" contests with prizes of around 3-10 Mojo. But one of my main goals is to avoid inflation.

答:
It looks pretty good, but remember that some users will eventually find ways to game any system.

Hopefully you can get a vague idea about the effectiveness of your reputation system after the public beta.

So that is about security.

A problem (may be it is how you designed it to be) I see with the system is that unlike SO or any other similar community site, you need to burn your points to contribute to the system rather than gaining points for those actions.

This decision may harm the growth of content in the site. Users will think like "I have a small number of points. So I will keep it and let my reputation grow". This means that your current system does not promote growth of content in the system.

OwnerDisplayName: Pies

Title: Is my reputation system secure?

LastEditorDisplayName: Pies

OwnerDisplayName: Niyaz

LastEditorDisplayName: Niyaz


问:
Could not find a part of the path ... bin\roslyn\csc.exe
I am trying to run an ASP.NET MVC (model-view-controller) project retrieved from TFS (Team Foundation Server) source control. I have added all assembly references and I am able to build and compile successfully without any error or warning.

But I get the following error in the browser:

Could not find a part of the path
'C:\B8akWorkspace\B8akProject\B8akSolution\B8AK.Portal\bin\roslyn\csc.exe'.

Here is a full screenshot of the error page.

After few days of research, I understood that Roslyn is a .NET compiler platform that offers advanced compiling features. However, I do not understand why my build is trying to find \bin\roslyn\csc.exe because I did not configure anything related to Roslyn. Nor did I intend to use Roslyn in my project.

答:
Too late for an answer but still posting incase it helps anyone.

Following the below steps fixed the error for me:

delete packages folder

open VS

rebuild

observe that NuGet packages are restored, but bin\roslyn isnt created

unload project

reload project

rebuild

observe that the bin\roslyn has been created now.


问:
How to pass a string from one page to another on flutter?
How can I pass image_category(a String value) from one page to another and replace it with a Text widget?

This is where I get the String from (scrlView):-

```<code>@override
Widget build(BuildContext context) {
return Padding(
  padding: const EdgeInsets.all(0.0),
  child: GestureDetector(
    onTap: () {
      print("$image_category"); //TODOPass tpped text to CatagoriesBar,
    },
</code>```

and this is where I want to replace it with the text widget(this is on a separate pageCategoriesBar):-

```<code>import 'package:flutter/material.dart';

 class CategoriesBar extends StatefulWidget {
 @override
 _CategoriesBarState createState() => _CategoriesBarState();
  }

 class _CategoriesBarState extends State<CategoriesBar> {
  @override
  Widget build(BuildContext context) {
   return  Align(
        alignment: Alignment.center,
        child: Text(
          "All Categories",//TODOReplace with category tapped on scrlView
          style: TextStyle(
            color: Colors.black,
            fontSize: 17.0,
            fontWeight: FontWeight.bold,
          ),
        ),
      );
    }
</code>```

I'm a newbie to flutter,
apologies. if details aren't enough(let me know in the comments I'll update the question)

Update

I've tried with Navigator.push and it pops a new black screen with the "image_category" on it.

Here is what I've tried:-scrlView

```<code>@override
 Widget build(BuildContext context) {
 return Padding(
 padding: const EdgeInsets.all(0.0),
 child: GestureDetector(
onTap: () {
  print("$image_category");
   Navigator.push(
                context,
               MaterialPageRoute(
                    builder: (context) => CategoriesBar (categoryTitle: image_caption),
                )
            );
},
</code>```

Here is what I've tried:-CategoriesBar

```<code>import 'package:flutter/material.dart';

class CategoriesBar extends StatefulWidget {
final String categoryTitle;
CategoriesBar({Key key, @required this.categoryTitle}) : super(key: key);
@override
_CategoriesBarState createState() => _CategoriesBarState();
}

class _CategoriesBarState extends State<CategoriesBar> {
 @override
 Widget build(BuildContext context) {
 return  Align(
    alignment: Alignment.center,
    child: Text(
      widget.categoryTitle,
      style: TextStyle(
        color: Colors.red,
        fontSize: 17.0,
        fontWeight: FontWeight.bold,
      ),
    ),
  );
}
</code>```

and this is what I got:-

答:
```<code>@override
Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.all(0.0),
        child: GestureDetector(
            onTap: () {
                print("$image_category");

                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => CategoriesBar (text: image_category),
                    )
                );
            },
        …
        )
    )
}
</code>```

And then:

```<code>import 'package:flutter/material.dart';

class CategoriesBar extends StatefulWidget {
    final String text;
    CategoriesBar ({Key key, @required this.text}) : super(key: key);
    @override
    _CategoriesBarState createState() => _CategoriesBarState();
}

class _CategoriesBarState extends State<CategoriesBar> {
    @override
    Widget build(BuildContext context) {
        return  Align(
            alignment: Alignment.center,
            child: Text(
                widget.text,
                style: TextStyle(
                    color: Colors.black,
                    fontSize: 17.0,
                    fontWeight: FontWeight.bold,
                ),
            ),
        );
    }
}
</code>```

More info on Passing data between screens in Flutter

UPDATE

You should wrap your content in a Scaffold view.

```<code>import 'package:flutter/material.dart';

class CategoriesBar extends StatefulWidget {
final String categoryTitle;
CategoriesBar({Key key, @required this.categoryTitle}) : super(key: key);
@override
_CategoriesBarState createState() => _CategoriesBarState();
}

class _CategoriesBarState extends State<CategoriesBar> {
 @override
 Widget build(BuildContext context) {
  return Scaffold(
        appBar: AppBar(
         title: Text("APPBAR"),
       ),
  body: Align(
    alignment: Alignment.center,
    child: Text(
      widget.categoryTitle,
      style: TextStyle(
        color: Colors.red,
        fontSize: 17.0,
        fontWeight: FontWeight.bold,
      ),
    ),
  ),
 );
}

</code>```

Please make sure to close brackets relevantly. I typed without any code editor. Vs code gives you nice formatting and error handling capabilities.

Body:
How can I pass image_category(a String value) from one page to another and replace it with a Text widget?

This is where I get the String from (scrlView):-

@override
Widget build(BuildContext context) {
return Padding(
  padding: const EdgeInsets.all(0.0),
  child: GestureDetector(
    onTap: () {
      print("$image_category"); //TODOPass tpped text to CatagoriesBar,
    },

and this is where I want to replace it with the text widget(this is on a separate pageCategoriesBar):-

import 'package:flutter/material.dart';

 class CategoriesBar extends StatefulWidget {
 @override
 _CategoriesBarState createState() => _CategoriesBarState();
  }

 class _CategoriesBarState extends State<CategoriesBar> {
  @override
  Widget build(BuildContext context) {
   return  Align(
        alignment: Alignment.center,
        child: Text(
          "All Categories",//TODOReplace with category tapped on scrlView
          style: TextStyle(
            color: Colors.black,
            fontSize: 17.0,
            fontWeight: FontWeight.bold,
          ),
        ),
      );
    }

I'm a newbie to flutter,
apologies. if details aren't enough(let me know in the comments I'll update the question)

Update

I've tried with Navigator.push and it pops a new black screen with the "image_category" on it.

Here is what I've tried:-scrlView

@override
 Widget build(BuildContext context) {
 return Padding(
 padding: const EdgeInsets.all(0.0),
 child: GestureDetector(
onTap: () {
  print("$image_category");
   Navigator.push(
                context,
               MaterialPageRoute(
                    builder: (context) => CategoriesBar (categoryTitle: image_caption),
                )
            );
},

Here is what I've tried:-CategoriesBar

import 'package:flutter/material.dart';

class CategoriesBar extends StatefulWidget {
final String categoryTitle;
CategoriesBar({Key key, @required this.categoryTitle}) : super(key: key);
@override
_CategoriesBarState createState() => _CategoriesBarState();
}

class _CategoriesBarState extends State<CategoriesBar> {
 @override
 Widget build(BuildContext context) {
 return  Align(
    alignment: Alignment.center,
    child: Text(
      widget.categoryTitle,
      style: TextStyle(
        color: Colors.red,
        fontSize: 17.0,
        fontWeight: FontWeight.bold,
      ),
    ),
  );
}

and this is what I got:-

Body:
@override
Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.all(0.0),
        child: GestureDetector(
            onTap: () {
                print("$image_category");

                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => CategoriesBar (text: image_category),
                    )
                );
            },
        …
        )
    )
}

And then:

import 'package:flutter/material.dart';

class CategoriesBar extends StatefulWidget {
    final String text;
    CategoriesBar ({Key key, @required this.text}) : super(key: key);
    @override
    _CategoriesBarState createState() => _CategoriesBarState();
}

class _CategoriesBarState extends State<CategoriesBar> {
    @override
    Widget build(BuildContext context) {
        return  Align(
            alignment: Alignment.center,
            child: Text(
                widget.text,
                style: TextStyle(
                    color: Colors.black,
                    fontSize: 17.0,
                    fontWeight: FontWeight.bold,
                ),
            ),
        );
    }
}

More info on Passing data between screens in Flutter

UPDATE

You should wrap your content in a Scaffold view.

import 'package:flutter/material.dart';

class CategoriesBar extends StatefulWidget {
final String categoryTitle;
CategoriesBar({Key key, @required this.categoryTitle}) : super(key: key);
@override
_CategoriesBarState createState() => _CategoriesBarState();
}

class _CategoriesBarState extends State<CategoriesBar> {
 @override
 Widget build(BuildContext context) {
  return Scaffold(
        appBar: AppBar(
         title: Text("APPBAR"),
       ),
  body: Align(
    alignment: Alignment.center,
    child: Text(
      widget.categoryTitle,
      style: TextStyle(
        color: Colors.red,
        fontSize: 17.0,
        fontWeight: FontWeight.bold,
      ),
    ),
  ),
 );
}

Please make sure to close brackets relevantly. I typed without any code editor. Vs code gives you nice formatting and error handling capabilities.


问:
Pandas count occurence of value in dictionary
Given a DF:

```<code>pd.DataFrame({"A":[1,2,3],
              "B": [{"Mon":"Closed", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Open"}]
              })
</code>```

How do i get a count of number of times "Closed" appears in the dict?

```<code>A  B    count
1 {..}  2
2 {..}  1
3 {..}  0
</code>```

I really don't know how to start on this to try

答:
Straightforward .apply() solution:

```<code>df['Count'] = df.B.apply(lambda x: sum('Closed' in v for v in x.values()))
print(df)
</code>```

Prints:

```<code>   A                                                  B  Count
0  1  {'Mon': 'Closed', 'Tue': 'Open', 'Wed': 'Closed'}      2
1  2    {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Closed'}      1
2  3      {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Open'}      0
</code>```

Benchmark:

```<code>import perfplot
import pandas as pd

def f1(df):
    df['Count'] = df.B.apply(lambda x: sum('Closed' in v for v in x.values()))
    return df

def f2(df):
    df['count'] = df.B.astype(str).str.count('Closed')
    return df

# Commented out because of timed-out:
# def f3(df):
#     df['count'] = df.B.apply(pd.Series).eq('Closed').sum(1)
#     return df

def f4(df):
    df['count'] = pd.DataFrame(df['B'].tolist()).stack().eq("Closed").sum(level=0)
    return df

def setup(n):
    A = [*range(n)]
    B = [{'Mon': 'Closed', 'Tue': 'Open', 'Wed': 'Closed'} for _ in range(n)]
    df = pd.DataFrame({'A': A,
                       'B': B})
    return df

perfplot.show(
    setup=setup,
    kernels=[f1, f2, f4],
    labels=['apply(sum)', 'str.count()', 'stack.eq()'],
    n_range=[10**i for i in range(1, 7)],
    xlabel='N (* len(df))',
    equality_check=None,
    logx=True,
    logy=True)
</code>```

Result:

So it seems that straightforward apply() with sum() is fastest.

Body:
Given a DF:

pd.DataFrame({"A":[1,2,3],
              "B": [{"Mon":"Closed", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Open"}]
              })

How do i get a count of number of times "Closed" appears in the dict?

A  B    count
1 {..}  2
2 {..}  1
3 {..}  0

I really don't know how to start on this to try

Body:
Straightforward .apply() solution:

df['Count'] = df.B.apply(lambda x: sum('Closed' in v for v in x.values()))
print(df)

Prints:

   A                                                  B  Count
0  1  {'Mon': 'Closed', 'Tue': 'Open', 'Wed': 'Closed'}      2
1  2    {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Closed'}      1
2  3      {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Open'}      0

Benchmark:

import perfplot
import pandas as pd

def f1(df):
    df['Count'] = df.B.apply(lambda x: sum('Closed' in v for v in x.values()))
    return df

def f2(df):
    df['count'] = df.B.astype(str).str.count('Closed')
    return df

# Commented out because of timed-out:
# def f3(df):
#     df['count'] = df.B.apply(pd.Series).eq('Closed').sum(1)
#     return df

def f4(df):
    df['count'] = pd.DataFrame(df['B'].tolist()).stack().eq("Closed").sum(level=0)
    return df

def setup(n):
    A = [*range(n)]
    B = [{'Mon': 'Closed', 'Tue': 'Open', 'Wed': 'Closed'} for _ in range(n)]
    df = pd.DataFrame({'A': A,
                       'B': B})
    return df

perfplot.show(
    setup=setup,
    kernels=[f1, f2, f4],
    labels=['apply(sum)', 'str.count()', 'stack.eq()'],
    n_range=[10**i for i in range(1, 7)],
    xlabel='N (* len(df))',
    equality_check=None,
    logx=True,
    logy=True)

Result:

So it seems that straightforward apply() with sum() is fastest.


问:
iOS convert large numbers to smaller format
How can I convert all numbers that are more than 3 digits down to a 4 digit or less number?

This is exactly what I mean:

```<code>10345 = 10.3k
10012 = 10k
123546 = 123.5k
4384324 = 4.3m
</code>```

Rounding is not entirely important, but an added plus.

I have looked into NSNumberFormatter but have not found the proper solution, and I have yet to find a proper solution here on SO. Any help is greatly appreciated, thanks!

答:
A little bit cleaner solution:

struct Shortener {

    func string(from value: String) -> String? {
        guard let value = Int(value) else { return nil }

        if value < 1000 {
            return "\(value)"
        }
        if value < 100_000 {
            return string(from: value, divisor: 1000, suffix: "K")
        }
        if value < 100_000_000 {
            return string(from: value, divisor: 1_000_000, suffix: "M")
        }

        return string(from: value, divisor: 1_000_000_000, suffix: "B")
    }

    private func string(from value: Int, divisor: Double, suffix: String) -> String? {
        let formatter = NumberFormatter()
        let dividedValue = Double(value) / divisor

        formatter.positiveSuffix = suffix
        formatter.negativeSuffix = suffix
        formatter.allowsFloats = true
        formatter.minimumIntegerDigits = 1
        formatter.minimumFractionDigits = 0
        formatter.maximumFractionDigits = 1

        return formatter.string(from: NSNumber(value: dividedValue))
    }

}
```

Body:
How can I convert all numbers that are more than 3 digits down to a 4 digit or less number?

This is exactly what I mean:

10345 = 10.3k
10012 = 10k
123546 = 123.5k
4384324 = 4.3m

Rounding is not entirely important, but an added plus.

I have looked into NSNumberFormatter but have not found the proper solution, and I have yet to find a proper solution here on SO. Any help is greatly appreciated, thanks!


问:
selector not working with layout and image view
I want to use selector for a layout and image view..But it is not working for me.
When I changed image view to imagebutton or button, it works fine. Any help will be greatly appreciated.. Thanks in advance..

here is the xmls I used..

```<code><?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:drawable="@drawable/bg"
        />
    <item
        android:drawable="@drawable/bg_01" />
</selector>
</code>```

The layout xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:orientation="vertical"
    android:layout_height="fill_parent">
    <ImageButton
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:text="layout tester"
        android:textColor="#000000"
        android:textStyle="bold"
        android:paddingTop="10dp"
        android:src="@drawable/testselector"
        android:layout_gravity="center_horizontal" />
    </LinearLayout>
</code>```

答:
try this

```<code>    <selector
  xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="true"
          android:state_pressed="false"
          android:drawable="@drawable/lastread_ok" />
    <item android:state_focused="true"
          android:state_pressed="true"
          android:drawable="@drawable/lastread_ok" />
    <item android:state_focused="false"
          android:state_pressed="true"
      android:drawable="@drawable/lastread_ok_selected" />
    <item android:drawable="@drawable/lastread_ok" />
</selector>
</code>```

you can use your image instead of lastread_ok & lastread_ok_selected

Body:
I want to use selector for a layout and image view..But it is not working for me.
When I changed image view to imagebutton or button, it works fine. Any help will be greatly appreciated.. Thanks in advance..

here is the xmls I used..

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:drawable="@drawable/bg"
        />
    <item
        android:drawable="@drawable/bg_01" />
</selector>

The layout xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:orientation="vertical"
    android:layout_height="fill_parent">
    <ImageButton
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:text="layout tester"
        android:textColor="#000000"
        android:textStyle="bold"
        android:paddingTop="10dp"
        android:src="@drawable/testselector"
        android:layout_gravity="center_horizontal" />
    </LinearLayout>

Body:
try this

    <selector
  xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="true"
          android:state_pressed="false"
          android:drawable="@drawable/lastread_ok" />
    <item android:state_focused="true"
          android:state_pressed="true"
          android:drawable="@drawable/lastread_ok" />
    <item android:state_focused="false"
          android:state_pressed="true"
      android:drawable="@drawable/lastread_ok_selected" />
    <item android:drawable="@drawable/lastread_ok" />
</selector>

you can use your image instead of lastread_ok & lastread_ok_selected


问:
Is there a Mongoose method to save multiple documents, but only when all success
I have an array of documents, but I only want to save them when every document will success. Is there a Method from Mongoose?

Something like:

```<code>Insert el[0] - success
Insert el[1] - success
Insert el[2] - fail
Delete el[1]
Delete el[0]
</code>```

答:
You can use transactions to implement this. Here's an example from the docs:

let session = null;
return Customer.createCollection().
  then(() => Customer.startSession()).
  then(_session => {
    session = _session;
    session.startTransaction();
    return Customer.create([{ name: 'Test' }], { session: session });
  }).
  then(() => Customer.create([{ name: 'Test2' }], { session: session })).
  then(() => session.abortTransaction()).
  then(() => Customer.countDocuments()).
  then(count => assert.strictEqual(count, 0)).
  then(() => session.endSession());

```

You can use abortTransaction to rollback queries in case of error.

Read more here:
https://mongoosejs.com/docs/transactions.html
https://www.mongodb.com/transactions

Body:
I have an array of documents, but I only want to save them when every document will success. Is there a Method from Mongoose?

Something like:

Insert el[0] - success
Insert el[1] - success
Insert el[2] - fail
Delete el[1]
Delete el[0]

Body:
You can use transactions to implement this. Here's an example from the docs:

let session = null;
return Customer.createCollection().
  then(() => Customer.startSession()).
  then(_session => {
    session = _session;
    session.startTransaction();
    return Customer.create([{ name: 'Test' }], { session: session });
  }).
  then(() => Customer.create([{ name: 'Test2' }], { session: session })).
  then(() => session.abortTransaction()).
  then(() => Customer.countDocuments()).
  then(count => assert.strictEqual(count, 0)).
  then(() => session.endSession());

You can use abortTransaction to rollback queries in case of error.

Read more here:
https://mongoosejs.com/docs/transactions.html
https://www.mongodb.com/transactions


问:
Is it possible to setText for an Edittext for a long data type element in android
Is it possible to setText for an Edittext view for a long data type element in android XML? I know that setText can take integer but it is not accepting any long data type. So how can I write a long variable in an Edittext without converting it to integer?</p>

答:
Try it like this:

```<code>editText.setText(Editable.Factory.getInstance().newEditable((String.valueOf(yourLongValue))));
</code>```

You can't set String value to EditText so convert the String value to Editable as well.

Body:
Try it like this:

editText.setText(Editable.Factory.getInstance().newEditable((String.valueOf(yourLongValue))));

You can't set String value to EditText so convert the String value to Editable as well.


问:
How to test custom async/await hook with react-hooks-testing-library
I created a custom react hook that is supposed to handle all less important api requests, which i don't want to store in the redux state. Hook works fine but I have trouble testing it. My test setup is jest and enzyme, but I decided to give a try react-hooks-testing-library here as well.

What I have tried so far is to first mock fetch request with a fetch-mock library, what works fine. Next, i render hook with renderHook method, which comes from react-hooks-testing-library. Unfortunately, looks like I do not quite understand the waitForNextUpdate method.

This is how my hook looks like.

useApi hook

```<code>export function useApi<R, B = undefined>(
    path: string,
    body: B | undefined = undefined,
    method: HttpMethod = HttpMethod.GET
): ResponseStatus<R> {
    const [response, setResponse] = useState();
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [error, setError] = useState<string | boolean>(false);

    useEffect(() => {
        const fetchData = async (): Promise<void> => {
            setError(false);
            setIsLoading(true);
            try {
                const result = await callApi(method, path, body);
                setResponse(result);
            } catch (errorResponse) {
                setError(errorResponse);
            }

            setIsLoading(false);
        };

        fetchData();
    }, [path, body, method]);

    return { response, isLoading, error };
}
</code>```

Hook can take 3 different state combinations that I would like to test. Unfortunately, I have no idea how.

Loading data:

```<code>{ response: undefined, isLoading: true, error: false }
</code>```

Loaded data:

```<code>{ response: R, isLoading: false, error: false }
</code>```

Error:

```<code>{ response: undefined, isLoading: false, error: true }
</code>```

This is how my test looks like at this moment:

```<code>import fetchMock from 'fetch-mock';
import { useApi } from './hooks';
import { renderHook } from '@testing-library/react-hooks';

test('', async () => {
    fetchMock.mock('*', {
        returnedData: 'foo'
    });

    const { result, waitForNextUpdate } = renderHook(() => useApi('/data-owners'));

    console.log(result.current);

    await waitForNextUpdate();

    console.log(result.current);
});
</code>```

callApi func

```<code>/**
 * Method to call api.
 *
 * @param {HttpMethod} method - Request type.
 * @param {string} path - Restful endpoint route.
 * @param {any} body - Request body data.
 */
export const callApi = async (method: HttpMethod, path: string, body: any = null) => {
    // Sends api request
    const response = await sendRequest(method, path, body);
    // Checks response and parse to the object
    const resJson = response ? await response.json() : '';

    if (resJson.error) {
        // If message contains error, it will throw new Error with code passed in status property (e.g. 401)
        throw new Error(resJson.status);
    } else {
        // Else returns response
        return resJson;
    }
};
</code>```

答:
It's all right that you did. Now, you need use expect for test.</p>

```<code>const value = {...}
expect(result.current).toEqual(value)
</code>```

Body:
I created a custom react hook that is supposed to handle all less important api requests, which i don't want to store in the redux state. Hook works fine but I have trouble testing it. My test setup is jest and enzyme, but I decided to give a try react-hooks-testing-library here as well.

What I have tried so far is to first mock fetch request with a fetch-mock library, what works fine. Next, i render hook with renderHook method, which comes from react-hooks-testing-library. Unfortunately, looks like I do not quite understand the waitForNextUpdate method.

This is how my hook looks like.

useApi hook

export function useApi<R, B = undefined>(
    path: string,
    body: B | undefined = undefined,
    method: HttpMethod = HttpMethod.GET
): ResponseStatus<R> {
    const [response, setResponse] = useState();
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [error, setError] = useState<string | boolean>(false);

    useEffect(() => {
        const fetchData = async (): Promise<void> => {
            setError(false);
            setIsLoading(true);
            try {
                const result = await callApi(method, path, body);
                setResponse(result);
            } catch (errorResponse) {
                setError(errorResponse);
            }

            setIsLoading(false);
        };

        fetchData();
    }, [path, body, method]);

    return { response, isLoading, error };
}

Hook can take 3 different state combinations that I would like to test. Unfortunately, I have no idea how.

Loading data:

{ response: undefined, isLoading: true, error: false }

Loaded data:

{ response: R, isLoading: false, error: false }

Error:

{ response: undefined, isLoading: false, error: true }

This is how my test looks like at this moment:

import fetchMock from 'fetch-mock';
import { useApi } from './hooks';
import { renderHook } from '@testing-library/react-hooks';

test('', async () => {
    fetchMock.mock('*', {
        returnedData: 'foo'
    });

    const { result, waitForNextUpdate } = renderHook(() => useApi('/data-owners'));

    console.log(result.current);

    await waitForNextUpdate();

    console.log(result.current);
});

callApi func

/**
 * Method to call api.
 *
 * @param {HttpMethod} method - Request type.
 * @param {string} path - Restful endpoint route.
 * @param {any} body - Request body data.
 */
export const callApi = async (method: HttpMethod, path: string, body: any = null) => {
    // Sends api request
    const response = await sendRequest(method, path, body);
    // Checks response and parse to the object
    const resJson = response ? await response.json() : '';

    if (resJson.error) {
        // If message contains error, it will throw new Error with code passed in status property (e.g. 401)
        throw new Error(resJson.status);
    } else {
        // Else returns response
        return resJson;
    }
};

Body:
It's all right that you did. Now, you need use expect for test.

const value = {...}
expect(result.current).toEqual(value)


问:
how to close a user defined Thread with close (X) icon of the scren in JavaFX?
I use the following code to create a user-defined Java Thread and perform some action continuously. then I want to destroy this Thread while the user wants to close the windows and clicks on (X) icon of the window.

```<code>class Simple
{
    Threa thread;
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        thread = new Thread(new MyThreadClass(this));
        thread.start();
    }
//code
}//Simple

class MedicalStoreSalesPageControllerThread implements Runnable {
    @Override
    public void run() {
        //Action which is continuously performed
    }
}//MedicalStoreSalesPageControllerThread
</code>```

I'm talking about (X) sign at top right corner of window

答:
I created a small exmaple how you could do it.

Main Class:

```<code>package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
        Parent root = loader.load();
        primaryStage.setScene(new Scene(root));

        // Get the controller instance
        Controller controller = loader.getController();

        // Prevent closing when user clicks on the (X) sign at top right corner of window:
        primaryStage.setOnCloseRequest(event -> {
            event.consume();
            controller.closeApp();
        });

        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Controller Class:

```<code>package sample;

import javafx.fxml.Initializable;

import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable {

    private MyTask myTask;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        myTask = new MyTask();
        new Thread(myTask).start();
    }

    void closeApp() {
        // Cancel task and close
        if (myTask.cancel())
            System.exit(0);
    }
}
</code>```

MyTask Class:

```<code>package sample;

import javafx.concurrent.Task;

class MyTask extends Task<Void> {

    @Override
    protected Void call() throws Exception {
        while (true) {
            System.out.println("running");
            Thread.sleep(1000);
        }
    }

    @Override
    protected void cancelled() {
        System.out.println("stopped");
    }
}
</code>```

Body:
I use the following code to create a user-defined Java Thread and perform some action continuously. then I want to destroy this Thread while the user wants to close the windows and clicks on (X) icon of the window.

class Simple
{
    Threa thread;
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        thread = new Thread(new MyThreadClass(this));
        thread.start();
    }
//code
}//Simple

class MedicalStoreSalesPageControllerThread implements Runnable {
    @Override
    public void run() {
        //Action which is continuously performed
    }
}//MedicalStoreSalesPageControllerThread

I'm talking about (X) sign at top right corner of window

Body:
I created a small exmaple how you could do it.

Main Class:

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
        Parent root = loader.load();
        primaryStage.setScene(new Scene(root));

        // Get the controller instance
        Controller controller = loader.getController();

        // Prevent closing when user clicks on the (X) sign at top right corner of window:
        primaryStage.setOnCloseRequest(event -> {
            event.consume();
            controller.closeApp();
        });

        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Controller Class:

package sample;

import javafx.fxml.Initializable;

import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable {

    private MyTask myTask;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        myTask = new MyTask();
        new Thread(myTask).start();
    }

    void closeApp() {
        // Cancel task and close
        if (myTask.cancel())
            System.exit(0);
    }
}

MyTask Class:

package sample;

import javafx.concurrent.Task;

class MyTask extends Task<Void> {

    @Override
    protected Void call() throws Exception {
        while (true) {
            System.out.println("running");
            Thread.sleep(1000);
        }
    }

    @Override
    protected void cancelled() {
        System.out.println("stopped");
    }
}


答:
Please don't put dictionaries into dataframe columns. You are losing all the speed of vectorized operations and make values hard to access.

Clean your df:

```<code>>>> df = pd.concat([df['A'], df['B'].apply(pd.Series)], axis=1)
>>> df
   A     Mon   Tue     Wed
0  1  Closed  Open  Closed
1  2    Open  Open  Closed
2  3    Open  Open    Open
</code>```

Now counting 'Closed' is easy.

```<code>>>> df['count'] = df.eq('Closed').sum(1)
>>> df
   A     Mon   Tue     Wed  count
0  1  Closed  Open  Closed      2
1  2    Open  Open  Closed      1
2  3    Open  Open    Open      0
</code>```

Title: Pandas count occurence of value in dictionary

Body:
Please don't put dictionaries into dataframe columns. You are losing all the speed of vectorized operations and make values hard to access.

Clean your df:

>>> df = pd.concat([df['A'], df['B'].apply(pd.Series)], axis=1)
>>> df
   A     Mon   Tue     Wed
0  1  Closed  Open  Closed
1  2    Open  Open  Closed
2  3    Open  Open    Open

Now counting 'Closed' is easy.

>>> df['count'] = df.eq('Closed').sum(1)
>>> df
   A     Mon   Tue     Wed  count
0  1  Closed  Open  Closed      2
1  2    Open  Open  Closed      1
2  3    Open  Open    Open      0


答:
First, ensure your Date column is a datetime object:

```<code>df['Date'] = df.Date.astype('datetime64')
</code>```

Then, group by the Date column, aggregate the names to list, resample by day and fill, finally perform an explode to expand the lists of names:

```<code>df.groupby('Date').agg(list).resample('D').ffill().explode('Name').reset_index()

# Result:
          Date     Name
0   2002-07-31     Paul
1   2002-07-31     John
2   2002-07-31   Silvia
3   2002-07-31     Mike
4   2002-07-31    Cindy
..         ...      ...
305 2002-09-30  Francis
306 2002-09-30  Michael
307 2002-09-30  Charlie
308 2002-09-30      Joe
309 2002-09-30   Hilary

[310 rows x 2 columns]
</code>```

Title: Resampling Dataframe from Monthly to Daily

Body:
Here is my problem:

This is a sample of my DataFrame (it actually goes from 2002 to 2012)

df = pd.DataFrame(
    {'Date':["2002-07-31","2002-07-31","2002-07-31","2002-07-31","2002-07-31","2002-08-31","2002-08-31","2002-08-31","2002-08-31","2002-08-31",'2002-09-30','2002-09-30','2002-09-30','2002-09-30','2002-09-30'],
     'Name': ["Paul", "John", "Silvia", "Mike", "Cindy","Paul", "David", "Harry", "Mike", "Britney","Francis", "Michael", "Charlie", "Joe", "Hilary"]})

Which gives this

       Date     Name
0   2002-07-31  Paul
1   2002-07-31  John
2   2002-07-31  Silvia
3   2002-07-31  Mike
4   2002-07-31  Cindy
5   2002-08-31  Paul
6   2002-08-31  David
7   2002-08-31  Harry
8   2002-08-31  Mike
9   2002-08-31  Britney
10  2002-09-30  Francis
11  2002-09-30  Michael
12  2002-09-30  Charlie
13  2002-09-30  Joe
14  2002-09-30  Hilary

and I would like to resample the serie from Monthly to Daily DataFrame by keeping all the names fix from 2002-07-31 to 2002-08-30 and from 2002-08-31 to 2002-09-30 (the change only occurs at the end of each month so it looks like resampling with the ffill() method).

The result I am looking for is something like that :

   Date     Name
2002-07-31  Paul
2002-07-31  John
2002-07-31  Silvia
2002-07-31  Mike
2002-07-31  Cindy
2002-08-01  Paul
2002-08-01  John
2002-08-01  Silvia
2002-08-01  Mike
2002-08-01  Cindy
2002-08-02  Paul
2002-08-02  John
2002-08-02  Silvia
2002-08-02  Mike
2002-08-02  Cindy
2002-08-03  Paul
2002-08-03  John
2002-08-03  Silvia
2002-08-03  Mike
2002-08-03  Cindy
.....

2002-08-31  Paul
2002-08-31  David
2002-08-31  Harry
2002-08-31  Mike
2002-08-31  Britney
2002-09-01  Paul
2002-09-01  David
2002-09-01  Harry
2002-09-01  Mike
2002-09-01  Britney
....

2002-09-30  Francis
2002-09-30  Michael
2002-09-30  Charlie
2002-09-30  Joe
2002-09-30  Hilary

As you can see, the names only change at the end of each month.
The most difficult step for me is that I have a selection of 5 names, and I don't really know how to resample to a daily Dataframe and still having 5 names for each day.

I already looked at this link

Resampling Error : cannot reindex a non-unique index with a method or limit

But It is not really the same issue and I still don't find any solution to manage mine.
If you have any ideas, you are welcome!

Body:
First, ensure your Date column is a datetime object:

df['Date'] = df.Date.astype('datetime64')

Then, group by the Date column, aggregate the names to list, resample by day and fill, finally perform an explode to expand the lists of names:

df.groupby('Date').agg(list).resample('D').ffill().explode('Name').reset_index()

# Result:
          Date     Name
0   2002-07-31     Paul
1   2002-07-31     John
2   2002-07-31   Silvia
3   2002-07-31     Mike
4   2002-07-31    Cindy
..         ...      ...
305 2002-09-30  Francis
306 2002-09-30  Michael
307 2002-09-30  Charlie
308 2002-09-30      Joe
309 2002-09-30   Hilary

[310 rows x 2 columns]