Popular New Releases in Business
yfinance
0.1.70
invoiceninja
v5.3.82
akaunting
2.1.33
stock
发布 v1.0 版本
ticker
v4.5.0
Popular Libraries in Business
by waditu python
11075 BSD-3-Clause
TuShare is a utility for crawling historical data of China stocks
by ranaroussi python
6548 Apache-2.0
Download market data from Yahoo! Finance's API
by invoiceninja php
6444 NOASSERTION
Invoices, Expenses and Tasks built with Laravel and Flutter
by mrjbq7 python
5392 NOASSERTION
Python wrapper for TA-Lib (http://ta-lib.org/).
by hql287 javascript
5187 LGPL-3.0
🎉 Flexible invoicing desktop app with beautiful & customizable templates.
by akaunting php
4821 GPL-3.0
Free and Online Accounting Software
by pythonstock python
4553 Apache-2.0
stock,股票系统。使用python进行开发。
by achannarasappa go
4150 GPL-3.0
Terminal stock ticker with live updates and position tracking
by bytefury php
4101 NOASSERTION
Free & Open Source Invoice App for Freelancers & Small Businesses
Trending New libraries in Business
by achannarasappa go
4150 GPL-3.0
Terminal stock ticker with live updates and position tracking
by iam-abbas python
1464 MIT
Fetch currently trending stocks on Reddit
by JerBouma python
662 MIT
This is a database of 180.000+ symbols containing Equities, ETFs, Funds, Indices, Futures, Options, Currencies, Cryptocurrencies and Money Markets.
by axiaoxin-com go
520 Apache-2.0
Golang实现财报分析、股票检测、基本面选股、基金检测、基金筛选、4433法则、基金持仓相似度、股票选基
by jacktrip-webrtc javascript
371 GPL-3.0
JackTrip meets WebRTC
by wbbhcb jupyter notebook
350
by marketsentiment python
269 GPL-3.0
Track live sentiment for stocks from Reddit and Twitter and identify growing stocks
by lukstei javascript
260
A web application to explore currently hyped stocks on Reddit
by shashankvemuri python
256 MIT
Here you can find all the quantitative finance algorithms that I've worked on and refined over the past year!
Top Authors in Business
1
7 Libraries
206
2
5 Libraries
140
3
4 Libraries
83
4
4 Libraries
188
5
3 Libraries
178
6
3 Libraries
93
7
3 Libraries
20
8
3 Libraries
348
9
3 Libraries
130
10
3 Libraries
86
1
7 Libraries
206
2
5 Libraries
140
3
4 Libraries
83
4
4 Libraries
188
5
3 Libraries
178
6
3 Libraries
93
7
3 Libraries
20
8
3 Libraries
348
9
3 Libraries
130
10
3 Libraries
86
Trending Kits in Business
No Trending Kits are available at this moment for Business
Trending Discussions on Business
Is there a C++14 alternative to explicit(expr) introduced in C++20?
Material-UI Data Grid onSortModelChange Causing an Infinite Loop
Java map function throws non-static method compiler error
How to access all draft campaigns with the Facebook marketing API?
How to implement the Hindenburg omen indicator?
jQuery .append doesn't work with $(document).ready
Project loom, what happens when virtual thread makes a blocking system call?
Koltin return null if value is null else
Pandas group cumsum with condition
Reactjs separation of UI and business logic
QUESTION
Is there a C++14 alternative to explicit(expr) introduced in C++20?
Asked 2022-Mar-04 at 07:43TL;DR: I am looking for a C++14 equivalent of the following C++20 MWE:
1template<int sz>
2struct bits {
3 int v; // note explicit(expr) below
4 explicit(sz > 1) operator bool() const { return bool(v); }
5};
6
7int main() {
8 bool c = bits<1>{1}; // Should work
9 bool d = bits<3>{1}; // Should fail
10}
11
Context:
We have a C++ class bits<sz>
representing bitvectors of length sz
. Conversion to bool
used to be implicit for all sz
, but this proved to be error-prone, so we changed operator bool()
to be explicit.
However, 1-bit
bitvectors are (in our context) almost-completely equivalent to Booleans, so it would be desirable for operator bool()
to be implicit when sz == 1
.
This can be achieved with explicit(sz > 1)
in C++20, but we are targeting C++14.
I tried to overload the operator for sz == 1
, but it seems that the explicit
qualifier applies to it as well: the following does not work.
1template<int sz>
2struct bits {
3 int v; // note explicit(expr) below
4 explicit(sz > 1) operator bool() const { return bool(v); }
5};
6
7int main() {
8 bool c = bits<1>{1}; // Should work
9 bool d = bits<3>{1}; // Should fail
10}
11template<int sz>
12struct bits {
13 int v;
14 explicit operator bool() const { return bool(v); }
15};
16
17template<> bits<1>::operator bool() const {
18 return bool(v);
19}
20
21int main() {
22 bool c = bits<1>{1}; // Fails: "No viable conversion"
23}
24
Hence the question: How can I specify in C++14 that operator bool()
should be explicit only for sz > 1
?
I'm including some background below for curious readers.
Background:
This problem came up in the context of an embedded domain-specific language in C++. One of the business requirements is that operator==
returns a bit<1>
, not a bool
. This is working smoothly with GNU's libstdc++, but we're running into trouble with that requirement on macOS because libstdc++ there implements operator==
on std::array
using the version of std::equal
that takes a predicate, and implements that predicate using a struct whose operator()
returns bool
with body a == b
(which in our case returns a bits<1>
, causing a conversion error).
To make it concrete for curious readers, the following program compiles fine on GNU, but not on macOS, because of the way operator==
on std::array
is implemented:
1template<int sz>
2struct bits {
3 int v; // note explicit(expr) below
4 explicit(sz > 1) operator bool() const { return bool(v); }
5};
6
7int main() {
8 bool c = bits<1>{1}; // Should work
9 bool d = bits<3>{1}; // Should fail
10}
11template<int sz>
12struct bits {
13 int v;
14 explicit operator bool() const { return bool(v); }
15};
16
17template<> bits<1>::operator bool() const {
18 return bool(v);
19}
20
21int main() {
22 bool c = bits<1>{1}; // Fails: "No viable conversion"
23}
24#include <array>
25
26struct S { explicit operator bool() const { return true; } };
27
28struct T {};
29S operator==(T, T) { return S(); }
30
31int main() {
32 std::array<T, 1> arr = { T() };
33 return arr == arr;
34}
35
That's because deep down in the implementation of ==
on arrays GNU libstdc++ has a test if (!(*it1 == *it2))
, which invokes the explicit operator bool()
on S
without trouble, where as on macOS the library uses if (!__pred(*it1, *it2))
with __pred
roughly equivalent to bool __pred(S a, S b) { return a == b; }
, which doesn't typecheck.
ANSWER
Answered 2022-Mar-04 at 07:43Yes. You can SFINAE the conversion operator:
1template<int sz>
2struct bits {
3 int v; // note explicit(expr) below
4 explicit(sz > 1) operator bool() const { return bool(v); }
5};
6
7int main() {
8 bool c = bits<1>{1}; // Should work
9 bool d = bits<3>{1}; // Should fail
10}
11template<int sz>
12struct bits {
13 int v;
14 explicit operator bool() const { return bool(v); }
15};
16
17template<> bits<1>::operator bool() const {
18 return bool(v);
19}
20
21int main() {
22 bool c = bits<1>{1}; // Fails: "No viable conversion"
23}
24#include <array>
25
26struct S { explicit operator bool() const { return true; } };
27
28struct T {};
29S operator==(T, T) { return S(); }
30
31int main() {
32 std::array<T, 1> arr = { T() };
33 return arr == arr;
34}
35#include <type_traits>
36
37template<int sz>
38struct bits {
39 int v;
40 explicit operator bool() const { return bool(v); }
41
42 template <int S = sz>
43 operator std::enable_if_t<S == 1, bool> () const { return bool(v);}
44};
45
Check it on godbolt
1template<int sz>
2struct bits {
3 int v; // note explicit(expr) below
4 explicit(sz > 1) operator bool() const { return bool(v); }
5};
6
7int main() {
8 bool c = bits<1>{1}; // Should work
9 bool d = bits<3>{1}; // Should fail
10}
11template<int sz>
12struct bits {
13 int v;
14 explicit operator bool() const { return bool(v); }
15};
16
17template<> bits<1>::operator bool() const {
18 return bool(v);
19}
20
21int main() {
22 bool c = bits<1>{1}; // Fails: "No viable conversion"
23}
24#include <array>
25
26struct S { explicit operator bool() const { return true; } };
27
28struct T {};
29S operator==(T, T) { return S(); }
30
31int main() {
32 std::array<T, 1> arr = { T() };
33 return arr == arr;
34}
35#include <type_traits>
36
37template<int sz>
38struct bits {
39 int v;
40 explicit operator bool() const { return bool(v); }
41
42 template <int S = sz>
43 operator std::enable_if_t<S == 1, bool> () const { return bool(v);}
44};
45int main()
46{
47 bool c1 = bits<1>{1}; // Ok
48 bool c2 = bits<3>{1}; // error cannot convert
49 bool c3 = static_cast<bool>(bits<3>{1}); // OK
50}
51
QUESTION
Material-UI Data Grid onSortModelChange Causing an Infinite Loop
Asked 2022-Feb-14 at 23:31I'm following the Sort Model documentation (https://material-ui.com/components/data-grid/sorting/#basic-sorting) and am using sortModel
and onSortModelChange
exactly as used in the documentation. However, I'm getting an infinite loop immediately after loading the page (I can tell this based on the console.log).
What I've tried:
- Using useCallback within the onSortChange prop
- Using server side sorting (https://material-ui.com/components/data-grid/sorting/#server-side-sorting)
- Using
if (sortModel !== model) setSortModel(model)
within the onSortChange function.
I always end up with the same issue. I'm using Blitz.js.
My code:
useState:
1const [sortModel, setSortModel] = useState<GridSortModel>([
2 {
3 field: "updatedAt",
4 sort: "desc" as GridSortDirection,
5 },
6 ])
7
rows definition:
1const [sortModel, setSortModel] = useState<GridSortModel>([
2 {
3 field: "updatedAt",
4 sort: "desc" as GridSortDirection,
5 },
6 ])
7 const rows = currentUsersApplications.map((application) => {
8 return {
9 id: application.id,
10 business_name: application.business_name,
11 business_phone: application.business_phone,
12 applicant_name: application.applicant_name,
13 applicant_email: application.applicant_email,
14 owner_cell_phone: application.owner_cell_phone,
15 status: application.status,
16 agent_name: application.agent_name,
17 equipment_description: application.equipment_description,
18 createdAt: formattedDate(application.createdAt),
19 updatedAt: formattedDate(application.updatedAt),
20 archived: application.archived,
21 }
22 })
23
columns definition:
1const [sortModel, setSortModel] = useState<GridSortModel>([
2 {
3 field: "updatedAt",
4 sort: "desc" as GridSortDirection,
5 },
6 ])
7 const rows = currentUsersApplications.map((application) => {
8 return {
9 id: application.id,
10 business_name: application.business_name,
11 business_phone: application.business_phone,
12 applicant_name: application.applicant_name,
13 applicant_email: application.applicant_email,
14 owner_cell_phone: application.owner_cell_phone,
15 status: application.status,
16 agent_name: application.agent_name,
17 equipment_description: application.equipment_description,
18 createdAt: formattedDate(application.createdAt),
19 updatedAt: formattedDate(application.updatedAt),
20 archived: application.archived,
21 }
22 })
23
24 const columns = [
25 { field: "id", headerName: "ID", width: 70, hide: true },
26 {
27 field: "business_name",
28 headerName: "Business Name",
29 width: 200,
30 // Need renderCell() here because this is a link and not just a string
31 renderCell: (params: GridCellParams) => {
32 console.log(params)
33 return <BusinessNameLink application={params.row} />
34 },
35 },
36 { field: "business_phone", headerName: "Business Phone", width: 180 },
37 { field: "applicant_name", headerName: "Applicant Name", width: 180 },
38 { field: "applicant_email", headerName: "Applicant Email", width: 180 },
39 { field: "owner_cell_phone", headerName: "Ownership/Guarantor Phone", width: 260 },
40 { field: "status", headerName: "Status", width: 130 },
41 { field: "agent_name", headerName: "Agent", width: 130 },
42 { field: "equipment_description", headerName: "Equipment", width: 200 },
43 { field: "createdAt", headerName: "Submitted At", width: 250 },
44 { field: "updatedAt", headerName: "Last Edited", width: 250 },
45 { field: "archived", headerName: "Archived", width: 180, type: "boolean" },
46 ]
47
Rendering DataGrid and using sortModel/onSortChange
1const [sortModel, setSortModel] = useState<GridSortModel>([
2 {
3 field: "updatedAt",
4 sort: "desc" as GridSortDirection,
5 },
6 ])
7 const rows = currentUsersApplications.map((application) => {
8 return {
9 id: application.id,
10 business_name: application.business_name,
11 business_phone: application.business_phone,
12 applicant_name: application.applicant_name,
13 applicant_email: application.applicant_email,
14 owner_cell_phone: application.owner_cell_phone,
15 status: application.status,
16 agent_name: application.agent_name,
17 equipment_description: application.equipment_description,
18 createdAt: formattedDate(application.createdAt),
19 updatedAt: formattedDate(application.updatedAt),
20 archived: application.archived,
21 }
22 })
23
24 const columns = [
25 { field: "id", headerName: "ID", width: 70, hide: true },
26 {
27 field: "business_name",
28 headerName: "Business Name",
29 width: 200,
30 // Need renderCell() here because this is a link and not just a string
31 renderCell: (params: GridCellParams) => {
32 console.log(params)
33 return <BusinessNameLink application={params.row} />
34 },
35 },
36 { field: "business_phone", headerName: "Business Phone", width: 180 },
37 { field: "applicant_name", headerName: "Applicant Name", width: 180 },
38 { field: "applicant_email", headerName: "Applicant Email", width: 180 },
39 { field: "owner_cell_phone", headerName: "Ownership/Guarantor Phone", width: 260 },
40 { field: "status", headerName: "Status", width: 130 },
41 { field: "agent_name", headerName: "Agent", width: 130 },
42 { field: "equipment_description", headerName: "Equipment", width: 200 },
43 { field: "createdAt", headerName: "Submitted At", width: 250 },
44 { field: "updatedAt", headerName: "Last Edited", width: 250 },
45 { field: "archived", headerName: "Archived", width: 180, type: "boolean" },
46 ]
47 <div style={{ height: 580, width: "100%" }} className={classes.gridRowColor}>
48 <DataGrid
49 getRowClassName={(params) => `MuiDataGrid-row--${params.getValue(params.id, "status")}`}
50 rows={rows}
51 columns={columns}
52 pageSize={10}
53 components={{
54 Toolbar: GridToolbar,
55 }}
56 filterModel={{
57 items: [{ columnField: "archived", operatorValue: "is", value: showArchived }],
58 }}
59 sortModel={sortModel}
60 onSortModelChange={(model) => {
61 console.log(model)
62 //Infinitely logs model immediately
63 setSortModel(model)
64 }}
65 />
66 </div>
67
Thanks in advance!
ANSWER
Answered 2021-Aug-31 at 19:57I fixed this by wrapping rows
and columns
in useRefs and used their .current
property for both of them. Fixed it immediately.
QUESTION
Java map function throws non-static method compiler error
Asked 2022-Jan-27 at 04:17I have an odd problem, where I am struggling to understand the nature of "static context" in Java, despite the numerous SO questions regarding the topic.
TL;DR:
I have a design flaw, where ...
This works:
1List<OrderExtnTrans> list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3
But this does not:
1List<OrderExtnTrans> list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4
The error shown in the second version is "Non-static method cannot be referenced from a static context".
The long version:
Object Model: The model consists of Business Type specific orders (eg. Stock exchange, payments), which inherit from a an order entity via an "InheritanceType.JOINED" inheritance strategy. The parent order can be parameterized with the business type specific DTO object of that order, so for example DtoStockExchangeOrder. This is to enable, that JPA objects can be mapped to their DTO equivalent within the Entity, rather than in a service (which I did previously. It worked, but its "less clean").
JPA Order:
1List<OrderExtnTrans> list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4@Entity
5@Table(name = "ORDER_BASE")
6@Inheritance(strategy = InheritanceType.JOINED)
7public class Order<DtoOrderType extends DtoOrder> implements Serializable {
8
9 @OneToMany(fetch = FetchType.LAZY, mappedBy = "order", orphanRemoval = true)
10 private List<OrderExtnTrans> orderExtnTransList = new ArrayList<>();
11
12}
13
JPA Order - Business Type specific example:
1List<OrderExtnTrans> list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4@Entity
5@Table(name = "ORDER_BASE")
6@Inheritance(strategy = InheritanceType.JOINED)
7public class Order<DtoOrderType extends DtoOrder> implements Serializable {
8
9 @OneToMany(fetch = FetchType.LAZY, mappedBy = "order", orphanRemoval = true)
10 private List<OrderExtnTrans> orderExtnTransList = new ArrayList<>();
11
12}
13@Entity
14@Table(name = "ORDER_STEX")
15@Inheritance(strategy = InheritanceType.JOINED)
16public class OrderStex extends Order<DtoOrderStex> implements Serializable {
17
Likewise, DTO orders follow the same pattern, where they can be parameterized with the business type specific JPA entity, to enable the relevant mapping:
DTO Order:
1List<OrderExtnTrans> list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4@Entity
5@Table(name = "ORDER_BASE")
6@Inheritance(strategy = InheritanceType.JOINED)
7public class Order<DtoOrderType extends DtoOrder> implements Serializable {
8
9 @OneToMany(fetch = FetchType.LAZY, mappedBy = "order", orphanRemoval = true)
10 private List<OrderExtnTrans> orderExtnTransList = new ArrayList<>();
11
12}
13@Entity
14@Table(name = "ORDER_STEX")
15@Inheritance(strategy = InheritanceType.JOINED)
16public class OrderStex extends Order<DtoOrderStex> implements Serializable {
17public class DtoOrder<OrderType extends Order> extends DtoEntity {
18
DTO Order - Business Type Specific Example
1List<OrderExtnTrans> list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4@Entity
5@Table(name = "ORDER_BASE")
6@Inheritance(strategy = InheritanceType.JOINED)
7public class Order<DtoOrderType extends DtoOrder> implements Serializable {
8
9 @OneToMany(fetch = FetchType.LAZY, mappedBy = "order", orphanRemoval = true)
10 private List<OrderExtnTrans> orderExtnTransList = new ArrayList<>();
11
12}
13@Entity
14@Table(name = "ORDER_STEX")
15@Inheritance(strategy = InheritanceType.JOINED)
16public class OrderStex extends Order<DtoOrderStex> implements Serializable {
17public class DtoOrder<OrderType extends Order> extends DtoEntity {
18public class DtoOrderStex extends DtoOrder<OrderStex> {
19
The DTOEntity class it inherits from is just a "wrapper" class, consisting of an ID and a name.
Now the tricky part: The DTOOrder class has a constructor which populates the fields that are common to all business types, like the list of process status transitions, an order goes through in its life cycle (placed, cancelled, executed, etc..). Staying with the example of the process status transitions, these are also modelled as JPA entities in the database, with their corresponding DTO counterparts (likewise parameterized, that part works fine).
Here the constructor:
1List<OrderExtnTrans> list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4@Entity
5@Table(name = "ORDER_BASE")
6@Inheritance(strategy = InheritanceType.JOINED)
7public class Order<DtoOrderType extends DtoOrder> implements Serializable {
8
9 @OneToMany(fetch = FetchType.LAZY, mappedBy = "order", orphanRemoval = true)
10 private List<OrderExtnTrans> orderExtnTransList = new ArrayList<>();
11
12}
13@Entity
14@Table(name = "ORDER_STEX")
15@Inheritance(strategy = InheritanceType.JOINED)
16public class OrderStex extends Order<DtoOrderStex> implements Serializable {
17public class DtoOrder<OrderType extends Order> extends DtoEntity {
18public class DtoOrderStex extends DtoOrder<OrderStex> {
19public DtoOrder(OrderType orderType) {
20 super(orderType);
21 // this is the part from above, which works (but it shows a warning: Unchecked assignment: 'java.util.List' to 'java.util.List<com.tradingvessel.core.persistence.model.OrderExtnTrans>' )
22 List<OrderExtnTrans> list = orderType.getOrderExtnTransList();
23 this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
24 // this is how I would have expected it to work, but it does not, with the error shown above: "Non-static method cannot be referenced from a static context"
25 this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
26}
27
If I comment out the non-working version, the application behaves as expected and throws no error, so "logically", this works. But JAVA does not allow it as developed in the second version.
If instead of OrderType I use "Order", it works as well, but obviously throws errors elsewhere, because the signature of the constructor changed. I assume another approach would be to parameterise the method based on the the caller of the constructor or to parameterise the parent class DtoOrder to know the type of the child class, but there should be a better way?
What am I doing wrong, and why does the upper version work as expected?
ANSWER
Answered 2022-Jan-26 at 17:11One way to solve the issue is by parameterizing the ParentDTO Class with its own children.
1List<OrderExtnTrans> list = orderType.getOrderExtnTransList();
2this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
3this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
4@Entity
5@Table(name = "ORDER_BASE")
6@Inheritance(strategy = InheritanceType.JOINED)
7public class Order<DtoOrderType extends DtoOrder> implements Serializable {
8
9 @OneToMany(fetch = FetchType.LAZY, mappedBy = "order", orphanRemoval = true)
10 private List<OrderExtnTrans> orderExtnTransList = new ArrayList<>();
11
12}
13@Entity
14@Table(name = "ORDER_STEX")
15@Inheritance(strategy = InheritanceType.JOINED)
16public class OrderStex extends Order<DtoOrderStex> implements Serializable {
17public class DtoOrder<OrderType extends Order> extends DtoEntity {
18public class DtoOrderStex extends DtoOrder<OrderStex> {
19public DtoOrder(OrderType orderType) {
20 super(orderType);
21 // this is the part from above, which works (but it shows a warning: Unchecked assignment: 'java.util.List' to 'java.util.List<com.tradingvessel.core.persistence.model.OrderExtnTrans>' )
22 List<OrderExtnTrans> list = orderType.getOrderExtnTransList();
23 this.dtoOrderExtnTransList = list.stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
24 // this is how I would have expected it to work, but it does not, with the error shown above: "Non-static method cannot be referenced from a static context"
25 this.dtoOrderExtnTransList = orderType.getOrderExtnTransList().stream().map(OrderExtnTrans::toDto).collect(Collectors.toList());
26}
27public class DtoOrderStex extends DtoOrder<OrderStex, DtoOrderStex> {
28
29
30 public DtoOrderStex(OrderStex orderStex) {
31 super(orderStex);
32 }
33
34 public DtoOrderStex() {
35 }
36}
37
This raises the question: Does this have any serious negative side effects, apart from the redundancy in the child classes? And why is that necessary in the first place, given that the class is already a child of its parent?
QUESTION
How to access all draft campaigns with the Facebook marketing API?
Asked 2022-Jan-17 at 14:53I'm trying to list all of my draft campaigns using the Facebook marketing API. By default, it seems, only non-draft (published?) campaigns are listed when calling
1curl -i -X GET \
2 "https://graph.facebook.com/v12.0/act_12345/campaigns?fields=id,name&access_token=<mytoken>"
3
When looking at the code of the facebook-python-business-sdk, there are multiple references to unpublished content type, which makes me think that there should be a way to list all unpublished campaigns. So my question is how can I list all campaigns, published and unpublished?
I know this question is a duplicate (see here, here, and here) but I'm asking it again since it has not been answered and I'd like to put out a bounty for a helpful response.
ANSWER
Answered 2021-Dec-01 at 15:44I believe the only way to get draft campaigns is below:
- You should get all
addrafts
. On my account I have only 1 addraft that contains all draft campaigns, but maybe you can have more. URL for gettingaddrafts
:
https://graph.facebook.com/v12.0/act_<ad_account_id>/addrafts?access_token=<access_token>&fields=name,ad_object_id,id
- Now you can get
addraft_fragments
. You can see all draft fragments of your ad_account (campaigns, adsets, ads), but you can easily find here what you want. URL for gettingaddraft_fragments
:
https://graph.facebook.com/v12.0/<addraft_id>/addraft_fragments?access_token=<access_token>&fields=name,id,ad_object_id,ad_object_type,budget,ad_object_name,values
QUESTION
How to implement the Hindenburg omen indicator?
Asked 2021-Dec-21 at 02:21As defined here the Hindenburg omen indicator is:
The daily number of new 52-week highs and 52-week lows in a stock market index are greater than a threshold amount (typically 2.2%).
To me it means, we roll daily and look back 52 weeks or 252 business/trading days, then count the number of highs (or lows) and finally compute the return of that or pct_change, which is the ratio of new highs (or lows) they want to monitor e.g., being above 2.2%
1import pandas as pd
2import numpy as np
3import yfinance as yf
4
5# download the S&P500
6df = yf.download('^GSPC')
7# compute the "highs" and "lows"
8df['Highs'] = df['Close'].rolling(252).apply(lambda x: x.cummax().diff().
9 apply(lambda x: np.where(x > 0, 1, 0)).sum()).pct_change()
10df['Lows'] = df['Close'].rolling(252).apply(lambda x: x.cummin().diff().
11 apply(lambda x: np.where(x < 0, 1, 0)).sum()).pct_change()
12
Did we understand it the same way? is there a better way to do it?
ANSWER
Answered 2021-Dec-21 at 02:21Interesting question! Could I suggest the following code - it runs much faster than the apply
solution because it is vectorised, and also lays out the steps a bit more clearly so you can inspect the interim results.
I got a different result to your code - you can compare by also plotting your result on the timeseries at bottom.
1import pandas as pd
2import numpy as np
3import yfinance as yf
4
5# download the S&P500
6df = yf.download('^GSPC')
7# compute the "highs" and "lows"
8df['Highs'] = df['Close'].rolling(252).apply(lambda x: x.cummax().diff().
9 apply(lambda x: np.where(x > 0, 1, 0)).sum()).pct_change()
10df['Lows'] = df['Close'].rolling(252).apply(lambda x: x.cummin().diff().
11 apply(lambda x: np.where(x < 0, 1, 0)).sum()).pct_change()
12import pandas as pd
13import numpy as np
14import yfinance as yf
15
16# download the S&P500
17df = yf.download('^GSPC')
18
19# Constants
20n_trading_day_window = 252
21
22# Simplify the input dataframe to only the relevant column
23df_hin_omen = df[['Close']]
24# Calculate rolling highs and lows
25df_hin_omen.insert(1, 'rolling_high', df_hin_omen['Close'].rolling(n_trading_day_window).max())
26df_hin_omen.insert(2, 'rolling_low', df_hin_omen['Close'].rolling(n_trading_day_window).min())
27# High and low are simply when the given row matches the 252 day high or low
28df_hin_omen.insert(3, 'is_high', df_hin_omen.Close == df_hin_omen.rolling_high)
29df_hin_omen.insert(4, 'is_low', df_hin_omen.Close == df_hin_omen.rolling_low)
30# Calculate rolling percentages
31df_hin_omen.insert(5, 'percent_highs', df_hin_omen.is_high.rolling(n_trading_day_window).sum() / n_trading_day_window)
32df_hin_omen.insert(6, 'percent_lows', df_hin_omen.is_low.rolling(n_trading_day_window).sum() / n_trading_day_window)
33
Once you have run this, you can inspect the results as follows:
1import pandas as pd
2import numpy as np
3import yfinance as yf
4
5# download the S&P500
6df = yf.download('^GSPC')
7# compute the "highs" and "lows"
8df['Highs'] = df['Close'].rolling(252).apply(lambda x: x.cummax().diff().
9 apply(lambda x: np.where(x > 0, 1, 0)).sum()).pct_change()
10df['Lows'] = df['Close'].rolling(252).apply(lambda x: x.cummin().diff().
11 apply(lambda x: np.where(x < 0, 1, 0)).sum()).pct_change()
12import pandas as pd
13import numpy as np
14import yfinance as yf
15
16# download the S&P500
17df = yf.download('^GSPC')
18
19# Constants
20n_trading_day_window = 252
21
22# Simplify the input dataframe to only the relevant column
23df_hin_omen = df[['Close']]
24# Calculate rolling highs and lows
25df_hin_omen.insert(1, 'rolling_high', df_hin_omen['Close'].rolling(n_trading_day_window).max())
26df_hin_omen.insert(2, 'rolling_low', df_hin_omen['Close'].rolling(n_trading_day_window).min())
27# High and low are simply when the given row matches the 252 day high or low
28df_hin_omen.insert(3, 'is_high', df_hin_omen.Close == df_hin_omen.rolling_high)
29df_hin_omen.insert(4, 'is_low', df_hin_omen.Close == df_hin_omen.rolling_low)
30# Calculate rolling percentages
31df_hin_omen.insert(5, 'percent_highs', df_hin_omen.is_high.rolling(n_trading_day_window).sum() / n_trading_day_window)
32df_hin_omen.insert(6, 'percent_lows', df_hin_omen.is_low.rolling(n_trading_day_window).sum() / n_trading_day_window)
33import matplotlib, matplotlib.pyplot as plt
34fig, ax = plt.subplots(figsize=(16, 6))
35df_hin_omen.resample('w').mean().percent_highs.plot(ax=ax)
36df_hin_omen.resample('w').mean().percent_lows.plot(ax=ax)
37
From the Hindenburg Omen Definition, "The Hindenburg Omen looks for a statistical deviation from the premise that under normal conditions, some stocks are either making new 52-week highs or new 52-week lows. It would be abnormal if both were occurring at the same time."
So from a look at our graph, my interpretation is that the stock market is currently closing at a lot of 52 week highs, but is not showing many 52 week lows. Please also note the article cited states that "It was reported that it had correctly predicted a significant stock market decline only 25% of the time." so I'm not sure if we can read too much into this...
Edit
I've had a look at your code and I don't think that the use of the pct_change
function is correct - that will calculate the change on the rolling differential, so a movement from eg 0.10% to 0.11% would actually equate to a 10% change. Instead you want the rolling sum over the past year and divide that by the number of days in the year, per my code above.
QUESTION
jQuery .append doesn't work with $(document).ready
Asked 2021-Dec-19 at 18:08This is a followup to toggleClass of parent div not changing with onClick
In my HTML layout, I've found that I need to generate the div #filters
after the records, not before, because I need to use PHP to build the buttons for each state. This gave me the idea to use jQuery .append
to move the #filters to the #move-filters-here above the records. But after I filter on a state, the filters appear below the records and .append
doesn't work to move the #filters to #move-filters-here above the records.
Is .append
not working with (document).ready?
Is there a different way to get .append
to move the #filters?
Does .append
need to "fire" again after the Onclick function?
Fiddle: https://jsfiddle.net/j3semt6h/10/
1$(document).ready(function(){
2
3$("#filters").append("#move-filters-here");
4
5$('.state-button').on('click', function() {
6
7 let _this = $(this);
8
9 if (!_this.hasClass('active')) {
10
11 $('.state-button.active, .record.active').removeClass('active');
12 $('[data-state=' + _this.data('state') + ']').addClass('active');
13
14 }
15
16});
17
18});
1$(document).ready(function(){
2
3$("#filters").append("#move-filters-here");
4
5$('.state-button').on('click', function() {
6
7 let _this = $(this);
8
9 if (!_this.hasClass('active')) {
10
11 $('.state-button.active, .record.active').removeClass('active');
12 $('[data-state=' + _this.data('state') + ']').addClass('active');
13
14 }
15
16});
17
18}); .record {
19 display: none;
20}
21
22.state-button {
23 border: 2px solid #c2c2c2;
24 padding: 5px;
25 border-radius: 5px;
26 margin: 0 10px 0 10px;
27}
28
29.state-button.active {
30 border-color: red;
31}
32
33.record.active {
34 display: block;
35}
1$(document).ready(function(){
2
3$("#filters").append("#move-filters-here");
4
5$('.state-button').on('click', function() {
6
7 let _this = $(this);
8
9 if (!_this.hasClass('active')) {
10
11 $('.state-button.active, .record.active').removeClass('active');
12 $('[data-state=' + _this.data('state') + ']').addClass('active');
13
14 }
15
16});
17
18}); .record {
19 display: none;
20}
21
22.state-button {
23 border: 2px solid #c2c2c2;
24 padding: 5px;
25 border-radius: 5px;
26 margin: 0 10px 0 10px;
27}
28
29.state-button.active {
30 border-color: red;
31}
32
33.record.active {
34 display: block;
35} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
36
37<div id="move-filters-here"></div>
38
39<div class="record" data-state="AK">
40 <h1 class="name">Customer 1</h1>
41 <ul>
42 <li class="focus">Focus: </li>
43 <li class="course">Course: </li>
44 <li class="business">Business: </li>
45 <li class="address">Location: 345 Cow Town, Anchorage, <span class="state">AK</span></li>
46 </ul>
47</div>
48<div class="record" data-state="AR">
49 <h1 class="name">Customer 2</h1>
50 <ul>
51 <li class="focus">Focus: </li>
52 <li class="course">Course: </li>
53 <li class="business">Business: </li>
54 <li class="address">Location: Mobile, <span class="state">AR</span></li>
55 </ul>
56</div>
57<div class="record" data-state="CA">
58 <h1 class="name">Customer 3</h1>
59 <ul>
60 <li class="focus">Focus: </li>
61 <li class="course">Course: </li>
62 <li class="business">Business: </li>
63 <li class="address">Location: Los Angeles <span class="state">CA</span></li>
64 </ul>
65</div>
66
67<div class="record" data-state="AZ">
68 <h1 class="name">Customer 3</h1>
69 <ul>
70 <li class="focus">Focus: </li>
71 <li class="course">Course: </li>
72 <li class="business">Business: </li>
73 <li class="address">Location: Flagstaff <span class="state">AZ</span></li>
74 </ul>
75</div>
76
77<div class="record" data-state="UT">
78 <h1 class="name">Customer 3</h1>
79 <ul>
80 <li class="focus">Focus: </li>
81 <li class="course">Course: </li>
82 <li class="business">Business: </li>
83 <li class="address">Location: SLC <span class="state">UT</span></li>
84 </ul>
85</div>
86
87
88<div id="filters">
89<button class="state-button state-button-ak" data-state="AK">Alaska</button>
90<button class="state-button state-button-ar" data-state="AR">Arkansas</button>
91<button class="state-button state-button-ca" data-state="CA">California</button>
92<button class="state-button state-button-ca" data-state="AZ">Arizona</button>
93<button class="state-button state-button-ut" data-state="UT">Utah</button>
94</div>
ANSWER
Answered 2021-Dec-19 at 18:07if you want append #filter
to #move-filters-here
you can do it like this:
1$(document).ready(function(){
2
3$("#filters").append("#move-filters-here");
4
5$('.state-button').on('click', function() {
6
7 let _this = $(this);
8
9 if (!_this.hasClass('active')) {
10
11 $('.state-button.active, .record.active').removeClass('active');
12 $('[data-state=' + _this.data('state') + ']').addClass('active');
13
14 }
15
16});
17
18}); .record {
19 display: none;
20}
21
22.state-button {
23 border: 2px solid #c2c2c2;
24 padding: 5px;
25 border-radius: 5px;
26 margin: 0 10px 0 10px;
27}
28
29.state-button.active {
30 border-color: red;
31}
32
33.record.active {
34 display: block;
35} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
36
37<div id="move-filters-here"></div>
38
39<div class="record" data-state="AK">
40 <h1 class="name">Customer 1</h1>
41 <ul>
42 <li class="focus">Focus: </li>
43 <li class="course">Course: </li>
44 <li class="business">Business: </li>
45 <li class="address">Location: 345 Cow Town, Anchorage, <span class="state">AK</span></li>
46 </ul>
47</div>
48<div class="record" data-state="AR">
49 <h1 class="name">Customer 2</h1>
50 <ul>
51 <li class="focus">Focus: </li>
52 <li class="course">Course: </li>
53 <li class="business">Business: </li>
54 <li class="address">Location: Mobile, <span class="state">AR</span></li>
55 </ul>
56</div>
57<div class="record" data-state="CA">
58 <h1 class="name">Customer 3</h1>
59 <ul>
60 <li class="focus">Focus: </li>
61 <li class="course">Course: </li>
62 <li class="business">Business: </li>
63 <li class="address">Location: Los Angeles <span class="state">CA</span></li>
64 </ul>
65</div>
66
67<div class="record" data-state="AZ">
68 <h1 class="name">Customer 3</h1>
69 <ul>
70 <li class="focus">Focus: </li>
71 <li class="course">Course: </li>
72 <li class="business">Business: </li>
73 <li class="address">Location: Flagstaff <span class="state">AZ</span></li>
74 </ul>
75</div>
76
77<div class="record" data-state="UT">
78 <h1 class="name">Customer 3</h1>
79 <ul>
80 <li class="focus">Focus: </li>
81 <li class="course">Course: </li>
82 <li class="business">Business: </li>
83 <li class="address">Location: SLC <span class="state">UT</span></li>
84 </ul>
85</div>
86
87
88<div id="filters">
89<button class="state-button state-button-ak" data-state="AK">Alaska</button>
90<button class="state-button state-button-ar" data-state="AR">Arkansas</button>
91<button class="state-button state-button-ca" data-state="CA">California</button>
92<button class="state-button state-button-ca" data-state="AZ">Arizona</button>
93<button class="state-button state-button-ut" data-state="UT">Utah</button>
94</div>$("#move-filters-here").append($("#filters"));
95
and if you do it vice-versa, you can acheive your goal like this:
1$(document).ready(function(){
2
3$("#filters").append("#move-filters-here");
4
5$('.state-button').on('click', function() {
6
7 let _this = $(this);
8
9 if (!_this.hasClass('active')) {
10
11 $('.state-button.active, .record.active').removeClass('active');
12 $('[data-state=' + _this.data('state') + ']').addClass('active');
13
14 }
15
16});
17
18}); .record {
19 display: none;
20}
21
22.state-button {
23 border: 2px solid #c2c2c2;
24 padding: 5px;
25 border-radius: 5px;
26 margin: 0 10px 0 10px;
27}
28
29.state-button.active {
30 border-color: red;
31}
32
33.record.active {
34 display: block;
35} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
36
37<div id="move-filters-here"></div>
38
39<div class="record" data-state="AK">
40 <h1 class="name">Customer 1</h1>
41 <ul>
42 <li class="focus">Focus: </li>
43 <li class="course">Course: </li>
44 <li class="business">Business: </li>
45 <li class="address">Location: 345 Cow Town, Anchorage, <span class="state">AK</span></li>
46 </ul>
47</div>
48<div class="record" data-state="AR">
49 <h1 class="name">Customer 2</h1>
50 <ul>
51 <li class="focus">Focus: </li>
52 <li class="course">Course: </li>
53 <li class="business">Business: </li>
54 <li class="address">Location: Mobile, <span class="state">AR</span></li>
55 </ul>
56</div>
57<div class="record" data-state="CA">
58 <h1 class="name">Customer 3</h1>
59 <ul>
60 <li class="focus">Focus: </li>
61 <li class="course">Course: </li>
62 <li class="business">Business: </li>
63 <li class="address">Location: Los Angeles <span class="state">CA</span></li>
64 </ul>
65</div>
66
67<div class="record" data-state="AZ">
68 <h1 class="name">Customer 3</h1>
69 <ul>
70 <li class="focus">Focus: </li>
71 <li class="course">Course: </li>
72 <li class="business">Business: </li>
73 <li class="address">Location: Flagstaff <span class="state">AZ</span></li>
74 </ul>
75</div>
76
77<div class="record" data-state="UT">
78 <h1 class="name">Customer 3</h1>
79 <ul>
80 <li class="focus">Focus: </li>
81 <li class="course">Course: </li>
82 <li class="business">Business: </li>
83 <li class="address">Location: SLC <span class="state">UT</span></li>
84 </ul>
85</div>
86
87
88<div id="filters">
89<button class="state-button state-button-ak" data-state="AK">Alaska</button>
90<button class="state-button state-button-ar" data-state="AR">Arkansas</button>
91<button class="state-button state-button-ca" data-state="CA">California</button>
92<button class="state-button state-button-ca" data-state="AZ">Arizona</button>
93<button class="state-button state-button-ut" data-state="UT">Utah</button>
94</div>$("#move-filters-here").append($("#filters"));
95$("#filters").append("#move-filters-here");
96
QUESTION
Project loom, what happens when virtual thread makes a blocking system call?
Asked 2021-Nov-30 at 21:58I was investigating how Project Loom works and what kind of benefits it can bring to my company.
So I understand the motivation, for standard servlet based backend, there is always a thread pool that executes a business logic, once thread is blocked because of IO it can't do anything but wait. So let's say I have a backend application that has single endpoint , the business logic behind this endpoint is to read some data using JDBC which internally uses InputStream which again will use blocking system call( read() in terms of Linux). So if I have 200 hundred users reaching this endpoint, I need to create 200 threads each waiting for IO.
Now let's say I switched a thread pool to use virtual threads instead. According to Ben Evans in the article Going inside Java’s Project Loom and virtual threads:
Instead, virtual threads automatically give up (or yield) their carrier thread when a blocking call (such as I/O) is made.
So as far as I understand, if I have amount of OS threads equals to amount of CPU cores and unbounded amount of virtual threads, all OS threads will still wait for IO and Executor service won't be able to assign new work for Virtual threads because there are no available threads to execute it. How is it different from regular threads , at least for OS threads I can scale it to thousand to increase the throughput. Or Did I just misunderstood the use case for Loom ? Thanks in advance
AddonI just read this mailing list:
Virtual threads love blocking I/O. If the thread needs to block in say a Socket read then this releases the underlying kernel thread to do other work
I am not sure I understand it, there is no way for OS to release the thread if it does a blocking call such as read, for these purposes kernel has non blocking syscalls such as epoll which doesn't block the thread and immediately returns a list of file descriptors that have some data available. Does the quote above implies that under the hood , JVM will replace a blocking read
with non blocking epoll
if thread that called it is virtual ?
ANSWER
Answered 2021-Nov-30 at 21:58Your first excerpt is missing the important point:
Instead, virtual threads automatically give up (or yield) their carrier thread when a blocking call (such as I/O) is made. This is handled by the library and runtime [...]
The implication is this: if your code makes a blocking call into the library (for example NIO) the library detects that you call it from a virtual thread and will turn the blocking call into a non-blocking call, park the virtual thread and continue processing some other virtual threads code.
Only if no virtual thread is ready to execute will a native thread be parked.
Note that your code never calls a blocking syscall, it calls into the java libraries (that currently execute the blocking syscall). Project Loom replaces the layers between your code and the blocking syscall and can therefore do anything it wants - as long as the result for your calling code looks the same.
QUESTION
Koltin return null if value is null else
Asked 2021-Nov-24 at 14:17I work with some business logic written in Kotlin. I've got such a case in my method - I check a value for null, and if it IS null - I want to return null, else do some logic. My version looks like:
1fun calculateFoo(parameter: SomeObject?): ReturnObject? =
2 if (parameter == null) null
3 else performCalculation(parameter)
4
Literally "If value is null then return itself else process it". Normally, we do something if value is NOT null, like elvis operator, but here is "reversed" logic. Is there a better solution for this?
ANSWER
Answered 2021-Nov-24 at 14:14You can use the ?.
operator in combination with let
.
1fun calculateFoo(parameter: SomeObject?): ReturnObject? =
2 if (parameter == null) null
3 else performCalculation(parameter)
4fun calculateFoo(parameter: SomeObject?): ReturnObject? =
5 parameter?.let { performCalculation(it) }
6
QUESTION
Pandas group cumsum with condition
Asked 2021-Oct-12 at 20:27I have the following df:
1df = pd.DataFrame({"values":[1,5,7,3,0,9,8,8,7,5,8,1,0,0,0,0,2,5],"signal":['L_exit',None,None,'R_entry','R_exit',None,'L_entry','L_exit',None,'R_entry','R_exit','R_entry','R_exit','L_entry','L_exit','L_entry','R_exit',None]})
2df
3
4 values signal
50 1 L_exit
61 5 None
72 7 None
83 3 R_entry
94 0 R_exit
105 9 None
116 8 L_entry
127 8 L_exit
138 7 None
149 5 R_entry
1510 8 R_exit
1611 1 R_entry
1712 0 R_exit
1813 0 L_entry
1914 0 L_exit
2015 0 L_entry
2116 2 R_exit
2217 5 None
23
My goal is to add a tx column like this:
1df = pd.DataFrame({"values":[1,5,7,3,0,9,8,8,7,5,8,1,0,0,0,0,2,5],"signal":['L_exit',None,None,'R_entry','R_exit',None,'L_entry','L_exit',None,'R_entry','R_exit','R_entry','R_exit','L_entry','L_exit','L_entry','R_exit',None]})
2df
3
4 values signal
50 1 L_exit
61 5 None
72 7 None
83 3 R_entry
94 0 R_exit
105 9 None
116 8 L_entry
127 8 L_exit
138 7 None
149 5 R_entry
1510 8 R_exit
1611 1 R_entry
1712 0 R_exit
1813 0 L_entry
1914 0 L_exit
2015 0 L_entry
2116 2 R_exit
2217 5 None
23 values signal num
240 1 L_exit nan
251 5 None nan
262 7 None nan
273 3 R_entry 1.00
284 0 R_exit 1.00
295 9 None 1.00
306 8 L_entry 1.00
317 8 L_exit 1.00
328 7 None nan
339 5 R_entry 2.00
3410 8 R_exit 2.00
3511 1 R_entry 2.00
3612 0 R_exit 2.00
3713 0 L_entry 2.00
3814 0 L_exit 2.00
3915 0 L_entry nan
4016 2 R_exit nan
4117 5 None nan
42
Business logic: when there's a signal of R_entry
we group a tx until there's L_exit
(if theres another R_entry - ignore it)
What have I tried?
1df = pd.DataFrame({"values":[1,5,7,3,0,9,8,8,7,5,8,1,0,0,0,0,2,5],"signal":['L_exit',None,None,'R_entry','R_exit',None,'L_entry','L_exit',None,'R_entry','R_exit','R_entry','R_exit','L_entry','L_exit','L_entry','R_exit',None]})
2df
3
4 values signal
50 1 L_exit
61 5 None
72 7 None
83 3 R_entry
94 0 R_exit
105 9 None
116 8 L_entry
127 8 L_exit
138 7 None
149 5 R_entry
1510 8 R_exit
1611 1 R_entry
1712 0 R_exit
1813 0 L_entry
1914 0 L_exit
2015 0 L_entry
2116 2 R_exit
2217 5 None
23 values signal num
240 1 L_exit nan
251 5 None nan
262 7 None nan
273 3 R_entry 1.00
284 0 R_exit 1.00
295 9 None 1.00
306 8 L_entry 1.00
317 8 L_exit 1.00
328 7 None nan
339 5 R_entry 2.00
3410 8 R_exit 2.00
3511 1 R_entry 2.00
3612 0 R_exit 2.00
3713 0 L_entry 2.00
3814 0 L_exit 2.00
3915 0 L_entry nan
4016 2 R_exit nan
4117 5 None nan
42g = ( df['signal'].eq('R_entry') | df_tx['signal'].eq('L_exit') ).cumsum()
43df['tx'] = g.where(df['signal'].eq('R_entry')).groupby(g).ffill()
44
problem is that it increments every time it has 'R_entry'
ANSWER
Answered 2021-Oct-12 at 20:18Let's try (hopefully self-explained):
1df = pd.DataFrame({"values":[1,5,7,3,0,9,8,8,7,5,8,1,0,0,0,0,2,5],"signal":['L_exit',None,None,'R_entry','R_exit',None,'L_entry','L_exit',None,'R_entry','R_exit','R_entry','R_exit','L_entry','L_exit','L_entry','R_exit',None]})
2df
3
4 values signal
50 1 L_exit
61 5 None
72 7 None
83 3 R_entry
94 0 R_exit
105 9 None
116 8 L_entry
127 8 L_exit
138 7 None
149 5 R_entry
1510 8 R_exit
1611 1 R_entry
1712 0 R_exit
1813 0 L_entry
1914 0 L_exit
2015 0 L_entry
2116 2 R_exit
2217 5 None
23 values signal num
240 1 L_exit nan
251 5 None nan
262 7 None nan
273 3 R_entry 1.00
284 0 R_exit 1.00
295 9 None 1.00
306 8 L_entry 1.00
317 8 L_exit 1.00
328 7 None nan
339 5 R_entry 2.00
3410 8 R_exit 2.00
3511 1 R_entry 2.00
3612 0 R_exit 2.00
3713 0 L_entry 2.00
3814 0 L_exit 2.00
3915 0 L_entry nan
4016 2 R_exit nan
4117 5 None nan
42g = ( df['signal'].eq('R_entry') | df_tx['signal'].eq('L_exit') ).cumsum()
43df['tx'] = g.where(df['signal'].eq('R_entry')).groupby(g).ffill()
44signals = df['signal']
45
46after_entry = signals.where(signals.eq('R_entry')).ffill().eq('R_entry')
47before_exit = signals.where(signals.eq('L_exit')).bfill().eq('L_exit')
48
49valids = after_entry & before_exit
50
51
52blocks = signals.where(valids).ffill()[::-1].eq('L_exit').cumsum()[::-1]
53valid_blocks = (blocks.groupby(blocks).transform('size') > 2)
54valid_entries = valid_blocks & (~blocks.duplicated())
55
56df.loc[valid_blocks, 'num'] = valid_entries.cumsum()
57
Output:
1df = pd.DataFrame({"values":[1,5,7,3,0,9,8,8,7,5,8,1,0,0,0,0,2,5],"signal":['L_exit',None,None,'R_entry','R_exit',None,'L_entry','L_exit',None,'R_entry','R_exit','R_entry','R_exit','L_entry','L_exit','L_entry','R_exit',None]})
2df
3
4 values signal
50 1 L_exit
61 5 None
72 7 None
83 3 R_entry
94 0 R_exit
105 9 None
116 8 L_entry
127 8 L_exit
138 7 None
149 5 R_entry
1510 8 R_exit
1611 1 R_entry
1712 0 R_exit
1813 0 L_entry
1914 0 L_exit
2015 0 L_entry
2116 2 R_exit
2217 5 None
23 values signal num
240 1 L_exit nan
251 5 None nan
262 7 None nan
273 3 R_entry 1.00
284 0 R_exit 1.00
295 9 None 1.00
306 8 L_entry 1.00
317 8 L_exit 1.00
328 7 None nan
339 5 R_entry 2.00
3410 8 R_exit 2.00
3511 1 R_entry 2.00
3612 0 R_exit 2.00
3713 0 L_entry 2.00
3814 0 L_exit 2.00
3915 0 L_entry nan
4016 2 R_exit nan
4117 5 None nan
42g = ( df['signal'].eq('R_entry') | df_tx['signal'].eq('L_exit') ).cumsum()
43df['tx'] = g.where(df['signal'].eq('R_entry')).groupby(g).ffill()
44signals = df['signal']
45
46after_entry = signals.where(signals.eq('R_entry')).ffill().eq('R_entry')
47before_exit = signals.where(signals.eq('L_exit')).bfill().eq('L_exit')
48
49valids = after_entry & before_exit
50
51
52blocks = signals.where(valids).ffill()[::-1].eq('L_exit').cumsum()[::-1]
53valid_blocks = (blocks.groupby(blocks).transform('size') > 2)
54valid_entries = valid_blocks & (~blocks.duplicated())
55
56df.loc[valid_blocks, 'num'] = valid_entries.cumsum()
57 values signal num
580 1 L_exit NaN
591 5 None NaN
602 7 None NaN
613 3 R_entry 1.0
624 0 R_exit 1.0
635 9 None 1.0
646 8 L_entry 1.0
657 8 L_exit 1.0
668 7 None NaN
679 5 R_entry 2.0
6810 8 R_exit 2.0
6911 1 R_entry 2.0
7012 0 R_exit 2.0
7113 0 L_entry 2.0
7214 0 L_exit 2.0
7315 0 L_entry NaN
7416 2 R_exit NaN
7517 5 None NaN
76
QUESTION
Reactjs separation of UI and business logic
Asked 2021-Sep-26 at 09:14I am new to react and I find it sore in the eyes to look at the component flooded with lots of functions and variable initializations together with the UI. Is it possible to separate them?
Instead of the default setup, like below. How do I separate the business logic into another file?
1function MyComponent() {
2 const [data, setData] = useState('');
3 const someFunc = () => {
4 //do something.
5 };
6 ... some 100-liner initializations
7
8 return (
9 ...
10 )
11}
12
ANSWER
Answered 2021-Sep-26 at 08:50A common approach that I use myself is to separate the business logic into its own file myComponentHelper.js
This will also make it easier to test the function because it will not be able to use and change the react state without having it passed in as arguments and returning the changes.
1function MyComponent() {
2 const [data, setData] = useState('');
3 const someFunc = () => {
4 //do something.
5 };
6 ... some 100-liner initializations
7
8 return (
9 ...
10 )
11}
12myComponent/
13 myComponent.jsx
14 myComponentHelper.js
15 myComponentTest.js
16
1function MyComponent() {
2 const [data, setData] = useState('');
3 const someFunc = () => {
4 //do something.
5 };
6 ... some 100-liner initializations
7
8 return (
9 ...
10 )
11}
12myComponent/
13 myComponent.jsx
14 myComponentHelper.js
15 myComponentTest.js
16// myComponent.js
17
18import { someFunc } from './myComponentHelper';
19
20function MyComponent() {
21 const [data, setData] = useState('');
22
23 const x = someFunc(data);
24
25 return (
26 ...
27 )
28}
29
1function MyComponent() {
2 const [data, setData] = useState('');
3 const someFunc = () => {
4 //do something.
5 };
6 ... some 100-liner initializations
7
8 return (
9 ...
10 )
11}
12myComponent/
13 myComponent.jsx
14 myComponentHelper.js
15 myComponentTest.js
16// myComponent.js
17
18import { someFunc } from './myComponentHelper';
19
20function MyComponent() {
21 const [data, setData] = useState('');
22
23 const x = someFunc(data);
24
25 return (
26 ...
27 )
28}
29// myComponentHelper.js
30
31export const someFunc = (data) => {
32 //do something.
33 return something;
34}
35
1function MyComponent() {
2 const [data, setData] = useState('');
3 const someFunc = () => {
4 //do something.
5 };
6 ... some 100-liner initializations
7
8 return (
9 ...
10 )
11}
12myComponent/
13 myComponent.jsx
14 myComponentHelper.js
15 myComponentTest.js
16// myComponent.js
17
18import { someFunc } from './myComponentHelper';
19
20function MyComponent() {
21 const [data, setData] = useState('');
22
23 const x = someFunc(data);
24
25 return (
26 ...
27 )
28}
29// myComponentHelper.js
30
31export const someFunc = (data) => {
32 //do something.
33 return something;
34}
35// myComponentTest.js
36
37import { someFunc } from './myComponentHelper';
38
39test("someFunc - When data is this - Should return this", () => {
40 const data = {...};
41 const result = someFunc(data);
42 expect(result).toEqual("correct business data");
43});
44
Community Discussions contain sources that include Stack Exchange Network
Tutorials and Learning Resources in Business
Tutorials and Learning Resources are not available at this moment for Business