date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/16
333
1,152
<issue_start>username_0: **Version Tell us which versions you are using:** ``` react-native-router-flux v4.0.0-beta.28 react-native v0.52.2 ``` Tried the following... `Actions.replace({ key: tabKey, props: tabPage }); Actions[key]({ type: ActionConst.REPLACE, tabPage: tabPage })` and several variations there of<issue_comment>username_1: I would recommend to try the most recent version - but if that's not possible, move to the last beta that was still using `react-navigation` 1.5 - there is a branch for that version only now (`4.0.0-beta`) and then use the `execute` method. ``` Actions.execute('replace', tabKey, { tabPage }); ``` And I believe the two examples you showed are not correct too, but I might be wrong, the number of changes during the work in this beta version was huge, but according to the code/API docs, this is the way you were supposed to be doing it: ``` Actions.replace(tabKey, { tabPage }); // or Actions[tabKey]({ tabPage }); // and use type={ActionsConst.REPLACE} on your `Scene` ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: you most use `Actions.replace('tab name');` and this work Upvotes: 0
2018/03/16
997
3,390
<issue_start>username_0: I've got different languages on my website. Every language has the same products with a different class name per product. so lets say we've got this: ``` Product 1 Product 2 Product 3 Product 4 Product 5 ``` This is the same for every language. As you can see every class has multiple classnames, and I only need the first classname to get the initials of the language that is currently active. I got the language initials out of the url by using ``` var url = window.location.pathname.split('/')[1]; ``` now I only have to use the outcome of 'url' to be added to the product1, product2, product3 classnames etc. So that eventually it will look like this (when the user is on the italian page for example): ``` Product 1 Product 2 Product 3 Product 4 Product 5 ``` I hope I stated my question clearly enough, if not please let me know, thanks a lot!<issue_comment>username_1: Follow below approach:- 1.Get class first. 2.Add url value to it. 3.Add this class back to the div Working snippet:- ```js $(document).ready(function(){ var url = 'it'; $('div#post-2036').find('div').each(function(){ var class_array = $(this).attr('class').split(' ');// split classes to make it array class_array[0] = class_array[0]+'_'+url; // add lang value to first class $(this).removeClass().addClass(class_array.join(' ')); // now add the new class to div }); }); ``` ```html Product 1 Product 2 Product 3 Product 4 Product 5 ``` Upvotes: 2 <issue_comment>username_2: You cant make it just like that. Better way to have one language one identification class. ``` Product 1 Product 2 Product 3 Product 4 Product 5 ``` Than when you switch to other language remove english and add new class french. More better way to put english language class just on one place in container for example. Except your product can be on one page in more different languages. Upvotes: 0 <issue_comment>username_3: You can use the `.attr()` function of jQuery to change the class tag of the elements by hand. Also you can use the `.find()` function to find elements with regex. Upvotes: 0 <issue_comment>username_4: You can find 1st class add something to class (in your case comes from url ) remove old class and add new class. ```js var url = 'it'; $('#post-2036').find('div').each(function(index, element) { var cls = $(this).attr('class'); var st = cls.split(' '); var firstClass = st[0]; var newClass=st[0]=firstClass+'_'+url console.log(newClass); $(this).removeClass(firstClass).addClass(newClass); }); ``` ```html Product 1 Product 2 Product 3 Product 4 Product 5 ``` Upvotes: 0 <issue_comment>username_5: The absolute simplest, and most preformant solution is to take the language variable you got from the url, and add it as a class on the `html` element. With that you can then use that class, combined with e.g. the `product1` and do like this: Script ``` (function (d,url) { d.classList.add(url); })(document.documentElement,window.location.pathname.split('/')[1]); ``` HTML ``` ``` CSS ``` .it .product1 { } ``` --- Or using an attribute Script ``` (function (d,url) { d.setAttribute('data-lang',url); })(document.documentElement,window.location.pathname.split('/')[1]); ``` HTML ``` ``` CSS ``` [data-lang='it'] .product1 { } ``` Upvotes: 1
2018/03/16
959
3,545
<issue_start>username_0: I've got a generic UIViewController in which I would like to hide the status bar. I've got more view controllers which should display the status bar, but this specific view controller should hide the status bar. I've implemented the following methods in the UIViewController class: ``` override func viewDidLoad() { super.viewDidLoad() // FIXME: hide status bar var prefersStatusBarHidden: Bool { return true } setNeedsStatusBarAppearanceUpdate() } override func viewWillAppear(_ animated: Bool) { UIApplication.shared.isStatusBarHidden = true } override func viewWillDisappear(_ animated: Bool) { UIApplication.shared.isStatusBarHidden = false } ``` In my info.plist, I've set up the following setting: [![enter image description here](https://i.stack.imgur.com/PkGAb.png)](https://i.stack.imgur.com/PkGAb.png) The status bar does not hide when I navigate to that view controller and is still visible.<issue_comment>username_1: In view controller where you want to hide the status bar, In the `viewWillAppear` method, `UIApplication.shared.isStatusBarHidden = true`, In the `viewWillDisAppear` method, `UIApplication.shared.isStatusBarHidden = false` Upvotes: 2 [selected_answer]<issue_comment>username_2: override `prefersStatusBarHidden` in your view controller: ``` override var prefersStatusBarHidden: Bool { return true } ``` Set a value `No` for `View Controller based status bar appearance` and then show/hide your status bar for specific view controller. [![enter image description here](https://i.stack.imgur.com/e94m7.png)](https://i.stack.imgur.com/e94m7.png) Here is result: [![enter image description here](https://i.stack.imgur.com/lcn84.png)](https://i.stack.imgur.com/lcn84.png) Upvotes: 3 <issue_comment>username_3: Add following line in your ViewController ``` extension UIViewController { func prefersStatusBarHidden() -> Bool { return true } } ``` Upvotes: -1 <issue_comment>username_4: ``` UIApplication.shared.isStatusBarHidden = true ``` above this Setter for '`isStatusBarHidden`' was deprecated in `iOS 9.0` so use below code it's working fine :) ``` override var prefersStatusBarHidden: Bool { return true } ``` Upvotes: 0 <issue_comment>username_5: App Delegate swift 4.2 ``` NotificationCenter.default.addObserver(self, selector: #selector(videoExitFullScreen), name:NSNotification.Name(rawValue: "UIWindowDidBecomeHiddenNotification") , object: nil) @objc func videoExitFullScreen() { UIApplication.shared.setStatusBarHidden(false, with: .none) } ``` Upvotes: 0 <issue_comment>username_6: **To turn off the status bar for some view controllers but not all**, remove this info.plist entry if it exists OR set it to YES: ``` View controller-based status bar appearance = YES ``` Then add this line to each view controller that needs the status bar hidden ``` override var prefersStatusBarHidden: Bool { return true } ``` **To turn off the status bar for the entire application**, add this to info.plist: ``` View controller-based status bar appearance = NO ``` This will allow the "Hide status bar" to work as expected. Check the hide status bar located in the project's General settings under Deployment Info. [![enter image description here](https://i.stack.imgur.com/2R0i2.png)](https://i.stack.imgur.com/2R0i2.png) Upvotes: 1 <issue_comment>username_7: **In Swift 5** ``` override var preferredStatusBarStyle: UIStatusBarStyle { return .default } ``` Upvotes: 0
2018/03/16
885
2,734
<issue_start>username_0: **EDIT: I've removed the tags that several people pointed out may be causing the issue and recreated the same layout with more correct CSS, which I've included below (using `width:100%` on the labels instead of a break), but am still getting the same bug.** I'm using `column-count:2` to put some grouped lists into columns. It's not very often I get to write this, but on IE it works as expected, all the grouped lists split into 2 columns. On Chrome, however, it's not splitting on a very short group of just two options. Why is this? **IE version, working as expected** [![IE working as expected](https://i.stack.imgur.com/XmYCj.png)](https://i.stack.imgur.com/XmYCj.png) **Chrome not splitting the first, short group into 2 columns** [![Chrome not splitting the first, short group into 2 columns](https://i.stack.imgur.com/3gbR2.png)](https://i.stack.imgur.com/3gbR2.png) ```css .aoi { column-count: 2; padding: 1em 1em 1em 2em; } .bfsubs_option_label { background: url(checkbox_bg.png); background-repeat: no-repeat; padding: 0 0 0 1.75em; height: 18px; cursor: pointer; display: inline-block; margin-bottom: .5em; background-position: 0 2px; width: 100%;} ``` ```html Event Invitations Insights ```<issue_comment>username_1: A few thoughs on that: * I've been reading in another thread that on Chrome there's some weird behaviour with two columns and `column-count`. To fix that, add `break-inside: avoid-column;` Reference: [Chrome columns bug when number of columns is less then column-count](https://stackoverflow.com/questions/42296604/chrome-columns-bug-when-number-of-columns-is-less-then-column-count) Another thread suggests to additionally add `-webkit-backface-visibility: hidden;` * Try adding `-webkit-column-count` property for Chrome. (However, I would've thought it works without): ``` div { -webkit-column-count: 3; /* Chrome, Safari, Opera */ -moz-column-count: 3; /* Firefox */ column-count: 3; } ``` Let me know if that worked :) Upvotes: 0 <issue_comment>username_2: a workaround, you can add `display: flex;` in `.aoi` and it'll work. ```css .aoi { column-count: 2; padding: 1em 1em 1em 2em; display: flex; } ``` ```html Event Invitations Insights ``` Upvotes: 0 <issue_comment>username_3: In this case, I would simply change the HTML structure to wrap label/input inside divs: ```css .aoi { column-count: 2; padding: 1em 1em 1em 2em; } ``` ```html Event Invitations Insights ``` With more inputs: ```css .aoi { column-count: 2; padding: 1em 1em 1em 2em; } ``` ```html Event Invitations Insights Event Invitations Insights Insights ``` Upvotes: 3 [selected_answer]
2018/03/16
2,841
11,067
<issue_start>username_0: My team is designing a scalable solution with micro-services architecture and planning to use gRPC as the transport communication between layers. And we've decided to use async grpc model. The design that example([greeter\_async\_server.cc](https://github.com/grpc/grpc/blob/master/examples/cpp/helloworld/greeter_async_server.cc)) provides doesn't seem viable if I scale the number of RPC methods, because then I'll have to create a new class for every RPC method, and create their objects in `HandleRpcs()` like this. [Pastebin](https://pastebin.com/PSJs3sqV) (Short example code). ``` void HandleRpcs() { new CallDataForRPC1(&service_, cq_.get()); new CallDataForRPC2(&service_, cq_.get()); new CallDataForRPC3(&service, cq_.get()); // so on... } ``` It'll be hard-coded, all the flexibility will be lost. *I've around 300-400RPC methods to implement and having 300-400 classes will be cumbersome* and inefficient when I'll have to handle more than 100K RPC requests/sec and this solution is a very bad design. I can't bear the overhead of creation of objects this way on every single request. Can somebody kindly provide me a workaround for this. Can async grpc `c++` not be simple like its sync companion? **Edit**: In favour of making the situation more clear, and for those who might be struggling to grasp the flow of this async example, I'm writing what I've understood so far, please make me correct if wrong somewhere. In async grpc, every time we have to bind a unique-tag with the completion-queue so that when we poll, the server can give it back to us when the particular RPC will be hit by the client, and we infer from the returned unique-tag about the type of the call. `service_->RequestRPC2(&ctx_, &request_, &responder_, cq_, cq_,this);` Here we're using the address of the current object as the unique-tag. This is like registering for our RPC call on the completion queue. Then we poll down in `HandleRPCs()` to see if the client hits the RPC, if so then `cq_->Next(&tag, &OK)` will fill the tag. The polling code snippet: ``` while (true) { GPR_ASSERT(cq_->Next(&tag, &ok)); GPR_ASSERT(ok); static_cast(tag)->Proceed(); } ``` Since, the unique-tag that we registered into the queue was the address of the CallData object so we're able to call `Proceed()`. This was fine for one RPC with its logic inside `Proceed()`. But with more RPCs each time we'll have all of them inside the CallData, then on polling, we'll be calling the only one `Proceed()` which will contain logic to (say) RPC1(postgres calls), RPC2(mongodb calls), .. so on. This is like writing all my program inside one function. So, to avoid this, I used a `GenericCallData` class with the `virtual void Proceed()` and made derived classes out of it, one class per RPC with their own logic inside their own `Proceed()`. This is a working solution but I want to avoid writing many classes. Another solution I tried was keeping all RPC-function-logics out of the `proceed()` and into their own functions and maintaining a global `std::map>` . So whenever I register an RPC with unique-tag onto the queue, I store its corresponding logic function (which I'll surely hard code into the statement and bind all the parameters required), then the unique-tag as key. On polling, when I get the `&tag` I do a lookup in the map for this key and call the corresponding saved function. Now, there's one more hurdle, I'll have to do this inside the function logic: ``` // pseudo code void function(reply, responder, context, service) { // register this RPC with another unique tag so to serve new incoming request of the same type on the completion queue service_->RequestRPC1(/*params*/, new_unique_id); // now again save this new_unique_id and current function into the map, so when tag will be returned we can do lookup map.emplace(new_unique_id, function); // now you're free to do your logic // do your logic } ``` You see this, code has spread into another module now, and it's per RPC based. Hope it clears the situation. I thought if somebody could have implemented this type of server in a more easy way.<issue_comment>username_1: This post is pretty old by now but I have not seen any answer or example regarding this so I will show how I solved it to any other readers. I have around 30 RPC calls and was looking for a way of reducing the footprint when adding and removing RPC calls. It took me some iterations to figure out a good way to solve it. So my interface for getting RPC requests from my (g)RPC library is a callback interface that the recepiant need to implement. The interface looks like this: ``` class IRpcRequestHandler { public: virtual ~IRpcRequestHandler() = default; virtual void onZigbeeOpenNetworkRequest(const smarthome::ZigbeeOpenNetworkRequest& req, smarthome::Response& res) = 0; virtual void onZigbeeTouchlinkDeviceRequest(const smarthome::ZigbeeTouchlinkDeviceRequest& req, smarthome::Response& res) = 0; ... }; ``` And some code for setting up/register each RPC method after the gRPC server is started: ``` void ready() { SETUP_SMARTHOME_CALL("ZigbeeOpenNetwork", // Alias that is used for debug messages smarthome::Command::AsyncService::RequestZigbeeOpenNetwork, // Generated gRPC service method for async. smarthome::ZigbeeOpenNetworkRequest, // Generated gRPC service request message smarthome::Response, // Generated gRPC service response message IRpcRequestHandler::onZigbeeOpenNetworkRequest); // The callback method to call when request has arrived. SETUP_SMARTHOME_CALL("ZigbeeTouchlinkDevice", smarthome::Command::AsyncService::RequestZigbeeTouchlinkDevice, smarthome::ZigbeeTouchlinkDeviceRequest, smarthome::Response, IRpcRequestHandler::onZigbeeTouchlinkDeviceRequest); ... } ``` This is all that you need to care about when adding and removing RPC methods. The SETUP\_SMARTHOME\_CALL is a home-cooked macro which looks like this: ``` #define SETUP_SMARTHOME_CALL(ALIAS, SERVICE, REQ, RES, CALLBACK_FUNC) \ new ServerCallData( \ ALIAS, \ std::bind(&SERVICE, \ &mCommandService, \ std::placeholders::\_1, \ std::placeholders::\_2, \ std::placeholders::\_3, \ std::placeholders::\_4, \ std::placeholders::\_5, \ std::placeholders::\_6), \ mCompletionQueue.get(), \ std::bind(&CALLBACK\_FUNC, requestHandler, std::placeholders::\_1, std::placeholders::\_2)) ``` I think the ServerCallData class looks like the one from gRPCs examples with a few modifications. ServerCallData is derived from a non-templete class with an abstract function `void proceed(bool ok)` for the CompletionQueue::Next() handling. When ServerCallData is created, it will call the `SERVICE` method to register itself on the CompletionQueue and on every first `proceed(ok)` call, it will clone itself which will register another instance. I can post some sample code for that as well if someone is interested. **EDIT:** Added some more sample code below. GrpcServer ``` class GrpcServer { public: explicit GrpcServer(std::vector services); virtual ~GrpcServer(); void run(const std::string& sslKey, const std::string& sslCert, const std::string& password, const std::string& listenAddr, uint32\_t port, uint32\_t threads = 1); private: virtual void ready(); // Called after gRPC server is created and before polling CQ. void handleRpcs(); // Function that polls from CQ, can be run by multiple threads. Casts object to CallData and calls CallData::proceed(). std::unique\_ptr mCompletionQueue; std::unique\_ptr mServer; std::vector mServices; std::list> mThreads; ... } ``` And the main part of the `CallData` object: ``` template class ServerCallData : public ServerCallMethod { public: explicit ServerCallData(const std::string& methodName, std::function\*, ::grpc::CompletionQueue\*, ::grpc::ServerCompletionQueue\*, void\*)> serviceFunc, grpc::ServerCompletionQueue\* completionQueue, std::function callback, bool first = false) : ServerCallMethod(methodName), mResponder(&mContext), serviceFunc(serviceFunc), completionQueue(completionQueue), callback(callback) { requestNewCall(); } void proceed(bool ok) override { if (!ok) { delete this; return; } if (callStatus() == ServerCallMethod::PROCESS) { callStatus() = ServerCallMethod::FINISH; new ServerCallData(callMethodName(), serviceFunc, completionQueue, callback); try { callback(mRequest, mReply); } catch (const std::exception& e) { mResponder.Finish(mReply, Status::CANCELLED, this); return; } mResponder.Finish(mReply, Status::OK, this); } else { delete this; } } private: void requestNewCall() { serviceFunc( &mContext, &mRequest, &mResponder, completionQueue, completionQueue, this); } ServerContext mContext; TREQUEST mRequest; TREPLY mReply; ServerAsyncResponseWriter mResponder; std::function\*, ::grpc::CompletionQueue\*, ::grpc::ServerCompletionQueue\*, void\*)> serviceFunc; std::function callback; grpc::ServerCompletionQueue\* completionQueue; }; ``` Upvotes: 3 <issue_comment>username_2: Although the thread is old I wanted to share a solution I am currently implementing. It mainly consists templated classes inheriting CallData to be scalable. This way, each new rpc will only require specializing the templates of the required CallData methods. ### `Calldata` header: ```cpp class CallData { protected: enum Status { CREATE, PROCESS, FINISH }; Status status; virtual void treat_create() = 0; virtual void treat_process() = 0; public: void Proceed(); }; ``` ### `CallData` Proceed implementation: ```cpp void CallData::Proceed() { switch (status) { case CREATE: status = PROCESS; treat_create(); break; case PROCESS: status = FINISH; treat_process(); break; case FINISH: delete this; } } ``` ### Inheriting from `CallData` header (*simplified*): ```cpp template class CallDataTemplated : CallData { static\_assert(std::is\_base\_of::value, "Request and reply must be protobuf messages"); static\_assert(std::is\_base\_of::value, "Request and reply must be protobuf messages"); private: Service,Cq,Context,ResponseWriter,... Request request; Reply reply; protected: void treat\_create() override; void treat\_process() override; public: ... }; ``` Then, for specific rpc's in theory you should be able to do things like: ```cpp template<> void CallDataTemplated::treat\_process() { ... } ``` It's a lot of templated methods but preferable to creating a class per rpc from my point of view. Upvotes: 2
2018/03/16
2,638
5,114
<issue_start>username_0: I am beginner with rvest. I am trying to scrape some tables from the website of the Italian Home Office. I use codes based on-line tutorials, but html\_table fails do find any table. This happens when I try to get all the tables: ``` url <- "http://finanzalocale.interno.gov.it/apps/floc.php/certificati/index/codice_ente/1030491450/cod/4/anno/2014/md/0/cod_modello/CCOU/tipo_modello/U/cod_quadro/04" webpage <- read_html(url) tables <- html_table(webpage) table1 <- tables[[1]] ``` and also when I try to get a single one using the Xpath ``` url <- "http://finanzalocale.interno.gov.it/apps/floc.php/certificati/index/codice_ente/1030491450/cod/4/anno/2014/md/0/cod_modello/CCOU/tipo_modello/U/cod_quadro/04" table <- url %>% read_html() %>% html_nodes(xpath='//*[@id="center"]/div[3]/table') %>% html_table() table <- table[[1]] head(table) ``` The issue seems to be specific to this website, because the above codes work on, for example, wikipedia pages. Solutions to similar problems posted on this website (e.g. removing comment tags) did not work for me. Any help would be most appreciated!<issue_comment>username_1: You can use `RSelenium` to open a browser in which the page is generated and then scrape the tables with `rvest` (just like you were doing): ``` library(rvest) library(RSelenium) rD <- rsDriver() remDr <- rD[["client"]] remDr$navigate("http://finanzalocale.interno.gov.it/apps/floc.php/certificati/index/codice_ente/1030491450/cod/4/anno/2014/md/0/cod_modello/CCOU/tipo_modello/U/cod_quadro/04") webpage <- read_html(remDr$getPageSource()[[1]]) tables <- webpage %>% html_table(fill=T) ``` Upvotes: 1 <issue_comment>username_2: Works *just fine* without RSelenium or splashr: ``` library(rvest) library(tidyverse) pg <- read_html("http://finanzalocale.interno.gov.it/apps/floc.php/certificati/index/codice_ente/1030491450/cod/4/anno/2014/md/0/cod_modello/CCOU/tipo_modello/U/cod_quadro/04") html_nodes(pg, "table.table-striped") %>% purrr::map(html_table) %>% purrr::map(as_tibble) ## [[1]] ## # A tibble: 75 x 11 ## `FUNZIONI E SERVIZI / … Personale `Acquisto di beni … `Prestazioni di… ## ## 1 Funzioni generali di a… 141.967.7… 2.489.137,83 59.941.306,62 ## 2 Organi istituzionali, … 16.229.61… 320.049,90 8.575.927,57 ## 3 indennità per gli orga… 0,00 0,00 4.741.000,00 ## 4 - Segreteria generale,… 40.013.84… 353.042,85 13.399.011,09 ## 5 Gestione economica, fi… 7.925.580… 48.425,00 8.885.886,94 ## 6 Gestione delle entrate… 7.630.190… 12.111,52 13.313.546,15 ## 7 Gestione dei beni dema… 2.166.540… 1.759,99 1.233.312,68 ## 8 Ufficio tecnico 14.404.02… 67.468,00 2.940.932,06 ## 9 Anagrafe, stato civile… 16.826.86… 293.263,23 6.139.023,55 ## 10 Altri servizi generali… 36.771.12… 1.393.017,34 5.453.666,58 ## # ... with 65 more rows, and 7 more variables: `Utilizzo di beni di ## # terzi` , Trasferimenti , `Interessi passivi e oneri ## # finanziari diversi` , `Imposte e tasse` , `Oneri ## # straordinari della gestione corrente` , `Ammortamenti di ## # esercizio` , Totale ## ## [[2]] ## # A tibble: 75 x 11 ## `FUNZIONI E SERVIZI / … Personale `Acquisto di beni … `Prestazioni di… ## ## 1 Funzioni generali di a… 131.219.7… 1.153.701,07 31.627.112,30 ## 2 Organi istituzionali, … 15.658.15… 94.401,50 5.841.240,89 ## 3 indennità per gli orga… 0,00 0,00 3.769.143,70 ## 4 Segreteria generale, p… 38.448.56… 167.482,23 7.507.263,62 ## 5 Gestione economica, fi… 7.662.138… 29.961,40 6.347.472,21 ## 6 Gestione delle entrate… 7.487.402… 7.671,92 2.497.130,97 ## 7 Gestione dei beni dema… 2.100.595… 1.759,99 852.589,53 ## 8 Ufficio tecnico 11.334.26… 47.329,00 1.568.994,43 ## 9 Anagrafe, stato civile… 16.144.91… 223.148,43 4.077.270,69 ## 10 Altri servizi generali… 32.383.70… 581.946,60 2.935.149,96 ## # ... with 65 more rows, and 7 more variables: `Utilizzo di beni di ## # terzi` , Trasferimenti , `Interessi passivi e oneri ## # finanziari diversi` , `Imposte e tasse` , `Oneri ## # straordinari della gestione corrente` , `Ammortamenti di ## # esercizio` , Totale ## ## [[3]] ## # A tibble: 74 x 11 ## `FUNZIONI E SERVIZI / … Personale `Acquisto di beni … `Prestazioni di… ## ## 1 Funzioni generali di a… 5.593.882… 2.190.159,89 22.691.402,00 ## 2 Organi istituzionali, … 463.851,43 1.649.220,45 2.549.386,60 ## 3 indennità per gli orga… 0,00 0,00 554.624,70 ## 4 Segreteria generale, p… 1.312.740… 47.613,00 8.238.186,49 ## 5 Gestione economica, fi… 227.143,48 12.365,99 2.101.177,76 ## 6 Gestione delle entrate… 220.687,71 16.698,92 3.981.304,84 ## 7 Gestione dei beni dema… 62.536,51 293,70 255.524,99 ## 8 Ufficio tecnico 1.933.388… 27.547,69 1.236.148,00 ## 9 Anagrafe, stato civile… 394.806,86 69.201,92 1.971.067,96 ## 10 Altri servizi generali 978.727,38 367.218,22 2.358.605,36 ## # ... with 64 more rows, and 7 more variables: `Utilizzo di beni di ## # terzi` , Trasferimenti , `Interessi passivi e oneri ## # finanziari diversi` , `Imposte e tasse` , `Oneri ## # straordinari della gestione corrente` , `Ammortamenti di ## # esercizio` , Totale ``` Upvotes: 2
2018/03/16
444
1,818
<issue_start>username_0: is there any way to logout a user in yii2 advanced, when the user faces unusual thing(like shut down his/her computer when the user works with his/her account). default of yii2:when you are login and your computer goes into shut down,when you start up for another time and go to your account ,you are in login state but your session ID will change. i want to logout the user or at least the session id never change.<issue_comment>username_1: If a user restarts their computer, the browser session cookies that are there will remain in place until they expire or the user chooses to delete them/clear data from their browser cache. By definition, if the user remains logged in, their session *has* been preserved. This has nothing to do with whether a client computer has been restarted or any other change of state on a client machine - your website is agnostic to this, i.e. it does not have any mechanism to know of this particular change in state and neither should it care. If you wish to logout a user programatically, you can use this code for the native [Yii2 user application component](http://www.yiiframework.com/doc-2.0/yii-web-user.html) in your controller: `Yii::$app->user->logout();` Upvotes: 1 <issue_comment>username_2: Maybe you want to disable `enableAutoLogin` parameter for User class, so that when user closes browser or shutdowns/restarts a computer, he will have to enter login data again. This kind of behavior is often used in banking systems (at least in my country) for security reasons. If that is what you are looking for, then this setting can be configured in `frontend/config/main.php` file ``` 'components' => [ .. 'user' => [ 'identityClass' => 'common\models\User', 'enableAutoLogin' => false, .. ], ``` Upvotes: 2
2018/03/16
569
2,227
<issue_start>username_0: I want to make generic metods ToSigned, ToUnsinged. This is what i have ``` public static class Number { // public static bool IsSigned = MinValue.Equals(0) ? false : true; // public static bool IsUnsigned = MinValue.Equals(0) ? true : false; public static object ToUnsigned(T input) { if (IsUnsigned) return input; // T is Signed // How to derive unsigned type from signed type ? // return SignedToUnsigned(input); return null; } public static object ToSigned(T input) { if (IsSigned) return input; // T is Unsigned // How to derive signed type from unsigned type ? // return UnsignedToSigned (input); return null; } } ``` I have successfully implemented SignedToUnsigned and UnsignedToSigned, but how do I derive the signed type from an unsigned type, or the unsigned type from a signed type ?<issue_comment>username_1: If a user restarts their computer, the browser session cookies that are there will remain in place until they expire or the user chooses to delete them/clear data from their browser cache. By definition, if the user remains logged in, their session *has* been preserved. This has nothing to do with whether a client computer has been restarted or any other change of state on a client machine - your website is agnostic to this, i.e. it does not have any mechanism to know of this particular change in state and neither should it care. If you wish to logout a user programatically, you can use this code for the native [Yii2 user application component](http://www.yiiframework.com/doc-2.0/yii-web-user.html) in your controller: `Yii::$app->user->logout();` Upvotes: 1 <issue_comment>username_2: Maybe you want to disable `enableAutoLogin` parameter for User class, so that when user closes browser or shutdowns/restarts a computer, he will have to enter login data again. This kind of behavior is often used in banking systems (at least in my country) for security reasons. If that is what you are looking for, then this setting can be configured in `frontend/config/main.php` file ``` 'components' => [ .. 'user' => [ 'identityClass' => 'common\models\User', 'enableAutoLogin' => false, .. ], ``` Upvotes: 2
2018/03/16
888
3,548
<issue_start>username_0: In the sample code below ComputeSomething() returns a reference to an array. **I was asked to use C++ core guidelines (NuGet package on MSVC toolchain) as an extra static analysis tool.** On the return line of `ComputeSomething()` the static analysis tool warns that there is an array to pointer decay. I assume the intent would be to change it in order to make the decay explicit (something like `&(computed_values[0])`) but then that would defeat the point of returning an array by reference. Is this a valid warning or is it noise, for this specific use-case of returning an array by reference? **(assumes a C++98 constraint)** ``` float (&ComputeSomething( const seed_t(&seed_data)[num_of_elems_seeded] ))[num_of_elems_calculated]{ static float computed_values[num_of_elems_calculated]; // do something... return computed_values; } ```<issue_comment>username_1: Yes. In the `ComputeSomething` function, `computed_values` is an array. And as usual with arrays it can naturally decay to a pointer to its first element. So the `ComputeSomething` function could be simplified to ``` const float* ComputeSomething(...){ ... } ``` --- To "preserve" size information, then to be able to use the function as it it now, the size needs to be known by the caller *anyway*. It's not something that is automatically transferred. So using a pointer will not change much, unless you absolutely want to use `sizeof` on the array, but that can be sidestepped by using the size you must provide in the variable declaration anyway. Using pointer will most definitely simplify the syntax, and as such also make the code more readable and maintainable. You could also use `std::vector`, which have built in size information. Or force the upgrade to a more modern compiler which can use C++11, and then use `std::array` if you want to have compile-time fixed-size arrays. I'm not sure if [`std::pair`](http://en.cppreference.com/w/cpp/utility/pair) exists in C++98, or if it came in C++03, but as some kind of middle-ground you could use `std::pair` to return both a pointer *and* the size. Then finally, you could always use `typedef` to create aliases to your array types. Then you don't need to explicitly specify the size everywhere, and it will simplify the syntax quite a lot: ``` typedef computed_values_type[num_of_elems_calculated]; .... computed_values_type& ComputeSomething(...) { ... } ... computed_values_type& computed_values = ComputeSomething(...); ``` Upvotes: -1 <issue_comment>username_2: From a compiled binaries point of view, reference to an array is just the same old pointer to the first element. It differs from raw pointer only by type itself, which contains information about array size. It may be used, for instance, for compile-time size checks, compiler warnings or `range-based for` loop Upvotes: -1 <issue_comment>username_3: For the method below: ``` float (&ComputeSomething())[num_of_elems_calculated]{ static float computed_values[num_of_elems_calculated]; // do something... return computed_values; } ``` Unlike what is probably happening in the static analysis tool, the *potential* array to pointer decay is not determined inside the method but instead when the caller calls the function: ``` // expected to decay float *some_computation = ComputeSomething(); // not expected to decay to pointer float (&safer_computation)[num_of_elems_calculated] = ComputeSomething(); ``` Thanks to @Galik for his input on this. Upvotes: 1 [selected_answer]
2018/03/16
629
2,337
<issue_start>username_0: Here's the [code](http://rextester.com/YVHG82549): ``` public class Program { public static void Main(string[] args) { Test test = new Test(); } } public class Test { public Test() { Console.WriteLine("type: " + Type.GetType("Registration")); } } public class Registration { public int mAge; public string mName; public Registration() {} } ``` When it try to get the type for `Registration`, it returns null. So both `.Name` or `.AssemblyQualifiedName` can't be accessed. I can provide `AssemblyQualifiedName` only if `GetType()` doesn't return `null`. Why `GetType()` returns null? Hope the question is clear.<issue_comment>username_1: You need to specify the full name of the type, including the namespace: ``` Console.WriteLine("type: " + Type.GetType("Rextester.Registration")); ``` Or alternatively - depending on what you're trying to do: ``` Console.WriteLine("type: " + typeof(Registration)); ``` Upvotes: 2 <issue_comment>username_2: You need to specifiy the "assembly qualified" type name: ``` Type.GetType("YourNameSpace.Registration"); ``` As the [documentation](https://learn.microsoft.com/en-us/dotnet/api/system.type.gettype?view=netframework-4.8#System_Type_GetType_System_String_) states: > > typeName > Type: System.String > > > The assembly-qualified name of the type to get. See > AssemblyQualifiedName. If the type is in the currently > executing assembly or in Mscorlib.dll, it is sufficient to supply the > type name qualified by its namespace. > > > Upvotes: 2 <issue_comment>username_3: That works fine. If it doesn't work for you, then there's probably a *namespace*, in which case you need `"TheNamespace.Registration"`. If the type is in a different assembly, you'll need to specify *that too*; ultimately the most reliable string version is the type's `AssemblyQualifiedName` - which could be something like `"Registration, ConsoleApp48, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"`, or longer if there's a strong-name involved. However, `typeof(Registration)` would be easier than *any* of these options. Upvotes: 4 [selected_answer]<issue_comment>username_4: I think you need to define the full namespace path to your class, so something like `TestNamespace.Registration` Upvotes: 0
2018/03/16
914
3,352
<issue_start>username_0: I am stuck since 2 days with this simple installation process of Visual Studio 2015 from my university portal (vs\_communityENUS.exe which is a 3260 KB application). I am not new to installation and troubleshooting but this one has got me insane. Every time I install it it throws me errors: 1. Microsoft Visual C++ 2015 Redistributable (x64) - 14.0.23918 : Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs in the Control Panel. 2. Visual Studio 2015 Update 3 Microsoft Visual C++ 2015 Redistributable (x64) - 14.0.24210 : The installer failed. Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs in the Control Panel. Error code: 0x80070666 3. Visual Studio 2015 Update 3 Microsoft Visual C++ 2015 Redistributable (x86) - 14.0.24210 : The installer failed. Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs in the Control Panel. Error code: 0x80070666 4. Microsoft Visual C++ 2015 Redistributable (x86) - 14.0.23918 : Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs in the Control Panel. I checked my control panel but I did not find any files with the above name. Than, I got this [amazing link](https://www.youtube.com/watch?v=Qi0deGqmo2g) that helped me remove any previous version of visual studio I have in my machine but a fresh installation after that also threw same errors. I am badly stuck, what I want is a simple visual studio version compatible to windows 8.1 and can successfully integrate with opencv, qt and vtk. Any help in this regard is highly and respectfully appreciated.<issue_comment>username_1: There are some known issues with Visual Studio 2017 redistributables interfering with VS2015 redistributables. Temporarily uninstalling them might allow you to install the whole of VS2015. Upvotes: 2 <issue_comment>username_2: Do you have the Visual C++ 2017 Redistributable installed before the VS 2015 installation? If so, please try to uninstall the Visual C++ 2017 Redistributable then install the VS 2015 again per [this similar issue](https://developercommunity.visualstudio.com/content/problem/14701/visual-c-redistributable-for-visual-studio-2015-ca.html) If not and you cannot find the higher version of the VS Visual C++ 2015 Redistributable under Control Panel, please [use MsiInv to gather information about what is installed on a computer](https://blogs.msdn.microsoft.com/astebner/2005/07/01/using-msiinv-to-gather-information-about-what-is-installed-on-a-computer/), if it is confirmed that a higher version is existing, then you can ignore this warning information to use VS 2015. Upvotes: 4 <issue_comment>username_3: I tried many different strategies to get this to be fixed, but I found a program that installed all the various visual c++ packages without a hitch and fixed my problems. <https://github.com/abbodi1406/vcredist> Upvotes: 0
2018/03/16
862
3,273
<issue_start>username_0: I have an angular5 service which does an HTTP get and returns a specific type as shown below ``` public getProductByIDproductId: string): Observable { const headers = new HttpHeaders({ "Content-Type": "application/json" }); const url = `${environment.productservice\_baseurl}/${productId}`; return this.http .get(url, { headers: headers }) .pipe( tap(data => (this.\_product = data)), catchError(this.handleError) ); } ``` The Product class is a class which has properties and methods. A small excerpt is below. ``` class Product{ productID:string; productName:string; setQuantity(quantity:number){ } } ``` When I call the setQuantity function on this.\_product returned by the get I get a 'setQuantity is not a function' error. When I try to check the instance of this.\_product, it is not of type Product but if type Object. Is the generic type set on the get method only to help compile-time type checking? How do I get a concrete instance of the product class from getProductByIDproductId method?<issue_comment>username_1: You could map the response for instance. ``` return this.http .get(url, { headers: headers }) .map(response => new Product(response)) // I don't know your constructor .pipe( tap(data => (this.\_product = data)), catchError(this.handleError) ); ``` This way, you're sure that your object will be a Typescript object that you defined. **EDIT** You can create an object "by hand" with only a few lines : ``` export class Product { // Your class ... public static createProductFromHttpResponse = (response: any) => { const ret = new Product(); for (let key in response.key) { ret[key] = response[key]; } return ret; } } ``` In your mapping : ``` .map(response => Product.createProductFromHttpResponse(response)) ``` Upvotes: 2 <issue_comment>username_2: As I know, to specify response type you should use interfaces instead classes, so your product should be an interface: ``` interface Product{ productID:string; productName:string; } ``` And as it is just interface and http response it should not have any methods **EDIT** The answer from @trichetriche probably one of the solution for this issue. Upvotes: 0 <issue_comment>username_3: You can't do what you're doing. When you fetch data from an URL, you get just JSON. You're telling TypeScript that `data` is of type `Product`, but that is just a hint for the compiler and does not make it true. `data` was not created with a call to `new Product` and so it doesn't share its methods. If you want your `this._product` to behave like a native `Product` instance, you can do this: ``` this._product = data; Object.setPrototypeOf(this._product, Product.prototype); ``` This way you turn `this._product` into a real `Product` instance, including its methods. Another option, if you are worried about `setPrototypeOf` and its potential performance drawback, is doing it this way: ``` this._product = new Product(); Object.assign(this._product, data); ``` Of course, this is only a good idea if `Product` has a parameterless constructor. And, in any case, if `data` has properties not defined in `Product` class you can also run into performance issues. Upvotes: 4 [selected_answer]
2018/03/16
533
1,930
<issue_start>username_0: I am implementing alarm functionality for Apple's Watch application. So here I have to compare current time with user time and I have to get current time for every 1 sec, so that I have implemented the code like below but this is not working. Can any body please post appropriate code in Objective-C.. ``` for (int i=0; i<86400; i++) { if ([getTotalDate isEqualToString:self.curTime]) { NSLog(@"It's Alarm Time"); [self presentControllerWithName:@"FifthViewController" context:nil]; break; } else { NSLog(@"not alarm time"); //[self currentTime]; } } ```<issue_comment>username_1: The best way is to set Local Notification for that particular time. And you should open `FifthViewController` in `didReceiveLocalNotification`. You can check the answer of following for how to use local notifications. [How to implement LocalNotification using objective C?](https://stackoverflow.com/questions/32087551/how-to-implement-localnotification-using-objective-c) Upvotes: 0 <issue_comment>username_2: Try using Stride Here is an Apple provided solution (loop iteration over time constraints): [Swift control flow with Stride](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-ID120) Some users might want fewer tick marks in their UI. They could prefer one mark every 5 minutes instead. Use the stride(from:to:by:) function to skip the unwanted marks. ``` let minuteInterval = 5 for tickMark in stride(from: 0, to: minutes, by: minuteInterval) { // render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55) } let hours = 12 let hourInterval = 3 for tickMark in stride(from: 3, through: hours, by: hourInterval) { // render the tick mark every 3 hours (3, 6, 9, 12) } ``` Upvotes: -1
2018/03/16
312
1,056
<issue_start>username_0: I have a bitbucket account set with ssh key I have copied the ssh public and private keys in my .ssh folder I have added a ssh config file : ``` cat .ssh/config host bitbucket.org IdentityFile ~/.ssh/bitbucket-ssh-key IdentitiesOnly yes ``` The ssh identification works well BUT it asks for my passphrase at each git push .. witch goes again the purpuse of all this setting. What have I done wrong ?<issue_comment>username_1: You probably do not have your private key added to the agent. See if doing an `ssh-add ~/.ssh/` helps. Also, make sure the agent is running. Check here: <https://help.github.com/enterprise/2.12/user/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/> Upvotes: 3 [selected_answer]<issue_comment>username_2: I get an error : ``` ssh-add .ssh/bitbucket-ssh-key Could not open a connection to your authentication agent. ``` I had forgotten to start the ssh-agent ``` eval "$(ssh-agent -s)" ``` Then git push went without a glitch ;) Thanks for the RTFM pointer! Upvotes: 0
2018/03/16
719
2,725
<issue_start>username_0: I'm trying something here that can really ease my pain. I just took back a project where the front end used is reactjs and the backend is .NET ASPNet 4.6. I'm just trying to get hot reload work with webpack (as it's much more better than building every time i want to see something working) The problem is i have a really hard time to configure to make it work, and i don't really understand how webpack hot reload work. I figure out that in the building process, the js file and css file are copied to special folder where .NET take it and re render it. How can i make it to listen to some file ? I really need to launch it from .NET because i have some controller there to acces the back-end that are built in. (I did not choose the architecture, it's imposed unfortunately). What i already tried : * some plugin from github, but infortunately they use ASPNet 5 and the method ``` public void Configuration(IApplicationBuilder app) { ConfigureAuth(app); } ``` and in my project : ``` public void Configuration(IAppBuilder app) { ConfigureAuth(app); } ``` I know, it's old .. so not compatible (it's in the Startup.cs file in .NET) * I tried to connect using http request but they choose to be built IN so i can't acces it via http :// * My react file css and js are loaded up by .NET in a .cshtml file that is loaded at the root of the path (so the user acces .NET, all .NET controller loaded, then react is loaded and landing react page is render). I have no idea what to look next if you have any idea i can try Don't hesitate to ask me for more information, i don't know what to provide. Thanks in advance from the community<issue_comment>username_1: After different setup and tries, i found a partial solution, it's not hot reload as we know it, but it avoid to build every time. In 2 lines of code, in webpack.config.js add one line at output : ``` output: { path: __dirname + "/src/output/", filename: "client.min.js", publicPath: 'http://localhost:3000/static/' ``` The important line is publicPath And then in index.cshtml : ``` ``` This make a public js file with a node serv on react side when you run npm run dev and the .NET server listen to it. Though you still have to reload your navigator page to see the changes, i'm gonna take a look on how to make it automatic and comment it here. If anyone have some clue about that feel free to help ! Upvotes: 2 [selected_answer]<issue_comment>username_2: You can use `browser-sync` webpack plugin: I found a neat example here: [Setting up a React Environment for ASP.NET MVC](https://dev.to/dance2die/setting-up-a-react-environment-for-aspnet-mvc-44la) Upvotes: 0
2018/03/16
492
1,784
<issue_start>username_0: I have this code below: ``` var rtypes = {!! $registration\_type !!} ``` With this in the source code it appears: ``` var rtypes = [{"id":1,"name":"general","description":"description geral","capacity":100},{"id":2,"name":"plus","description":"description plus","capacity":10}] ``` But I would like to have only the registration type names like "['general', 'plus', ...];" Do you know how to get only the name attribute in the JS? **Method that returns the view:** ``` public function edit($id) { $conf = Conf::find($id); $registrationType = RegistrationType::where('conf_id', $id)->get(); return view('questions.edit') ->with('registration_type', $registrationType) } ```<issue_comment>username_1: After different setup and tries, i found a partial solution, it's not hot reload as we know it, but it avoid to build every time. In 2 lines of code, in webpack.config.js add one line at output : ``` output: { path: __dirname + "/src/output/", filename: "client.min.js", publicPath: 'http://localhost:3000/static/' ``` The important line is publicPath And then in index.cshtml : ``` ``` This make a public js file with a node serv on react side when you run npm run dev and the .NET server listen to it. Though you still have to reload your navigator page to see the changes, i'm gonna take a look on how to make it automatic and comment it here. If anyone have some clue about that feel free to help ! Upvotes: 2 [selected_answer]<issue_comment>username_2: You can use `browser-sync` webpack plugin: I found a neat example here: [Setting up a React Environment for ASP.NET MVC](https://dev.to/dance2die/setting-up-a-react-environment-for-aspnet-mvc-44la) Upvotes: 0
2018/03/16
777
1,836
<issue_start>username_0: I have following problem. I want to nest time series by date but include x amount of earlier dates to nest as well. little example will clear this one: lets create sample tbl: ``` set.seed(13) tibble(date = c(rep("2018-01-31", 3), rep("2018-02-28", 3), rep("2018-03-31", 3), rep("2018-04-30", 3)), form = rep(c("A", "B", "C"), 4), value = rnorm(n = 12), ind = runif(12)) -> tbl ``` And lets nest it: ``` tbl %>% nest(-date) # A tibble: 4 x 2 date data 1 2018-01-31 2 2018-02-28 3 2018-03-31 4 2018-04-30 ``` I love this format of data structure (I hate normal lists). I would like to have following: ``` # A tibble: 4 x 2 date data 1 2018-01-31 2 2018-02-28 3 2018-03-31 4 2018-04-30 ``` Where data in row 2018-02-28 would include Jan and Feb data and row 2018-03-31 would include Feb and Mar data and so on. Flexible solution, so I can say how many previous periods to include would be great result.<issue_comment>username_1: The scenario of two is relatively easy, by binding tables: ``` tbl %>% nest(-date) %>% mutate(data2 = map2(data, lag(data), ~safely(bind_rows, otherwise = NA)(.y, .x)$result)) ``` > > > ``` > # A tibble: 4 x 3 > date data data2 > > 1 2018-01-31 > 2 2018-02-28 > 3 2018-03-31 > 4 2018-04-30 > > ``` > > Upvotes: 1 [selected_answer]<issue_comment>username_2: Here is my idea, seems to be working. Thanks to username_1, giving me this idea. helper function: ``` bind_roll <- rollify(~dplyr::bind_rows(.), window = 3, unlist = FALSE) tbl %>% nest(-date) %>% mutate(data2 = bind_roll(data)) # A tibble: 4 x 3 date data data2 1 2018-01-31 2 2018-02-28 3 2018-03-31 4 2018-04-30 ``` Upvotes: 1
2018/03/16
687
2,317
<issue_start>username_0: I would like run the ionic app in the browser. I used this command `ionic serve` But I got this error `Error: spawn EACCES` I check ionic info but I got ionic framework is unknown ``` global packages: @ionic/cli-utils : 1.4.0 Cordova CLI : 7.0.1 Gulp CLI : CLI version 3.9.1 Local version 3.9.1 Ionic CLI : 3.4.0 ``` local packages: ``` @ionic/cli-plugin-cordova : 1.4.1 Cordova Platforms : android 6.4.0 Ionic Framework : unknown ``` System: ``` Node : v7.10.1 OS : Linux 4.13 Xcode : not installed ios-deploy : not installed ios-sim : not installed npm : 4.2.0 ```<issue_comment>username_1: Install ionic and Cordova globally by using these commands. 1 . sudo npm install -g ionic@latest. 2 . sudo npm install -g cordova@latest. Upvotes: 0 <issue_comment>username_2: Remove and install Ionic latest/stable Version and open the project in Android Studio and perform a successful gradle. Once done with the above procedure run the following command on your terminal in case you are using a MAC: > > sudo chmod 777 "/Applications/Android > Studio.app/Contents/gradle/gradle-4.1/bin/gradle" > > > Upvotes: 0 <issue_comment>username_3: Go to root folder of your ionic project and Follow the below instructions: run `sudo cordova prepare` run `sudo chmod -R 777 ./` run `ionic serve` Upvotes: 0 <issue_comment>username_4: This problem occurs for linux and mac system 1st add “read and write“ permission to the project folder Right click on the project folder-> click on get info -> add permissions Now use “sudo” before all syntax Like , sudo ionic cordova run android Upvotes: 0 <issue_comment>username_5: might you missing to add path in environment for C:\Users\username\AppData .otherwise you have install ionic CLI once again with respected node version user name is respected to your user name Upvotes: 0 <issue_comment>username_6: You have to **reinstall ionic and cordova**. Run this command: ``` npm install -g ionic cordova ``` Upvotes: 1 <issue_comment>username_7: Install ionic and Cordova globally by using these commands. To install the ionic cli: `npm install -g ionic@latest` To install the cordova cli: `npm install -g cordova@latest` Then run: `ionic serve` Upvotes: 0
2018/03/16
609
2,290
<issue_start>username_0: I want to expose 2 new endpoints on my controller. 1 has the method signature to add a single entity: ``` [HttpPost] [Route("v1/entities")] public IHttpActionResult AddEntity([FromBody] Entity entity) ``` The other is almost identical except it accepts an IEnumerable to add multiple entities: ``` [HttpPost] [Route("v1/entities")] public IHttpActionResult AddEntities([FromBody] IEnumerable entities) ``` Clearly this won't work since it won't know what action method to call. So how can I get around this to support both methods. Should I simply rename the second route to something like "v1/entitieslist"? Thanks<issue_comment>username_1: Install ionic and Cordova globally by using these commands. 1 . sudo npm install -g ionic@latest. 2 . sudo npm install -g cordova@latest. Upvotes: 0 <issue_comment>username_2: Remove and install Ionic latest/stable Version and open the project in Android Studio and perform a successful gradle. Once done with the above procedure run the following command on your terminal in case you are using a MAC: > > sudo chmod 777 "/Applications/Android > Studio.app/Contents/gradle/gradle-4.1/bin/gradle" > > > Upvotes: 0 <issue_comment>username_3: Go to root folder of your ionic project and Follow the below instructions: run `sudo cordova prepare` run `sudo chmod -R 777 ./` run `ionic serve` Upvotes: 0 <issue_comment>username_4: This problem occurs for linux and mac system 1st add “read and write“ permission to the project folder Right click on the project folder-> click on get info -> add permissions Now use “sudo” before all syntax Like , sudo ionic cordova run android Upvotes: 0 <issue_comment>username_5: might you missing to add path in environment for C:\Users\username\AppData .otherwise you have install ionic CLI once again with respected node version user name is respected to your user name Upvotes: 0 <issue_comment>username_6: You have to **reinstall ionic and cordova**. Run this command: ``` npm install -g ionic cordova ``` Upvotes: 1 <issue_comment>username_7: Install ionic and Cordova globally by using these commands. To install the ionic cli: `npm install -g ionic@latest` To install the cordova cli: `npm install -g cordova@latest` Then run: `ionic serve` Upvotes: 0
2018/03/16
450
1,620
<issue_start>username_0: So, I am writing a crypto trading bot. I can work out how much of ETH I can buy with the BTC I have, but you can only buy ETH in incremental values. The increments would range from 1000 to 0.001 depending on coin. Question is how do I round 123.456789 down to 123.456 if the increment is 0.001 and 120 if the increment is 10. Edit-The other question suggested was with a fixed number of DP while this was variable.<issue_comment>username_1: Assuming that increment values are powers of ten, positive or negative, the algorithm for this is as follows: * Divide the value by the increment * Truncate the decimal portion of the result * Multiply truncated value by the increment Multiplying by a power of ten "shifts" the position of the decimal point by the number of digits equal to the power by which you multiply. Doing so positions the part that you want to truncate after the decimal point. ``` public static decimal RoundDown(decimal val, decimal pos) { return pos * Math.Truncate(val / pos); } ``` Note that this approach works for increments both above and below 1. When the increment is 10, dividing yields 12.3456789, truncation yields 12, and multiplying back yields the desired value of 120. [Demo.](https://ideone.com/TIaeLw) Upvotes: 2 [selected_answer]<issue_comment>username_2: You can use floor: ``` double val = (double)Math.Floor(originalValue / increment) * increment; ``` Using Math.Floor(originaValue / increment) gives the amount of "**crypto unit**" that you can spend and then you multiply by increment to have the total of "**crypto unit**". Upvotes: 0
2018/03/16
1,057
3,761
<issue_start>username_0: I have a todo list that is generated via jsonplaceholder , the button on click populates the div with dummy content. What I am trying to achieve is that when I click on an individual div(task) it should be removed/hidden. So far, ``` Show Todo * {{todo.title}} * Task Status : {{todo.completed}} ``` JS ``` var vm = new Vue({ el: '#app', data() { return { todos: [], isActive: false } }, methods: { getTodo: function() { axios.get('https://jsonplaceholder.typicode.com/todos') .then((response) => { this.todos = response.data; }) }, removeTask: function() { this.isActive = !this.isActive; } } }) ``` The 'removeTask' event handler toggles the classes for all the generated divs(tasks) and not to the clicked div. How do I add/remove the class on the clicked div?<issue_comment>username_1: `isActive` is one for the entire instance, not every individual todo. What you'll need to do is to to populate the todo list either by mapping the response data or simply use the response data's `completed` property. ``` { "userId": 10, "id": 193, "title": "rerum debitis voluptatem qui eveniet tempora distinctio a", "completed": true } ``` Every item of the response's todo has the `completed` prop, so you can use that. That's how you'd go about doing it: ```js var vm = new Vue({ el: '#app', data() { return { todos: [] } }, methods: { getTodo: function() { axios.get('https://jsonplaceholder.typicode.com/todos') .then((response) => { this.todos = response.data; }) }, toggleCompleted: function(todo) { todo.completed = !todo.completed; } } }) ``` ```html Show Todo * {{todo.title}} * Task Status : {{todo.completed ? 'Completed' : 'Active'}} ``` Upvotes: 1 <issue_comment>username_2: Using the `axios` API i get the todos and pragmatically loop over the individual todos and apply an `isActive` prop to all of them. These props can now be toggled via `toggleTodo` when passing the todo' `id` to the method. :-) Notice i have applied a `v-if="todo.isActive"` upon the `ul` this can also be translated to `:class="{active: todo.isActive}"` if you were wanting to apply some styling i.e for transitions etc. By using this approach you can use the same logic to create methods such as `completeTodo` and `removeTodo` etc I have added a `showList` prop in order to show/hide the actual full list. I noticed you are using `v-bind` and `v-on` - this is absolutely valid but VUE ^2.0 can handle [shorthand binding](https://v1.vuejs.org/guide/syntax.html#Shorthands) :-) I also noticed you are using `single` quotes for your HTML attributes... Although this does not break your markup i think it's best practice to keep them as `double quotes`. ```js var vm = new Vue({ el: '#app', data: { todos: [], showList: false }, mounted () { this.getTodos() }, methods: { getTodos () { axios.get('https://jsonplaceholder.typicode.com/todos') .then(res => { res.data = res.data.map(todo => { todo.isActive = false return todo }) this.todos = res.data }) }, showTodos () { this.showList = !this.showList }, toggleTodo (id) { this.todos = this.todos.map(todo => { if (todo.id === id) { todo.isActive = !todo.isActive } return todo }) } } }) ``` ```html {{this.showList ? 'Hide' : 'Show'}} Todos Toggle Todo * {{todo.title}} * Task Status : {{todo.completed}} .active { border: 2px solid green; } ``` Upvotes: 3 [selected_answer]
2018/03/16
691
1,980
<issue_start>username_0: **I have a List** ``` List myList = Arrays.asList("1234", "1214", "1334"); ``` **My input is**: ``` String mInput = "1214" ``` --- How to write a comparator to compare all the elements of `myList` to `mInput` and if it is equal, move it to the top of the list<issue_comment>username_1: You don't need a comparator you can use : ``` List myList = new ArrayList<>(Arrays.asList("1234", "1214", "1334")); String mInput = "1214"; if (myList.contains(mInput)) { myList.remove(mInput);// remove mInput myList.add(0, mInput);// add it to to index 0 (top of list) } System.out.println(myList);// Input [1214, 1234, 1334] ``` --- Note you have to use `new ArrayList<>(Arrays.asList("1234", "1214", "1334"))` to understand why, you can read this [UnsupportedOperationException when trying to remove from the list returned by Array.asList](https://stackoverflow.com/questions/1624144/unsupportedoperationexception-when-trying-to-remove-from-the-list-returned-by-ar) Upvotes: 2 <issue_comment>username_2: If you really need comparator here, you can do something like this (assuming that `mInput` is not `null`): `myList.sort((String o1, String o2) -> mInput.equals(o1) && !mInput.equals(o2) ? -1 : o1.compareTo(o2));` Upvotes: 1 <issue_comment>username_3: You can write your own `Comparator`: ``` class BringToFrontComparator> implements Comparator { T front; public BringToFrontComparator(T front) { this.front = front; } @Override public int compare(T o1, T o2) { return o1.equals(front) && !o2.equals(front) // Front one is always less than anything other than itself. ? -1 // Normal comparison elsewhere. : o1.compareTo(o2); } } public void test(String[] args) throws Exception { List myList = Arrays.asList("1234", "1214", "1334"); String mInput = "1334"; Collections.sort(myList, new BringToFrontComparator<>(mInput)); System.out.println(myList); } ``` prints > > [1334, 1214, 1234] > > > Upvotes: 3 [selected_answer]
2018/03/16
815
2,430
<issue_start>username_0: How can be possible that 'this' in React.Component life cycle have changed to different object? In `render()` and in `componentDidMount()` `this` points to different objects? 1. I use React 16.0.0 2. All life-cycle methods called only once 3. I transpile Typescript with Webpack 4. I couldn't repeat it in a browser, in browser `one === two // true` 5. I have very big app, so I thought it can be ReactFiber some kind of optimization? Like here: [JsBin](https://jsbin.com/qenixobosa/edit?html,js,console,output) [![This is changed](https://i.stack.imgur.com/CSVmp.png)](https://i.stack.imgur.com/CSVmp.png) [![enter image description here](https://i.stack.imgur.com/Jlhpd.png)](https://i.stack.imgur.com/Jlhpd.png)<issue_comment>username_1: You don't need a comparator you can use : ``` List myList = new ArrayList<>(Arrays.asList("1234", "1214", "1334")); String mInput = "1214"; if (myList.contains(mInput)) { myList.remove(mInput);// remove mInput myList.add(0, mInput);// add it to to index 0 (top of list) } System.out.println(myList);// Input [1214, 1234, 1334] ``` --- Note you have to use `new ArrayList<>(Arrays.asList("1234", "1214", "1334"))` to understand why, you can read this [UnsupportedOperationException when trying to remove from the list returned by Array.asList](https://stackoverflow.com/questions/1624144/unsupportedoperationexception-when-trying-to-remove-from-the-list-returned-by-ar) Upvotes: 2 <issue_comment>username_2: If you really need comparator here, you can do something like this (assuming that `mInput` is not `null`): `myList.sort((String o1, String o2) -> mInput.equals(o1) && !mInput.equals(o2) ? -1 : o1.compareTo(o2));` Upvotes: 1 <issue_comment>username_3: You can write your own `Comparator`: ``` class BringToFrontComparator> implements Comparator { T front; public BringToFrontComparator(T front) { this.front = front; } @Override public int compare(T o1, T o2) { return o1.equals(front) && !o2.equals(front) // Front one is always less than anything other than itself. ? -1 // Normal comparison elsewhere. : o1.compareTo(o2); } } public void test(String[] args) throws Exception { List myList = Arrays.asList("1234", "1214", "1334"); String mInput = "1334"; Collections.sort(myList, new BringToFrontComparator<>(mInput)); System.out.println(myList); } ``` prints > > [1334, 1214, 1234] > > > Upvotes: 3 [selected_answer]
2018/03/16
1,262
2,930
<issue_start>username_0: In the following code I print out entire outputs and the minimum of them: ``` l= 4.98648387414 q= 4.96850590047 l= 6.22734941766 8.30807062837 q= 2.50807065862 6.36351958551 l= 6.55113742501 8.91180674608 1.62449083617 q= 6.58695963821 0.0460316539106 6.79113942876 min is= [ 6.55113743 8.91180675 1.62449084] [ 6.58695964 0.04603165 6.79113943] ``` But the output that I want to have is the minimum of `l` and the relevant `q` which means: `min is= [1.62449084] [6.79113943]` How should I do that and another question is that How should print out the outputs in a column not in front of each other. like this: ``` l= 4.98648387414 q= 4.96850590047 #for i=1 l= 6.22734941766 q= 2.50807065862 #for i=2 l= 8.30807062837 q= 6.36351958551 #for i=2 ``` the code is: ``` from numpy import * import numpy as np a=None temp=1e10 for i in range (1,4): r=np.random.uniform(0,3,i) x=np.random.uniform(0,9,i) h=np.random.uniform(0,1,i) l=h*10 if (l<1.0).any(): q=r elif (l>1.0).any(): q=x print("l= ",*l, "q= ",*q) if (l<temp).any(): temp=l a=q print("min is=", temp,a) </code> ``` I appreciate your help and your consideration.<issue_comment>username_1: You don't need a comparator you can use : ``` List myList = new ArrayList<>(Arrays.asList("1234", "1214", "1334")); String mInput = "1214"; if (myList.contains(mInput)) { myList.remove(mInput);// remove mInput myList.add(0, mInput);// add it to to index 0 (top of list) } System.out.println(myList);// Input [1214, 1234, 1334] ``` --- Note you have to use `new ArrayList<>(Arrays.asList("1234", "1214", "1334"))` to understand why, you can read this [UnsupportedOperationException when trying to remove from the list returned by Array.asList](https://stackoverflow.com/questions/1624144/unsupportedoperationexception-when-trying-to-remove-from-the-list-returned-by-ar) Upvotes: 2 <issue_comment>username_2: If you really need comparator here, you can do something like this (assuming that `mInput` is not `null`): `myList.sort((String o1, String o2) -> mInput.equals(o1) && !mInput.equals(o2) ? -1 : o1.compareTo(o2));` Upvotes: 1 <issue_comment>username_3: You can write your own `Comparator`: ``` class BringToFrontComparator> implements Comparator { T front; public BringToFrontComparator(T front) { this.front = front; } @Override public int compare(T o1, T o2) { return o1.equals(front) && !o2.equals(front) // Front one is always less than anything other than itself. ? -1 // Normal comparison elsewhere. : o1.compareTo(o2); } } public void test(String[] args) throws Exception { List myList = Arrays.asList("1234", "1214", "1334"); String mInput = "1334"; Collections.sort(myList, new BringToFrontComparator<>(mInput)); System.out.println(myList); } ``` prints > > [1334, 1214, 1234] > > > Upvotes: 3 [selected_answer]
2018/03/16
507
2,120
<issue_start>username_0: I have two intents **brand** and **brand\_model**. **brand** intent contains training phrases like * latest apple products * budget apple phones and so on where **apple** is the **brand**. **brand\_model** intent contains training phrases like * price of apple iphone 6 * show me the variants of apple iphone 6 which contains **brand** as **apple** and **model** as **iphone 6**. I want **brand\_model** to be triggered if user specifically enters **model** of the product (mandatory). Issue is if user enters "**show me some apple laptops**", it is triggering the **brand\_model** intent instead of **brand** intent. How can this be solved? Am I doing anything wrong?<issue_comment>username_1: if a user enters `"show me some apple laptops"`, it is triggering the `brand_model` intent instead of `brand intent`. To solve this problem you have to train you bot for that go in the training phase and when user's query is triggering wrong intent mark that query as wrong or assign the intent in training phase. By doing that when a user asks the same question or related to that it will trigger the intent which you assigned in the training which will be the true intent and you will get the right response . Upvotes: 2 <issue_comment>username_2: You're not doing anything wrong, but your phrases and entities might be what is influencing the choice of intent. Two things to consider: 1. What entity type are you using for `brand` and `model`? If you are using `@sys.any`, then the system has a pretty broad latitude to fill that in with anything, and it searches the rest of the phrase for exact patterns that match. If, however, you have entity types with specific brands and specific models, then it can better constrain what might match. 2. You may not have enough training phrases to give a good idea of what the user might say. So it may be picking up on the "Show me" part of the pattern for the `brand_model` intent and not even considering it for the `brand` intent. Try adding the phrase to the `brand` intent as well and see if it then starts matching better. Upvotes: 0
2018/03/16
1,331
4,024
<issue_start>username_0: When I use Pango to draw text onto a transparent Cairo recording surface, the text becomes quite heavily discoloured, particularly in the semi-transparent anti-aliased regions. For example, [this image has the correct (top) and incorrect (bottom) rendition of some text](https://i.stack.imgur.com/tBhA9.png). ([Segment of previous image zoomed in](https://i.stack.imgur.com/GL805.png)). My question, obviously, is how to get the correct colour rendition when using a transparent recording surface. At least, I am *assuming* this problem has to do with me not understanding the pangocairo pipeline very well. If it's a bug in Pango or Cairo, please do let me know. Code used to generate the image above: ``` #include #include int main(int argc, char \*\*argv) { cairo\_surface\_t \*canvas = cairo\_image\_surface\_create(CAIRO\_FORMAT\_ARGB32, 320, 60); cairo\_t \*cctx = cairo\_create(canvas); cairo\_surface\_t \*surf = cairo\_recording\_surface\_create( CAIRO\_CONTENT\_COLOR\_ALPHA, NULL); cairo\_t \*ctx = cairo\_create(surf); PangoFontDescription \*fd = pango\_font\_description\_new(); PangoLayout \*layout = pango\_cairo\_create\_layout(ctx); PangoAttrList \*attrs = pango\_attr\_list\_new(); PangoAttribute \*at; cairo\_set\_source\_rgba(cctx, 1, 1, 1, 1); cairo\_paint(cctx); cairo\_translate(cctx, 16, 8); pango\_font\_description\_set\_family(fd, "DejaVu Sans Mono"); pango\_layout\_set\_font\_description(layout, fd); pango\_layout\_set\_text(layout, "Bless the Maker and His water", -1); pango\_layout\_set\_attributes(layout, attrs); at = pango\_attr\_foreground\_new(0, 0xffff, 0xffff); pango\_attr\_list\_change(attrs, at); at = pango\_attr\_foreground\_alpha\_new(0xffff); pango\_attr\_list\_change(attrs, at); cairo\_save(ctx); cairo\_set\_source\_rgba(ctx, 1, 1, 1, 1); cairo\_set\_operator(ctx, CAIRO\_OPERATOR\_SOURCE); cairo\_paint(ctx); cairo\_restore(ctx); pango\_cairo\_update\_layout(ctx, layout); pango\_cairo\_show\_layout(ctx, layout); cairo\_set\_source\_surface(cctx, surf, 0, 0); cairo\_paint(cctx); cairo\_save(ctx); cairo\_set\_source\_rgba(ctx, 0, 0, 0, 0); cairo\_set\_operator(ctx, CAIRO\_OPERATOR\_SOURCE); cairo\_paint(ctx); cairo\_restore(ctx); pango\_cairo\_update\_layout(ctx, layout); pango\_cairo\_show\_layout(ctx, layout); cairo\_translate(cctx, 0, 24); cairo\_set\_source\_surface(cctx, surf, 0, 0); cairo\_paint(cctx); cairo\_surface\_write\_to\_png(canvas, "test.png"); g\_object\_unref(layout); pango\_attr\_list\_unref(attrs); pango\_font\_description\_free(fd); cairo\_destroy(ctx); cairo\_destroy(cctx); cairo\_surface\_destroy(surf); cairo\_surface\_destroy(canvas); return 0; } ``` **Update:** this seems to be caused by something in the video pipeline, and is probably a bug. I can reproduce this on two boxes using AMD video cards, but not on one with an nVidia card. I'm leaving this open in case anybody knows a fix.<issue_comment>username_1: First: You example code does not reproduce the problem here. There are no "color fringes" in the resulting image. If you allow me to guess: Cairo is assuming a subpixel order of RGB for you. According to the documentation for `cairo_subpixel_order_t` this is only used with `CAIRO_ANTIALIAS_SUBPIXEL`. Thus, I would suggest you to do: ``` cairo_font_options_t *opts = cairo_get_font_options(some_cairo_context); cairo_font_options_set_antialias(opts, CAIRO_ANTIALIAS_GRAY); // or _NONE cairo_set_font_options(some_cairo_context, opts); cairo_font_options_destroy(opts); ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: Turns out @uli-schlachter is *almost* correct: you have to set the antialiasing options on a Pango layout object: ``` PangoContext *pctx = pango_layout_get_context(layout); cairo_font_options_t *opts = cairo_font_options_create(); cairo_font_options_set_antialias(opts, CAIRO_ANTIALIAS_GRAY); pango_cairo_context_set_font_options(pctx, opts); cairo_font_options_destroy(opts); ``` Upvotes: 1
2018/03/16
1,025
2,722
<issue_start>username_0: How should be the for-loop if I am trying to generalize this : given `Number = 3` ``` FirstCellToWrite.Value = Controls("txtBox" & 1).Text FirstCellToWrite.Offset(1, 0).Value = Controls("txtBox" & 2).Text FirstCellToWrite.Offset(2, 0).Value = Controls("txtBox" & 3).Text FirstCellToWrite.Offset(0, 1).Value = Controls("txtBox" & 4).Text FirstCellToWrite.Offset(1, 1).Value = Controls("txtBox" & 5).Text FirstCellToWrite.Offset(2, 1).Value = Controls("txtBox" & 6).Text FirstCellToWrite.Offset(0, 2).Value = Controls("txtBox" & 7).Text FirstCellToWrite.Offset(2, 2).Value = Controls("txtBox" & 9).Text FirstCellToWrite.Offset(1, 2).Value = Controls("txtBox" & 8).Text ``` What I tried is: ``` q= 0 For p = 1 To number For i = 0 To number - 1 FirstCellToWrite.Offset(i, q).Value = Controls("txtBox" & p).Text Next i q = q+1 Next p ``` But this is not working<issue_comment>username_1: I think your p and q should be the other way around: `FirstCellToWrite.Offset(i,p).value = Controls("txtBox" & q).Text` And the `q = q + 1` should be between the "i" for loop. Upvotes: 0 <issue_comment>username_2: Try it without q or i and some maths on p. ``` For p = 0 To number - 1 debug.print "i=" & p mod 3 & ", q=" & int(p/3) & ", p=" & p+1 FirstCellToWrite.Offset(p mod 3, int(p/3)).Value = Controls("txtBox" & p+1).Text Next p ``` Immediate window results: ``` i=0, q=0, p=1 i=1, q=0, p=2 i=2, q=0, p=3 i=0, q=1, p=4 i=1, q=1, p=5 i=2, q=1, p=6 i=0, q=2, p=7 i=1, q=2, p=8 i=2, q=2, p=9 ``` Upvotes: 2 <issue_comment>username_3: Try using something like the following: ``` Dim ctrl As Long, RowCount As Long, ColumnCount As Long, IncrementCounter As Long IncrementCounter = 3 For ctrl = 1 To 9 FirstCellToWrite.Offset(RowCount, ColumnCount).Value2 = Controls("txtBox" & ctrl).Text RowCount = RowCount + 1 If ctrl Mod IncrementCounter = 0 Then ColumnCount = ColumnCount + 1 RowCount = 0 End If Next ctrl ``` Upvotes: 1 <issue_comment>username_4: If you simplify it less, using just 1 loop: ``` For p = 0 To (number-1)\3 'Using \ instead of / returns just the integer part 'i.e. 1/2 = 0.5, 1\2 = 0 and 5/2 = 2.5, 5\2 = 2 FirstCellToWrite.Offset(0, p).Value = Controls("txtBox" & (3*p + 1)).Text FirstCellToWrite.Offset(1, p).Value = Controls("txtBox" & (3*p + 2)).Text FirstCellToWrite.Offset(2, p).Value = Controls("txtBox" & (3*p + 3)).Text Next p ``` Then it becomes easier to see how you can make the inside a second loop: ``` For p = 0 To (number-1)\3 For i=1 To 3 FirstCellToWrite.Offset(i-1, p).Value = Controls("txtBox" & (3*p + i)).Text Next i Next p ``` Upvotes: 2
2018/03/16
2,871
8,200
<issue_start>username_0: so I have 5 dataframes of the top 80 rated players taken from FIFA 13-17 each containing a players name, rating and club. My end goal is to merge all of these datasets together so I can have a rating per player every year and a null value if they didn't make it. Obviously, some players are not in the top 80 every year ie: Retirement. Heres a snippet of three of the dataframes. FIFA18 `Name Overall Club 0 <NAME> 94 Real Madrid CF 1 <NAME> 93 FC Barcelona 2 Neymar 92 FC Barcelona 3 <NAME> 92 FC Barcelona 4 <NAME> 92 FC Bayern Munich 5 De Gea 90 Manchester United 6 <NAME> 90 FC Bayern Munich 7 <NAME> 90 FC Bayern Munich 8 <NAME> 90 Real Madrid CF 9 <NAME> 90 Manchester United 10 T. Courtois 89 Chelsea` FIFA13 `Name Overall Club 0 <NAME> 94 FC Barcelona 1 <NAME> 92 Real Madrid CF 2 <NAME> 90 FC Bayern Munich 3 Xavi 90 FC Barcelona 4 Iniesta 90 FC Barcelona 5 <NAME> 89 Manchester United 6 <NAME> 89 Manchester United 7 Casillas 89 Real Madrid CF 8 David Silva 88 Manchester City 9 Falcao 88 Atlético Madrid 10 <NAME> 88 Paris Saint-Germain` An example of where this occurs could be with N. Vidić who has since retired. My goal table would be this `Name FIFA17 FIA13 Club 0 <NAME> 94 92 Real Madrid CF 1 <NAME> 93 94 FC Barcelona 2 Neymar 92 83 FC Barcelona 3 <NAME> 92 86 FC Barcelona 4 <NAME> 92 87 FC Bayern Munich 5 De Gea 90 82 Manchester United 6 <NAME> 90 80 FC Bayern Munich 7 <NAME> 90 84 FC Bayern Munich 8 <NAME> 90 86 Real Madrid CF 9 <NAME> 90 88 Manchester United 10 <NAME> 89 83 Chelsea 11 <NAME> 86 90 FC Bayern Munich 12 Xavi 0 90 FC Barcelona 13 Iniesta 88 90 FC Barcelona 14 <NAME> 0 89 Manchester United 15 <NAME> 0 89 Manchester United 16 Casillas 0 89 Real Madrid CF 17 <NAME> 87 88 Manchester City 18 Falcao 0 88 Atlético Madrid` I am new to python and pandas but I have tried use join and merge but it always seems to use the index of each table rather than unique names. Any help would be greatly appreciated!<issue_comment>username_1: Here is one way via `pd.concat` and `pivot_table`. It assumes you are able to put your dataframes in a dictionary, which can be of arbitrary length. The solution also deals with multiple clubs, keeping the latest club only. ``` dfs = {13: df13, 18: df18} df = pd.concat([dfs[k].assign(Year=k) for k in dfs]) club_map = df.sort_values('Year', ascending=False)\ .drop_duplicates('Name')\ .set_index('Name')['Club'] df['Club'] = df['Name'].map(club_map) res = df.pivot_table(index=['Name', 'Club'], columns='Year', values='Overall', aggfunc=np.sum, fill_value=0)\ .reset_index().rename_axis(None, axis='columns') ``` **Result** ``` Name Club 13 18 0 Casillas Real Madrid CF 89 0 1 <NAME> Real Madrid CF 92 94 2 <NAME> Manchester City 88 0 3 De Gea Manchester United 0 90 4 <NAME> FC Bayern Munich 90 0 5 Falcao Atlético Madrid 88 0 6 <NAME> Real Madrid CF 0 90 7 Iniesta FC Barcelona 90 0 8 <NAME> FC Bayern Munich 0 90 9 <NAME> FC Barcelona 94 93 10 <NAME> FC Barcelona 0 92 11 <NAME> FC Bayern Munich 0 92 12 <NAME> Manchester United 89 0 13 Neymar FC Barcelona 0 92 14 <NAME> FC Bayern Munich 0 90 15 <NAME> Chelsea 0 89 16 <NAME> Manchester United 89 0 17 Xavi FC Barcelona 90 0 18 <NAME> Manchester United 88 90 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Use [`set_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html) for `MultiIndex` in columns with [`concat`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html), then replace `NaN`s by [`fillna`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html), cast to `integer`s and last convert `MultiIndex` to columns by [`reset_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html): ``` s1 = df1.drop_duplicates(['Name','Club']).set_index(['Name','Club'])['Overall'] s2 = df2.drop_duplicates(['Name','Club']).set_index(['Name','Club'])['Overall'] df = pd.concat([s2, s1], axis=1, keys=('FIFA13','FIFA18')).fillna(0).astype(int).reset_index() print (df) Name Club FIFA13 FIFA18 0 Casillas Real Madrid CF 89 0 1 <NAME> Real Madrid CF 92 94 2 <NAME> Manchester City 88 0 3 <NAME> Manchester United 0 90 4 <NAME> FC Bayern Munich 90 0 5 Falcao Atlético Madrid 88 0 6 <NAME> Real Madrid CF 0 90 7 Iniesta FC Barcelona 90 0 8 <NAME> FC Bayern Munich 0 90 9 <NAME> FC Barcelona 94 93 10 <NAME> FC Barcelona 0 92 11 <NAME> FC Bayern Munich 0 92 12 <NAME> Manchester United 89 0 13 Neymar FC Barcelona 0 92 14 <NAME> FC Bayern Munich 0 90 15 <NAME> Chelsean 0 89 16 <NAME> Manchester United 89 0 17 Xavi FC Barcelona 90 0 18 <NAME> Manchester United 0 90 19 <NAME> Paris Saint-Germain 88 0 ``` If order is important solution is similar, only get unique pairs `Names` with `Club`, join together and remove duplicates by [`drop_duplicates`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html) and [`reindex`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html): ``` s1 = df1.drop_duplicates(['Name','Club']).set_index(['Name','Club'])['Overall'] s2 = df2.drop_duplicates(['Name','Club']).set_index(['Name','Club'])['Overall'] df = pd.concat([s2, s1], axis=1, keys=('FIFA13','FIFA18')).fillna(0).astype(int) idx = pd.concat([df1[['Name','Club']], df2[['Name','Club']]]).drop_duplicates() df = df.reindex(idx).reset_index().drop_duplicates('Name', keep='last') print (df) Name Club FIFA13 FIFA18 0 <NAME> FC Barcelona 94 93 1 <NAME> Real Madrid CF 92 94 2 <NAME> FC Bayern Munich 90 0 3 Xavi FC Barcelona 90 0 4 Iniesta FC Barcelona 90 0 5 <NAME> Manchester United 89 0 6 <NAME> Manchester United 89 0 7 Casillas Real Madrid CF 89 0 8 <NAME> Manchester City 88 0 9 Falcao Atlético Madrid 88 0 11 Neymar FC Barcelona 0 92 12 <NAME> FC Barcelona 0 92 13 <NAME> FC Bayern Munich 0 92 14 De Gea Manchester United 0 90 15 <NAME> FC Bayern Munich 0 90 16 <NAME> FC Bayern Munich 0 90 17 <NAME> Real Madrid CF 0 90 18 <NAME> Manchester United 0 90 19 <NAME> Chelsean 0 89 ``` For general solution use `list comprehension`s: ``` dfs = [df2, df1] names= ['FIFA13','FIFA18'] s = [x.drop_duplicates(['Name','Club']).set_index(['Name','Club'])['Overall'] for x in dfs] df = pd.concat(s, axis=1, keys=(names)).fillna(0).astype(int) s1 = [x[['Name','Club']] for x in dfs] idx = pd.concat(s1).drop_duplicates() df = df.reindex(idx).reset_index().drop_duplicates('Name', keep='last') ``` Upvotes: 2
2018/03/16
584
1,761
<issue_start>username_0: I want to hide the **specific div**(Example 2) but it has no class or id so i am unable to apply jquery on that specific div(Example 2)...Please guide me how can hide that div with jquery. Here is my div structure: ``` ##### Heading Sample Example 1 00:00 Check-out 00:00 Example 2 Example 3 ```<issue_comment>username_1: You can use DOM relationship and target the desired element using its siblings. ```js $('.booking-hide-on-wholeday').next().hide() ``` ```html ##### Heading Sample Example 1 00:00 Check-out 00:00 Example 2 ``` Upvotes: 1 <issue_comment>username_2: You could select that div with `.purhist-desc-col div:last-of-type` since you need to target the last div inside that container so the jQuery code would be ``` $('.purhist-desc-col div:last-of-type').hide() ``` and in *vanillaJS* ``` document.querySelector('.purhist-desc-col div:last-of-type').style.display = 'none' ``` Upvotes: 0 <issue_comment>username_3: You can achieve this by `+` (next) selector. ```js $(document).ready(function(e) { $('.booking-hide-on-wholeday + div').hide(); }); ``` ```html ##### Heading Sample Example 1 00:00 Check-out 00:00 Example 2 ``` Upvotes: 1 <issue_comment>username_4: For this, you have to write a lineer jquery code for it. ``` $('div.booking-hide-on-wholeday').next('div').hide(); ``` That will solve your question. Thanks Upvotes: 0 <issue_comment>username_5: And why jQuery if we can do it easily with CSS : ```css .purhist-desc-col>div:nth-child(5) { display: none; } /* OR booking-hide-on-wholeday + div { display: none; } */ ``` ```html ##### Heading Sample Example 1 00:00 Check-out 00:00 Example 2 Example 3 ``` Upvotes: 2 [selected_answer]
2018/03/16
1,190
4,276
<issue_start>username_0: Context: I'm trying to download a binary file from a backend (that requires some data posted as json-body) and save it with file-saver using the filename specified by the backend in the content-disposition header. To access the headers I think I need the HttpResponse. But I'm unable to use angular's `HttpClient.post(...): Observable>;` method with a Blob. When I call ``` this.httpclient.post('MyBackendUrl', params, {observe: 'response', responseType: 'blob'}); the compiler complains about the 'blob' ('json' is accepted by the compiler): error TS2345: Argument of type '{ observe: "response"; responseType: "blob"; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'. Types of property 'observe' are incompatible. Type '"response"' is not assignable to type '"body"'. ``` When I put the options in an own object as seen in <https://stackoverflow.com/a/48016652/2131459> (but without the "as" ...) the post(...):Observable is called and I cannot access the headers. Btw, even the simple example `return this.http.get('backendUrl', {responseType: 'blob'});` as seen e.g. in <https://stackoverflow.com/a/46882407/2131459> doesn't work for me. Versions used * Angular Version: 5.0.3 (will be updated to latest 5 in a week or so) * typescript: 2.4.2 * webpack: 3.8.1<issue_comment>username_1: When using `observe:response`, don't type the call (`post(...)`), as the returned Observable will be of HttpResponse. So this should work: ``` this.httpclient.post('MyBackendUrl', params, {observe: 'response', responseType: 'blob'} ); ``` Why this happens, is there's two versions of the post method, one with a generic type, one without: ``` /** * Construct a POST request which interprets the body as JSON and returns the full event stream. * * @return an `Observable` of all `HttpEvent`s for the request, with a body type of `T`. */ post(url: string, body: any | null, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: 'events'; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }): Observable>; /\*\* \* Construct a POST request which interprets the body as an `ArrayBuffer` and returns the full response. \* \* @return an `Observable` of the `HttpResponse` for the request, with a body type of `ArrayBuffer`. \*/ post(url: string, body: any | null, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: 'response'; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; }): Observable>; ``` Upvotes: 8 [selected_answer]<issue_comment>username_2: you can use as like ``` responseType: 'blob' as 'json' ``` Upvotes: 5 <issue_comment>username_3: Other answers are right but they are missing the example. **The main answer** first when the responseType is set the return type of the response is changed to Blob. To solve this add `observe: 'response'` which returns HTTPResponse. **Example:** I stumbled upon this issue and spent 6 hours solving. So, here I present an example to get filename from headers and download the file: ``` downloadPDF(url: string): Observable { return this.http.get(url, { responseType: 'blob', observe: 'response' }).pipe( map((result:HttpResponse) => { console.log(result); saveAs(result, "Quotation.pdf"); return result; })); ``` Here the `http` is instance of HttpClient, `saveAs()` is a method of [FileSaver](https://www.npmjs.com/package/file-saver) npm package same as the OP. There is one more problem you might get only [5 headers(Cache-Control, Pragma, etc)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers) in the result.headers and not your custom header for e.g. `x-filename`. The reason behind this CORS. Basically CORS doesn't allow browsers to access more than handfull of headers (listed in the link above). So solve this you would have to change server/API to send **Access-Control-Expose-Headers** header with the request. Upvotes: 5
2018/03/16
283
981
<issue_start>username_0: How can I reset the input field, after clicking on the button? ```html Eingabe function getInput(){ ET\_Event.eventStart('TestCloud', document.getElementById('search').value, 'TestCloud') } ```<issue_comment>username_1: Set value of the input = ''; *document.getElementById('search').value = '';* ```html Eingabe function getInput(){ //ET\_Event.eventStart('TestCloud', document.getElementById('search').value, 'TestCloud') document.getElementById('search').value = ''; } ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: Try this code, there is some unwanted code in yours. ```html Eingabe function getInput() { document.getElementById('search').value = ''; alert('Danke fuer Ihre Eingabe Thank you'); } ``` Upvotes: 1 <issue_comment>username_3: Here is a simplified example using jQuery to delete the content. ```js $("#delete-button").click(()=>{ $("#search").val("") }) ``` ```html Delete ``` Upvotes: 1
2018/03/16
297
1,032
<issue_start>username_0: I need to make perfect round of the `UIView`. When I try to make it perfect Its not looking like I exactly want. Which is good to make it by Interface Builder or code? ``` viewRound.layer.cornerRadius = 45.0 viewRound.layer.masksToBounds = true ```<issue_comment>username_1: Set value of the input = ''; *document.getElementById('search').value = '';* ```html Eingabe function getInput(){ //ET\_Event.eventStart('TestCloud', document.getElementById('search').value, 'TestCloud') document.getElementById('search').value = ''; } ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: Try this code, there is some unwanted code in yours. ```html Eingabe function getInput() { document.getElementById('search').value = ''; alert('Danke fuer Ihre Eingabe Thank you'); } ``` Upvotes: 1 <issue_comment>username_3: Here is a simplified example using jQuery to delete the content. ```js $("#delete-button").click(()=>{ $("#search").val("") }) ``` ```html Delete ``` Upvotes: 1
2018/03/16
510
1,838
<issue_start>username_0: I have an App Service on Azure Cloud for my .NET Core Web application. I decided to update my solution to .NET Core SDK to version 2.1.101 with runtime in version 2.0.6. When I try to start my application on Azure App Service, I get error which tells me that I can not run my application because of missing runtime in version 2.0.6. The highest installed version on Azure is 2.0.5. The question is how can I install the newest version of .NET Core SDK (2.1.101)? I tried with Site Extensions (Kudu) and run PowerShell scripts, but nothing works for me.<issue_comment>username_1: Based on my test, **currently the installed version on Azure is 2.0.6**. You can verify this by going to the Console and running ‘dotnet –info’. It should look like this: [![enter image description here](https://i.stack.imgur.com/kmEHM.png)](https://i.stack.imgur.com/kmEHM.png) We could also update the .NET Core runtime with *Azure App Service site extension* [![enter image description here](https://i.stack.imgur.com/zILss.png)](https://i.stack.imgur.com/zILss.png) In your case, if you publish it with VS,I recommond that you could check the [Remove additional files at destination] button during republish. That will remove the files existing in the WebApp before upload the files. [![enter image description here](https://i.stack.imgur.com/zklpe.png)](https://i.stack.imgur.com/zklpe.png) Upvotes: 3 [selected_answer]<issue_comment>username_2: You can change NetCore Runtime on Configuration -> General settings -> Major version = [Select Net code version] and Save Changes. You can check the net core version on Development Tools -> SSH. Though there is no dotnetsdk so dotnet --info won't run. [![enter image description here](https://i.stack.imgur.com/m758x.png)](https://i.stack.imgur.com/m758x.png) Upvotes: 1
2018/03/16
1,426
4,704
<issue_start>username_0: I recently added the Camera and File plugins to my Ionic 1.3/ Cordova app, and now the app is intermittently crashing on the Android device I am using. The crash is not happening when I am actually using the plugins, nonetheless I wanted to see if the problem would go away if I used more up to date plugins. If I remove the Camera plugin and add it again, I can see this in the output window: > > Warning: Unmet project requirements for latest version of > cordova-plugin-camera: Warning: cordova-android (5.2.1 in project, > > > > > > > =6.3.0 required) Warning: Fetching highest version of cordova-plugin-camera that this project supports: 2.4.1 (latest is > > 4.0.2) > > > > > > > > > Currently in Visual Studio 2017 you can specify a Toolset that uses Cordova 6.3.1 or a Global Cordova version, so I thought I would try using the latest version of Cordova and on a command line entered: `npm install -g cordova`. I had to restart my computer, but now in my config.xml I can choose "Global Cordova 8.0.0". Now, in order to use the latest Camera plugin I need to get the `cordova-android` platform `>=6.3.0`. But if I use `cordova platform add android`, it fails because that command needs to be run inside a Cordova-based project. So I navigate to my existing project folder and run `cordova platform add android` again. It tries to fetch `cordova-android@5.2.1` - so I guess it's now using cordova 6.3.1, because that's the local version. Wrong! - `cordova -v` tells me it's 8.0.0, so it must be choosing `5.2.0` for some other reason. So what do I need to do now? Do I need to uninstall the local cordova from a command line? Do I delete the existing node\_modules, platforms, plugins folders? Do I change the config.xml? (current example entry: - . If I do all that then decide I need to go back to using Visual Studio's toolset, will I have to keep copies of everything and install manually or can I just go back and select the 6.3.1 toolset again?<issue_comment>username_1: After a few try i have found a way: **Follow this steps:** 1. install nodejs **4.8.7** on your machine 2. in visual studio go under tools>options>"Tools for apache cordova" and deflag chekbox **"use a sandboxed version of NodeJS"** 3. Edit **taco.json** file of your project and set **"cordova-cli": "7.1.0"** 4. Open a new console and install cordova on your machine (**npm install -g cordova@7.1.0**) **For android build:** 1. open prompt, digit android and press return 2. download **API 26 SDK** from tool 3. download **gradle 2.x** and put bin folder in your system path 4. install **jdk 1.8.x** and set **java\_home** system var to it 5. reboot the system Hope it help. Upvotes: 1 <issue_comment>username_2: Changing the Cordova CLI version in Visual Studio 2017 is not as straightforward as it would appear. Here are the steps I had to follow to change to **Cordova 7.1.0** and **cordova-android 6.3.0**, surely it will allow you to move to [Cordova 8.0](https://cordova.apache.org/news/2017/12/18/tools-release.html) and [cordova-android 7.1.0](https://cordova.apache.org/announcements/2018/02/26/cordova-android-7.1.0.html) as well. Follow these steps: Go to `File > New > Project > Blank App (Apache Cordova)` Open `config.xml` in View Code mode and find this: ``` 6.3.1 ``` Replace with: ``` 8.0.0 ``` Where `8.0.0` is your globally installed Cordova version. Select `Device` as target. Now `Build > Build Solution` Save, close and reload the project. When you access `config.xml` in designer mode you'll see **Global Cordova 8.0.0** as the selected toolset. [![enter image description here](https://i.stack.imgur.com/ZrwZC.png)](https://i.stack.imgur.com/ZrwZC.png) In order to build you may need to use the external Android SDK Build Tools (API 27 I guess - it was API 26 for CLI 7.1.0) instead of the ones provided by Visual Studio (API 25). [![enter image description here](https://i.stack.imgur.com/84BOh.png)](https://i.stack.imgur.com/84BOh.png) Use the [Android SDK Manager](https://stackoverflow.com/questions/41407396/is-gui-for-android-sdk-manager-gone) to manage versions, no need to get Android Studio for this. [![enter image description here](https://i.stack.imgur.com/5nX2y.png)](https://i.stack.imgur.com/5nX2y.png) Remember to follow [the **guidelines** from Microsoft](https://learn.microsoft.com/en-us/visualstudio/cross-platform/tools-for-cordova/change-cordova-version/change-cli-version?view=toolsforcordova-2015) when changing the CLI on existing projects. However I strongly recommend creating a new one and then importing your files and adding your plugins to avoid potential problems. Upvotes: 3 [selected_answer]
2018/03/16
326
1,226
<issue_start>username_0: I have a fairly complex and performance-critical Haskell program. I have used cost center profiling to optimize to the point where there are no major remaining hot spots. Furthermore, the program runs about 15x faster with `-O2` (and no profiling) than it does with `stack build --profile`, so I have doubts as to whether the cost center profiler is helping much at all with finding bottlenecks that remain post-optimization. What are my options for finding hot spots that remain after optimization? I am aware of ticky-ticky profiling, but it is described in the docs as not for "mere mortals", and I am a mere mortal.<issue_comment>username_1: This is a very general question, but do you have searched for space leaks ? One nice package is [weigh](https://hackage.haskell.org/package/weigh). The author has written a very good [article](https://www.fpcomplete.com/blog/2016/05/weigh-package) about it. Upvotes: -1 <issue_comment>username_2: Since GHC 9.4.1 you can use the [`-fprof-late`](https://downloads.haskell.org/ghc/9.4.1/docs/users_guide/profiling.html#ghc-flag--fprof-late) flag to have the compiler add automatic cost centre annotations after optimizations. Upvotes: 2 [selected_answer]
2018/03/16
584
1,570
<issue_start>username_0: ``` +------+------+------------+--------------------+ | id | C_Br | C_Date | daily_typing_pages | +------+------+------------+--------------------+ | 1 | 51 | 2007-01-01 | 100 | | 2 | 52 | 2007-01-01 | 100 | | 3 | 53 | 2007-01-01 | 100 | | 3 | 54 | 2007-01-01 | 100 | | 4 | 51 | 2007-01-02 | 220 | | 5 | 52 | 2007-01-02 | 300 | | 5 | 53 | 2007-01-02 | 350 | +------+------+------------+--------------------+ ``` I am trying to calculate per date average with below query: ``` SELECT Month(C_Date) as Date,avg(daily_typing_pages) FROM tbl_data GROUP BY C_Br,Month(C_Date) ``` But rather than dividing it by no of days in a month it is also dividing with count of C\_Br. Is there any solution to calculate monthly average (Assuming sum of total daily\_typing\_pages per day as one unit)<issue_comment>username_1: ``` SELECT Month(C_Date) as Date,sum(daily_typing_pages)/DAY(LAST_DAY(max(C_Date))) FROM tbl_data GROUP BY C_Br,Month(C_Date) ``` Date wise avg() ``` SELECT C_Date as Date,avg(daily_typing_pages) as AVG FROM tbl_data GROUP BY C_Date; ``` Upvotes: 2 <issue_comment>username_2: You should try for average month and year, so here is the query. ``` SELECT CONCAT(YEAR(t.`C_Date`), '-', MONTH(t.`C_Date`)) AS ym, AVG(t.`daily_typing_pages`) FROM tbl_data t WHERE 1 GROUP BY ym ``` `ym` is year and month, which I used for grouping results and calculating average. Upvotes: 0
2018/03/16
999
4,179
<issue_start>username_0: The question is on how to design a REST web service which performs time-consuming jobs (order of magnitude of several seconds and minutes). The fastest solution would be to proceed as follows: 1. client sends a POST request to server (POST /job), the answer has HTTP status 202 and will contain the job id; 2. client asks periodically the job status with a GET (e.g. `GET /job/:id/status`); 3. when the job completes the client requests the results with a GET (e.g. `GET /job/:id/result`). What I don't like is step 2 because with many jobs in progress the server is unnecessarily overloaded. To avoid this I thought two other solutions: * when the client does the first POST request, it gives also a URL which can be used as a *callback* from the server. When the server ends the elaboration, it will notify the client at this URL with a GET/POST request; * the server makes available a [WebSocket](https://en.wikipedia.org/wiki/WebSocket) where the client can register and get "notifications" on job completion; All the three solutions have aspects that I do not like: 1. ***polling:*** server overload; 2. ***callback:*** client must make a URL available to the server; 3. ***websocket:*** why introduce another "tecnology" to the REST webservice? Perhaps, at that point, it is better to use only websockets to do all requests. Are there other solutions? If no, which of the three you would consider more reliable?<issue_comment>username_1: You almost answered your question by yourself. The thing is, what approach would you choose based on your requirements. All of your proposals are solutions for your problem, but you have to put weight on them and decide for yourself. However I think you put too much exaggeration on method 1. If you develop a progression strategy, like doing the poll (not pool) irregularly, say first poll after 30 seconds, next one after 20 more, then after 10, then after 5, then maybe repeat that sequence, then it won't be that stressful for the server. Also, the intervals you choose may be based on the response from the POST request if you can somehow predict the complexity of the job. So if the job would take minutes, no point in polling every 5 seconds for example. You may develop a strategy like an array (time in seconds): [300, 120, 60, 30, 20, 10], meaning you would wait 5 minutes first, then another 2 minutes, then 1 minute, etc. - you get it, and you can finish with intervals of 10 seconds. Since the job itself could take minutes, I don't think it is critical if the result gets delayed by some seconds, i.e. ready, but not served right on time. Upvotes: 1 <issue_comment>username_2: Polling tends to be very easy to implement and it can be very reliable. The reliability comes from the simplicity of the solution. Polling requests should be very cheap requests in general. Polling can be made efficient by backing off the polling frequency and by checking more than one job at a time (e.g. send 1000 IDs in one request). Any non-polling solution must be a form of active notification. The HTTP callback solution you proposed requires the client to have a web server running. It can be done but it seems unnecessary. The web socket idea clearly works as well. You will need reconnect logic and handle the case that the job completes while the client happens to be disconnected. Client-side code will likely involve threading since you probably don't want one web socket connection per job. A simpler idea than using web sockets would be to use a "comet" HTTP request. The server keeps the HTTP request open until the job completes. This can be very efficient with async IO so that no thread is blocked while waiting. But if the connection is severed some reconnect strategy must be implemented. You could make the server write a message to a queue that the client reads. All of these notification solutions tend to be much more complicated than the simple polling solution. They need more developer time and will break in production more often. But they can have lower latency and use less resources. I'd try to make polling work. Likely it will work and you're done quickly. Upvotes: 2
2018/03/16
1,872
5,123
<issue_start>username_0: In the default Flutter application code, I tried to change the following code from: ``` primarySwatch: Colors.blueGrey ``` to: ``` primarySwatch: Colors.blueGrey[500] ``` but this throws an error: ``` ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ I/flutter ( 4512): The following assertion was thrown building MyApp(dirty): I/flutter ( 4512): type 'Color' is not a subtype of type 'MaterialColor' of 'primarySwatch' where I/flutter ( 4512): Color is from dart:ui I/flutter ( 4512): MaterialColor is from package:flutter/src/material/colors.dart I/flutter ( 4512): int is from dart:core I/flutter ( 4512): I/flutter ( 4512): Either the assertion indicates an error in the framework itself, or we should provide substantially I/flutter ( 4512): more information in this error message to help you determine and fix the underlying cause. I/flutter ( 4512): In either case, please report this assertion by filing a bug on GitHub: I/flutter ( 4512): https://github.com/flutter/flutter/issues/new I/flutter ( 4512): I/flutter ( 4512): When the exception was thrown, this was the stack: I/flutter ( 4512): #0 new ThemeData (package:flutter/src/material/theme_data.dart:78:19) I/flutter ( 4512): #1 MyApp.build (/data/user/0/com.hackathon.gunbanana/cache/gun_bananaEMVSSI/gun_banana/lib/main.dart:11:18) I/flutter ( 4512): #2 StatelessElement.build (package:flutter/src/widgets/framework.dart:3678:28) I/flutter ( 4512): #3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3625:15) I/flutter ( 4512): #4 Element.rebuild (package:flutter/src/widgets/framework.dart:3478:5) I/flutter ( 4512): #5 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3605:5) I/flutter ( 4512): #6 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5) I/flutter ( 4512): #7 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14) I/flutter ( 4512): #8 Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12) I/flutter ( 4512): #9 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:852:16) I/flutter ( 4512): #10 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:823:5) I/flutter ( 4512): #11 RenderObjectToWidgetAdapter.attachToRenderTree. (package:flutter/src/widgets/binding.dart:769:17) I/flutter ( 4512): #12 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2205:19) I/flutter ( 4512): #13 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:768:13) I/flutter ( 4512): #14 BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&RendererBinding&WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:657:7) I/flutter ( 4512): #15 runApp (package:flutter/src/widgets/binding.dart:699:7) I/flutter ( 4512): #16 main (/data/user/0/com.hackathon.gunbanana/cache/gun\_bananaEMVSSI/gun\_banana/lib/main.dart:3:16) I/flutter ( 4512): #17 \_startIsolate. (dart:isolate-patch/dart:isolate/isolate\_patch.dart:279) I/flutter ( 4512): #18 \_RawReceivePortImpl.\_handleMessage (dart:isolate-patch/dart:isolate/isolate\_patch.dart:165) I/flutter ( 4512): ════════════════════════════════════════════════════════════════════════════════════════════════════ ``` ![Message on the mobile](https://i.stack.imgur.com/P3Oyb.png) How do I use shades?<issue_comment>username_1: **TLDR** Do ``` ThemeData(primarySwatch: Colors.lime), ``` Don't ``` ThemeData(primarySwatch: Colors.lime.shade700), ``` --- primarySwatch is not *one* color. It's all the possible material shades. If you look into `ThemeData`'s doc it says : > > The primary color palette (the [primarySwatch]), chosen from > one of the swatches defined by the material design spec. This > should be one of the maps from the [Colors] class that do not > have "accent" in their name. > > > This implies that when needed the material component will use primary[500] but may also use other shades ! In fact, `primarySwatch` is a shortcut to set a bunch of different colors : * primaryColor * primaryColorLight/Dark * accentColor * ... But you can override them separatly depending on your needs, with a `Color` (and not the `MaterialColor` that primarySwatch requires) Upvotes: 5 <issue_comment>username_2: In main.dart file make your custom color outside of MyApp class as below : ``` Map color = { 50: Color.fromRGBO(255, 92, 87, .1), 100: Color.fromRGBO(255, 92, 87, .2), 200: Color.fromRGBO(255, 92, 87, .3), 300: Color.fromRGBO(255, 92, 87, .4), 400: Color.fromRGBO(255, 92, 87, .5), 500: Color.fromRGBO(255, 92, 87, .6), 600: Color.fromRGBO(255, 92, 87, .7), 700: Color.fromRGBO(255, 92, 87, .8), 800: Color.fromRGBO(255, 92, 87, .9), 900: Color.fromRGBO(255, 92, 87, 1), }; MaterialColor colorCustom = MaterialColor(0xFFFF5C57, color); ``` And then just set it to your primarySwatch property inside ThemeData like below ``` primarySwatch: colorCustom, ``` Upvotes: 4
2018/03/16
732
2,879
<issue_start>username_0: I found this and online and now trying to put it in TS. Running the following throws `Uncaught TypeError: Cannot set property 'toggle' of null` ``` @Injectable() export class HomeUtils { private canvas: HTMLCanvasElement; private context; private toggle = true; constructor() { } public startNoise(canvas: HTMLCanvasElement) { this.canvas = canvas; this.context = canvas.getContext('2d'); this.resize(); this.loop(); } private resize() { this.canvas.width = window.innerWidth; this.canvas.height = window.innerHeight; } private loop() { this.toggle = false; if (this.toggle) { requestAnimationFrame(this.loop); return; } this.noise(); requestAnimationFrame(this.loop); } private noise() { const w = this.context.canvas.width; const h = this.context.canvas.height; const idata = this.context.createImageData(w, h); const buffer32 = new Uint32Array(idata.data.buffer); const len = buffer32.length; let i = 0; for (; i < len;) { buffer32[i++] = ((255 * Math.random()) | 0) << 24; } this.context.putImageData(idata, 0, 0); } } ``` I'm lost.<issue_comment>username_1: It's the call to `requestAnimationFrame`. You are passing a function not bound to a context, and so, inside that call to `loop` there is no `this`. Change the call to: ``` requestAnimationFrame(() => this.loop()); ``` Arrow functions, contrarily to normal functions, are bound to `this`. Upvotes: 3 <issue_comment>username_2: Methods do not capture `this` and are dependent on the caller to call them with the correct `this`. So for example: ``` this.loop() // ok let fn = this.loop; fn(); // Incorect this fn.apply(undefined) // Undefined this ``` Since you pass `loop` to another function `requestAnimationFrame` you need to ensure that `this` is captured from the declaration context and not decided by `requestAnimationFrame` : You can either pass an arrow function to `requestAnimationFrame` ``` private loop() { this.toggle = false; if (this.toggle) { requestAnimationFrame(() => this.loop()); return; } this.noise(); requestAnimationFrame(() => this.loop()); } ``` Or you can make loop an arrow function not a method: ``` private loop = () => { this.toggle = false; if (this.toggle) { requestAnimationFrame(this.loop); return; } this.noise(); requestAnimationFrame(this.loop); } ``` The second approach has the advantage of not creating a new function instance on each call to `requestAnimationFrame`, since this will be called a lot, you might want to go with the second version to minimize memory allocations. Upvotes: 6 [selected_answer]
2018/03/16
1,664
6,426
<issue_start>username_0: Could someone advice me on how to integrate FontAwesome 5 **Pro** with React? I know there are packages @fortawesome/react-fontawesome and for example @fortawesome/fontawesome-free-regular but is there a way how to include **pro version** of icons? When I log in to FontAwesome website, I can download the pro-version JS but I guess that's of no use in React.<issue_comment>username_1: I think you will be able to use them be adding the JS script and appropriate CSS files to your **index.html** Let's say if you want to use the default font awesome without having any packages installed then directly include file in **index.html** as shown below ```js ``` Upvotes: 0 <issue_comment>username_2: OK, I solved it myself. What I did was to import `@fortawesome/react-fontawesome`. Then I manually downloaded the pro package of FontAwesome and from the folder `/advanced-options/use-with-node-js/fontawesome-pro-light` I copied desired icons (there are JS files such as `faUsers.js`) to my project folder and included these icons as well. So at the beginning of the file I have something like ``` import FontAwesomeIcon from '@fortawesome/react-fontawesome'; import faUser from '../font-awesome/faUser'; ``` Then I used it ``` render() { return() ( ... ... ); } ``` It's a little bit annoying because I need to manually import every single icon but I couldn't think of any better solution. Upvotes: 1 <issue_comment>username_3: I managed to make it work without having to import each icon, with ``` import FontAwesomeIcon from '@fortawesome/react-fontawesome'; import fontawesome from '@fortawesome/fontawesome' import solid from '@fortawesome/fontawesome-pro-solid' fontawesome.library.add(solid) ``` And then using the icons as ``` ``` Upvotes: 0 <issue_comment>username_4: You must use a TOKEN to access Font Awesome Pro via NPM. ======================================================== Manually downloading the icons and installing them locally is an anti-pattern and not the way the Font Awesome team expects you to use Font Awesome Pro with Node and NPM. Accessing to the Pro packages requires you to configure the @fortawesome scope to use the Font Awesome Pro NPM registry using your **TOKEN** which can be found in your Font Awesome account settings. 1. **Login to see your token**: <https://fontawesome.com/account/services> 2. **Navigate to this step-by-step tutorial** after logging in and it will contain your token in all the examples: <https://fontawesome.com/how-to-use/on-the-web/setup/using-package-managers#installing-pro> 3. **Install react-fontawesome** and follow the examples to render icons: <https://github.com/FortAwesome/react-fontawesome> **Note:** If you're looking to use Font Awesome Pro in **React Native**, check out: [react-native-fontawesome-pro](https://github.com/shyaniv7/react-native-fontawesome-pro) Upvotes: 2 <issue_comment>username_5: **tldr;** Use `@fortawesome/pro-light-svg-icons`, `@fortawesome/pro-regular-svg-icons` NPM packages. I ran into this problem today, and I think the main question of how to use Pro version of the icons has not been addressed. The official docs aren't much help. This is what I had to do for using `faFilePlus` icon, the light version: `import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faFilePlus } from '@fortawesome/pro-light-svg-icons/faFilePlus';` and then: Note the use of `@fortawesome/pro-light-svg-icons` NPM package. This is undocumented anywhere in the FA's official docs and I had to dig through several places to arrive at this solution. The official docs only talk about the use of "free" icons but don't say where to find the equivalent NPM package for light, regular etc. Also note that this does require NPM to be authenticated as mentioned in one of the answers. Upvotes: 3 <issue_comment>username_6: Here's how to integrate Font Awesome 5 Pro with React (2018): 1. Purchase a Pro licence from [Font Awesome's pricing page](https://fontawesome.com/pricing) 2. Upon success, ignore the success pages. You should be logged into Font Awesome. In the login state, go to this guide: [Font Awesome Installation Guide](https://fontawesome.com/how-to-use/on-the-web/setup/using-package-managers#installing-pro). 3. If you are logged in and have a valid license key in your account, every code snippet in this tutorial will use your access token. 4. Now, you can install your license key globally via (A) `npm config set ...` or locally per project via (B) `.npmrc`. I recommend (B) so other team-mates can also install the pro package. 5. For (B), Go to your package.json directory and create a `.npmrc` file. In that file, paste the code snippet provided in the guide. It should look something like this: ``` // .npmrc @fortawesome:registry=https://npm.fontawesome.com/ //npm.fontawesome.com/:_authToken= ``` 6. Once done, you should now be able to install the pro packages. They are according to the official react adapter [react-fontawesome](https://github.com/FortAwesome/react-fontawesome) available as the following npm packages: * @fortawesome/pro-solid-svg-icons * @fortawesome/pro-regular-svg-icons * @fortawesome/pro-light-svg-icons 7. So now do `npm install @fortawesome/pro--svg-icons` to install the pro package of your choice. 8. Thereafter, continue usage as provided by the react-fontawesome package. Which should look something like this in your react code if you installed the light version and using the ['Library' method by react-fontawesome](https://github.com/FortAwesome/react-fontawesome#build-a-library-to-reference-icons-throughout-your-app-more-conveniently): ``` // app.js import { library, config } from '@fortawesome/fontawesome-svg-core' import { fal } from '@fortawesome/pro-light-svg-icons' library.add(fal) ``` 9. Finally, usage looks something like this in a component file (available in both JS and TS flavours): ``` // Foo.jsx import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' const Foo = () => { return ( ) } export default Foo ``` And if you are into Typescript: ``` // Foo.tsx import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { IconLookup } from '@fortawesome/fontawesome-svg-core' const Foo = () => { const icon: IconLookup = { prefix: 'fal', iconName: 'utensils' } return ( ) } export default Foo ``` Upvotes: 6 [selected_answer]
2018/03/16
1,525
5,307
<issue_start>username_0: I'm using Stripe to charge my users for coaching services. Currently, a coach can decide what plans he wants to offer in his settings. If a coach only has basic\_coaching set to `false` then that is the only Stripe button that should **not** appear. How would I go about that? Here is my schema: ``` t.boolean "basic_coaching", default: true t.boolean "professional_coaching", default: true t.boolean "premium_coaching", default: true t.boolean "platinum_coaching", default: true ``` Here is my controller: ``` @usd_plans = { # Plan ID -> Description 'basic_usd': 'Basic Coaching', 'professional_usd': 'Professional Coaching', 'premium_usd': 'Premium Coaching', 'platinum_usd': 'Platinum Coaching' } ``` Here is my view: ``` - @usd_plans.each do |plan_id, description| td = form_tag(subscriptions_path) do = hidden_field_tag 'plan', plan_id = hidden_field_tag 'coach_id', @user.id = hidden_field_tag 'user_id', current_user.id = hidden_field_tag 'description', description - if current_user.coupon_code = hidden_field_tag 'coupon_code', current_user.coupon_code script.stripe-button( src='https://checkout.stripe.com/checkout.js' data-key=Rails.configuration.stripe[:publishable_key] data-name="#{@user.name}" data-description=description data-image="#{@user.avatar.url}" data-locale='auto' data-panel-label='Subscribe now' data-label='Buy' data-allow-remember-me='false' data-email=current_user.email ) ``` Here is what it looks like with all 4 booleans set to `true`. Ideally, I would just hide a button, if that specific boolean is set to `false`. [![enter image description here](https://i.stack.imgur.com/Jzuf5.png)](https://i.stack.imgur.com/Jzuf5.png)<issue_comment>username_1: You can decide the when you build `@usd_plans`, e.g. something like: ``` @usd_plans = {}.tap do |plans| # Plan ID -> Description plans['basic_usd'] = 'Basic Coaching' if coach.basic_coaching? plans['professional_usd'] = 'Professional Coaching' if coach.professional_coaching? plans['premium_usd'] = 'Premium Coaching' if coach.premium_coaching? plans['platinum_usd'] = 'Platinum Coaching' if coach.platinum_coaching? end ``` You can of course make it more DRY with some string concatenation and metaprogramming. The repetitive version is better for understanding :). **EDIT:** If you want to keep the layout, try to hide it in the view ``` @usd_plans = {}.tap do |plans| # Plan ID -> Description plans['basic_usd'] = {name: 'Basic Coaching', visible: coach.basic_coaching? } # etc... end - @usd_plans.each do |plan_id, data| td next unless data[:visible] = form_tag(subscriptions_path) do = hidden_field_tag 'plan', data[:plan_id] = hidden_field_tag 'coach_id', @user.id = hidden_field_tag 'user_id', current_user.id = hidden_field_tag 'description', description - if current_user.coupon_code = hidden_field_tag 'coupon_code', current_user.coupon_code script.stripe-button( src='https://checkout.stripe.com/checkout.js' data-key=Rails.configuration.stripe[:publishable_key] data-name="#{@user.name}" data-description=description data-image="#{@user.avatar.url}" data-locale='auto' data-panel-label='Subscribe now' data-label='Buy' data-allow-remember-me='false' data-email=current_user.email ) ``` Upvotes: 2 <issue_comment>username_2: Following your comment on @username_1's good answer, I'd suggest you might need to handle the logic in your view, so can add a placeholder if the plan button isn't required. Something like: Keep `@usd_plans` as is: ``` @usd_plans = { # Plan ID -> Description 'basic_usd': 'Basic Coaching', 'professional_usd': 'Professional Coaching', 'premium_usd': 'Premium Coaching', 'platinum_usd': 'Platinum Coaching } ``` Then in your view: ``` - @usd_plans.each do |plan_id, description| td - if @user.try(description.underscore) # or description.downcase.split(' ').join('_'), I haven't got Rails handy to test `underscore` = form_tag(subscriptions_path) do = hidden_field_tag 'plan', plan_id = hidden_field_tag 'coach_id', @user.id = hidden_field_tag 'user_id', current_user.id = hidden_field_tag 'description', description - if current_user.coupon_code = hidden_field_tag 'coupon_code', current_user.coupon_code script.stripe-button( src='https://checkout.stripe.com/checkout.js' data-key=Rails.configuration.stripe[:publishable_key] data-name="#{@user.name}" data-description=description data-image="#{@user.avatar.url}" data-locale='auto' data-panel-label='Subscribe now' data-label='Buy' data-allow-remember-me='false' data-email=current_user.email ) ``` This way, crucially, the `td` tag will be inserted regardless, while the button only plugged in if the user has that attribute set. Give it a try and let me know how you get on - happy to help with any questions. Upvotes: 2 [selected_answer]
2018/03/16
1,263
3,710
<issue_start>username_0: I am new to Scala and learning about the language using *Programming in Scala (second edition)*. I came across this topic of List concatenation, I was playing around with the language and got something here: ``` val scooters = List("Activa") val newCars = List("Ritz") val allCars = "Toyota" :: "Innova" :: newCars ::: newCars :: newCars allCars.foreach(println) ``` Output: ``` Toyota Innova Ritz List(Ritz) Ritz ``` Why is this not coming out as ``` Toyota Innova Ritz Ritz Ritz ```<issue_comment>username_1: In Scala, the associativity of a method is determined by its last character. If it ends with a colon (`:`), it's right-associative. This means that in `1 :: Nil`, you're calling the method `::` of `Nil`, not of `1`. This is why `1 :: 2` doesn't compile, while `1 :: 2 :: Nil` does. * `::` is a List method to add a single element at the beggining of the list. Then, if you have a `List[Int]` of size 1 and try to append another list (as a single element), you end up with a list of size 2 and type `List[Any]`. * `:::` is a List method to add multiple elements. With all this in mind, you end up with the following code: ``` val allCars = "Toyota" :: "Innova" :: newCars ::: newCars ::: newCars ``` Upvotes: 1 <issue_comment>username_2: Because ``` "Toyota" :: "Innova" :: newCars ::: newCars :: newCars ``` desugars into ``` (((newCars.::(newCars)).:::(newCars)).::("Innova")).::("Toyota") ``` Notice what happens in the very first step: ``` newCars.::(newCars) ``` it produces the list with two elements: a `String` "Ritz" and a `List("Ritz")` of type `List[String]`, so you obtain ``` List(List("Ritz"), "Ritz") ``` in the first step. Note that the type of the whole expression becomes quite nonsensical for this context, (`List[Serializable]`, because `Serializable` is the least upper bound of both `String` and `List[String]`), and the compiler can tell you about it, simply declare the type of the expected outcome explicitly: ``` val newCars = List("Ritz") val allCars: List[String] = "Toyota" :: "Innova" :: newCars ::: newCars :: newCars allCars.foreach(println) ``` When you declare `allCars` with an explicit type, the compiler will tell you immediately what went wrong: ``` error: type mismatch; found : List[java.io.Serializable] required: List[String] val allCars: List[String] = "Toyota" :: "Innova" :: newCars ::: newCars :: newCars ``` In this way, you don't have to run it and to look at the output, or to cover it by a ridiculous number of tests: mistakes of this kind can be detected at compile time. The obvious fix is ouf course: ``` val allCars: List[String] = "Toyota" :: "Innova" :: newCars ::: newCars ::: newCars ``` Upvotes: 2 <issue_comment>username_3: Well... the thing you need to consider here is operator associativity. ``` val newCars = List("Ritz") ``` When you write something like following, ``` val allCars = "Toyota" :: "Innova" :: newCars ::: newCars :: newCars ``` It is actually, ``` val allCars = ("Toyota" :: ("Innova" :: newCars)) ::: (newCars :: newCars) ``` Which is equivalent to, ``` scala> val ll1 = "Innova" :: newCars // Or scala> val ll1 = newCars.::("Innova") // ll1: List[String] = List(Innova, Ritz) scala> val ll2 = "Toyota" :: ll1 // Or scala> val ll2 = ll1.::("Toyota") // ll2: List[String] = List(Toyota, Innova, Ritz) scala> val rl1 = newCars :: newCars // Or scala> val rl1 = newCars.::(newCars) // rl1: List[java.io.Serializable] = List(List(Ritz), Ritz) scala> val allCars = ll1 ::: rl1 // Or scala> val allCars = rl1.:::(ll1) // allCars: List[java.io.Serializable] = List(Innova, Ritz, List(Ritz), Ritz) ``` I hope this clears things up. Upvotes: 1
2018/03/16
1,871
7,061
<issue_start>username_0: I am building an application where Web API and IdentityServer4 are inside the same .Net Core 2.0 project. This API is consumed by Aurelia SPA web app. IdentityServer4 set to use JWT and ImplicitFlow. Everything works good (Client app gets redirected to login, gets token, sends it back on header, etc.) up to the point where user needs to be authorized in the API controller, then it just cannot authorize user, because it's null. There are many similar questions exists, but I tried all proposed solutions and none of them worked for me. I already spent 2 days on this issue and starting to loose hope and patience. I probably missing something obvious, but just can't find it. I posting my configs here - what is wrong with them? Will appreciate any help. My Startup class (I have omitted some extra things like logging, localization, etc.): ``` public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity() .AddEntityFrameworkStores() .AddDefaultTokenProviders(); services.AddCors(options => { options.AddPolicy("default", policy => { policy.WithOrigins(Config.APP1\_URL) .AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddMvc(); services.Configure(options => { // Password settings options.Password.RequireDigit = false; options.Password.RequiredLength = 8; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequireLowercase = false; options.Password.RequiredUniqueChars = 4; // Lockout settings options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30); options.Lockout.MaxFailedAccessAttempts = 10; options.Lockout.AllowedForNewUsers = true; // User settings options.User.RequireUniqueEmail = true; }); services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryPersistedGrants() .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryApiResources(Config.GetApiResources()) .AddInMemoryClients(Config.GetClients()) .AddAspNetIdentity(); services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = Config.HOST\_URL + "/"; options.RequireHttpsMetadata = false; options.ApiName = "api1"; }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseIdentityServer(); app.UseAuthentication(); app.UseCors("default"); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } ``` This is my Config class: ``` public class Config { public static string HOST_URL = "http://dev.example.com:5000"; public static string APP1_URL = "http://dev.example.com:9000"; public static IEnumerable GetIdentityResources() { return new List { new IdentityResources.OpenId(), new IdentityResources.Profile() }; } public static IEnumerable GetApiResources() { return new List { new ApiResource("api1", "My API") }; } public static IEnumerable GetClients() { return new List { new Client { ClientId = "reporter", ClientName = "ReporterApp Client", AccessTokenType = AccessTokenType.Jwt, AllowedGrantTypes = GrantTypes.Implicit, RequireConsent = false, AllowAccessTokensViaBrowser = true, RedirectUris = { $"{APP1\_URL}/signin-oidc" }, PostLogoutRedirectUris = { $"{APP1\_URL}/signout-oidc" }, AllowedCorsOrigins = { APP1\_URL }, AllowedScopes = { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, "api1" } } }; } } ``` And the token Aurelia app gets from IdentityServer: ``` { "alg": "RS256", "kid": "52155e28d23ddbab6154ce0c34511c9a", "typ": "JWT" }, { "nbf": 1521195164, "exp": 1521198764, "iss": "http://dev.example.com:5000", "aud": ["http://dev.example.com:5000/resources", "api1"], "client_id": "reporter", "sub": "767381df-446a-4c34-af27-7bdf9e4563f3", "auth_time": 1521195163, "idp": "local", "scope": ["openid", "profile", "api1"], "amr": ["pwd"] } ```<issue_comment>username_1: First thing swap your order UseAuthencation over writes some stuff. ``` app.UseAuthentication(); app.UseIdentityServer(); ``` second change the cookie scheme. Identityserver4 has its own so your user is null because its not reading the cookie. ``` services.AddAuthentication(IdentityServerConstants.DefaultCookieAuthenticationScheme) .AddIdentityServerAuthentication(options => { // base-address of your identityserver options.Authority = Configuration.GetSection("Settings").GetValue("Authority"); // name of the API resource options.ApiName = "testapi"; options.RequireHttpsMetadata = false; }); ``` Idea number three: I had to add the type to the api call so that it would read the bearer token. ``` [HttpPost("changefiscal")] [Authorize(AuthenticationSchemes = "Bearer")] public async Task ChangeFiscal([FromBody] long fiscalId) { // STuff here } ``` Upvotes: 1 <issue_comment>username_2: Well, it's finally works now. I found an answer [here](https://stackoverflow.com/a/49266721/215535). All what was necessary to do, is to replace "Bearer" authentication scheme in the Startup class (`services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)`) with following: ``` services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) ``` Edit: It worked for a moment while I had a valid token. Probably authorization still works, but now I have another issue - authentication is broken, the login page goes into a loop. So complicated. **Edit 2.** Working solution found [here](https://stackoverflow.com/a/46778882/215535). It's necessary to add both ``` services.AddMvc(config => { var defaultPolicy = new AuthorizationPolicyBuilder(new[] { IdentityServerAuthenticationDefaults.AuthenticationScheme, IdentityConstants.ApplicationScheme }) .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(defaultPolicy)); }) ``` and default authentication scheme ``` services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) ``` Into Startup class Upvotes: 0
2018/03/16
674
2,414
<issue_start>username_0: $ Flutter doctor terminal command not working on ubuntu, giving error message "curl: (35) gnutls\_handshake() failed: Error in the pull function. "<issue_comment>username_1: This is not Flutter nor "flutter doctor" specific, it's to do with curl. Googling this error seems to bring up results that are either related to; * Virtualbox * Networking * Some combination of the above two Upvotes: 0 <issue_comment>username_2: Flutter depends on these command-line tools being available in your environment. ``` bash, mkdir, rm, git, curl, unzip, which ``` before working with flutter you need to install all of them . if you want to install curl then write just ``` apt-get install curl ``` and similarly install all of them . if they are available then upgrade them Here is the source <https://flutter.io/setup-linux/> for lunix Upvotes: 0 <issue_comment>username_3: I'm using Ubuntu 18.04 LTS. Assuming you have successfully downloaded and extracted [flutter\_linux\_v0.5.1-beta.tar.xz](https://storage.googleapis.com/flutter_infra/releases/beta/linux/flutter_linux_v0.5.1-beta.tar.xz) (latest update until now) onto your preferred directory. ``` export PATH=`pwd`/flutter/bin:$PATH ``` Running this command in your ubuntu terminal (Ctrl + Alt + T) adds flutter commands PATH variable to your system path for **temporary** session. As soon as you close the terminal, the system path is removed. **In order for ubuntu terminal to remember flutter commands permanently, you need to:** > > 1.) open up terminal and cd to $HOME. for eg: user@linux:~$ > > > 2.) open the hidden file `.bashrc` with your desired editor. It resides in $HOME. > > > 3.) add the following line > `export PATH=/home/yourname/flutter/bin:$PATH` > somewhere as a newline in `.bashrc` file preferably as a last line edit & save file. > > > 4.) run `source /home/yourname/.bashrc` in terminal to process your recent changes. > > > 5.) finally, run `echo $PATH` to see flutter dir is in your system path along with other such paths. for eg: `/home/yourname/flutter/bin` > > > Now close current terminal and reopen new terminal to check `flutter doctor`. It should process along with all other available flutter commands everytime now onwards. Thank you ! :) Upvotes: 3 <issue_comment>username_4: For **MAC** add below line in **.bash\_profile** file `export PATH=~/flutter/bin:$PATH;` Upvotes: 0
2018/03/16
804
2,909
<issue_start>username_0: I am trying to write a script, that will look for folders in the current directory, once found, it will check to see if the folder contains the following folders: 'Contracts' & 'Other Documents', if these are found the folder can be ignored. If not, I need to have the script make these folders. This is what I have so far: ``` import os import sys folders_to_be_made = ['Contracts', 'Other Documents'] for folder in os.listdir('.'): if os.path.isdir(folder): filepath = os.path.join(os.getcwd(), folder) print filepath ``` Can anyone please advise on how I would go about creating the folder if missing. Thank you.<issue_comment>username_1: This is not Flutter nor "flutter doctor" specific, it's to do with curl. Googling this error seems to bring up results that are either related to; * Virtualbox * Networking * Some combination of the above two Upvotes: 0 <issue_comment>username_2: Flutter depends on these command-line tools being available in your environment. ``` bash, mkdir, rm, git, curl, unzip, which ``` before working with flutter you need to install all of them . if you want to install curl then write just ``` apt-get install curl ``` and similarly install all of them . if they are available then upgrade them Here is the source <https://flutter.io/setup-linux/> for lunix Upvotes: 0 <issue_comment>username_3: I'm using Ubuntu 18.04 LTS. Assuming you have successfully downloaded and extracted [flutter\_linux\_v0.5.1-beta.tar.xz](https://storage.googleapis.com/flutter_infra/releases/beta/linux/flutter_linux_v0.5.1-beta.tar.xz) (latest update until now) onto your preferred directory. ``` export PATH=`pwd`/flutter/bin:$PATH ``` Running this command in your ubuntu terminal (Ctrl + Alt + T) adds flutter commands PATH variable to your system path for **temporary** session. As soon as you close the terminal, the system path is removed. **In order for ubuntu terminal to remember flutter commands permanently, you need to:** > > 1.) open up terminal and cd to $HOME. for eg: user@linux:~$ > > > 2.) open the hidden file `.bashrc` with your desired editor. It resides in $HOME. > > > 3.) add the following line > `export PATH=/home/yourname/flutter/bin:$PATH` > somewhere as a newline in `.bashrc` file preferably as a last line edit & save file. > > > 4.) run `source /home/yourname/.bashrc` in terminal to process your recent changes. > > > 5.) finally, run `echo $PATH` to see flutter dir is in your system path along with other such paths. for eg: `/home/yourname/flutter/bin` > > > Now close current terminal and reopen new terminal to check `flutter doctor`. It should process along with all other available flutter commands everytime now onwards. Thank you ! :) Upvotes: 3 <issue_comment>username_4: For **MAC** add below line in **.bash\_profile** file `export PATH=~/flutter/bin:$PATH;` Upvotes: 0
2018/03/16
1,571
5,397
<issue_start>username_0: How to call function or module using ScriptEngine. here is my sample code , which is compiling fine , but at runtime its throwing exception scalaVersion := "2.12.4" and sbt.version = 0.13.16, java is jdk1.8.0\_131 ``` import java.io.FileReader import javax.script._ object DemoApp extends App { val engine: ScriptEngine with Compilable with javax.script.Invocable = new ScriptEngineManager() .getEngineByName("scala") .asInstanceOf[ScriptEngine with javax.script.Invocable with Compilable] val reader = new FileReader("src/main/scala/Demo.sc") engine.compile(reader).eval() val result = engine.invokeFunction("fun") } ``` below is the Demo.sc ``` def fun: String = { "Rerutn from Fun" } ``` Below is the exception at runtime ``` Exception in thread "main" java.lang.ClassCastException: scala.tools.nsc.interpreter.Scripted cannot be cast to javax.script.Invocable at DemoApp$.delayedEndpoint$DemoApp$1(DemoApp.scala:13) at DemoApp$delayedInit$body.apply(DemoApp.scala:5) at scala.Function0.apply$mcV$sp(Function0.scala:34) at scala.Function0.apply$mcV$sp$(Function0.scala:34) at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12) at scala.App.$anonfun$main$1$adapted(App.scala:76) at scala.collection.immutable.List.foreach(List.scala:389) at scala.App.main(App.scala:76) at scala.App.main$(App.scala:74) at DemoApp$.main(DemoApp.scala:5) at DemoApp.main(DemoApp.scala) ```<issue_comment>username_1: I think the problem is that the *Scala* script engine implements `Compilable`, but not `Invocable`, which is why you're getting a cast exception. In any case, when you call `eval` on the result of the compilation, your code is executed, so you don't need to invoke anything via `Invocable`. Using `asInstanceOf` is a little frowned-upon, so the following is more idiomatic. Try this: ```scala import java.io.FileReader import javax.script._ object DemoApp extends App { // Get the Scala engine. val engine = new ScriptEngineManager().getEngineByName("scala") // See if the engine supports compilation. val compilerEngine = engine match { case c: Compilable => Some(c) case _ => None } // If the engine supports compilation, compile and run the program. val result = compilerEngine.map {ce => val reader = new FileReader("src/main/scala/Demo.sc") ce.compile(reader).eval() } println(result.fold("Script not compilable")(_.toString)) } ``` Alternatively, if you just want to get your original code working, you should so this: ```scala import java.io.FileReader import javax.script._ object DemoApp extends App { val engine = new ScriptEngineManager() .getEngineByName("scala") .asInstanceOf[ScriptEngine with Compilable] val reader = new FileReader("src/main/scala/Demo.sc") val result = engine.compile(reader).eval() // Output the result println(result.toString) } ``` Upvotes: 2 <issue_comment>username_2: workaround using actor in scripts - Main application Demo ``` class SampleActor extends Actor { implicit val log = Logging(context.system, this) def fun() = { val settings: Settings = new Settings settings.sourcepath.value = "src/main/scripts" settings.usejavacp.value = true settings.dependencyfile.value = "*.scala" val engine: Scripted = Scripted(new Scripted.Factory, settings) engine.getContext.setAttribute("context0",context,ScriptContext.ENGINE_SCOPE) val reader = new FileReader("src/main/scripts/ActorScript.scala") engine.eval("import akka.actor.ActorContext \n" +"val context1 = context0.asInstanceOf[ActorContext]") val compiledScript : CompiledScript = engine.compile(reader) val x = compiledScript.eval() x.asInstanceOf[ActorRef] ! "Arikuti" x.asInstanceOf[ActorRef] ! 1 } override def receive: Receive = { case x : String => log.info("Receveid from ScriptEngine: " + x) case i : Int => log.info("Receveid from ScriptEngine : " + i) } override def preStart(): Unit = { super.preStart() fun() } } object ActorDemo { def main(args: Array[String]): Unit = { val system = ActorSystem("clientAdapter") val x = system.actorOf(Props(classOf[SampleActor]),"Main") } } ``` And below 3 scrips are i placed in src/main/scripts ActorScript.scala ``` import akka.actor.{Actor, ActorRef, Props} import akka.event.Logging class ActorScript extends Actor { implicit val log = Logging(context.system, this) override def receive = { case y : Int => log.info("Recevied from Main Int : " + y.toString ) log.info(Convert.fun()) sender.tell(2,self) case x : String => log.info("Recevied from Main String " + x) log.info(Second.fun()) sender.tell("Arikuti",self) } } object ActorScript { def apply: ActorRef = { context1.actorOf(Props(new ActorScript),"ScriptActor") } } ActorScript.apply ``` Convert.scala ``` object Convert { def fun(): String = { "I am from Converter:: fun" } } ``` Second.scala ``` object Second { def fun(): String = { "I am from Second::fun" } } ``` In build.sbt ``` excludeFilter in unmanagedSourceDirectories := "src/main/scripts/*.scala" ``` now from Application i can send message to compiled script actor and recevied processed values form the Scripipts Upvotes: 1
2018/03/16
690
2,241
<issue_start>username_0: I'm trying to do a ngIf where the result is depending on a promise. The template ``` Renault Bmw Good choice! ``` So far, the function isDisplayed is ``` isDisplayed() { return this.carValue === 'bmw'; } ``` But I'd like it to be asynchronous. Something like ``` isDisplayed() { return this.getBestChoice().then((result) => result); } getBestChoice() { // fake http call return new Promise((resolve) => { setTimeout(() => resolve('bmw'), 3000); }); } ``` Obviously it won't work. I have ideas how to implement this but not sure it is clean. * Bind an event ngModelChange. Each time user pick a new car. It reloads a variable "isDisplayed" * Save the promise and use aync pipe in the template. But it won't reload the data. Here is a [punker](https://plnkr.co/edit/ti2oCfWbgYTQqAEEzHRa?p=preview).<issue_comment>username_1: Why not go with Observables, it's the Angular way. You can just set one as a public property and run it throught AsyncPipe which'll handle sub/unsub and change detection triggering for you. ``` import { Component } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { timer } from 'rxjs/observable/timer'; import { map, share, tap } from 'rxjs/operators'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { carValue = ''; showCongrats$: Observable; check() { // fake API call this.showCongrats$ = timer(1000).pipe( map(() => 'bmw'), // "API" says bmw rocks tap(console.log), map(bestCar => this.carValue === bestCar), share() // so multiple async pipes won't cause multiple API calls ); } } ``` Template: ``` Choose Renault Bmw Good Choice! Not the Best Choice! ``` Working stackblitz: <https://stackblitz.com/edit/angular-cxcq89?file=app%2Fapp.component.ts> Upvotes: 2 [selected_answer]<issue_comment>username_2: I solved it like this: class.ts ``` export class FieldHeaderSectionComponent implements OnInit { hasBody: Promise; constructor() { this.hasBody = this.haveBody(); } public haveBody() : Promise { // ... logic return Promise.resolve(false); } } ``` template.html ``` ... ``` Upvotes: 2
2018/03/16
6,027
16,978
<issue_start>username_0: The following script, reproduces an equivalent problem as it was stated in h2o Help (`Help -> View Example Flow` or `Help -> Browse Installed packs.. -> examples -> Airlines Delay.flow`, [download](https://www.sugarsync.com/pf/D309535_3_7294556508)), but using h2o R-package and a fixed seed (`123456`): ``` library(h2o) # To use avaliable cores h2o.init(max_mem_size = "12g", nthreads = -1) IS_LOCAL_FILE = switch(1, FALSE, TRUE) if (IS_LOCAL_FILE) { data.input <- read.csv(file = "allyears2k.csv", stringsAsFactors = F) allyears2k.hex <- as.h2o(data.input, destination_frame = "allyears2k.hex") } else { airlinesPath <- "https://s3.amazonaws.com/h2o-airlines-unpacked/allyears2k.csv" allyears2k.hex <- h2o.importFile(path = airlinesPath, destination_frame = "allyears2k.hex") } response <- "IsDepDelayed" predictors <- setdiff(names(allyears2k.hex), response) # Copied and pasted from the flow, then converting to R syntax predictors.exc = c("DayofMonth", "DepTime", "CRSDepTime", "ArrTime", "CRSArrTime", "TailNum", "ActualElapsedTime", "CRSElapsedTime", "AirTime", "ArrDelay", "DepDelay", "TaxiIn", "TaxiOut", "Cancelled", "CancellationCode", "Diverted", "CarrierDelay", "WeatherDelay", "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed") predictors <- setdiff(predictors, predictors.exc) # Convert to factor for classification allyears2k.hex[, response] <- as.factor(allyears2k.hex[, response]) # Copied and pasted from the flow, then converting to R syntax fit1 <- h2o.glm( x = predictors, model_id="glm_model", seed=123456, training_frame=allyears2k.hex, ignore_const_cols = T, y = response, family="binomial", solver="IRLSM", alpha=0.5,lambda=0.00001, lambda_search=F, standardize=T, non_negative=F, score_each_iteration=F, max_iterations=-1, link="family_default", intercept=T, objective_epsilon=0.00001, beta_epsilon=0.0001, gradient_epsilon=0.0001, prior=-1, max_active_predictors=-1 ) # Analysis confMatrix <- h2o.confusionMatrix(fit1) print("Confusion Matrix for training dataset") print(confMatrix) print(summary(fit1)) h2o.shutdown() ``` This is the Confusion Matrix for the training set: ``` Confusion Matrix (vertical: actual; across: predicted) for F1-optimal threshold: NO YES Error Rate NO 0 20887 1.000000 =20887/20887 YES 0 23091 0.000000 =0/23091 Totals 0 43978 0.474942 =20887/43978 ``` And the metrics: ``` H2OBinomialMetrics: glm ** Reported on training data. ** MSE: 0.2473858 RMSE: 0.4973789 LogLoss: 0.6878898 Mean Per-Class Error: 0.5 AUC: 0.5550138 Gini: 0.1100276 R^2: 0.007965165 Residual Deviance: 60504.04 AIC: 60516.04 ``` On contrary the result of h2o flow has a better performance: [![training Metrics for max f1 threshold](https://i.stack.imgur.com/cNOCK.jpg)](https://i.stack.imgur.com/cNOCK.jpg) and Confusion Matrix for max f1 threshold: [![Confusion Matrix](https://i.stack.imgur.com/s5IM5.jpg)](https://i.stack.imgur.com/s5IM5.jpg) *The h2o flow performance is much better than running the same algorithm using the equivalent R-package function*. **Note**: For sake of simplicity I am using Airlines Delay problem, that is a well-known problem using h2o, but I realized that such kind of significant difference are found in other similar situations using `glm` algorithm. Any thought about why these significant differences occur **Appendix A: Using default model parameters** Following the suggestion from @DarrenCook answer, just using default building parameters except for excluding columns and seed: *h2o flow* Now the `buildModel` is invoked like this: ``` buildModel 'glm', {"model_id":"glm_model-default", "seed":"123456","training_frame":"allyears2k.hex", "ignored_columns": ["DayofMonth","DepTime","CRSDepTime","ArrTime","CRSArrTime","TailNum", "ActualElapsedTime","CRSElapsedTime","AirTime","ArrDelay","DepDelay", "TaxiIn","TaxiOut","Cancelled","CancellationCode","Diverted", "CarrierDelay","WeatherDelay","NASDelay","SecurityDelay", "LateAircraftDelay","IsArrDelayed"], "response_column":"IsDepDelayed","family":"binomial" ``` } and the results are: [![/ROC curve and parameters for max f1 criterion](https://i.stack.imgur.com/o3S36.jpg)](https://i.stack.imgur.com/o3S36.jpg) and the training metrics: [![enter image description here](https://i.stack.imgur.com/dicLD.jpg)](https://i.stack.imgur.com/dicLD.jpg) *Running R-Script* The following script allows for an easy switch into default configuration (via `IS_DEFAULT_MODEL` variable) and also keeping the configuration as it states in the Airlines Delay example: ``` library(h2o) h2o.init(max_mem_size = "12g", nthreads = -1) # To use avaliable cores IS_LOCAL_FILE = switch(2, FALSE, TRUE) IS_DEFAULT_MODEL = switch(2, FALSE, TRUE) if (IS_LOCAL_FILE) { data.input <- read.csv(file = "allyears2k.csv", stringsAsFactors = F) allyears2k.hex <- as.h2o(data.input, destination_frame = "allyears2k.hex") } else { airlinesPath <- "https://s3.amazonaws.com/h2o-airlines-unpacked/allyears2k.csv" allyears2k.hex <- h2o.importFile(path = airlinesPath, destination_frame = "allyears2k.hex") } response <- "IsDepDelayed" predictors <- setdiff(names(allyears2k.hex), response) # Copied and pasted from the flow, then converting to R syntax predictors.exc = c("DayofMonth", "DepTime", "CRSDepTime", "ArrTime", "CRSArrTime", "TailNum", "ActualElapsedTime", "CRSElapsedTime", "AirTime", "ArrDelay", "DepDelay", "TaxiIn", "TaxiOut", "Cancelled", "CancellationCode", "Diverted", "CarrierDelay", "WeatherDelay", "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed") predictors <- setdiff(predictors, predictors.exc) # Convert to factor for classification allyears2k.hex[, response] <- as.factor(allyears2k.hex[, response]) if (IS_DEFAULT_MODEL) { fit1 <- h2o.glm( x = predictors, model_id = "glm_model", seed = 123456, training_frame = allyears2k.hex, y = response, family = "binomial" ) } else { # Copied and pasted from the flow, then converting to R syntax fit1 <- h2o.glm( x = predictors, model_id = "glm_model", seed = 123456, training_frame = allyears2k.hex, ignore_const_cols = T, y = response, family = "binomial", solver = "IRLSM", alpha = 0.5, lambda = 0.00001, lambda_search = F, standardize = T, non_negative = F, score_each_iteration = F, max_iterations = -1, link = "family_default", intercept = T, objective_epsilon = 0.00001, beta_epsilon = 0.0001, gradient_epsilon = 0.0001, prior = -1, max_active_predictors = -1 ) } # Analysis confMatrix <- h2o.confusionMatrix(fit1) print("Confusion Matrix for training dataset") print(confMatrix) print(summary(fit1)) h2o.shutdown() ``` It produces the following results: ``` MSE: 0.2473859 RMSE: 0.497379 LogLoss: 0.6878898 Mean Per-Class Error: 0.5 AUC: 0.5549898 Gini: 0.1099796 R^2: 0.007964984 Residual Deviance: 60504.04 AIC: 60516.04 Confusion Matrix (vertical: actual; across: predicted) for F1-optimal threshold: NO YES Error Rate NO 0 20887 1.000000 =20887/20887 YES 0 23091 0.000000 =0/23091 Totals 0 43978 0.474942 =20887/43978 ``` Some metrics are close, but the Confusion Matrix is quite diferent, the R-Script predict all flights as delayed. **Appendix B: Configuration** ``` Package: h2o Version: 3.18.0.4 Type: Package Title: R Interface for H2O Date: 2018-03-08 ``` Note: I tested the R-Script also under 3.19.0.4231 with the same results This is the cluster information after running the R: ``` > h2o.init(max_mem_size = "12g", nthreads = -1) R is connected to the H2O cluster: H2O cluster version: 3.18.0.4 ... H2O API Extensions: Algos, AutoML, Core V3, Core V4 R Version: R version 3.3.3 (2017-03-06) ```<issue_comment>username_1: Troubleshooting Tip: build the all-defaults model first: ``` mDef = h2o.glm(predictors, response, allyears2k.hex, family="binomial") ``` This takes 2 seconds and gives almotst exactly the same AUC and confusion matrix as in your Flow screenshots. So, we now know the problem you see is due to all the model customization you have done... ...except when I build your `fit1` I get basically the same results as my default model: ``` NO YES Error Rate NO 4276 16611 0.795279 =16611/20887 YES 1573 21518 0.068122 =1573/23091 Totals 5849 38129 0.413479 =18184/43978 ``` This was using your script exactly as given, so it fetched the remote csv file. (Oh, I removed the max\_mem\_size argument, as I don't have 12g on this notebook!) Assuming you can get exactly your posted results, running exactly the code you posted (and in a fresh R session, with a newly started H2O cluster), one possible explanation is you are using 3.19.x, but the latest stable release is 3.18.0.2? (My test was with 3.14.0.1) Upvotes: 2 <issue_comment>username_2: Finally, I guess this is the explanation: both have the same parameter configuration for building the model (that is not the problem), but the H2o flow uses a specific parsing customization converting some variables values into `Enum`, that the R-script did not specify. The Airlines Delay problem how it was specified in the h2o Flow example uses as predictor variables (the flow defines the ignored\_columns): ``` "Year", "Month", "DayOfWeek", "UniqueCarrier", "FlightNum", "Origin", "Dest", "Distance" ``` Where all of the predictors should be parsed as: `Enum` except `Distance`. Therefore the R-Script needs to convert such columns from `numeric` or `char` into `factor`. *Executing using h2o R-package* Here the R-Script updated: ``` library(h2o) h2o.init(max_mem_size = "12g", nthreads = -1) # To use avaliable cores IS_LOCAL_FILE = switch(2, FALSE, TRUE) IS_DEFAULT_MODEL = switch(2, FALSE, TRUE) if (IS_LOCAL_FILE) { data.input <- read.csv(file = "allyears2k.csv", stringsAsFactors = T) allyears2k.hex <- as.h2o(data.input, destination_frame = "allyears2k.hex") } else { airlinesPath <- "https://s3.amazonaws.com/h2o-airlines-unpacked/allyears2k.csv" allyears2k.hex <- h2o.importFile(path = airlinesPath, destination_frame = "allyears2k.hex") } response <- "IsDepDelayed" predictors <- setdiff(names(allyears2k.hex), response) # Copied and pasted from the flow, then converting to R syntax predictors.exc = c("DayofMonth", "DepTime", "CRSDepTime", "ArrTime", "CRSArrTime", "TailNum", "ActualElapsedTime", "CRSElapsedTime", "AirTime", "ArrDelay", "DepDelay", "TaxiIn", "TaxiOut", "Cancelled", "CancellationCode", "Diverted", "CarrierDelay", "WeatherDelay", "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed") predictors <- setdiff(predictors, predictors.exc) column.asFactor <- c("Year", "Month", "DayofMonth", "DayOfWeek", "UniqueCarrier", "FlightNum", "Origin", "Dest", response) # Coercing as factor (equivalent to Enum from h2o Flow) # Note: Using lapply does not work, see the answer of this question # https://stackoverflow.com/questions/49393343/how-to-coerce-multiple-columns-to-factors-at-once-for-h2oframe-object for (col in column.asFactor) { allyears2k.hex[col] <- as.factor(allyears2k.hex[col]) } if (IS_DEFAULT_MODEL) { fit1 <- h2o.glm(x = predictors, y = response, training_frame = allyears2k.hex, family = "binomial", seed = 123456 ) } else { # Copied and pasted from the flow, then converting to R syntax fit1 <- h2o.glm( x = predictors, model_id = "glm_model", seed = 123456, training_frame = allyears2k.hex, ignore_const_cols = T, y = response, family = "binomial", solver = "IRLSM", alpha = 0.5, lambda = 0.00001, lambda_search = F, standardize = T, non_negative = F, score_each_iteration = F, max_iterations = -1, link = "family_default", intercept = T, objective_epsilon = 0.00001, beta_epsilon = 0.0001, gradient_epsilon = 0.0001, prior = -1, max_active_predictors = -1 ) } # Analysis print("Confusion Matrix for training dataset") confMatrix <- h2o.confusionMatrix(fit1) print(confMatrix) print(summary(fit1)) h2o.shutdown() ``` Here the result running the R-Script under default configuraiton `IS_DEFAULT_MODEL=T`: ``` H2OBinomialMetrics: glm ** Reported on training data. ** MSE: 0.2001145 RMSE: 0.4473416 LogLoss: 0.5845852 Mean Per-Class Error: 0.3343562 AUC: 0.7570867 Gini: 0.5141734 R^2: 0.1975266 Residual Deviance: 51417.77 AIC: 52951.77 Confusion Matrix (vertical: actual; across: predicted) for F1-optimal threshold: NO YES Error Rate NO 10337 10550 0.505099 =10550/20887 YES 3778 19313 0.163614 =3778/23091 Totals 14115 29863 0.325799 =14328/43978 ``` *Executing under h2o flow* Now executing the flow: [Airlines\_Delay\_GLMFixedSeed](https://www.sugarsync.com/pf/D309535_3_7293406786), we can obtain the same results. Here the detail about the flow configuration: The `parseFiles` function: ``` parseFiles paths: ["https://s3.amazonaws.com/h2o-airlines-unpacked/allyears2k.csv"] destination_frame: "allyears2k.hex" parse_type: "CSV" separator: 44 number_columns: 31 single_quotes: false column_names: ["Year","Month","DayofMonth","DayOfWeek","DepTime","CRSDepTime","ArrTime", "CRSArrTime","UniqueCarrier","FlightNum","TailNum","ActualElapsedTime", "CRSElapsedTime","AirTime","ArrDelay","DepDelay","Origin","Dest", "Distance","TaxiIn","TaxiOut","Cancelled","CancellationCode", "Diverted","CarrierDelay","WeatherDelay","NASDelay","SecurityDelay", "LateAircraftDelay","IsArrDelayed", "IsDepDelayed"] column_types ["Enum","Enum","Enum","Enum","Numeric","Numeric", "Numeric","Numeric", "Enum","Enum","Enum","Numeric", "Numeric", "Numeric","Numeric","Numeric", "Enum","Enum","Numeric","Numeric","Numeric", "Enum","Enum","Numeric","Numeric","Numeric", "Numeric","Numeric","Numeric","Enum","Enum"] delete_on_done: true check_header: 1 chunk_size: 4194304 ``` where the following predictor columns are converted to `Enum`: `"Year", "Month", "DayOfWeek", "UniqueCarrier", "FlightNum", "Origin", "Dest"` Now invoking the `buildModel` function as follows, using the default parameters except for `ignored_columns` and `seed`: ``` buildModel 'glm', {"model_id":"glm_model-default","seed":"123456", "training_frame":"allyears2k.hex", "ignored_columns":["DayofMonth","DepTime","CRSDepTime","ArrTime", "CRSArrTime","TailNum", "ActualElapsedTime","CRSElapsedTime","AirTime","ArrDelay","DepDelay", "TaxiIn","TaxiOut","Cancelled","CancellationCode","Diverted", "CarrierDelay","WeatherDelay","NASDelay","SecurityDelay", "LateAircraftDelay","IsArrDelayed"],"response_column":"IsDepDelayed", "family":"binomial"} ``` and finally we get the following result: [![Confusion matrix for max f1 treshold](https://i.stack.imgur.com/UWpiU.jpg)](https://i.stack.imgur.com/UWpiU.jpg) and Training Output Metrics: ``` model glm_model-default model_checksum -2438376548367921152 frame allyears2k.hex frame_checksum -2331137066674151424 description · model_category Binomial scoring_time 1521598137667 predictions · MSE 0.200114 RMSE 0.447342 nobs 43978 custom_metric_name · custom_metric_value 0 r2 0.197527 logloss 0.584585 AUC 0.757084 Gini 0.514168 mean_per_class_error 0.334347 residual_deviance 51417.772427 null_deviance 60855.951538 AIC 52951.772427 null_degrees_of_freedom 43977 residual_degrees_of_freedom 43211 ``` *Comparing both results* The training metrics are almost the same for first 4-significant digits: ``` R-Script H2o Flow MSE: 0.2001145 0.200114 RMSE: 0.4473416 0.447342 LogLoss: 0.5845852 0.584585 Mean Per-Class Error: 0.3343562 0.334347 AUC: 0.7570867 0.757084 Gini: 0.5141734 0.514168 R^2: 0.1975266 0.197527 Residual Deviance: 51417.77 51417.772427 AIC: 52951.77 52951.772427 ``` Confusion Matrix is slightly different: ``` TP TN FP FN R-Script 10337 19313 10550 3778 H2o Flow 10341 19309 10546 3782 Error R-Script 0.325799 H2o Flow 0.3258 ``` My understanding is that the difference are withing the acceptable threshold (around `0.0001`), therefore we can say that both interfaces provide the same result. Upvotes: 1 [selected_answer]
2018/03/16
696
2,226
<issue_start>username_0: I need to match the multiple same column value of MySQL table using PHP and MySQL. I am explaining my table below. **db\_user:** ``` id status book_id 1 0 22 2 0 22 3 1 22 4 0 23 ``` Here I need the `select query` and condition is if `status=0` for same `book_id` means if table has lets say `book_id=22 and all status=0` then only it will return value true otherwise false. I am writing one example below. ``` $sql=mysqli_query($connect,"select * from db_user where status=0 and...."); if(mysqli_num_rows($sql) > 0){ $row=mysqli_fetch_array($sql); $data=$row['book_id']; }else{ return 0; } ``` Here as per the example table only last row will fetch because for `book_id=22` there is `status=1` present. The data will only fetch when for one `book_id` all status=0.<issue_comment>username_1: You could use a not in for the id with status 1 ``` select * from my_table where book_id not in ( select book_id from my_table where status = 1 ) ``` Upvotes: 0 <issue_comment>username_2: One option uses aggregation to check the status values: ``` SELECT book_id FROM db_user GROUP BY book_id HAVING SUM(CASE WHEN status <> 0 THEN 1 ELSE 0 END) = 0; ``` We can also use `EXISTS`: ``` SELECT DISTINCT t1.book_id FROM db_user t1 WHERE NOT EXISTS (SELECT 1 FROM db_user t2 WHERE t1.book_id = t2.book_id AND t2.status <> 0); ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: Back in the day, we would have solved it this way. I say, if it ain't broke, don't fix it... ``` SELECT DISTINCT x.* FROM my_table x LEFT JOIN my_table y ON y.book_id = x.book_id AND y.status = 1 WHERE y.id IS NULL; ``` Upvotes: 0 <issue_comment>username_4: its very simple: `SELECT book_id,MAX(status) max_status FROM db_user GROUP BY book_id` is `max_status` is 0 then all is 0 no larger than that. Upvotes: -1 <issue_comment>username_5: You can use below query. ``` select * from db_user where status=0 and book_id not in (select book_id from db_user where status = 1 ); ``` I have tested it and it works. Upvotes: -1
2018/03/16
128
466
<issue_start>username_0: I have given editable bottom so i am getting default delete icon of odoo11. But i want to change it only to my module. How to change the delete icon to my own module ? ``` Attachments attachments ``` Thanks in Advance !<issue_comment>username_1: just add `delete="false"` in tree view ``` Attachments attachments ``` Upvotes: 1 <issue_comment>username_2: You can add **delete="false"** in tree tag ex. ``` ``` Upvotes: 0
2018/03/16
184
764
<issue_start>username_0: I have a Main VC which has a connection to Tab Bar Controller via segue and that Tab Bar controller has 2 sections and those are 2 ViewControllers. I need to pass data from Main VC to that specific VC which derived from Tab Bar Controller using segue. Since i am able to use only one segue (to show only TBController), is there any way to achieve to pass data directly from main to another by skipping Tab Bar controller? Ps. Those 2 VC have a navigation controller connection between Tab Bar Controller and themselves as well.<issue_comment>username_1: just add `delete="false"` in tree view ``` Attachments attachments ``` Upvotes: 1 <issue_comment>username_2: You can add **delete="false"** in tree tag ex. ``` ``` Upvotes: 0
2018/03/16
630
2,502
<issue_start>username_0: the console.log(workingWeekdaysVar) line; is outside the findOne's scope, and the variable was declared outside it too, yet it's giving me null ... when i put console.log(workingWeekdaysVar); inside the findOne's scope, it does give the right output, but this is useless for me because I wanna use workingWeekdaysVar elsewhere below. The two commented out lines are the 2nd approach i attempted to do, but it gave me an undesirable output because this whole code is inside a complicated for loop. How can I simply pass the fetched value of workingWeekdaysVar out of the scope? ``` var workingWeekdaysVar = []; buyerSupplierFisModel.findOne(filter).then(function (combo) { workingWeekdaysVar = combo.workingWeekdays; //server.getWorkingWeekdays = function () { return combo.workingWeekdays }; }); console.log(workingWeekdaysVar); //console.log(server.getWorkingWeekdays()); ```<issue_comment>username_1: `findOne()` is an asynchronous function (it returns a promise object). This means that it returns inmediately and your next code line is run (in this case, `console.log(workingWeekdaysVar);`. But, since the function isn't done yet, `workingWeekdaysVar` is empty, and it will be empty until `findOne()` has done its job and returned the results in the provided chained callback `.then(function (combo) {...`. So if you want to do anything with the results, you'll have to do it in the callback. One option to this would be to use `async / await`: ``` (async () => { try { const { workingWeekdaysVar } = await buyerSupplierFisModel.findOne(filter) console.log(workingWeekdaysVar) } catch (e) { console.log(`Error: ${e}`); } })() ``` Upvotes: 1 <issue_comment>username_2: Re-arranging your code a bit: ``` let doToResponse = (combo)=>{ workingWeekdaysVar = combo.workingWeekdays; console.log(workingWeekdaysVar); } buyerSupplierFisModel.findOne(filter).then(function (combo) { doToResponse(combo) }); ``` * good for re-usability My personal favorite: ``` buyerSupplierFisModel.findOne(filter).then(combo=> { workingWeekdaysVar = combo.workingWeekdays; console.log(workingWeekdaysVar); }); ``` The important thing is keep in mind, as username_1 says.. findOne - returns a promise. At that point you have another thread with different local (Lexical?) scope Upvotes: 0
2018/03/16
1,009
4,255
<issue_start>username_0: I was trying to use `Spring Data JPA` on `Spring Boot` and I kept getting error, I can't figure out what the problem is: > > Unable to locate Attribute with the the given name [firstName] on > this ManagedType [com.example.h2demo.domain.Subscriber] > > > FirstName is declared in my entity class. I have used a service class with DAO before with different project and worked perfectly. My Entity class (getters and setters are also in the class) : ``` @Entity public class Subscriber { @Id @GeneratedValue private long id; private String FirstName,LastName,Email; public Subscriber(long id, String firstName, String lastName, String email) { this.id = id; this.FirstName = firstName; this.LastName = lastName; this.Email = email; } } ... ``` My Repository Class ``` @Component public interface SubscriberRepository extends JpaRepository { Subscriber findByFirstName(String FirstName); Subscriber deleteAllByFirstName(String FirstName); } ``` My Service Class ``` @Service public class SubscriberService { @Autowired private SubscriberRepository subscriberRepository; public Subscriber findByFirstName(String name){ return subscriberRepository.findByFirstName(name); } public Subscriber deleteAllByFirstName(String name){ return subscriberRepository.deleteAllByFirstName(name); } public void addSubscriber(Subscriber student) { subscriberRepository.save(student); } } ``` And My Controller class: ``` @RestController @RequestMapping("/subscribers") public class SubscriberController { @Autowired private SubscriberService subscriberService; @GetMapping(value = "/{name}") public Subscriber findByFirstName(@PathVariable("name") String fname){ return subscriberService.findByFirstName(fname); } @PostMapping( value = "/add") public String insertStudent(@RequestBody final Subscriber subscriber){ subscriberService.addSubscriber(subscriber); return "Done"; } } ```<issue_comment>username_1: Try changing `private String FirstName,LastName,Email;` to `private String firstName,lastName,email;` It should work. `findByFirstName` in `SubscriberRepository` tries to find a field `firstName` by convention which is not there. Further reference on how properties inside the entities are traversed <https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions> Upvotes: 7 [selected_answer]<issue_comment>username_2: As per [the specification](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions), the property names should start with lower case. > > [...]The resolution algorithm starts with interpreting the entire part (`AddressZipCode`) as the property and checks the domain class for a property with that name (uncapitalized)[...]. > > > It will try to find a property with uncapitalized name. So use `firstName` instead of `FirstName` and etc.. Upvotes: 3 <issue_comment>username_3: After I change my `entity class` variables from capital letter to small letter for instance `Username` to `username` the method `Users findByUsername(String username);` is working for me now . Upvotes: 3 <issue_comment>username_4: The same problem was when i had deal with Spring Data Specifications (<https://www.baeldung.com/rest-api-search-language-spring-data-specifications>) Initial piece of code was: ``` private Specification checkCriteriaByProjectNumberLike(projectNumber: String) { (root, query, criteriaBuilder) -> criteriaBuilder.like(root.get("project\_number"), "%" + projectNumber) } ``` The problem was in root.get("project\_number"). Inside the method, I had to put the field name as in the model (projectNumber), but I sent the field name as in the database (project\_number). That is, the final correct decision was: ``` private Specification checkCriteriaByProjectNumberLike(projectNumber: String) { (root, query, criteriaBuilder) -> criteriaBuilder.like(root.get("projectNumber"), "%" + projectNumber) } ``` Upvotes: 4
2018/03/16
640
1,829
<issue_start>username_0: Why does the following code give me a segmentation fault: ``` #include #include #include using namespace std; double f(double a, double b, double\* c) { \*c = a + b; } int main() { vector a ={1,2,3,4,5,6,7,8}; vector b ={2,1,3,4,5,2,8,2}; int size = a.size(); vector c(size); vector threads(size); for (int i = 0; i < size; ++i) { thread\* t = new thread(f, a[i], b[i], &c[i]); threads.push\_back(t); } for (vector::iterator it = threads.begin(); it != threads.end(); it++) { (\*it)->join(); } cout << "Vector c is: "; for (int i =0; i < size; ++i) { cout << c[i] << " "; } } ``` I know that the segmentation fault happens inside the for loop where the iterator is used, but I'm not sure why.<issue_comment>username_1: ``` vector threads(size); ``` Declaration creates a vector with `size` amount of default-initialized `thread*` objects which are `nullptr`. Then with `push_back` you insert additional non-null objects but the null ones remain there, and you dereference them when iterating over vector at the end. Upvotes: 5 [selected_answer]<issue_comment>username_2: You should change the `for` loop to read as below: ```cpp for (int i = 0; i < size; ++i) { thread *t = new thread(f, a[i], b[i], &c[i]); threads[i] = t; } ``` And before ending, you should `delete` your heap-allocated `thread`s. ```cpp for (auto thread : threads) delete thread; ``` Even better is to simply use: ```cpp vector threads(size); for (int i = 0; i < size; ++i) threads[i] = thread(f, a[i], b[i], &c[i]); for (auto& thread : threads) thread.join(); ``` By the way, you should pay attention to the compiler warnings. Change ``` double f(double a, double b, double *c) { *c = a + b; } ``` to ``` void f(double a, double b, double *c) { *c = a + b; } ``` Upvotes: 3
2018/03/16
660
2,231
<issue_start>username_0: I've been looking for a while, but I haven't found anything in Ruby like `python`'s `-i` flag. Common behaviour for me if I'm testing something is to run the unfinished `python` script with a `-i` flag so that I can see and play around with the values in each variable. If I try `irb` , it still terminates at `EOF`, and, obviously `ruby` doesn't work either. Is there a command-line flag that I'm missing, or some other way this functionality can be achieved? **Edit:** Added an explanation of what kind of functionality I'm talking about. ### Current Behaviour in Python *file.py* ``` a = 1 ``` *Command Prompt* ``` $ python -i file.py >>> a 1 ``` As you can see, the value of the variable `a` is available in the console too.<issue_comment>username_1: You can use the command irb. When that has started you can load and execute any ruby file with `load './filename.rb'` Upvotes: 0 <issue_comment>username_2: > > Is there a command-line flag that I'm missing, or some other way this functionality can be achieved? > > > Yes, there are both. I'll cover an "other way". Starting with ruby 2.5, you can put a `binding.irb` in some place of your code and then the program will go into an interactive console at that point. ``` % cat stop.rb puts 'hello' binding.irb ``` Then ``` % ruby stop.rb hello From: stop.rb @ line 3 : 1: puts 'hello' 2: => 3: binding.irb irb(main):001:0> ``` It was possible for a long time before, with `pry`. But now it's in the standard package. Upvotes: 3 [selected_answer]<issue_comment>username_3: You can use `irb -r ./filename.rb` (`-r` for "require"), which should basically do the same as `python -i ./filename.py`. **Edit** to better answer the refined question: Actually, `irb -r ./filename.rb` does the equivalent of running `irb` and subsequently running `irb(main):001:0> require './filename.rb'`. Thus, local variables from `filename.rb` do not end up in scope for inspection. `python -i ./filename.py` seems to do the equivalent of adding `binding.irb` to the last line of the file and then running it with `ruby ./filename.rb`. There seems to be no one-liner equivalent to achieve this exact behaviour for ruby. Upvotes: 3
2018/03/16
537
1,779
<issue_start>username_0: I need to replace first and last character in random string. Why this code doesn't work? ``` function symbExchange(line) { var tmp = line[0]; var str = line.replace(line[0], line[line.length-1]); var str2 = str.replace(str[str.length-1], tmp); return str2; } ```<issue_comment>username_1: You can use the command irb. When that has started you can load and execute any ruby file with `load './filename.rb'` Upvotes: 0 <issue_comment>username_2: > > Is there a command-line flag that I'm missing, or some other way this functionality can be achieved? > > > Yes, there are both. I'll cover an "other way". Starting with ruby 2.5, you can put a `binding.irb` in some place of your code and then the program will go into an interactive console at that point. ``` % cat stop.rb puts 'hello' binding.irb ``` Then ``` % ruby stop.rb hello From: stop.rb @ line 3 : 1: puts 'hello' 2: => 3: binding.irb irb(main):001:0> ``` It was possible for a long time before, with `pry`. But now it's in the standard package. Upvotes: 3 [selected_answer]<issue_comment>username_3: You can use `irb -r ./filename.rb` (`-r` for "require"), which should basically do the same as `python -i ./filename.py`. **Edit** to better answer the refined question: Actually, `irb -r ./filename.rb` does the equivalent of running `irb` and subsequently running `irb(main):001:0> require './filename.rb'`. Thus, local variables from `filename.rb` do not end up in scope for inspection. `python -i ./filename.py` seems to do the equivalent of adding `binding.irb` to the last line of the file and then running it with `ruby ./filename.rb`. There seems to be no one-liner equivalent to achieve this exact behaviour for ruby. Upvotes: 3
2018/03/16
841
2,905
<issue_start>username_0: I have been implementing a like and dislike system. The code is below: ``` ![](/img/like.png) ``` As you can see above, when the user clicks on above like block, I have created a function call which registers a `like` in the system through ajax call. Here, the `$id` is the post\_id which I am passing to the function. The code is below: ``` function like(id) { var pid = id; $.ajax({ url: '/like.php?id=' + pid, type: "get", }).done(function(data) { $('#like' + pid).html(data); }); } ``` But, the problem here is, a single user can click on `like` as many times as he wants and the system still registers the likes. I want to implement a system in which users can only register a single like or dislike for a single post or single `$id`.<issue_comment>username_1: Inside like.php you would need to check the user id against the post id to avoid duplicate likes. If it's guests (users not logged in) then maybe record some identifier e.g. ip? Upvotes: 0 <issue_comment>username_2: you can try to remove the onclick attribute immediatelly, like following: ``` onclick="like('.$id.'); $(this).attr(\'onclick\',\'\');" ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: I would suggest to handle this from client side as to add data attribute to manage the state of like or dislike button: ``` like($id) { var state = $(this).data('isactive'); if(!state) { // your ajax function $(this).data('isactive', true); } } dislike($id) { var state = $(this).data('isactive'); if(!state) { // your ajax function $(this).data('isactive', true); } } ``` and also manage if user click on like button then set the data-isactive attribute to false and vice versa. You can maintain the button state in local-storage of browser. Hope this may help you. Upvotes: 0 <issue_comment>username_4: When you first render the page you have to show this HTML if the user has never clicked the like or dislike button ``` ![](/img/like.png) ![](/img/dislike.png) ``` if the user already clicked the like button you have to show this HTML ``` ![](/img/dislike.png) ``` otherwise you show this HTML ``` ![](/img/like.png) ``` then on the like function you have to dinamically change the preference button ``` var LIKE_BUTTON = "" + " ![](/img/like.png)" + ""; var DISLIKE_BUTTON = "" + " ![](/img/dislike.png)" + ""; function like(id, like) { var pid = id; $.ajax({ url: '/like.php?id=' + pid + '&like=' + (like ? "true" : "false"), type: "get", }).done(function(data) { $('#like' + pid).html(data); $("#preference-container").empty().append($(like ? DISLIKE_BUTTON : LIKE_BUTTON)); }); } ``` Upvotes: 1 <issue_comment>username_5: Removing attribute `onclick` immediately after the function call: ``` ![](/img/like.png) ``` Upvotes: 0
2018/03/16
2,134
5,379
<issue_start>username_0: Suppose I have a frequency chart of the ten most popular names of babies born in the US in 2006: ``` myfreq <- c(24835, 22630, 22313, 21398, 20504, 20326, 20054, 19711, 19672, 19400) names(myfreq) <- c("Jacob", "Michael", "Joshua", "Emily", "Ethan", "Matthew", "Daniel", "Andrew", "Christopher", "Anthony") > myfreq Jacob Michael Joshua Emily Ethan Matthew Daniel 24835 22630 22313 21398 20504 20326 20054 <NAME> Anthony 19711 19672 19400 ``` Now consider the set of 210,843 babies with those names, born in the US in 2006. This set has 2^210843 subsets. I want the babyname-frequency chart for a **random subset** of the babies, with each subset being equally likely. My code is as follows: ``` subfreq <- sapply(myfreq, function(k) sum(rbinom(k, 1, 0.5))) ``` Is that doing what I want it to do? And is there some way to improve performance? It's going to be in a loop with millions of iterations, and the rbinom function seems very slow; I wonder if there is a faster function in R for this special case of the binomial distribution where p=1/2. Thanks for any assistance.<issue_comment>username_1: Unsure if you mean you want to simulate draws with bootstraps, but if that's what you're going for, I'd try the following approach with data.table. For a single draw: ``` library(data.table) # Example data: dat.namefreqs <- data.table(name=LETTERS, count=sample(1e4, size=26)) # Format: name count A 7466 B 10000 C 8897 D 6833 E 8614 F 8128 G 1837 H 9349 I 7798 J 1158 K 1707 L 3368 M 1019 N 795 O 1840 P 4476 Q 5345 R 247 S 5430 T 9879 U 1328 V 4530 W 6865 X 6693 Y 2186 Z 1754 # Total all individuals N.tot <- sum(dat.namefreqs$count) # Repeat each name * its frequency dat.expanded <- dat.namefreqs[rep(1:.N, count)] # For a single random draw, # Create a vector of binomial draws of 1s and 0s from rbinom, size = N.tot # Use that as a true/false vector to extract names, and aggregate counts by name dat.expanded[which(rbinom(N.tot, 1, 0.5)==1)][, .N, by=name] ``` Example output for a single draw: ``` name N 1: A 1339 2: B 1851 3: C 2898 4: D 4548 5: E 1066 6: F 4421 7: G 4754 8: H 3337 9: I 3144 10: J 286 11: K 1065 12: L 880 13: M 3435 14: N 1942 15: O 3851 16: P 2471 17: Q 3549 18: R 4933 19: S 1911 20: T 3799 21: U 4632 22: V 1092 23: W 3229 24: X 631 25: Y 1321 26: Z 1883 ``` And for repeating through bootstrapping with foreach: My machine runs ~1000 bootstraps in 17 seconds on a single core with the above table(136654 rows, a little over half the size yours would be) ``` library(foreach) dat.namefreqs <- data.table(name=LETTERS, count=sample(1e4, size=26)) N.tot <- sum(dat.namefreqs$count) dat.expanded <- dat.namefreqs[rep(1:.N, count)] results <- foreach(n=1:1000, .combine="rbind") %do% { dat <- dat.expanded[which(rbinom(N.tot, 1, 0.5)==1)][, .N, by=name] dat[, bootstrap := n] return(dat[]) } > results name N bootstrap 1: A 1339 1 2: B 1851 1 3: C 2898 1 4: D 4548 1 5: E 1066 1 --- 25996: V 1055 1000 25997: W 3234 1000 25998: X 636 1000 25999: Y 1315 1000 26000: Z 1895 1000 ``` Upvotes: 0 <issue_comment>username_2: Can't be done exactly. You can't construct all the possible subsets, so forget that approach. Could be done approximately if you know some math. First you need the probability of the sample size being `n`, which is (in `R`) naively: ``` choose(N, n)/2^N ``` That will break down for moderate `N` and `n` (for example `N=1050` and `n=525`). So you can try logarithms and after some work you get (where `lgamma` is the log of the gamma function and the gamma function at n+1 is the same as n!) the probability given by: ``` exp(lgamma(N+1) - lgamma(n+1) - lgamma(N-n+1) - N*log(2)) ``` To get all the probabilities into one vector we can wrap this into a function: ``` pmf <- function(N,n) { exp(lgamma(N+1) - lgamma(n+1) - lgamma(N-n+1) - N*log(2)) } N <- sum(myfreq) probs <- sapply(0:N, function(n) pmf(N,n)) ``` Note that most sample sizes have 0 probability (approximately). Now to select your sample you would first pick a sample size according to the probabilities in `probs` and then pick a sample of that size from the population of names. We need to make that population first from the frequencies you gave. ``` mypop <- rep(mynames, myfreq) ``` The sample itself: ``` sample(mypop, sample(0:N, 1, prob = probs)) ``` To replicate a bunch of times: ``` k <- 100 samps <- replicate(k, sample(mypop, sample(0:N, 1, prob = probs))) ``` `samps` is a list of samples of randomly selected sizes. Note that the only sample sizes with non-zero probabilities to be selected are: ``` range(which(probs > 0)) #> 96603 114242 ``` so the properties of your samples aren't going to be as interesting as you might have thought. They will be very close to the population distribution of baby names. Definitely more interesting to have made the babies to begin with. Upvotes: 2 [selected_answer]
2018/03/16
536
1,760
<issue_start>username_0: I try to dynamic notify when I wrote some messages. That's my vue.js code. ``` Vue.http.options.emulateJSON = true; // Send as new Vue({ el: '#app', data: { name : "", postResult : "" }, methods: { click: function() { this.$http.post('/api/test', {name:this.name}).then(function(response){ var result = response.data; //this.postResults.push(result.name); if (result.name == "1234") { this.postResult = "<div> Success </div>"; } else { this.postResult = "<div> Fail </div>"; } }, function(response){ // Error Handling }); } } }); ``` When I use jQuery's Ajax, I used this method. But my vue.js script is not working. Should I study more about Vue JS? or I forget some syntax in this vue.js?<issue_comment>username_1: You don't have "this" inside your response callback. Do `var me = this` at the top level of your click function, then do `me.postResult = ...` in the callback. In general terms, try and keep all your markup in the template element, no ? Upvotes: 0 <issue_comment>username_2: ```js Fail Success Vue.http.options.emulateJSON = true; // Send as new Vue({ el: '#app', data: { name : "", postResult : null, requestCompleted: false }, methods: { click: function() { this.$http.post('/api/test', {name:this.name}).then((response)=>{ var result = response.data; this.requestCompleted=true; if (result.name == "1234") { this.postResult = true; } else { this.postResult = false; } }, function(response){ // Error Handling }); } } }); ``` Use arrow functions for getting access to 'this' inside your callback function. For HTTP requests, it's better to use Axios. Also, you can use vuex store and manage your requests with actions Upvotes: 3 [selected_answer]
2018/03/16
306
878
<issue_start>username_0: I work with symfony4. I would add same validation to my input number to accept only values like : ``` 1 10 100 1000 10000 100000 1000000 ```<issue_comment>username_1: You have to use Choice validation. All info about choice validation You can find [here](https://symfony.com/doc/current/reference/constraints/Choice.html) Upvotes: 1 <issue_comment>username_2: You can use regex with this pattern > > "/^1+0\*/" > > > Example ``` class MyClass { /** * @Assert\Regex( * pattern = "/^1+0*/", * message="Wrong number" * ) */ protected $myNumber; } ``` Upvotes: 1 <issue_comment>username_3: You can use regex with this pattern ``` "/^1[0]*$/" ``` Demo: <https://regex101.com/r/eSnOfp/1> Upvotes: 1 <issue_comment>username_4: I solved it by this pattern : ``` pattern="[0-1]+" ``` Upvotes: 0
2018/03/16
658
2,027
<issue_start>username_0: Is there any way to place an images half is on top of another image using only constraint layout. I know it can be done using relative and frame layouts but in the case of constraint layout is there anyway? prefer ways which do not require any hardcoding of heights/widths the requirement will look like this [![enter image description here](https://i.stack.imgur.com/wiPAK.png)](https://i.stack.imgur.com/wiPAK.png)<issue_comment>username_1: Try this ``` xml version="1.0" encoding="utf-8"? ``` **OUTPUT** [![enter image description here](https://i.stack.imgur.com/sAVkN.png)](https://i.stack.imgur.com/sAVkN.png) **OR THIS** ``` ``` **OUTPUT** [![enter image description here](https://i.stack.imgur.com/BYgzp.png)](https://i.stack.imgur.com/BYgzp.png) Upvotes: 2 <issue_comment>username_2: Check it out margin. Put it in your ConstraintLayout. ``` ``` Upvotes: 2 <issue_comment>username_3: you can set layout using only constraint layout like below : ``` xml version="1.0" encoding="utf-8"? ``` **Note:** If you are using support library then you have to use **android.support.constraint.ConstraintLayout** instead of **androidx.constraintlayout.widget.ConstraintLayout** [![enter image description here](https://i.stack.imgur.com/xhWyy.png)](https://i.stack.imgur.com/xhWyy.png) Upvotes: 6 [selected_answer]<issue_comment>username_4: **Simplest way** ``` ``` [![enter image description here](https://i.stack.imgur.com/GgQ5n.png)](https://i.stack.imgur.com/GgQ5n.png) Upvotes: 3 <issue_comment>username_5: ``` xml version="1.0" encoding="utf-8"? ``` Upvotes: -1 <issue_comment>username_6: Simplest way just have to use two line code. > > card\_1 card\_2 > > > > ``` > In constraints of card_2 add two constraints: > app:layout_constraintBottom_toBottomOf="@+id/card_1" > app:layout_constraintTop_toBottomOf="@+id/card_1" > > ``` > > ``` xml version="1.0" encoding="utf-8"? ``` Output: [enter image description here](https://i.stack.imgur.com/DpsDT.png) Upvotes: 0
2018/03/16
351
1,439
<issue_start>username_0: I am trying to upload my graphql schema to aws appsync. My graphql schema is nearly 5000 lines long. I tried uploading using cli and gui, both. (1.) When using cli, I am continually getting error "Failed to parse schema document - ensure it's a valid SDL-formatted document." (2.) When using gui, the pipes in all the unions in my graphql schema ( eg. union UnionType = Type1 | Type2 | Type3 ) are replaced with whitespaces, causing syntax error. After solving this by manual replacement of whitespaces, the tab becomes unresponsive, and needs to be killed. I tried uploading a small graphql schema with a union from cli, and it worked successfully. However, from gui, it caused the same error of replacing pipes with whitespaces in union. I need help understanding this behaviour with aws cli and aws console.<issue_comment>username_1: I've got a similar issue and AppSync didn't allow to put any comments in it with just only one # symbol. Make sure you have no comments with just one # and use double sharps ## Anyway, it happens you have some invalid format or syntax AppSync doesn't support yet. Upvotes: 2 <issue_comment>username_2: It turns out that, in our case, the problem was the existence of reserved keys defined in out schema ([DynamoDB reserved words](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html)) even though we are not using Dynamo at all. Upvotes: 1
2018/03/16
773
2,769
<issue_start>username_0: I have an application where i have a wysiwyg editor to design emails and send them to contacts in a database, i have the email function working as when i test with an input form it sends to my database contacts, however i am trying to pass the content in the wysiwyg editor through ajax to my controller but when the emails are received they show up with the word 'false'.. My Controller ``` public function sendmail() { $this->load->library('email'); $this->load->model('Email_model'); $this->load->library('session'); $this->email->from($this->input->post('email'), $this->input- >post('name')); $this->email->to($this->Email_model->emailsend()); $this->email->subject('Hello This is an email'); $this->email->message($this->input->post('content')); if ($this->email->send()){ $this->load->view('header'); $this->load->view('sentConfirm'); $this->load->view('footer'); }else{ echo $this->email->print_debugger(); } } ``` My Ajax ``` $('#sendEmail').click(function () { $.ajax({ type: 'POST', url: "=site_url("dashboard/sendmail"); ?", data: { content: $("trumbowyg-demo").trumbowyg('html') }, dataType: 'json', success: function(response){ console.log('Sent Successfully'); } }); }); ```<issue_comment>username_1: We recommend phpmailer instead of codeigniter email assistant. Try it ; <https://github.com/ivantcholakov/codeigniter-phpmailer> Upvotes: 0 <issue_comment>username_2: ajax ``` $('#sendEmail').click(function () { $.ajax({ type: 'POST', url: "=site_url("dashboard/sendmail"); ?", data: {content: $("trumbowyg-demo").trumbowyg('html')}, dataType: 'json', success: function(response){ if(response.ok==1) { alert('sent'); }else{ alert('failed'); } }, error: function(response){ alert('error'); } }); }); ``` your controller ``` public function sendmail() { $configs = Array( 'mailtype' => 'html' //see other config in https://www.codeigniter.com/user_guide/libraries/email.html#email-preferences ); $this->load->library('email'); $this->email->initialize($configs); $this->load->model('Email_model'); $this->load->library('session'); $this->email->from($this->input->post('email'), $this->input->post('name')); $this->email->to($this->Email_model->emailsend()); $this->email->subject('Hello This is an email'); $this->email->message($this->input->post('content')); $result['ok'] = 0; if ($this->email->send()){ $result["ok"]=1; } echo json_encode($result); } ``` Upvotes: 2 [selected_answer]
2018/03/16
648
2,041
<issue_start>username_0: i'm recently start to learning C because i start a course in my university. In one of my lesson I need to write a program that converts a number of in ms to days, hours, minutes, second and milliseconds. I use this source code: ``` #include int main () { long int time\_ms; int d, h, m, s, ms; printf("insert the value in ms: \n"); scanf("%ld\n", &time\_ms); d = time\_ms/(24\*60\*60\*1000); //ms in a day time\_ms = time\_ms%(24\*60\*60\*1000); //reminder in ms h = time\_ms/(60\*60\*1000); time\_ms = time\_ms%(60\*60\*1000); m = time\_ms/(60\*1000); time\_ms = time\_ms%(60\*1000); s = (time\_ms/1000); ms = time\_ms%1000; printf("%d d %d h %d m %d s %d ms\n", d, h, m, s, ms); } ``` i compling it, and it work, but after i insert the number of milliseconds the shell of MacOs (were i'm working) doesn't print anything until i type "exit". what do i wrong?<issue_comment>username_1: Here's your problem: ``` scanf("%ld\n", &time_ms); ``` You have a `\n` in your sequence. That means that after entering a number and pressing enter, `scanf` reads the number, then reads the newline, then is waiting for something that isn't a newline before returning. Remove the newline character from the format string: ``` scanf("%ld", &time_ms); ``` Upvotes: 2 <issue_comment>username_2: You have made one of the classic mistakes: you used `scanf`. There are a whole bunch of reasons not to use `scanf` *ever*, but right now the important reason is that `scanf("%d\n")` is going to *keep trying to read input* after the number, until it receives either EOF or something that isn't whitespace. What you want to do instead is use `fgets`, which will read one entire line of input no matter what its contents are, and then `sscanf` to parse the number. When you start writing more sophisticated programs you'll discover that even `sscanf` is troublesome and it's better to use lower-level functions like `strtol` and `strsep`, but for a classroom exercise like this `sscanf` is fine. Upvotes: 3 [selected_answer]
2018/03/16
490
1,606
<issue_start>username_0: I have a task to create sql queries to insert data in oracle column. The datatype is SDO\_GEOMETRY I have only Latitude and Longitude values. Any pointers will be helpful<issue_comment>username_1: The full doc has more examples but here's the snippet you need. ``` SDO_GEOMETRY(2001, 4326, SDO_POINT_TYPE(37.783333, -122.416667, NULL), NULL, NULL) ``` Full Doc: <https://docs.oracle.com/cd/E17781_01/appdev.112/e18750/xe_locator.htm#XELOC563> Upvotes: 1 <issue_comment>username_2: In addition to saving the Lat&Lng in the SDO\_GEOMETRY column as [username_1](https://stackoverflow.com/users/3715100/kris-rice) said, you can use the many useful features of Oracle Spatial and Oracle Locator to achieve some useful results. In order to use those features, the below steps must be taken: 1. Alter the table to add a geometry (SDO\_GEOMETRY) column. 2. Update the table to populate the SDO\_GEOMETRY objects using existing location-related data values. 3. Update the spatial metadata (USER\_SDO\_GEOM\_METADATA). 4. Create the spatial index on the table. The detail of the above steps is explained [here](https://docs.oracle.com/database/121/SPATL/spatially-enabling-table.htm#SPATL1514). After the above steps have been done, you can use useful operators provided by Oracle Locator. For example, you can find the locations that are within X meters distance from a given point. For more details, read [this](https://docs.oracle.com/cd/E17781_01/appdev.112/e18750/xe_locator.htm#XELOC100) Oracle document. Upvotes: 0
2018/03/16
3,125
7,787
<issue_start>username_0: I've created an area chart with a white fill and red outline: [![enter image description here](https://i.stack.imgur.com/yDneZ.png)](https://i.stack.imgur.com/yDneZ.png) It works fine, but I would like to get rid of the red outline along the X and Y axes and just leave the outline that represents the actual data. So in the screenshot above I'd like to remove the red lines that track vertically and horizontally along the axes. My current code: ``` x.domain(d3.extent(data, function(d) { return d.date; })); if(full){ y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]); area.y0(y(0)); } else { y.domain([0.98*d3.min(data, function(d) { return d.value; }), 1.02*d3.max(data, function(d) { return d.value; })]); area.y0(y(0.98*d3.min(data, function(d) { return d.value; }))); } g.append("path") .datum(data) .attr("fill", "#fff") .attr("stroke", "#fa0d18") .attr("d", area); g.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x).tickFormat(d3.timeFormat("%m/%d"))) .selectAll("text") .style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", "rotate(-65)"); g.append("g") .call(d3.axisLeft(y)) .append("text") .attr("fill", "#000") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", "0.71em") .attr("text-anchor", "end") .text("Price ($)"); ``` Is this possible and how? P.S. Please disregard the grey vertical line in the middle of the screen, it's not relevant here.<issue_comment>username_1: You can limit which points are displayed using defined Every sample gets passed through the function and where it returns false, the points aren't shown... ``` var line = d3.line() .defined(function(d) { return d.x < xMax && dx > xMin && d.y > yMin && d.y< yMax; }) .x(function(d) { return x(d.x); }) .y(function(d) { return y(d.y); }); ``` Alternatively, you can use a clip-path like in this example. <https://bl.ocks.org/mbostock/4015254> Upvotes: 0 <issue_comment>username_2: Currently the red line it is a result of `stroke` attribute here (you can remove this attribute and see that red line is disappear): ``` g.append("path") .datum(data) .attr("fill", "#fff") .attr("stroke", "#fa0d18") // <== !!! .attr("d", area); ``` I imitate your problem using [this blocks](https://bl.ocks.org/d3noob/119a138ef9bd1d8f0a8d57ea72355252) as basis. See hidden snippet below: ```js var dataAsCSV = `date,close 1-May-12,58.13 30-Apr-12,53.98 27-Apr-12,67.00 26-Apr-12,89.70 25-Apr-12,99.00 24-Apr-12,130.28 23-Apr-12,166.70 20-Apr-12,234.98 19-Apr-12,345.44 18-Apr-12,443.34 17-Apr-12,543.70 16-Apr-12,580.13 13-Apr-12,605.23 12-Apr-12,622.77 11-Apr-12,626.20 10-Apr-12,628.44 9-Apr-12,636.23 5-Apr-12,633.68 4-Apr-12,624.31 3-Apr-12,629.32 2-Apr-12,618.63 30-Mar-12,599.55 29-Mar-12,609.86 28-Mar-12,617.62 27-Mar-12,614.48 26-Mar-12,606.98`; // set the dimensions and margins of the graph var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; // parse the date / time var parseTime = d3.timeParse("%d-%b-%y"); // set the ranges var x = d3.scaleTime().range([0, width]); var y = d3.scaleLinear().range([height, 0]); // define the area var area = d3.area() .x(function(d) { return x(d.date); }) .y0(height) .y1(function(d) { return y(d.close); }); // append the svg obgect to the body of the page // appends a 'group' element to 'svg' // moves the 'group' element to the top left margin var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); const data = d3.csvParse(dataAsCSV); // format the data data.forEach(function(d) { d.date = parseTime(d.date); d.close = +d.close; }); // scale the range of the data x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([0, d3.max(data, function(d) { return d.close; })]); // add the area svg.append("path") .data([data]) .attr("class", "area") .attr("stroke", "#fa0d18") .attr("d", area); // add the X Axis svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); // add the Y Axis svg.append("g") .call(d3.axisLeft(y)); ``` ```css .area { fill: lightsteelblue; } ``` To draw the red line that represents the actual data you have to make three steps (you have another dataset, so you should use appropriate properties names - `value`, `date` as I can see from your code): 1) Remove `stroke` attribute. 2) Specify the function for line drawing this way: ``` var valueline = d3.line() .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.close); }); ``` 3) And draw the line: ``` svg.append("path") .data([data]) .attr('fill', 'none') .attr('stroke', '#fa0d18') .attr("class", "line") .attr("d", valueline); ``` See result in the hidden demo below: ```js var dataAsCSV = `date,close 1-May-12,58.13 30-Apr-12,53.98 27-Apr-12,67.00 26-Apr-12,89.70 25-Apr-12,99.00 24-Apr-12,130.28 23-Apr-12,166.70 20-Apr-12,234.98 19-Apr-12,345.44 18-Apr-12,443.34 17-Apr-12,543.70 16-Apr-12,580.13 13-Apr-12,605.23 12-Apr-12,622.77 11-Apr-12,626.20 10-Apr-12,628.44 9-Apr-12,636.23 5-Apr-12,633.68 4-Apr-12,624.31 3-Apr-12,629.32 2-Apr-12,618.63 30-Mar-12,599.55 29-Mar-12,609.86 28-Mar-12,617.62 27-Mar-12,614.48 26-Mar-12,606.98`; // set the dimensions and margins of the graph var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; // parse the date / time var parseTime = d3.timeParse("%d-%b-%y"); // set the ranges var x = d3.scaleTime().range([0, width]); var y = d3.scaleLinear().range([height, 0]); // define the area var area = d3.area() .x(function(d) { return x(d.date); }) .y0(height) .y1(function(d) { return y(d.close); }); // define the line var valueline = d3.line() .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.close); }); // append the svg obgect to the body of the page // appends a 'group' element to 'svg' // moves the 'group' element to the top left margin var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); const data = d3.csvParse(dataAsCSV); // format the data data.forEach(function(d) { d.date = parseTime(d.date); d.close = +d.close; }); // scale the range of the data x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([0, d3.max(data, function(d) { return d.close; })]); // add the area svg.append("path") .data([data]) .attr("class", "area") .attr("d", area); // add the valueline path. svg.append("path") .data([data]) .attr('stroke', '#fa0d18') .attr('fill', 'none') .attr("class", "line") .attr("d", valueline); // add the X Axis svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); // add the Y Axis svg.append("g") .call(d3.axisLeft(y)); ``` ```css .area { fill: lightsteelblue; } ``` Upvotes: 3 [selected_answer]
2018/03/16
499
1,688
<issue_start>username_0: <https://github.com/seyhunak/twitter-bootstrap-rails> says: Twitter Bootstrap for Rails 5 and **Rails 4** Asset Pipeline but after bundle install I see this: ``` Bundler could not find compatible versions for gem "actionpack": In Gemfile: rails (= 4.1.7) was resolved to 4.1.7, which depends on actionpack (= 4.1.7) twitter-bootstrap-rails (~> 4.0.0) was resolved to 4.0.0, which depends on actionpack (>= 5.0.1, ~> 5.0) ``` Is it possible to make twitter-bootstrap-rails 4.0.0 worked with Rails 4.1.7?<issue_comment>username_1: Version you are using for `twitter-bootstrap-rails` is `4.0.0` having dependency on rails `>= 5.0.1, ~> 5.0` you can check [here](https://rubygems.org/gems/twitter-bootstrap-rails/versions/4.0.0). Use version `3.2.0` instead, it will work for you. ``` gem "twitter-bootstrap-rails", '~> 3.2.0' ``` Upvotes: 1 <issue_comment>username_2: * Cloned twitter-bootstrap-rails repo * Analyzed latest commits * Changed gemspecs * ???? * PROFIT!!! Upvotes: 1 [selected_answer]<issue_comment>username_3: I vote for using bootstrap 4 **WITHOUT** gem. In some cases and my experiences, this kind of implementation need less work when we integrate it to Rails manually : * download all the needed CSS, Java, creatives * put them all in the proper Rails assets folder * include them properly on the assets main file ( application.js, application.css, images ) * use it by following the proper guide from the bootstrap website * have a desired looks as you wish This way, you won't have to worries about gem dependencies or even ruby and rails versions. And totally welcoming any better ideas than mine. Upvotes: 0
2018/03/16
454
1,430
<issue_start>username_0: I have two models `Post` and `Author` in my project > > Post => `return $this->hasMany('App\Author')` > > > Author => `return $this->belongsTo('App\Post')` > > > Currently i have one record in `Post` and two in `Author`, Now i am removing one record from the list and saving it and it gives me exception. > > Undefined offset: 1 > > > Following is the code : ``` $post = \App\Post::with('authors')->where('id', $id)->first(); $post->user_id = Auth()->user()->id; $post->name = $request->name; foreach ($post->authors as $key => $author) { $author->post_id = $post->id; $author->life_span = $request->life_span[$key]; $author->duration = $request->duration[$key]; $author->save(); } $post->save(); ```<issue_comment>username_1: I don't get what you are trying to do with this foreach but add an `if` check ``` foreach ($post->authors as $key => $author) { $author->post_id = $post->id; if(isset($request->life_span[$key]) && isset($request->duration[$key])) { $author->life_span = $request->life_span[$key]; $author->duration = $request->duration[$key]; } $author->save(); } ``` Upvotes: 1 <issue_comment>username_2: ``` Undefined offset: 1 ``` It means an array doesn't have an index or key. Please check > > $request->life\_span[$key]; > > > does it exist? Probably you miss that. Upvotes: 0
2018/03/16
1,173
4,612
<issue_start>username_0: I have followed the steps described in the link below: [angular-localstorage4](https://www.npmjs.com/package/angular-localstorage4) When I am trying to import WebStorageModule and LocalStorageService from angular-localstorage. I am getting the following error in console although the compilation is successful.Any help is much appreciated. [![console error message](https://i.stack.imgur.com/r9ZYp.png)](https://i.stack.imgur.com/r9ZYp.png) My app.module.ts file looks like the following: ``` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { MatButtonModule, MatCheckboxModule, MatSidenavModule } from '@angular/material'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {FormsModule} from '@angular/forms'; import { AppComponent } from './app.component'; import { LoginComponent } from './login.component'; import { AppRoutingModule } from './/app-routing.module'; import { HeaderComponent } from './header/header.component'; import { NavigationComponent } from './navigation/navigation.component'; import {MatSidenav} from '@angular/material/sidenav'; import { MatIconModule } from "@angular/material/icon"; import { DashboardComponent } from './dashboard/dashboard.component'; import { ProfileComponent } from './profile/profile.component'; **import {WebStorageModule, LocalStorageService} from 'angular-localstorage';** @ NgModule({ declarations: [ AppComponent, LoginComponent, HeaderComponent, NavigationComponent, DashboardComponent, ProfileComponent, ], imports: [ BrowserModule, MatButtonModule, MatSidenavModule, MatCheckboxModule, FormsModule, MatIconModule, BrowserAnimationsModule, AppRoutingModule, **WebStorageModule** //That is when the problem appears ], providers: [//LocalStorageService ], bootstrap: [AppComponent] }) export class AppModule { } ```<issue_comment>username_1: You are getting this error b'coz no module is defined for LocalStorageService.Add CDN dependency in `index.html` and add `angular.module('myApp', ['LocalStorageModule',....])`. Also if you want to modify existing configuration of local storage then you can add 'localStorageServiceProvider' inside .config and provide custom configuartion. [for supporting Doc](https://www.npmjs.com/package/angular-local-storage) For using this in controller just inject 'localStorageService' `angular.module(myApp).controller('myCtrl', ['localStorageService', ....])` for setting value you can use `localStorageService.set(key, val);` and for retrieving use `var value = localStorageService.get(key);` Hope this may helps you Upvotes: 2 <issue_comment>username_2: > > We can use `LocalStorageService` and `SessionStorageService` using > `ngx-webstorage`. > > > This `ngx-webstorage` library provides an easy way to use service to manage the web storages (i.e. local and session) from your Angular application. But i would like to suggest that we can use localStorage and sessionStorage same as we use in javascript, as we know that **Typescript** is a superset of javascript. also using this we don't need to add extra library in our application. > > localStorage > > > You can store both string and array into location storage. To store data in localStorage, we use `setItem();` `localStorage.setItem(key, value);` and using array we can write it as ``` let key: 'employee'; let value: [{'name':'Elon','email':'<EMAIL>'}, {'name':'<NAME>','email':'<EMAIL>'}]; value = JSON.stringify(value); localStorage.setItem(key, value); ``` Now, to get stored data from localStorage, we use `getItem();` ``` const item = localStorage.getItem('key'); ``` eg. ``` const emp = localStorage.getItem('employee'); ``` Also we can remove and clear data from localStorage using, `localStorage.removeItem('key');` and `localStorage.clear();` respectively. Note : In `ngx-webstorage` you will get different functions to store, read, and clear the localStorage and use of decorators. link : <https://www.npmjs.com/package/ngx-webstorage> Upvotes: 1 <issue_comment>username_3: Although I was not able to find any working solutions for my problem, I found an alternative which serves the same purpose. Instead of using angular-localstorage, I used **angular-async-local-storage** which did the job for me. ``` "angular-async-local-storage": "^3.1.1", ``` Upvotes: 1 [selected_answer]
2018/03/16
585
2,083
<issue_start>username_0: I have comma seperated value in my table, tbl\_request as follows: ``` request_id name1 price 4 12,14 99.23 ``` From this table I need to find the data from another table based on the value name1 i.e. 12, 14. I have tried following code ``` SELECT r.price, ( SELECT GROUP_CONCAT(pd.product_name) FROM tbl_products AS pd WHERE ( pd.product_id IN(GROUP_CONCAT(r.name1)) ) ) as xyz FROM tbl_request AS r WHERE r.request_id = 4 ``` I need to get the product name of the id in name1 in comma seperated value. But with above code I can get only one value. How can I fix this problem?<issue_comment>username_1: You may use `FIND_IN_SET`: ``` SELECT * FROM yourTable WHERE FIND_IN_SET('12', name1) > 0; -- a non-zero value means a match ``` The above call to `FIND_IN_SET` would search the `name1` column, which consists of CSV strings, for the value `12` appearing as any value. Note that it is generally bad practice to store CSV data in your database tables, because it represents unnormalized data, and you can expect bad performance. Upvotes: 2 <issue_comment>username_2: You have a broken data structure. Here are reasons why it is bad: * It is bad to store numbers as strings. * A column in a SQL database should have one value. * SQL has poor string-manipulation support. * Foreign key relationships should be properly defined (and you cannot do that with a list). * String manipulations preclude the use of indexes. Fix your data and put the values into a proper *junction* table, with the right types and foreign key relationships. Sometimes, we are stuck with other people's really bad, bad, bad, bad, bad design decisions. MySQL offers `find_in_set()` which can help with this purpose: ``` SELECT r.price, GROUP_CONCAT(pd.product_name) as xyz FROM tbl_request r LEFT JOIN tbl_products p ON find_in_set(p.product_id, r.name1) > 0 WHERE r.request_id = 4 GROUP BY r.price; ``` Upvotes: 3 [selected_answer]
2018/03/16
644
2,332
<issue_start>username_0: I've 2 questions with the following code: ``` positive = {'yes','Yes','y','Y'} negative = {'no','No''n','N'} month = March while True: a = input('The month that you want to archive is March' '(Y or N) ? ') if a=='N': input("You will now leave, press Enter......") break elif a=='Y': print("Let's do it") input("The archive will start now, press Enter......") continue else: print("Enter either 'Y' to continue or 'N' to leave") print (month) etc.... ``` **Questions:** 1 - How can I accept the *input* as one of *positive* variable options ('yes','Yes','y','Y') ? 2 - How can I have the *month* variable written in the *input* question instead of March hardcoded (as it is in this moment)? 3 - I don't know how to keep running the code when users users press "Y" then Enter. It keeps repeating the question instead of running the *print(month)* code. Thank you very much in advance<issue_comment>username_1: You may use `FIND_IN_SET`: ``` SELECT * FROM yourTable WHERE FIND_IN_SET('12', name1) > 0; -- a non-zero value means a match ``` The above call to `FIND_IN_SET` would search the `name1` column, which consists of CSV strings, for the value `12` appearing as any value. Note that it is generally bad practice to store CSV data in your database tables, because it represents unnormalized data, and you can expect bad performance. Upvotes: 2 <issue_comment>username_2: You have a broken data structure. Here are reasons why it is bad: * It is bad to store numbers as strings. * A column in a SQL database should have one value. * SQL has poor string-manipulation support. * Foreign key relationships should be properly defined (and you cannot do that with a list). * String manipulations preclude the use of indexes. Fix your data and put the values into a proper *junction* table, with the right types and foreign key relationships. Sometimes, we are stuck with other people's really bad, bad, bad, bad, bad design decisions. MySQL offers `find_in_set()` which can help with this purpose: ``` SELECT r.price, GROUP_CONCAT(pd.product_name) as xyz FROM tbl_request r LEFT JOIN tbl_products p ON find_in_set(p.product_id, r.name1) > 0 WHERE r.request_id = 4 GROUP BY r.price; ``` Upvotes: 3 [selected_answer]
2018/03/16
2,306
5,333
<issue_start>username_0: I am trying to create a VBScript to find and replace a certain string located between two strings. Here is an example of a file that the script will be executed on: ```none % N1 ( POSTED FILE NAME - WORKNC POST ) N2 ( INPUT FILE NAME - _6033_Cavity__01.TBA) N3 (DATE/TIME: Thu Mar 15 06:36:08 2018) N4 G0 G40 G80 G90 G98 N5 G17 N6 G57H901 N7 G173W0.0 N8 B0.000 N9 (Tapper 0.250000) N10 T21 N11 M06 N12 S100 N13 M843 N14 G173 W0.0 N15 (- ) N16 ( Tapping ) N17 G0 G90 X-0.0001 Y8.8135 N18 G43 Z10.0632 H21 N19 G01 F500. X-0.0001 Y8.8135 N20 G01 Z9.7163 F500. N21 G98 G84 X-0.0001 Y8.8135 Z6.0376 R7.6376 E10. N22 G80 G01 F500. N23 X-0.0001 Y8.8135 Z9.7163 N24 X-0.0001 Y8.8135 Z9.7163 N25 N26 M845 N27 G91 G28 Z0 N28 G90 N29 G57H901 N30 G173W0.0 N31 B0.000 N32 (Drill 0.005000) N33 T19 N34 M06 N35 S5000 N36 M3 N37 G173 W0.0 N38 (- ) N39 ( Contour Chamfer ) N40 G0 G90 X-0.0001 Y8.8135 N41 G43 Z9.7163 H19 N42 Z7.6375 N43 G01 Z9.8376 F500. N44 X-0.0001 Y8.8135 Z10.0632 N45 N46 M05 N47 G91 G28 Z0 N48 G90 N49 G57H901 N50 G173W0.0 N51 B0.000 N52 (Tapper 0.750000) N53 T21 N54 M06 N55 S100 N56 M843 N57 G173 W0.0 N58 (- ) N59 ( Tapping ) N60 G0 G90 X-0.0001 Y8.8135 N61 G43 Z10.0632 H21 N62 G01 F500. X-0.0001 Y8.8135 N63 G01 Z9.7163 F500. N64 G98 G84 X-0.0001 Y8.8135 Z6.0376 R7.6376 E10. N65 G98 G84 X-0.0001 Y10.8135 Z6.0376 R7.6376 E10. N66 G80 G01 F500. N67 X-0.0001 Y8.8135 Z9.7163 N68 X-0.0001 Y8.8135 Z9.7163 N69 N70 M845 N71 G91 G28 Z0 N72 G90 N73 M30 % ``` So in this particular code there are two Tapping operations. I am trying to make a script that looks between `Tapper 0.250000` and `M845`, and replaces all instances of `E10.` with a variable that will be based on the number in `Tapper 0.250000`. So for example lets say there is `Tapper 0.250000` and some X lines later `M845`, the `E10.`'s that occur between those two need to be replaced with `E0.250000`. If there is another tapping operation such as `Tapper 0.750000` the `E10.`'s that are in between the Tapper and M845 need to be replaced with `E0.787`. Here is my VBScript so far: ``` strFileName = Wscript.Arguments(0) strOutputFile = Wscript.Arguments(0) Set fso = CreateObject("Scripting.FileSystemObject") 'Variable patterns to search for. There may be 9 of these total strPattern25 = "(Tapper 0.250000)(.|\s)*(M845)" strPattern375 = "(Tapper 0.375000)(.|\s)*(M845)" strPattern5 = "(Tapper 0.500000)(.|\s)*(M845)" strPattern75 = "(Tapper 0.750000)(.|\s)*(M845)" strFindString = "E10." 'String to find and then replace each instance of between pattern 'Variables of the replace string strReplaceString25 = "E0.05" strReplaceString375 = "E0.0625" strReplaceString5 = "E0.0769" strReplaceString75 = "E0.787" strTestString = fso.OpenTextFile(strFileName, 1).ReadAll 'open and read the file 'Replacing script. Currently replaces all text between the strPattern. Need to create another function in order to only replace the E10. strNewText25 = fReplaceText(strPattern25, strTestString, strReplaceString25) strNewText375 = fReplaceText(strPattern375, strTestString, strReplaceString375) strNewText5 = fReplaceText(strPattern5, strTestString, strReplaceString5) strNewText75 = fReplaceText(strPattern75, strTestString, strReplaceString75) fso.OpenTextFile(strOutputFile, 2, True).WriteLine strNewText MsgBox "Done!" 'Function Function fReplaceText(sPattern, sStr, sReplStr) Dim regEx, oMatch, colMatches, temp Set regEx = New RegExp ' Create a regular expression. regEx.Pattern = sPattern ' Set pattern regEx.IgnoreCase = True ' Set case insensitivity. regEx.Global = True ' Set global applicability Set colMatches = regEx.Execute(sStr) ' Execute search If colMatches.Count = 0 Then temp = "" Else For Each oMatch In colMatches temp = regEx.Replace(sStr, oMatch.SubMatches(0) & vbCrlf & sReplStr & vbCrlf & oMatch.SubMatches(2)) Next End If fReplaceText = temp End Function ```<issue_comment>username_1: You may use `FIND_IN_SET`: ``` SELECT * FROM yourTable WHERE FIND_IN_SET('12', name1) > 0; -- a non-zero value means a match ``` The above call to `FIND_IN_SET` would search the `name1` column, which consists of CSV strings, for the value `12` appearing as any value. Note that it is generally bad practice to store CSV data in your database tables, because it represents unnormalized data, and you can expect bad performance. Upvotes: 2 <issue_comment>username_2: You have a broken data structure. Here are reasons why it is bad: * It is bad to store numbers as strings. * A column in a SQL database should have one value. * SQL has poor string-manipulation support. * Foreign key relationships should be properly defined (and you cannot do that with a list). * String manipulations preclude the use of indexes. Fix your data and put the values into a proper *junction* table, with the right types and foreign key relationships. Sometimes, we are stuck with other people's really bad, bad, bad, bad, bad design decisions. MySQL offers `find_in_set()` which can help with this purpose: ``` SELECT r.price, GROUP_CONCAT(pd.product_name) as xyz FROM tbl_request r LEFT JOIN tbl_products p ON find_in_set(p.product_id, r.name1) > 0 WHERE r.request_id = 4 GROUP BY r.price; ``` Upvotes: 3 [selected_answer]
2018/03/16
1,778
6,146
<issue_start>username_0: I have a element and which will show a paragraph with no line breaks like in the example ```html Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum ``` Here the text will split as a number of lines according to the width of its container, I am trying to wrap each of the auto-sized lines into a span element.but I failed to do this because we can't find the end of the lines using `\n`.is there any method to achieve this? Note- I find an answer for this when i am searching [Can I wrap each line of multi-line text in a span?](https://stackoverflow.com/questions/4147080/can-i-wrap-each-line-of-multi-line-text-in-a-span) . but the questin is not similer to this,here i have a test in single line and there is no line break.but the above question have line break on each line<issue_comment>username_1: This should do what you want, or close to it. ``` function trimByPixel(str, width) { var spn = $('').text(str).appendTo('body'); var txt = str; while (spn.width() > width) { txt = txt.slice(0, -1); spn.text(txt + "..."); } return txt; } var stri = $(".str").text(); function run(){ var s = trimByPixel(stri, $(".str").width()).trim() stri = stri.replace(s,"") $(".result").append(""+s+""); if(stri.trim().length > 0){ run(); } } run(); ``` **Demo** ```js function trimByPixel(str, width) { var spn = $('').text(str).appendTo('body'); var txt = str; while (spn.width() > width) { txt = txt.slice(0, -1); spn.text(txt + "..."); } return txt; } var stri = $(".str").text(); function run(){ var s = trimByPixel(stri, $(".str").width()).trim() stri = stri.replace(s,"") $(".result").append(""+s+""); if(stri.trim().length > 0){ run(); $(".str").remove(); //remove original } } run(); ``` ```css .str{ width:300px; } .result span{ display:block } ``` ```html Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: To be able to calculate when there is a new line, we must first know when the last word of the sentence is. To find out, we will put a tag for every word. We then take the Y coordinates of each word. If there is a difference, we know that a new rule has started. For updates <https://github.com/nielsreijnders/textSplitter/blob/master/src/index.ts> ```js // Openingtag & closingtag has to be a string!! function splitLines(container, openingtag, closingtag) { // Get the spans in the paragraph var spans = container.children, top = 0, // set tmp as a string tmp = ''; // Put spans on each word, for now we use the tag because, we want to save 5 bytes:) container.innerHTML = container.textContent.replace(/\S+/g, '$&'); // Loop through each words (spans) for (let i = 0; i < spans.length; i++) { // Get the height of each word var rect = spans[i].getBoundingClientRect().top; // If top is different as the last height of the word use a closingtag and use an opentag after that if (top < rect) tmp += closingtag + openingtag; top = rect; // Add the spans + space between each word tmp += spans[i].textContent + ' '; } // Add the lines back to the paragraph container.innerHTML = tmp += closingtag; } ``` ```js function splitLines(container, opentag, closingtag) { var spans = container.children, top = 0, tmp = ''; container.innerHTML = container.textContent.replace(/\S+/g, '$&'); for (let i = 0; i < spans.length; i++) { var rect = spans[i].getBoundingClientRect().top; if (top < rect) tmp += closingtag + opentag; top = rect; tmp += spans[i].textContent + ' '; } container.innerHTML = tmp += closingtag; } splitLines(document.querySelectorAll('p')[0], '','') ``` ```css * { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; line-height: 22px; } h1 { letter-spacing: 1px; border-bottom: 1px solid #eaecef; padding-bottom: .5em; } p { font-size: 14px; width: 350px; } p span:nth-child(even) { color: #fff; background: #000; } ``` ```html TextSplitter ============ Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. ``` You have to update the lines when resizing your window! Upvotes: 3
2018/03/16
885
3,147
<issue_start>username_0: I have developed a website using PhalconPHP. the website works perfectly fine on my local computer with the following specifications: ``` PHP Version 7.0.22 Apache/2.4.18 PhalconPHP 3.3.1 ``` and also on my previous Server (with DirectAdmin): ``` PHP Version 5.6.26 Apache 2 PhalconPHP 3.0.1 ``` But recently I have migrated to a new VPS. with cPanel: ``` CENTOS 7.4 vmware [server] cPanel v68.0.30 PHP Version 5.6.34 (multiple versions available, this one selected by myself) PhalconPHP 3.2.2 ``` On the new VPS my website always gives me `Error 500`. in my Apache Error logs file: `[cgi:error] End of script output before headers: ea-php70, referer: http://mywebsitedomain.net` What I suspect is the new database System. the new one is not mySql. it is `MariaDB 10.1`. I tried to downgrade to MySQL 5.6 but the WHM says there is no way I could downgrade to lower versions. this is my config file: ``` [database] adapter = Mysql host = localhost username = root password = <PASSWORD> dbname = XXXXXXXXXXXX charset = utf8 ``` and my `Services.php`: ``` protected function initDb() { $config = $this->get('config')->get('database')->toArray(); $dbClass = 'Phalcon\Db\Adapter\Pdo\\' . $config['adapter']; unset($config['adapter']); return new $dbClass($config); } ``` And in my controllers... for example this code throws `Error 500`: ``` $this->view->files = Patients::query()->orderBy("id ASC")->execute(); ``` but changing `id` to `fname` fixes the problem: ``` $this->view->files = Patients::query()->orderBy("fname ASC")->execute(); ``` or even the following code throws `error 500`: ``` $user = Users::findFirst(array( "conditions" => "id = :id:", "bind" => array("id" => $this->session->get("userID")) )); ``` is there a problem with the compatibility of PhalconPHP and MariaDB?<issue_comment>username_1: MariaDB was built to be *mostly* compatible with MySQL clients, it's unlikely to be the reason for your problems. If you're still concerned, you can switch from MariaDB to MySQL (and vice versa) by dumping (exporting) your tables, switching over, and importing them again. More likely, the error line you're showing indicates that your new server is actually running PHP7 (`ea-php70`) and not PHP5.6 as you thought you selected. The error `End of script output before headers` means the CGI script (in this case PHP7 itself) did not produce any HTTP headers before terminating. I suspect that your version of PhalconPHP is incompatible with PHP7 and therefore just crashes immediately. If cPanel doesn't let you properly configure your infrastructure you likely have no other option but to drop it and set up your stack manually. But since you probably paid for cPanel, you could try opening a support ticket with them first: <https://cpanel.com/support/> Upvotes: 4 [selected_answer]<issue_comment>username_2: Most probably old phalconPHP version it does not support latest php 7.x version i guess. as i remember I have read similiar problem in another blog question. Upvotes: 0
2018/03/16
1,146
4,148
<issue_start>username_0: This is my code. ``` public static void test1() throws IOException { System.setProperty("webdriver.chrome.driver", "data/chromedriver.exe"); drive = new ChromeDriver(); drive.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); try { drive.get("http://youtube.com"); }catch(TimeoutException e) { printSS(); } } public static void printSS() throws IOException{ String path = "logs/ss/"; File scrFile = ((TakesScreenshot)drive).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File(path + "asdasdas" + ".jpg")); } ``` All time when driver.get() throw TimeoutException I want to take a screenshot at browser. But when throw TimeoutException, getScreenshotAs() from printSS() don't take screenshot because throw another TimeoutException. Why getScreenshotAs() throw TimeoutException and how to take screenshot at browser P.S.: Increase pageLoadTimeout time is not the answer I want.<issue_comment>username_1: While working with *Selenium 3.x*, *ChromeDriver 2.36* and *Chrome 65.x* you need to mention the relative path of the location (**with respect of your project**) where you intend to store the *screenshot*. I took you code and did a few minor modification as follows : * Declared *driver* as *WebDriver* instance as **static** and added **@Test** annotation. * Reduced **pageLoadTimeout** to **2** seconds to purposefully raise the **TimeoutException**. * Changed the *location* of `String path` to a sub-directory wthin the project scope as follows : ``` String path = "./ScreenShots/"; ``` * Added a log as : ``` System.out.println("Screenshot Taken"); ``` * Here is the code block : ``` package captureScreenShot; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; public class q49319748_captureScreenshot { public static WebDriver drive; @Test public static void test1() throws IOException { System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe"); drive = new ChromeDriver(); drive.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS); try { drive.get("http://youtube.com"); }catch(TimeoutException e) { printSS(); } } public static void printSS() throws IOException{ String path = "./ScreenShots/"; File scrFile = ((TakesScreenshot)drive).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File(path + "asdasdas" + ".jpg")); System.out.println("Screenshot Taken"); } } ``` * Console Output : ``` [TestNG] Running: C:\Users\username\AppData\Local\Temp\testng-eclipse--153679036\testng-customsuite.xml Starting ChromeDriver 2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91) on port 42798 Only local connections are allowed. Mar 16, 2018 5:37:59 PM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Detected dialect: OSS Screenshot Taken PASSED: test1 ``` * Screenshot : ![asdasdas](https://i.stack.imgur.com/TzJlq.png) --- Reference --------- You can find a detailed discussion in [How to take screenshot with Selenium WebDriver](https://stackoverflow.com/questions/3422262/how-to-take-screenshot-with-selenium-webdriver/55120087#55120087) Upvotes: 2 <issue_comment>username_2: The problem is that while Selenium waits for the page to complete loading it cannot take any other command. This is why it throws TimeoutException also from the exception handler when you try take the screenshot. The only option I see is to take the screenshot not through Selenium, but using other means that take a screenshot of the entire desktop. I've written such a thing in C#, but I'm pretty sure you can either find a way to do it in Java too. Upvotes: 1 [selected_answer]
2018/03/16
294
1,004
<issue_start>username_0: I'm trying to concatenate 2 columns using delimiter as "." **code :** ``` PCollection first = apps.apply(BeamSql.query( "SELECT \*,('CatLib' || 'ProdKey') AS CatLibKey from PCOLLECTION")); ``` How shall I specify delimiter between 2 columns ?<issue_comment>username_1: I'd say go for ``` SELECT COALESCE(CatLib, '') || '.' || COALESCE(ProdKey, '') AS CatLibKey, (any other columns here...) FROM PCOLLECTION; ``` but in SQL there is no "Select everything but column X" or "Select everything else" so you'd have to write down every name of the column you want to select. Upvotes: 2 [selected_answer]<issue_comment>username_2: Thanks @username_1. I have modified my query to : ``` PCollection first = apps.apply(BeamSql.query( "SELECT Outlet, CatLib, ProdKey, Week, SalesComponent, DuetoValue, PrimaryCausalKey, CausalValue, ModelIteration, Published, (CatLib || '.' || ProdKey) AS CatLibKey from PCOLLECTION")); ``` and this worked perfectly. Upvotes: 0
2018/03/16
424
1,669
<issue_start>username_0: I have a web application in which I'm maintaining many static Maps to store my relevant information. Since the application is deployed on a server. Each and every hit to the server side java uses these maps to match the key and get appropriate result and send back to the client side. My code contains a rank and retrieval feature so I have to read the entire keySet of each of these Maps. My question is: **1. Is working with static variables better than storing this data in a local embedded DB like Apache Derby and then using it?** **2. The use of this data is very frequent. So if I use database will that be faster approach? Since I read the full keyset the where clause may not come handy in many operations.** **3. How does the server's memory gets impacted on holding data in static variables?** My no. of maps are fixed but the size of the Maps keeps increasing? Please suggest the better solution.<issue_comment>username_1: I'd say go for ``` SELECT COALESCE(CatLib, '') || '.' || COALESCE(ProdKey, '') AS CatLibKey, (any other columns here...) FROM PCOLLECTION; ``` but in SQL there is no "Select everything but column X" or "Select everything else" so you'd have to write down every name of the column you want to select. Upvotes: 2 [selected_answer]<issue_comment>username_2: Thanks @username_1. I have modified my query to : ``` PCollection first = apps.apply(BeamSql.query( "SELECT Outlet, CatLib, ProdKey, Week, SalesComponent, DuetoValue, PrimaryCausalKey, CausalValue, ModelIteration, Published, (CatLib || '.' || ProdKey) AS CatLibKey from PCOLLECTION")); ``` and this worked perfectly. Upvotes: 0
2018/03/16
2,707
7,662
<issue_start>username_0: I want to create a tablayout in bootstrap that looks like the ones in android. I am trying to create these tabs like they explain here: <https://bootsnipp.com/snippets/featured/bootstrap-line-tabs-by-keenthemes> But I want to use bootstrap 4.0.0. My code is here: <https://jsfiddle.net/3y2wgsao/1/> css: ``` /*** Bootstrap Line Tabs by @keenthemes A component of Metronic Theme - #1 Selling Bootstrap 3 Admin Theme in Themeforest: Licensed under MIT ***/ /* Tabs panel */ .tabbable-panel { border:1px solid #eee; padding: 10px; } /* Default mode */ .tabbable-line > .nav-tabs { border: none; margin: 0px; } .tabbable-line > .nav-tabs > li { margin-right: 2px; } .tabbable-line > .nav-tabs > li > a { border: 0; margin-right: 0; color: #737373; } .tabbable-line > .nav-tabs > li > a > i { color: #a6a6a6; } .tabbable-line > .nav-tabs > li.open, .tabbable-line > .nav-tabs > li:hover { border-bottom: 4px solid #fbcdcf; } .tabbable-line > .nav-tabs > li.open > a, .tabbable-line > .nav-tabs > li:hover > a { border: 0; background: none !important; color: #333333; } .tabbable-line > .nav-tabs > li.open > a > i, .tabbable-line > .nav-tabs > li:hover > a > i { color: #a6a6a6; } .tabbable-line > .nav-tabs > li.open .dropdown-menu, .tabbable-line > .nav-tabs > li:hover .dropdown-menu { margin-top: 0px; } .tabbable-line > .nav-tabs > li.active { border-bottom: 4px solid #f3565d; position: relative; } .tabbable-line > .nav-tabs > li.active > a { border: 0; color: #333333; } .tabbable-line > .nav-tabs > li.active > a > i { color: #404040; } .tabbable-line > .tab-content { margin-top: -3px; background-color: #fff; border: 0; border-top: 1px solid #eee; padding: 15px 0; } .portlet .tabbable-line > .tab-content { padding-bottom: 0; } ``` html: ``` * [Tab 1](#tab_default_1) * [Tab 2](#tab_default_2) * [Tab 3](#tab_default_3) I'm in Tab 1. Duis autem eum iriure dolor in hendrerit in vulputate velit esse molestie consequat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat. Learn more... Howdy, I'm in Tab 2. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat. Ut wisi enim ad minim veniam, quis nostrud exerci tation. Click for more features... Howdy, I'm in Tab 3. Duis autem vel eum iriure dolor in hendrerit in vulputate. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat Learn more... ``` As you can see, the red line doesn't change to the active link. Does anyone know why this is the case?<issue_comment>username_1: There are couple of mistakes in the HTML and CSS. See if my developed fiddle is what you want. <https://jsfiddle.net/3y2wgsao/14/> css: ``` /* Tabs panel */ .tabbable-panel { border:1px solid #eee; padding: 10px; } /* Default mode */ .tabbable-line > .nav-tabs { border: none; margin: 0px; } .tabbable-line > .nav-tabs > li { margin-right: 2px; } .tabbable-line > .nav-tabs > li > a { border-left:0; border-right:0; border-top:0; border-bottom: 4px solid transparent; margin-right: 0; color: #737373; } .tabbable-line > .nav-tabs > li > a > i { color: #a6a6a6; } .tabbable-line > .nav-tabs > li.open, .tabbable-line > .nav-tabs > li:hover { } .tabbable-line > .nav-tabs > li.open > a, .tabbable-line > .nav-tabs > li:hover > a { background: none !important; border-bottom-color: #fbcdcf; color: #333333; } .tabbable-line > .nav-tabs > li.open > a > i, .tabbable-line > .nav-tabs > li:hover > a > i { color: #a6a6a6; } .tabbable-line > .nav-tabs > li.open .dropdown-menu, .tabbable-line > .nav-tabs > li:hover .dropdown-menu { margin-top: 0px; } .tabbable-line > .nav-tabs > li > a.active { border-bottom-color: #f3565d; position: relative; display:block; color: #333333; } .tabbable-line > .nav-tabs > li > a.active > i { color: #404040; } .tabbable-line > .tab-content { margin-top: -3px; background-color: #fff; border: 0; border-top: 1px solid #eee; padding: 15px 0; } .portlet .tabbable-line > .tab-content { padding-bottom: 0; } ``` html: ``` * [Tab 1](#tab_default_1) * [Tab 2](#tab_default_2) * [Tab 3](#tab_default_3) I'm in Tab 1. Duis autem eum iriure dolor in hendrerit in vulputate velit esse molestie consequat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat. [Learn more...](#) Howdy, I'm in Tab 2. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat. Ut wisi enim ad minim veniam, quis nostrud exerci tation. [Click for more features...](#) Howdy, I'm in Tab 3. Duis autem vel eum iriure dolor in hendrerit in vulputate. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat [Learn more...](#) ``` Thanks Upvotes: 1 <issue_comment>username_2: You need to change the CSS selectors now that the `active` class is applied the anchor instead of the `li` in Bootstrap 4... <https://www.codeply.com/go/xV3CvpV2yy> ``` .tabbable-line > .nav-tabs > li > a { border: 0; margin-right: 0; color: #737373; border-bottom: 4px solid transparent; } .tabbable-line > .nav-tabs > li a:not(.active):hover { border-bottom: 4px solid #fbcdcf; } .tabbable-line > .nav-tabs > li .active { border-bottom: 4px solid #f3565d; } ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: make bootstrap.js below the jquery.js. check this fiddle <https://jsfiddle.net/raj_mutant/3y2wgsao/16/> ``` * [Tab 1](#tab_default_1) * [Tab 2](#tab_default_2) * [Tab 3](#tab_default_3) I'm in Tab 1. Duis autem eum iriure dolor in hendrerit in vulputate velit esse molestie consequat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat. Learn more... Howdy, I'm in Tab 2. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat. Ut wisi enim ad minim veniam, quis nostrud exerci tation. Click for more features... Howdy, I'm in Tab 3. Duis autem vel eum iriure dolor in hendrerit in vulputate. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat Learn more... ``` Upvotes: 0
2018/03/16
632
2,830
<issue_start>username_0: I'm writing my own `BeanPostProcessor` and so creating a class implementing BeanPostProcessor interface in eclipse Oxygen and java 9 infrastructure. Now the question is - compiler is not allowing me to use @Override annotation for methods - `postProcessBeforeInitialization(Object,String)` and `postProcessAfterInitialization(Object,String)`. Why? And **Even if I do not provide implementation for these methods in my class**, I'm not getting compiler complaints which is against Interface rule. I mean I should get compiler error telling me that interface methods must be implemented. But not. Why? please guide me.<issue_comment>username_1: If you look at the signature of e.g.`postProcessBeforeInitialization` ``` @Nullable default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } ``` You will notice that this method is defined in an interface but is already declared as **default** and thus has an implementation. So you do not need to override it. Upvotes: 0 <issue_comment>username_2: ``` import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class DisplayNameBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("Before "+bean.getClass() + " " + beanName); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("After "+bean.getClass() + " " + beanName); return bean; } } ``` The compiler will allow you to use @Override. ``` @Nullable default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } ``` In method definition we have the 'default' keyword introduced in Java 8 due to which it's not necessary for you to implement this method. In this case, Java has provided 'return bean;' as the body for this method. Upvotes: 2 <issue_comment>username_3: I have same question, Now you do want to override the methods, I want to create my own bean processor so I override the two methods Now in the interface the parameters are @Nullable So I can suppress the warning or add @NullAble annotations to my parameters of my methods. You can override default methods. I have Intellij and java9 with springboot-2 and I do annotate my methods with @override as you should be able to override non final method including default Interface methods. `@Override public Object postProcessBeforeInitialization(@Nullable final Object bean, String beanName) throws BeansException` Upvotes: 0
2018/03/16
674
2,836
<issue_start>username_0: I am trying to boostrap OpenMeetings using this boostrap package <https://github.com/l0rdn1kk0n/wicket-bootstrap>. According to the tutorial of how to, I'll do it thus: ``` // best place to do this is in Application#init() Bootstrap.install(this); // if you want to customize bootstrap: BootstrapSettings settings = new BootstrapSettings(); settings.setXXX(...); Bootstrap.install(this, settings); ``` I am new to OpenMeetings, please can anyone kindly point me to where I am to put this snippet. As stated above it is suppose to be in Application#init(), but I don't know where the such a file could be in OpenMeetings.<issue_comment>username_1: If you look at the signature of e.g.`postProcessBeforeInitialization` ``` @Nullable default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } ``` You will notice that this method is defined in an interface but is already declared as **default** and thus has an implementation. So you do not need to override it. Upvotes: 0 <issue_comment>username_2: ``` import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class DisplayNameBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("Before "+bean.getClass() + " " + beanName); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("After "+bean.getClass() + " " + beanName); return bean; } } ``` The compiler will allow you to use @Override. ``` @Nullable default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } ``` In method definition we have the 'default' keyword introduced in Java 8 due to which it's not necessary for you to implement this method. In this case, Java has provided 'return bean;' as the body for this method. Upvotes: 2 <issue_comment>username_3: I have same question, Now you do want to override the methods, I want to create my own bean processor so I override the two methods Now in the interface the parameters are @Nullable So I can suppress the warning or add @NullAble annotations to my parameters of my methods. You can override default methods. I have Intellij and java9 with springboot-2 and I do annotate my methods with @override as you should be able to override non final method including default Interface methods. `@Override public Object postProcessBeforeInitialization(@Nullable final Object bean, String beanName) throws BeansException` Upvotes: 0
2018/03/16
620
2,282
<issue_start>username_0: In the ISO *International Standard* for C++11, a summary of the differences between c++ 2003 and C++ 2011 is given. One of the difference is: > > ### [diff.cpp03.special] > > > **Change**: Implicitly-declared special member functions are defined as deleted when the implicit definition > would have been ill-formed. > > > **Rationale**: Improves template argument deduction failure. > > > **Effect on original feature**: A valid C++ 2003 program that uses one of these special member functions in a context where the definition is not required (e.g., in an expression that is not potentially evaluated) becomes ill-formed. > > > I fail to see in which condition such special functions would be ill-formed, and how it could break SFINAE. So my question boils down to: * Why such a change does *"improves template argument deduction failure"*? * Could you give an example?<issue_comment>username_1: ``` struct NonCopyable { NonCopyable() {} private: NonCopyable(const NonCopyable &); }; struct S { NonCopyable field; } s; int main() { return sizeof S(s); } ``` Here, `NonCopyable` is non-copyable, but as the copy constructor is explicitly provided, no implicit copy constructor is created. For `S`, no copy constructor is provided by the user, so an implicit copy constructor is created. This copy constructor would copy the `NonCopyable` `field` field, which is non-copyable, so the copy constructor would be ill-formed. In `main`, the size of a copy-constructed `S` object is taken. This requires a copy constructor of `S`, but doesn't actually call it. In C++03, this is valid. The copy constructor would be ill-formed, but since no copy is ever made, it's okay. In C++11, this is invalid. The copy constructor is marked as deleted, so cannot be used even as the operand to `sizeof`. This allows metaprogramming to detect whether the type is copyable, which was impossible in C++03. Upvotes: 6 [selected_answer]<issue_comment>username_2: If you want a concrete example, std::pair is usually very easy to copy, but if one of the members is, say, a std::unique\_ptr, unique\_ptr doesn't allow copying from Lvalue, so it would be ill-formed: so the std::pair default Lvalue copy operations are automatically deleted. Upvotes: 1
2018/03/16
735
2,368
<issue_start>username_0: I've been googling for a while now, but I can't seem to find an answer, nor anyone else with the same issue. I'm trying to add a menu item, "My Files", above the "Logout" item. Here's the code I'm using: ``` // Add Menu Item function my_account_menu_items( $items ) { return array_merge( array_slice( $items, 0, count( $items ) - 1 ), array( 'my-files' => 'My Files' ), array_slice( $items, count( $items ) - 1 ) ); } add_filter( 'woocommerce_account_menu_items', 'my_account_menu_items', 10, 1); ``` I've tried calling the filter in a different way, without the last two arguments. I've also tried doing ``` function my_account_menu_items( $items ) { $items['my-files'] = 'My Files'; return $items; } ```<issue_comment>username_1: You should try the following instead: ``` add_filter( 'woocommerce_account_menu_items', 'add_item_to_my_account_menu', 30, 1 ); function add_item_to_my_account_menu( $items ) { $new_items = array(); // Loop throu menu items foreach( $items as $key => $item ){ if( 'customer-logout' == $key ) $new_items['my-files'] = __( 'My Files' ); $new_items[$key] = $item; } return $new_items; } ``` *Code goes in function.php file of your active child theme (or active theme).* Tested and works. [![enter image description here](https://i.stack.imgur.com/RUGUI.png)](https://i.stack.imgur.com/RUGUI.png) Upvotes: 2 <issue_comment>username_2: This is tested and working: ``` function custom_my_account_menu_items( $items ) { $new_items = array(); foreach($items as $key => $value){ if($key != 'customer-logout'){ $new_items[$key] = $value; }else{ $new_items['my-files'] = 'My Files'; $new_items[$key] = $value; } } return $new_items; } add_filter( 'woocommerce_account_menu_items', 'custom_my_account_menu_items' ); ``` Upvotes: 0 <issue_comment>username_3: You could just make sure login stays at the bottom by unsetting it and adding it back last thing. ``` //keep logout the last menu item function custom_my_account_menu_items( $items ) { unset($items['customer-logout']); $items['customer-logout'] = 'Logout'; return $items; } add_filter( 'woocommerce_account_menu_items', 'custom_my_account_menu_items', 999 ); ``` Upvotes: 0
2018/03/16
1,330
4,228
<issue_start>username_0: I have a list of tuples like with a hash and path to a file. I would like to find all duplicates as well as similar items based on hamming-distance. I have a function for haming distance score where I give to values and get the score. I stuck with the problem to loop through the list and find matching items. ``` list = [('94ff39ad', '/path/to/file.jpg'), ('94ff39ad', '/path/to/file2.jpg'), ('94ff40ad', '/path/to/file3.jpg'), ('cab91acf', '/path/to/file4.jpg')] score = haming_score(h1, h2) # score_for_similar > 0.4 ``` I need a dictionary with an original (path) as key and a list of possible similar or duplicates as value. like: ``` result = {'/path/to/file.jpg': ['/path/to/file2.jpg', '/path/to/file3.jpg'], '/path/to/file4.jpg': []} ``` The second dict key value pair {'/path/to/'file4.jpg': []} is not necessary but helpful to have. Currently I loop twice through the list and compare the values with each other. But I get double results. I would be very greateful for your help. P.S. to calculate the hamming-distance score I use: ``` def hamming_dist(h1, h2): h1 = list(h1) h2 = list(h2) score = scipy.spatial.distance.hamming(h1, h2) return score ```<issue_comment>username_1: ``` import Levenshtein as leven # This is your list xlist = [('94ff39ad', '/path/to/file.jpg'), ('512asasd', '/somepath/to/file.jpg'), ('94ff39ad', '/path/to/file2.jpg'), ('94ff40ad', '/path/to/file3.jpg'), ('cab91acf', '/path/to/file4.jpg')] # Here's what you'll base the difference upon: simalarity_threshhold = 80 # 80% results = {} for item in xlist: path = item[1] print('Examining path:', path) max_similarity = None similarity_key = None for key in results: diff = leven.distance(path, key) diff_percentage = 100 / max(len(path), len(key)) * (min(len(path), len(key)-diff)) print(' {} vs {} = {}%'.format(path, key, int(diff_percentage))) if diff_percentage > simalarity_threshhold: if not max_similarity or diff_percentage > max_similarity: max_similarity = diff_percentage similarity_key = key if not max_similarity: results[path] = {} else: results[similarity_key][path] = max_similarity print(results) ``` If two paths have a similarity above 80% of the distance value of each other, they will be paired as a potential match. If another path is more similar, it will be added to that instead. And if the path is below 80% similarity, it will create it's own result path/tree/structure. Again, this is just one example of how you'd solve it. There's [many ways to do it](https://stackoverflow.com/questions/17904097/python-difference-between-two-strings), but I prefer [Levenshtein](https://github.com/ztane/python-Levenshtein) because it's easy to work with and pretty accurate. I left some debug code in there so you could see the way of thinking, what values are being passed where etc. again, this is all up to your rule-set for determining what's a match and not. Oh, and I also stored the values as sub-dictionaries. This so that each potential candidate kept it's score it got upon checking. You could save them as a list as well. But lists are extremely slow in comparison to dictionaries, both in iteration, comparison and storing. Second "oh".. This code is not regression tested.. There is bound to be some logical issues here.. Especially in the `diff_percentage` calculation.. I'm by noooo means a math wizard. But you catch my drift :) Upvotes: 2 [selected_answer]<issue_comment>username_2: to log how I solved the problem and to be a help for others, here is my code: ``` test = [('94ff39ad', '/path/to/file.jpg'), ('94ff39ad', '/path/to/file2.jpg'), ('94ff40ad', '/path/to/file3.jpg'), ('cab91acf', '/path/to/file4.jpg')] seen = {} new_seen = False counter = 0 for x in test: added = False for k, v in seen.items(): if x[0] == k or hamming_dist(x[0], k) < .4: v.append(x[1]) added = True if not seen or not added: seen[x[0]] = [x[1]] print(seen) >> {'/path/to/file.jpg': ['/path/to/file2.jpg', '/path/to/file3.jpg'], '/path/to/file4.jpg': []} ``` Upvotes: 0
2018/03/16
545
1,747
<issue_start>username_0: I have an array of json from the server. Like ``` ArrayExp = [ { "id" : "number", "name" : "<NAME>", ... }, { "id" : "number", "name" : "<NAME>", ... }, ... ]; ``` And I want to remove a "id" from all of the Array. I am trying with: ``` for (int i = 0; i < ArrayExp.Length; i++) { ArrayExp[i].id // I don't know how to remove it! } ``` Can anyone help me?<issue_comment>username_1: `ArrayExp` elements are objects of [anonymous type](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types). In order to remove property on it, you should map each element into new one without `id`. ``` var newArrayExpr = ArrayExp .Select(it => new { it.name, ... }); ``` Upvotes: 1 <issue_comment>username_2: I used [ExpandoObject](https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.110).aspx) from System.Dynamic, hope it helps you ``` public static void Main() { var arrayExp = GetArray(); var newCollection = ArrayExp.ToList().Select(x => RedefineObject(x, "Id")); } static object[] GetArray() { var person1 = new { Name = "name", Id = 1 }; var person2 = new { Name = "name", Id = 2 }; var person3 = new { Name = "name", Id = 3 }; return new[] { person1, person2, person3 }; } static object RedefineObject(object obj, string propertyToRemove) { var properties = obj.GetType().GetProperties().Where(x => x.Name != propertyToRemove); var dict = new Dictionary(); var eobj = new ExpandoObject(); var eoColl = (ICollection>)eobj; properties.ToList().ForEach(x => dict.Add(x.Name, x.GetValue(obj))); dynamic dynObj = dict; return dynObj; } ``` Upvotes: 0
2018/03/16
497
1,621
<issue_start>username_0: How can I search for the types of `length, take, drop, splitAt, !!` and `replicate` all in one go, without entering in `:t length`, `:t take`, `:t drop`, etc, for all of these functions?<issue_comment>username_1: ghci includes a `:def` command. The command has the form `:def` , where is the new command to define, and is a Haskell function of type `String -> IO String` saying how to convert arguments to the new command into an existing chain of commands. We can use this to our advantage: we'll make a new command, `:manyt`, which takes a list of names and runs `:t` on each. For simplicity, I'll split on spaces; but if you want to ask for the types of many *expressions* rather than just names you may want to do some more complicated delimiting/parsing. So, in `~/.ghci`, add a line like this: ``` :def manyt (\s -> Prelude.return (Prelude.unlines [":t " Prelude.++ n | n <- Prelude.words s])) ``` (The excessive `Prelude` qualification is so that this works even when `-XNoImplicitPrelude` is enabled.) Try it out: ``` > :manyt length take drop splitAt (!!) replicate length :: Foldable t => t a -> Int take :: Int -> [a] -> [a] drop :: Int -> [a] -> [a] splitAt :: Int -> [a] -> ([a], [a]) (!!) :: [a] -> Int -> a replicate :: Int -> a -> [a] ``` Upvotes: 4 <issue_comment>username_2: Is it too simple to suggest searching the type of a tuple or these functions? ``` Prelude> :t (length, take, drop, splitAt) (length, take, drop, splitAt) :: Foldable t => (t a1 -> Int, Int -> [a2] -> [a2], Int -> [a3] -> [a3], Int -> [a4] -> ([a4], [a4])) Prelude> ``` Upvotes: 0
2018/03/16
1,128
3,696
<issue_start>username_0: As a programmer you always have the choice to add methods to a class or creating the same method which takes a class instance of that object as an argument. One way of doing it is like this: ``` List Oldtimers = new List(); class Car { int speed; int size; public bool IsBig(){ return size >5; } public bool isFast(){ return speed > 120; } } ``` Or you could also try to save space like that ``` class CarCollection { List Supercars = new List(); class Car2{ public int speed; public int size; } bool IsBig(Car2 car){ return car.size > 5 } bool isFast(Car2 car){ return car.speed > 120; } } ``` Does a Car2 instance now actually take up less space than Car, because there are no methods attached to it? Which List is better? Is there even a difference in the bytecode? I would also like to know what the standard is, or if there are some performance issues that I did not see. Thanks for your help!<issue_comment>username_1: > > Does a Car2 instance now actually take up less space than Car, b > > > No. Each instance has a pointer to its Type, and some other information attached to it. But that overhead is fixed, even when virtual methods are used. Only fields take up space inside your instances. Upvotes: 3 [selected_answer]<issue_comment>username_2: If you really need to save bytes per instance you can switch to a list of structs that store the data and have a manager class that accesses the data like in your example. The tricky part is when cars are removed. You could also look at using smaller numeric types like short or byte. Here is an example: ``` public struct CarHandle { internal int m_id; internal CarHandle(int id) { m_id = id; } public int ID { get { return m_id; } } } public class CarManager { private struct CarData { public int Speed; public int Size; } private List m\_cars = new List(); private List m\_removedCars = new List(); public CarHandle CreateCar(int speed, int size) { var carData = new CarData() { Speed = speed, Size = size }; // see if there is an empty slot we can use if (m\_removedCars.Count > 0) { int ix = m\_removedCars[m\_removedCars.Count - 1]; m\_removedCars.RemoveAt(m\_removedCars.Count - 1); m\_cars[ix] = carData; return new CarHandle(ix); } else { m\_cars.Add(carData); return new CarHandle(m\_cars.Count-1); } } public void RemoveCar(ref CarHandle handle) { if (m\_cars.Count > handle.ID && m\_cars[handle.ID].Size != -1) { // remove from list if it is the last car in list if (handle.ID == m\_cars.Count - 1) { m\_cars.RemoveAt(m\_cars.Count - 1); } else { // if we remove this item from the list, it would invalidate // all handles after this index, so we just remember that we // can reuse this slot m\_removedCars.Add(handle.ID); m\_cars[handle.ID] = new CarData() { Size = -1, Speed = -1 }; } } // invalidate the handle so it cannot be used again handle.m\_id = -1; } public int GetSize(CarHandle handle) { // TODO: add error checking! return m\_cars[handle.ID].Size; } } class Program { static void Main(string[] args) { CarManager manager = new CarManager(); var car1 = manager.CreateCar(10, 20); var s1 = manager.GetSize(car1); System.Diagnostics.Debug.Assert(s1 == 20); var car2 = manager.CreateCar(30, 40); var s2 = manager.GetSize(car2); System.Diagnostics.Debug.Assert(s2 == 40); manager.RemoveCar(ref car1); System.Diagnostics.Debug.Assert(car1.ID == -1); s2 = manager.GetSize(car2); var car3 = manager.CreateCar(50, 60); var s3 = manager.GetSize(car3); System.Diagnostics.Debug.Assert(s3 == 60); } } ``` Upvotes: 0
2018/03/16
892
3,756
<issue_start>username_0: I am new to polymer. Currently I am stuck at a step which I don't know how to solve. Suppose I have an **index.html** in which I have used two components: and . The table uses a parameter `items` that holds the content of the table. And basically searches from DB based on some search criteria. Now how to update the `item` parameter of the from inside the element. I hope that I have made myself clear. If not, then please ask me . Thank you<issue_comment>username_1: There's different paradigms in which you could take this problem. One common paradigm is to keep 1-way data flow (known as data down, actions up), which is idiomatic to frameworks like React. Polymer can handle two-way binding, so you could also handle it this way. I would 1. Make a parent container that holds both your search and your table elements. 2. Keep track of the current item that was searched upon in your parent container as a property 3. Have a method that updates that current item property that takes in a parameter that represents the item the user selected 4. Pass this method as a property into your table component 5. Use iron-ajax component to fetch your data and assign the result to your items parameter Use another iron-ajax that takes in your search URL with a parameter 6. Attach an onClick handler to the items in your table and have it call the method you defined earlier and use the item as an argument 7. When the current item property on the parent component updates, this will trigger the iron-ajax to refetch the search query with the new item. when the new data comes up, it will automatically propagate that down to the search component, which should automatically update itself. This is an example of the data down/actions up paradigm using a higher-order-component. that is your parent component in this case. it is coordinating the updating/flow of the other 2 components. I added a [plunkr](http://plnkr.co/edit/ewqokw?p=preview) so you can also see an example of polymer's 2-way binding. The main difference between this and the instructions above is that we are not passing any methods down from the parent to the children for the children to call. Instead we are enabling the data bindings to be bi-directional, which means that if the child updates a passed down property, the change will automatically propagate up without you having to intervene. You make a prop double bound by using the curly braces and not the bracket braces and in the property definitions of the child, set the `notify` property to true. Which way you choose to go is up to you and your team. Some teams find that 2-way binding is difficult to reason about because it could be hard with deeply nested components to discover who changed a property. Passing down an action to deeply nested components in my opinion can also be confusing, so I am not necessarily against 2-way binding, which also got a bad name because early implementations of it in other frameworks had performance issues, but Polymer's in my experience does not. Upvotes: 3 [selected_answer]<issue_comment>username_2: You can alternatively make use of events to pass the data, answer given by Trey is also correct and his suggestion is apt. You should use parent component do all that hard work. However if you still wish to continue in the manner you have gone so far I suggest you use events to pass the data, ``` handleIncomingData(e) { this.dispatchEvent(new CustomEvent('kick', {detail: {ajaxData: yourAjaxData}})); } ``` this snippet is adopted from the polymer site itself, make sure you pass the data using the detail property of the event. Refer this link, ``` https://www.polymer-project.org/2.0/docs/devguide/events ``` Upvotes: 1
2018/03/16
832
2,632
<issue_start>username_0: I have an application with tens of signal slot connections, in particular multiple classes (with decomposition) are implementing almost identical `QObject::connect` signals to slots, the problem I am facing is sometimes, in QtCreator *Application Output*, I get the usual error: > > QObject::connect: Cannot connect > (null)::SessionClosed() to > mainWindow\_Desktop::stop\_Scanning() > > > But it lacks any indication from which file/line or code segment the error is coming from and the expense of that is I have to check all similar connections to detect which one went in error! my question is: I**s there any way to directly know the file/line the error refers to**?<issue_comment>username_1: Set breakpoints on `QMessageLogger::warning`, `QMessageLogger::critical` etc.. Then you'll have your application stopped on such messages by `qWarning`, `qCritical` etc. from Qt, and call stack will tell you where they originate. Example code: ``` #include void f() { QObject::connect(0,"kkk",0,"aaa"); } int main() { f(); } ``` After compiling, when I run it with GDB, I get: ```none $ gdb -ex 'set breakpoint pending on' -ex 'b QMessageLogger::warning' \ -ex r -ex bt ./test Reading symbols from ./test...done. Function "QMessageLogger::warning" not defined. Breakpoint 1 (QMessageLogger::warning) pending. Starting program: /tmp/test/test [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Breakpoint 1, QMessageLogger::warning (this=this@entry=0x7fffffffd2e0, msg=msg@entry=0x7ffff7c3ac80 "QObject::connect: Cannot connect %s::%s to %s::%s") at global/qlogging.cpp:541 541 { #0 QMessageLogger::warning (this=this@entry=0x7fffffffd2e0, msg=msg@entry=0x7ffff7c3ac80 "QObject::connect: Cannot connect %s::%s to %s::%s") at global/qlogging.cpp:541 #1 0x00007ffff7b64a4d in QObject::connect (sender=0x0, signal=0x400838 "kkk", receiver=, method=, type=) at kernel/qobject.cpp:2618 #2 0x0000000000400788 in f () at test.cpp:5 #3 0x00000000004007a0 in main () at test.cpp:10 ``` Here we can see that the bad call to `connect` occurs in `test.cpp:5` in `f()`. Upvotes: 2 <issue_comment>username_2: `QMetaObject::Connection QObject::connect()` has a return value, which comes with an implicit bool conversion operator, so you can simply test whether it succeeded with an `if` statement and if necessary issue a warning that can tell you where it happens if verbose warnings are enabled. Naturally you can manually use the `__FILE__`, `__LINE__` and `__FUNCTION__` macros yourself. Upvotes: 3 [selected_answer]
2018/03/16
606
1,754
<issue_start>username_0: I'm trying to write RegEX to match all eventtypes in next string (should end with whitespace character or bracket. ``` (STUNNEL-SECURITY AND NOT ( eventtype=sec-stunnel-client-* OR eventtype=sec-stunnel-crl-* OR eventtype=sec-stunnel-loaded-* OR eventtype=sec-stunnel-loading-* OR eventtype=sec-stunnel-no-* OR eventtype=sec-stunnel-openssl-* OR eventtype=sec-stunnel-sconnect-* OR eventtype=sec-stunnel-server-* OR eventtype=sec-stunnel-service-* OR eventtype=sec-stunnel-session-* OR eventtype=sec-stunnel-socket-* OR eventtype=sec-stunnel-ssl-* OR eventtype=sec-stunnel-stats-* OR eventtype=sec-stunnel-threading-* OR eventtype=sec-stunnel-timeout-* OR eventtype=sec-stunnel-various-* ) ) ``` I need to get array of all matches, eg. `array("sec-stunnel-client-*", "sec-stunnel-crl-*", "sec-stunnel-loaded-*"...)`. How this should be done?<issue_comment>username_1: Try this regex: ``` (?<=eventtype=)\S* ``` It looks for non-whitespace characters preceded by `eventtype=`. Try it online [here](https://regex101.com/r/VFJnhP/1). Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use `\K` instead of positive lookahead `(?<=)` far less steps. **Regex**: [`eventtype=\K\S+`](https://regex101.com/r/XXUgbk/1) Details: * `\K` Resets the starting point of the reported match * `\S+` Matches any non-whitespace character between one and unlimited times **PHP code**: ``` preg_match_all("~eventtype=\K\S+~", $str, $matches); ``` Output: ``` Array ( [0] => sec-stunnel-client-* [1] => sec-stunnel-crl-* [2] => sec-stunnel-loaded-* [3] => sec-stunnel-loading-* [4] => sec-stunnel-no-* ... ) ``` [Code demo](https://ideone.com/rnJO8j) Upvotes: 1
2018/03/16
872
3,194
<issue_start>username_0: I'm developing a small Ruby on Rails application for a small shop which sells used cars. The site contains a list with all avalaible cars including an image of the car. There are at maximum 20 cars in the shop. I read that it is not the best practice to save images directly in the database and it's better to store the files with a cloud storage service like Amazon Web Services, but I don't think that a service like this is necessary for a small website with a maximum of 20 images at a time. My idea is to save the images in `/app/assets/images`. Employees will upload information and images of the cars through a form. Is it possible to upload and save images in the folder `/app/assets/images` through a form in Rails?<issue_comment>username_1: > > Is it possible to upload and save images in the folder `/app/assets/images` through a form in Rails? > > > Possible, but shouldn't be done. `/app/assets/images` is for your app assets. They're processed on deployment (fingerprinted, etc.). You don't need this treatment for user files. User uploads normally go somewhere in `/public`. For example, `/public/uploads/images`. > > but I don't think that a service like this is necessary for a small website with a maximum of 20 images at a time > > > Amazon S3 has a free tier. Your 20 images will surely fit there. Yes, it's a bit complicated to set up, but it *is* a best practice. Upvotes: 3 [selected_answer]<issue_comment>username_2: > > As @Sergio already mentioned about assets folder and AWS S3 service. > > > AWS is good, But limited only for 1 year free tier and upto 5GB. Alternate solution for cloud image storage is [Cloudinary](https://cloudinary.com). It's lifetime free <10GB, bandwidth included, [Link: How to use in Rails samples](https://cloudinary.com/documentation/rails_integration) *Also Cloudinary uses AWS(S3) services, behind the scene!* ``` #Gemfile gem 'cloudinary' gem 'carrierwave' # config/initializers/cloudinary.rb, if not exist create the file # make sure to fill api keys!!! Cloudinary.config do |config| config.cloud_name = .... config.api_key = .... config.api_secret = .... config.cdn_subdomain = false end # model/image.rb in my case. class Image < ActiveRecord::Base mount_uploader :image, ImageUploader end # app/uploaders/image_uploader.rb class ImageUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick include CarrierWave::ImageOptimizer include Cloudinary::CarrierWave process :convert => 'png' # process :tags => ['team_registration'] # process :resize_to_fill => [300, 300, :north] def store_dir # "images/#{model.class.to_s.underscore}/#{model.team_name}" "images/car_images/" end def public_id "yr_domain_name_here/car_images/#{model.team_name}" end def cache_dir "/tmp/cache/#{model.class.to_s.underscore}" end def filename "#{model.team_name}_#{model.game.title}" + ".png" if original_filename.present? end def content_type_whitelist /image\// end def extension_white_list %w(jpg jpeg gif png) end end ``` Upvotes: 2
2018/03/16
828
2,506
<issue_start>username_0: I would like to know how long it takes to process a certain list. ``` for a in tqdm(list1): if a in list2: #do something ``` but this doesnt work. If I use `for a in tqdm(range(list1))` i wont be able to retrieve the list values. Do you know how do do it?<issue_comment>username_1: ``` import tqdm for p in tqdm.tqdm([10,50]): print(p) ``` or ``` from tqdm import tqdm for p in tqdm([10,50]): print(p) ``` Upvotes: 5 <issue_comment>username_2: I had also this problem. In my case I wrote: ``` import tqdm ``` instead ``` from tqdm import tqdm ``` Upvotes: 3 <issue_comment>username_3: List is a list of elements in it, hence if you do `len(ls)`, it gives you number of elements in the list. `range` builtin function will iterate over the range, hence following for loop should work for `tqdm` ``` from tqdm import tqdm ls = [i for i in range(0,20000000)] for i in tqdm(range(len(ls))): ## code goes here ## pass ``` Upvotes: 0 <issue_comment>username_4: I've written so many answers because I personally have used all these at different places in my mini-projects and projects. Some may be irrelevant according to question, but will be useful elsewhere. ``` list1 = list(range(100)) import tqdm for x in tqdm.tqdm(list1): sleep(0.01) ``` Or ``` tlist1 = tqdm.tqdm(list1) for x in tlist1: sleep(0.01) ``` Basically, you are passing the list to create a tqdm instance. You can use another workaround as in [tqdm documentation](https://github.com/tqdm/tqdm): ``` # DOESN't work well in terminal, but should be ok in Jupyter Notebook with tqdm.tqdm(total=len(list1)) as t: for x in list1: sleep(0.01) t.update(1) ``` Using generators with manual update of trange object: ``` def literate(list1): t = trange(len(list1)) for x in list1: t.update(1) yield x for x in literate(list1): sleep(0.01) ``` With automatic update: ``` def li_iterate(li): l = iter(li) for _ in trange(len(li)): yield next(l) for x in li_iterate(list1): sleep(0.01) ``` Apart from the question, if you are using pandas dataframe, you may want to use this sometime (in google-colaboratory): ``` # %% implies cell magic in google-colab %%capture from tqdm.notebook import tqdm as tq tq().pandas() def fn(x): for a in list2: print(x, a) import pandas as pd list1 = list(range(0, 9)) pd.DataFrame(data=list1).progress_apply(fn) ``` -*Himanshu* Upvotes: 2
2018/03/16
1,089
3,605
<issue_start>username_0: I was wondering if I could grab a StartDate and an EndDate from a database table instead of assigning the StartDate and EndDate parameters as shown below? I already have the dates in another table. I need to get the data between those two dates. ``` DECLARE @StartDate datetime = '1/4/2015' DECLARE @EndDate datetime = '5/20/2015' ``` Is it possible to do this?<issue_comment>username_1: If you want to get the dates from another table just use ``` DECLARE @StartDate DATETIME DECLARE @EndDate DATETIME SELECT @StartDate = NameOfStartDateColumn, @EndDate = NameOfEndDateColumn FROM TableName ``` And as mentioned in the comments if TableName contains more than 1 row you can add a WHERE clause onto the above to select the row you are after. Upvotes: 2 <issue_comment>username_2: Assign the values to the variable in a `SELECT` statement: ``` DECLARE @MyVar DATETIME; SELECT @MyVar = MyDateTimeColumn FROM MyTable WHERE ...; ``` Be aware, that only one value will be assigned to the variable, make sure, that your select statement returns only one record to prevent unpredictable results! You can of course assign an aggregated value to the variable, such as the result of a MIN/MAX/SUM/etc function: ``` SELECT @MyVar = MAX(MyDateTimeColumn) FROM MyTable; ``` In this case, I would highly recommend to provide a default value in case there is no result returned: ``` SELECT @MyVar = ISNULL(MAX(MyDateTimeColumn), '2200-01-01') FROM MyTable; ``` You can assign values to multiple variables in one query, but you have to assign all columns to a variable: ``` SELECT @MyVarMin = ISNULL(MIN(MyDateTimeColumn), '1900-01-01') , @MyVarMax = ISNULL(MAX(MyDateTimeColumn), '2200-01-01') FROM MyTable; ``` Now, to validate, that you have the correct value: ``` SELECT @MyVar; ``` You can use your variable in any subsequent queries as usual. You can also join your source table to the parameter table, the actual solution depends on your data model and on what you want to achieve. Upvotes: 0 <issue_comment>username_3: My understanding is, you have one table with data, which contains one column of type `datetime` and another table that contains the desired date range, e.g.: ``` CREATE TABLE [dbo].[Dates]( [StartDate] [datetime] NULL, [EndDate] [datetime] NULL ) ON [PRIMARY] ``` And now you want to select data from your data table (let's call it `MyData`) which is in the range defined by the entries in your `Dates` table, right? Then you can just make a subselect ``` SELECT * FROM [TEST].[dbo].[MyData] WHERE Date between (SELECT BeginDate FROM dbo.dates) and (SELECT EndDate FROM dbo.dates) ``` Upvotes: 0 <issue_comment>username_4: Demo Note you will get the last date read and there is no natural order so you need a unique sort to get a good assignment. ``` declare @dates table(iden int identity primary key, d1 datetime, d2 datetime) insert into @dates values ('1/1/1910', '1/2/1910'), ('1/1/1915', '1/2/1915'); DECLARE @StartDate DATETIME = (select top (1) d.d1 from @dates d); DECLARE @EndDate DATETIME; SELECT @StartDate = d.d1, @EndDate = d.d2 FROM @dates d; select @StartDate, @EndDate SELECT top (1) @StartDate = d.d1, @EndDate = d.d2 FROM @dates d order by d.iden; select @StartDate, @EndDate ----------------------- ----------------------- 1915-01-01 00:00:00.000 1915-01-02 00:00:00.000 ----------------------- ----------------------- 1910-01-01 00:00:00.000 1910-01-02 00:00:00.000 ``` In the declare line you need to use ( ) and only return 1 Upvotes: 2 [selected_answer]
2018/03/16
1,101
3,660
<issue_start>username_0: I have two pages, **"Home-Page"** and **"Landing-Page"**. I want to modify the *"Landing-Page"* content based on which button you clicked from the previous page *(That previous page being the "Home-Page")*. I attempted to use anchor tags, but because that method relies on being client-side only, it make it difficult to work 100% of the time. Does anyone have any better options I could try in **Jquery**? Thanks again, Charlie<issue_comment>username_1: If you want to get the dates from another table just use ``` DECLARE @StartDate DATETIME DECLARE @EndDate DATETIME SELECT @StartDate = NameOfStartDateColumn, @EndDate = NameOfEndDateColumn FROM TableName ``` And as mentioned in the comments if TableName contains more than 1 row you can add a WHERE clause onto the above to select the row you are after. Upvotes: 2 <issue_comment>username_2: Assign the values to the variable in a `SELECT` statement: ``` DECLARE @MyVar DATETIME; SELECT @MyVar = MyDateTimeColumn FROM MyTable WHERE ...; ``` Be aware, that only one value will be assigned to the variable, make sure, that your select statement returns only one record to prevent unpredictable results! You can of course assign an aggregated value to the variable, such as the result of a MIN/MAX/SUM/etc function: ``` SELECT @MyVar = MAX(MyDateTimeColumn) FROM MyTable; ``` In this case, I would highly recommend to provide a default value in case there is no result returned: ``` SELECT @MyVar = ISNULL(MAX(MyDateTimeColumn), '2200-01-01') FROM MyTable; ``` You can assign values to multiple variables in one query, but you have to assign all columns to a variable: ``` SELECT @MyVarMin = ISNULL(MIN(MyDateTimeColumn), '1900-01-01') , @MyVarMax = ISNULL(MAX(MyDateTimeColumn), '2200-01-01') FROM MyTable; ``` Now, to validate, that you have the correct value: ``` SELECT @MyVar; ``` You can use your variable in any subsequent queries as usual. You can also join your source table to the parameter table, the actual solution depends on your data model and on what you want to achieve. Upvotes: 0 <issue_comment>username_3: My understanding is, you have one table with data, which contains one column of type `datetime` and another table that contains the desired date range, e.g.: ``` CREATE TABLE [dbo].[Dates]( [StartDate] [datetime] NULL, [EndDate] [datetime] NULL ) ON [PRIMARY] ``` And now you want to select data from your data table (let's call it `MyData`) which is in the range defined by the entries in your `Dates` table, right? Then you can just make a subselect ``` SELECT * FROM [TEST].[dbo].[MyData] WHERE Date between (SELECT BeginDate FROM dbo.dates) and (SELECT EndDate FROM dbo.dates) ``` Upvotes: 0 <issue_comment>username_4: Demo Note you will get the last date read and there is no natural order so you need a unique sort to get a good assignment. ``` declare @dates table(iden int identity primary key, d1 datetime, d2 datetime) insert into @dates values ('1/1/1910', '1/2/1910'), ('1/1/1915', '1/2/1915'); DECLARE @StartDate DATETIME = (select top (1) d.d1 from @dates d); DECLARE @EndDate DATETIME; SELECT @StartDate = d.d1, @EndDate = d.d2 FROM @dates d; select @StartDate, @EndDate SELECT top (1) @StartDate = d.d1, @EndDate = d.d2 FROM @dates d order by d.iden; select @StartDate, @EndDate ----------------------- ----------------------- 1915-01-01 00:00:00.000 1915-01-02 00:00:00.000 ----------------------- ----------------------- 1910-01-01 00:00:00.000 1910-01-02 00:00:00.000 ``` In the declare line you need to use ( ) and only return 1 Upvotes: 2 [selected_answer]
2018/03/16
1,203
3,867
<issue_start>username_0: I have following log string and I need to get from them only `MedSoftware` part, which means * after `.com\` * before first occurence of `\` > > SERVERNAME2018-03-08 18:40:28 File: "x:\_default\app.address.com\MedSoftware.data\BackEnd.Technical.Dictionaries.Service-180308182311\Web.config", Name: "dictionaries\_data\_product", CS: "###connectionStrings.dictionariesdataproduct.connectionString" info: Format of the initialization string does not conform to specification starting at index 0. 6069 > > > Now my regex looks like this: ``` ((?<=.com\\).*(?=\\)) ``` and catches all after `.com` but goes to LAST occurence of `\`<issue_comment>username_1: If you want to get the dates from another table just use ``` DECLARE @StartDate DATETIME DECLARE @EndDate DATETIME SELECT @StartDate = NameOfStartDateColumn, @EndDate = NameOfEndDateColumn FROM TableName ``` And as mentioned in the comments if TableName contains more than 1 row you can add a WHERE clause onto the above to select the row you are after. Upvotes: 2 <issue_comment>username_2: Assign the values to the variable in a `SELECT` statement: ``` DECLARE @MyVar DATETIME; SELECT @MyVar = MyDateTimeColumn FROM MyTable WHERE ...; ``` Be aware, that only one value will be assigned to the variable, make sure, that your select statement returns only one record to prevent unpredictable results! You can of course assign an aggregated value to the variable, such as the result of a MIN/MAX/SUM/etc function: ``` SELECT @MyVar = MAX(MyDateTimeColumn) FROM MyTable; ``` In this case, I would highly recommend to provide a default value in case there is no result returned: ``` SELECT @MyVar = ISNULL(MAX(MyDateTimeColumn), '2200-01-01') FROM MyTable; ``` You can assign values to multiple variables in one query, but you have to assign all columns to a variable: ``` SELECT @MyVarMin = ISNULL(MIN(MyDateTimeColumn), '1900-01-01') , @MyVarMax = ISNULL(MAX(MyDateTimeColumn), '2200-01-01') FROM MyTable; ``` Now, to validate, that you have the correct value: ``` SELECT @MyVar; ``` You can use your variable in any subsequent queries as usual. You can also join your source table to the parameter table, the actual solution depends on your data model and on what you want to achieve. Upvotes: 0 <issue_comment>username_3: My understanding is, you have one table with data, which contains one column of type `datetime` and another table that contains the desired date range, e.g.: ``` CREATE TABLE [dbo].[Dates]( [StartDate] [datetime] NULL, [EndDate] [datetime] NULL ) ON [PRIMARY] ``` And now you want to select data from your data table (let's call it `MyData`) which is in the range defined by the entries in your `Dates` table, right? Then you can just make a subselect ``` SELECT * FROM [TEST].[dbo].[MyData] WHERE Date between (SELECT BeginDate FROM dbo.dates) and (SELECT EndDate FROM dbo.dates) ``` Upvotes: 0 <issue_comment>username_4: Demo Note you will get the last date read and there is no natural order so you need a unique sort to get a good assignment. ``` declare @dates table(iden int identity primary key, d1 datetime, d2 datetime) insert into @dates values ('1/1/1910', '1/2/1910'), ('1/1/1915', '1/2/1915'); DECLARE @StartDate DATETIME = (select top (1) d.d1 from @dates d); DECLARE @EndDate DATETIME; SELECT @StartDate = d.d1, @EndDate = d.d2 FROM @dates d; select @StartDate, @EndDate SELECT top (1) @StartDate = d.d1, @EndDate = d.d2 FROM @dates d order by d.iden; select @StartDate, @EndDate ----------------------- ----------------------- 1915-01-01 00:00:00.000 1915-01-02 00:00:00.000 ----------------------- ----------------------- 1910-01-01 00:00:00.000 1910-01-02 00:00:00.000 ``` In the declare line you need to use ( ) and only return 1 Upvotes: 2 [selected_answer]
2018/03/16
730
1,825
<issue_start>username_0: I have this code on my html ``` Date issued: {{orderPrint.orderDetails.received\_date | date : "medium"}} ``` It displays something like this: Date: Mar 16, 2018 7:39:08 PM I want to display Date: Mar 16, 2023 7:39:08 PM. how can I do that?<issue_comment>username_1: > > We can do this using setYear() in Date. > > > For eg. ``` var myDate = new Date(); ``` and +1 to add a year in current date. ``` myDate.setYear(userdob.getFullYear() + 1); ``` In your case, just update your date value as below. ``` var updatedYear = orderPrint.orderDetails.received_date.getFullYear() + 5; orderPrint.orderDetails.received_date.setYear(updatedYear); ``` Upvotes: 2 <issue_comment>username_2: Usage In HTML Template Binding: ``` {{ date_expression | date : format : timezone}} ``` Example: ``` {{1288323623006 | date:'medium'}}: {{1288323623006 | date:'medium'}} {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}} {{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}} {{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}: {{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}} ``` For more details: <https://docs.angularjs.org/api/ng/filter/date> Upvotes: 0 <issue_comment>username_3: If you want to add timezone then use this new Date().toLocaleString("en-US", {timeZone: "America/Los\_Angeles"}) if you want to just add year/month/time in date. then follow this steps step 1- first need to parse date. use var a = data.parse(new date()); step 2 - a = a + (365\*24\*60\*60\*1000) Upvotes: 0 <issue_comment>username_4: if you want to add year follow this javascript ``` var dat=new Date(); var y=dat.getFullYear()+5; dat.setFullYear(y); ``` and amol bhor also fine. Upvotes: 0
2018/03/16
381
1,281
<issue_start>username_0: I'm trying to read a downloaded html-file ```perl6 my $file = "sn.html"; my $in_fh = open $file, :r; my $text = $in_fh.slurp; ``` and I get the following error message: ```perl6 Malformed UTF-8 in block at prog.p6 line 10 ``` How to avoid this and get access to the file's contents?<issue_comment>username_1: If you do not specify an encoding when opening a file, it will assume `utf8`. Apparently, the file that you wish to open, contains bytes that cannot be interpreted as UTF-8. Hence the error message. Depending on what you want to do with the file contents, you could either set the `:bin` named parameter, to have the file opened in binary mode. Or you could use the special `utf8-c8` encoding, which will assume UTF-8 until it encounters bytes it cannot encode: in that case it will generate temporary code points. See <https://docs.raku.org/language/unicode#UTF8-C8> for more information. Upvotes: 5 [selected_answer]<issue_comment>username_2: For slurp, if you have some idea about encoding, you can also add encoding specifically. From documentation (`https://docs.perl6.org/routine/slurp`): ``` my $text_contents = slurp "path/to/file", enc => "latin1"; ``` I used it today for a stupid file encoded in ISO-8859-1. Upvotes: 2
2018/03/16
989
3,552
<issue_start>username_0: I have this issue. I using Woocommerce 3.3.3 in this moment in my site and noticed one weird issue. After customer placed order, their order is stuck on "On Hold" into Woocommerce orders. [![on hold status](https://i.stack.imgur.com/8QBfY.png)](https://i.stack.imgur.com/8QBfY.png) and customer dont get any order confirmation mail. When go to order and move status on order from "On Hold" to "Processing" customer is getting Order Confirmation mail, that should be automatically. Searched, and found this "[fix](https://github.com/woocommerce/woocommerce/issues/16617)": ``` add_filter( ‘woocommerce_defer_transactional_emails’, ‘__return_false’ ); ``` to be placed into functions.php, but seems that dont changed nothing. Anyone with similar issue?<issue_comment>username_1: Try the following instead: ``` add_action('woocommerce_new_order', 'new_order_on_hold_notification', 30, 1 ); function new_order_on_hold_notification( $order_id ) { $order = wc_get_order( $order_id ); // Only for on hold new orders if( ! $order->has_status('on-hold') ) return; // Exit // Send Customer On-Hold Order notification WC()->mailer()->get_emails()['WC_Email_Customer_On_Hold_Order']->trigger( $order_id ); } ``` To change "on-hold" paid orders to "processing" use that: ``` add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_prrocessing_paid_order', 10, 1 ); function custom_woocommerce_auto_prrocessing_paid_order( $order_id ) { if ( ! $order_id ) return; $order = wc_get_order( $order_id ); // No updated status for orders delivered with Bank wire, Cash on delivery and Cheque payment methods. if ( in_array( $order->get_payment_method(), array( 'bacs', 'cod', 'cheque', '' ) ) ) { return; } // "Processing" updated status for paid Orders with all others payment methods else { if( $order->has_status('on-hold') ) $order->update_status( 'processing' ); } } ``` Code goes in function.php file of your active child theme (or active theme). It should work. Upvotes: 2 [selected_answer]<issue_comment>username_2: Just to point out: The solution @username_1 mentioned works: ``` add_action('woocommerce_new_order', 'new_order_on_hold_notification', 30, 1 ); function new_order_on_hold_notification( $order_id ) { $order = wc_get_order( $order_id ); // Only for on hold new orders if( ! $order->has_status('on-hold') ) return; // Exit // Send Customer On-Hold Order notification WC()->mailer()->get_emails()['WC_Email_Customer_On_Hold_Order']->trigger( $order_id ); } ``` However there's an issue with this solution, at the time `woocommerce_new_order`hook is called the order hasn't been fully created yet, so as result in the email notification the order items are not displayed. Use the following hook instead: ``` add_action('woocommerce_checkout_order_processed', 'new_order_on_hold_notification'); function new_order_on_hold_notification( $order_id ) { $order = wc_get_order( $order_id ); // Only for on hold new orders if( ! $order->has_status('on-hold') ) return; // Exit // Send Customer On-Hold Order notification WC()->mailer()->get_emails()['WC_Email_Customer_On_Hold_Order']->trigger( $order_id ); } ``` At the time `woocommerce_checkout_order_processed` is called the order items are already available for your email. Upvotes: 0
2018/03/16
497
1,581
<issue_start>username_0: I am facing with this exception when I using `libgdx` in Java: ``` Exception in thread "Thread-12" java.lang.RuntimeException: No OpenGL context found in the current thread. at org.lwjgl.opengl.GLContext.getCapabilities(GLContext.java:124) at org.lwjgl.opengl.GL11.glGenTextures(GL11.java:1403) at com.badlogic.gdx.backends.lwjgl.LwjglGL20.glGenTexture(LwjglGL20.java:348) at com.badlogic.gdx.graphics.Texture.(Texture.java:120) at com.badlogic.gdx.graphics.Texture.(Texture.java:100) at com.badlogic.gdx.graphics.Texture.(Texture.java:92) at com.badlogic.gdx.graphics.Texture.(Texture.java:88) at Utils.Player$2.run(Player.java:79) at java.lang.Thread.run(Thread.java:748) ``` How can i solve this? I'm using libgdx. line 79 of Player.java: ``` TextureRegion textureRegion = new TextureRegion(new Texture("textures/Textures.png"), 50, 15, 4, 4); ```<issue_comment>username_1: You should not use Thread in libgdx actually, it is not recommended to use Thread. Html does not support threading and it will not work at Html. If you must use threading use, ``` Gdx.app.postRunnable(new Runnable() { @Override public void run() { // process the result, e.g. add it to an Array field of the ApplicationListener. results.add(result); } }); ``` To understand what is going on here, check it official document <https://github.com/libgdx/libgdx/wiki/Threading> Upvotes: 3 <issue_comment>username_2: In Kotlin: ``` Gdx.app.postRunnable { // Your code in the context of OpenGL } ``` Upvotes: -1
2018/03/16
409
1,492
<issue_start>username_0: I have two lists ``` class FirstElement { private int id; private String name; } class SecondElement { private int id; private String someString; } List listF = getListOfSomeElements1(); List listS = getListOfSomeElements2(); ``` I need to find element in `listF` if properties name=someString If I need to find by corresponding of elements, i use for example: ``` if(listF.contains(listS.get(1))){...} ``` I use own method ``` boolean compareProperties(List firstList, SecondElement secondElement){ for(FirstElement firstElement:firstList){ if (firstElement.getName().equals(secondElement.getSomestring)){ return true; } } return false; } ``` how to remove my method with Stream?<issue_comment>username_1: You can filter the stream by the field that you need Upvotes: 0 <issue_comment>username_2: If you want to convert your current method into a stream version then you can use `anyMatch`. ``` boolean exists = listF.stream() .anyMatch(e -> e.getName().equals(secondElement.getSomestring)); ``` If you want to find the first element that satisfies the provided criteria then you can do: ``` Optional firstElement = listF.stream() .filter(e -> e.getName().equals(secondElement.getSomestring)) .findFirst(); ``` There are various ways to unwrap an `Optional` which can be found [here](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html). Upvotes: 2 [selected_answer]
2018/03/16
380
1,194
<issue_start>username_0: As you can see below, the svg icons are broken when opened in chrome. (The icon does not display in firefox) Software: FreeNas Jail - FreeBSD 11.1 Release Apache 2.4 NextCloud 13.0.0 [![Screenshot](https://i.stack.imgur.com/yUOfk.png)](https://i.stack.imgur.com/yUOfk.png)<issue_comment>username_1: 1. update to [NextCloud 13.0.1](https://nextcloud.com/changelog/) since this is the latest version of it now. 2. if the bug still exists create an issue in the [github nextcloud server repository](https://github.com/nextcloud/server). Upvotes: 0 <issue_comment>username_2: Apparently, this issue had to do with the nextcloud configuration. As the nextcloud is running behind proxy, the images are being sent from http to https causing a mixed content warning in the browser. In order to solve this issue, it is necessary to edit the nextcloud configuration as such. ``` 'trusted_proxies' => array ( 0 => '555.555.555.555', ), 'overwriteprotocol' => 'https', 'overwrite.cli.url' => 'https://my.domain.tld', 'overwritecondaddr' => '^555\\.555\\.555\\.555$', ``` 555.555.555.555 is the internal ip address of your proxy server. Upvotes: 2 [selected_answer]