text
stringlengths
15
59.8k
meta
dict
Q: Combine two codes into one - check if url exist / login I have written a code to relink depending on the user input (token). For example: if the user inserts 1234, and presses enter or presses the button login. The website will redirect to: example.com/login/1234. Now I want to combine it with a url check. So if the url doesn't exist, they receive a message that the token is not valid, instead of a 404 error. This is the valid code for the login: var input = document.getElementById("token"); input.addEventListener("keyup", function(event) { if (event.keyCode === 13) { event.preventDefault(); document.getElementById("loginenter").click(); } }); function changeQuery(){ var input_query = document.getElementById('token').value; window.parent.location = "https://www.example.com/login/" + input_query; } And this is the check for a not valid of broken URL: var request = new XMLHttpRequest(); var status; var statusText; request.open("GET", URL, true); request.send(); request.onload = function(){ status = request.status; statusText = request.statusText; } if (status == 200) { //if(statusText == OK) window.parent.location = "https://www.example.com/login/" + input_query; } else { console.log("not valid"); } Combined I have this: var input = document.getElementById("token"); var request = new XMLHttpRequest(); var status; var statusText; request.open("GET", URL, true); request.send(); request.onload = function(){ status = request.status; statusText = request.statusText; } if(status == 200) { //if(statusText == OK) window.parent.location = "https://www.example.com/login/" + input_query; } else { console.log("not valid"); } input.addEventListener("keyup", function(event) { if (event.keyCode === 13) { event.preventDefault(); document.getElementById("loginenter").click(); } }); function changeQuery(){ var input_query = document.getElementById('token').value; var request = new XMLHttpRequest(); var status; var statusText; request.open("GET", URL, true); request.send(); request.onload = function(){ status = request.status; statusText = request.statusText; } if(status == 200) { //if(statusText == OK) window.parent.location = "https://www.example.com/login/" + input_query; } else { console.log("not valid"); } I would like it to return a message "that the token is not valid" but it doesn't seem to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/56546740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to run LLVM bitcode generated from Haskell source code I'm trying to run LLVM bitcode generated from Haskell source code instead of compiling the code to a native binary on macOS. I have following file: $ cat hello_world.hs main = putStrLn "Hello world!" And I'm using following steps to create the .bc file: $ brew install stack $ brew install llvm@6 $ stack ghc -- -keep-llvm-files hello_world.hs $ clang -c -emit-llvm hello_world.ll -o hello_world.bc When I now try to run it, I get following error: $ lli hello_world.bc 'main' function not found in module. When I set -fllvm to compile to a native binary via LLVM it all works, so it doesn't seem to be a problem with my LLVM setup. How can this be fixed?
{ "language": "en", "url": "https://stackoverflow.com/questions/56322704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Identifying path of current JSF / XHTML page I need something that will uniquely identify my JSF (XHTML) page. I know that I have: String URI = servletRequest.getRequestURI(); This gives my full path, but that doesn't help if I use PrettyFaces or any other URL changing library. A: You can use UIViewRoot#getViewId() for this: String viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId(); It's also available in EL as follows: #{view.viewId}
{ "language": "en", "url": "https://stackoverflow.com/questions/12371100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Next and prev slide I have the following html - <div id='slides'> <div id='slide1'>Slide1!</div> <div id='slide2'>Slide2!</div> <div id='slide3'>Slide3!</div> </div> I am able to slide between the divs by using this technique with three buttons btnSlide1, btnSlide2, btnSlide3 - $(document).on('click', '#btnSlide1', function (e) { var slideW = $('#slides').width(); e.preventDefault(); $('#slides').animate({ scrollLeft: slideW }, 600); }); And then either add or minus slideW depending on which button is clicked. This works fine however as the numbers of slides increase this does not really scale, so what I would prefer is a next and previous button instead of individual buttons for individual slides. My problem is with only two buttons the context of slideW is no longer valid as I dont know which slide I am on at the time of the button click. Is there a way to do this with just a next and prev option? I have tried to - $(document).on('click', '#btnNext', function (e) { $('#slides').animate({ Left: '100%' }, 600); }); However this resulted in the first slide partially moving left. Current JSFiddle A: I have kept your HTML/CSS, and just added var current to track current slide. slideW = $('#slides').width(); current = 0; $(document).on('click', '#prev', function(e) { if (current > 0 && current <= $('#slides').children().length - 1) { current--; } console.log(current); e.preventDefault(); $('#slides').animate({ scrollLeft: slideW * current - 100 }, 600); }); $(document).on('click', '#next', function(e) { if (current < $('#slides').children().length - 1) current++; console.log(current); e.preventDefault(); $('#slides').animate({ scrollLeft: slideW * current + 100 }, 600); }); Demo: http://jsfiddle.net/86he7L41/1/ Of course, there are conditions to prevent undesired scrolling: left, or right - number of slides is limit.
{ "language": "en", "url": "https://stackoverflow.com/questions/32224346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL ORDER BY date and team I would like to order by date and then team in a MySQL query. It should be something similar to this: SELECT * FROM games ORDER BY gamedate ASC, team_id AND it should output something like this: 2010-04-12 10:20 Game 1 Team 1 2010-04-12 11:00 Game 3 Team 1 2010-04-12 10:30 Game 2 Team 2 2010-04-14 10:00 Game 4 Team 1 So that Team 1 is under each other on the same date, but separate on a new date A: Assuming that gamedate is a date field rather than a datetime field, that should work. If it's a datetime field, you would have to use something like date(gamedate) as the first ordering predicate: SELECT * FROM games ORDER BY date(gamedate) ASC, team_id ASC
{ "language": "en", "url": "https://stackoverflow.com/questions/2620397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Memory Still Valid? I have a C++ class defined as Now, assume that I am newing up the memory of the map sessionConnections in the constructor itself. My question is that pointer value of connCtx stored in the map of m_sessionConnections will be always there and not go out of scope, once it is returned from the function. I am seeing that when in the other function, I am using the ierator to get the value of connCtx, it is sometimes coming as some dangling pointer. A: If you allocate memory on the heap (with new) then it is valid until you explicitly delete it.
{ "language": "en", "url": "https://stackoverflow.com/questions/8292188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: PHP variable declaration shorthand (similar to JavaScript) In JavaScript, I can do this: var somevar = { propertyTwo : false, propertyThree : "hello!" } var test = somevar.propertyOne || somevar.propertyTwo || somevar.propertyThree alert(test); //displays "hello!" Is there a similar functionality in PHP for this? Haven't been able to find anything online. I tried this, but PHP just treats it like a comparison and echo's 1 (true) $somevar = array( 'propertyTwo' => false, 'propertyThree' => "hello!" ); $test = $somevar['propertyOne'] || $somevar['propertyTwo'] || $somevar['propertyThree']; echo $test; //displays '1' Not really a big deal if there isn't, but I figured that with all of the bells and whistles provided in php 5.x, there would be some kind of shorthand for assigning the first true value in a list of values to a single variable like that. I suppose I could write a function. EDIT : As I suspected, PHP doesn't have the same quirk. Quick function I wrote function assign_list($list){ foreach($list as $v) if(isset($v) && $v) return $v; return false; } Just pass it an array of stuff A: The following will work in PHP >= 5.3, but you will still receive a Notice Error because propertyOne is not defined. <?php $somevar = array( 'propertyTwo' => false, 'propertyThree' => "hello!" ); $test = $somevar['propertyOne'] ?: $somevar['propertyTwo'] ?: $somevar['propertyThree']; echo $test; //displays 'hello!' You could however work around this by supressing the variables, but it is highly unrecommended: $test = @$somevar['propertyOne'] ?: @$somevar['propertyTwo'] ?: @$somevar['propertyThree']; A: This doesn't work in PHP, and here's why: $somevar['propertyOne'] = false; $somevar['propertyTwo'] = true; $test = $somevar['propertyOne'] || $somevar['propertyTwo']; Imagine typing that query into an if statement: if( $somevar['propertyOne'] || $somevar['propertyTwo'] ){ ... } This will return true (evaluates to 1) if either variable is true. Now, if we make all of the variables = false: $somevar['propertyOne'] = false; $somevar['propertyTwo'] = false; $test = $somevar['propertyOne'] || $somevar['propertyTwo']; The variable returns false (evaluates to 0). Another thing we can do is: $somevar['propertyOne'] = true; $somevar['propertyTwo'] = true; $test = $somevar['propertyOne'] && $somevar['propertyTwo']; This will return true (evaluates to 1) as both variables meet the criteria. This means that we can do things like this in PHP though: $test = $somevar['propertyOne'] || $somevar['propertyTwo']; if($test){ ... } TL,DR: In PHP you are storing the result of the expression into a variable, not doing any validation on anything.
{ "language": "en", "url": "https://stackoverflow.com/questions/17454884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: wordpress customized theme, default add image in full width I have written a very basic theme, and want to make sure for every new post, when an image is added, the default attribute would be "width=100%". any hints please? A: Your individual posts will probably have a class or id on them - if not you need to add one. For example my site uses this: <div class="post"> <!-- post content --> </div> in the CSS for that class then add: .post img { width: 100%; } Note that this is a quick solution giving you exactly what you asked for. The images probably won't look very good in the posts unless you control your images i.e. only post images that are the same pixel width or larger than the column in which they appear on the site. Additionally this CSS will target ALL IMAGES in that post, which is fine if your posts are just text and the images you upload. A: Maybe you should try this - content width
{ "language": "en", "url": "https://stackoverflow.com/questions/48359333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to click on a particular cell in selenium web table having dynamic id Web Table will look like - I would like to click on Edit button for Steve Smith . <table style="width:100%"> <tr> <td>Steve</td> <td>Smith</td> <td>Edit</td> </tr> <tr> <td>Mark</td> <td>Jackson</td> <td>Edit </td> </tr> </table> What should be the approach for such scenerios? A: I am making some assumptions here. * *The first name and last name is known (eg: Steve Smith) *You can identify the target table without any issues. You can use the following XPath. This Xpath will find the tr which has text Steve Smith and then navigate to the td containing Edit. //tr[./td[.='Steve']][./td[.='Smith']]/td[.='Edit'] All this is based on the HTML you posted. Hope this helps you.
{ "language": "en", "url": "https://stackoverflow.com/questions/33125531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: terraform apply trying to destroy launch configuration that is deleted manually I've deleted couple of launch configurations from AWS console which I didn't need. Now with an updated terraform script, terraform apply tries to deleted launch configurations that are deleted manually and fails. Prior to terraform apply terraform is accompanied by terraform init and plan. It gives a validation error with launch configuration not found.
{ "language": "en", "url": "https://stackoverflow.com/questions/56435354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Added GWT to web app. Other devs complain about compile time. What should I tell them? I recently added GWT to our project to implement an Ajax feature of our web app. The other devs are complaining about the extra time GWT compile adds to the build and are asking why I didn't use JSON and jQuery instead. What should I tell them? A: Try to make the build smarter, if it isn't already: The GWT (client) part should only be re-compiled, when the client source changes. I assume, it's mostly you who changes that source, so the other developers won't experience the pain. Caveat: This doesn't work of course, if your client source shares code with the existing project (I assume, it's a Java project on the server side?). But maybe you should avoid shared code in your case: Even though that's violating the DRY (Don't Repeat Yourself) principle, realize that you'd violate it anyway, if you didn't use GWT. However, if you do reuse code from the server project, then you have a good argument, why you used GWT. A: If developers have to compile the whole GWT stuff (all the permutations) in order to develop application it is real pain. Starting from GWT 2 you can configure the webapp project to be run in "development mode". It can be started directly from eclipse (Google plugin) thanks to built in jetty container. In such scenario only requested resources are compiled, and the process is incremental. I find this very convenient - GWT compilation overhead in our seam+richfaces+GWT application is very small during development cycle. When it comes to application builds there are several options which can speed up GWT compilation. Here is checklist: * *disable soyc reports *enable draftCompile flag which skips some optimization *by adjusting localWorkers flag you can speed things a bit when building on multi-core CPU *compile limited set of permutation: e.g. only for browsers used during development and only for one language Release builds of the webapp should have draftCompile disabled though. Also all the laguage variants should be enabled. Maven profiles are very useful for parametrization of builds. A: What was the reason you used GWT instead of JSON/jQuery? I would ask the same question since for what you need, GWT may not be legitimately needed. A: In my experience, I totally understand the complaints you are getting. GWT is a wonderful technology, and it has many benefits. It also has downsides and one of them is long compile time. The GWT compiler does lots of static code analysis and it's not something that has an order-of-magnitude solution. As a developer, the most frustrating thing in the world is long development-deploy-test cycles. I know how your developers feel. You need to make an architectural decision if the technological benefits of GWT are worth it. If they are, your developers will need to get used to the technology, and there are many solutions which can make the development much easier. A: If there was a good reason for using GWT instead of pure javascript, you should tell them this reason (skills, debugging for a very hard to implement problem, you didn't want to deal with browser compatibility, etc). If there is no good reason, maybe they're right to be upset. I use GWT myself and I know about this compile time :-) If you used GWT for an easy-to-implement-in-javascript widget or something like that, maybe you should have consider using javascript instead. A: What tool you're using to compile project? Long time ago I've used ant and it was smart enough to find out that, when none of source files for GWT app (client code) has changed, the GWT compiler task was not called. However, after that I've used maven and it was real pain, because it's plugin didn't recognize the code hasn't changed and GWT compilation was run all and over, no matter if it was needed or not. I would recommend ant for GWT projects. Alternative would be rewriting the maven plugin or getting developers used to long compile time.
{ "language": "en", "url": "https://stackoverflow.com/questions/3602992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: coding asp page for avoid of hack all of us know that most of attacks to websites is from their URL. i saw some websites code their page for example we see http:/www.*.com/code/ instead of http:/www.*.com/code/code.aspx how do that? every one can give me some tutorials that tell how can i do that in asp.net? A: The topic you're interested in is called "url rewriting". You will also see similar looking url's on sites using MVC as well. It has very little to do with preventing security exploits. I think you are referring to sql injection when you say most websites are attacked from their URL. This is possible when using GET variables (the one's passed by url) in unsanitized sql statements. The same techniques are easily used against sites that use POST variables, it's just requires a little more effort to populate the values. I suggest you focus your research on "SQL Injection" instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7692732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DDD and Microservices - data flow and structure I'm trying to create a simple blogging platform and at the same time learn more about DDD and Microservices, so I wanted to ask you about two advises in this context: * *One of the business rules I assumed in my project is that only users in roles Publicist and Administrator are able to create posts, but posts created by Publicist have to be approved by Administrator first before they go public. In my understanding this is a part of a Posts.Domain, so in Post aggregate (and at the same time entity) I encapsulated changing the post's status into methods like SetPublishedStatusBy that take User (requestor) data as parameters and evaluate above rule (+ create domain events). However now I'm having some doubts whether information about requestor is really a part of the Posts.Domain. Maybe requestor should be evaulated in a different place, like Posts.API or some other service and SetPublishedStatus would be then called without parameters after it is already done? *Let's stick to above context. Despite Posts microservice, I'm also developing independent Users microservice responsible for storing the users and providing some tools for Administrator to manage them. What would be then the proper data flow when a user wants to publish a new post? I'd imagine this in a following way: * *Client sends PublishPost command with a post ID to the gateway *Gateway authenticates user from HTTP request (probably done via cookie with JWT) *Gateway sends a PublishPost command to Posts microservice *Posts microservice calls Users microservice to get relevant user data from DB *Posts microservice retreives post from DB by ID *All business rules are evaluated through the Posts.Domain and status is changed to Public *Posts microservice updates DB if everything goes fine and notifies Gateway that sends Success HTTP response A: My thoughts ... For DDD, you're best served by taking guidance from the Ubiquitous Language of the domain when discussed with a domain expert. The term "SetPublishedStatusBy" probably wouldn't come up in that discussion. I think the most likely outcome of that discussion would be: * *An Administrator and publish a post. *A Publicist can submit a post that an Administrator must approve before it is published. *An Administrator can approve a submitted post that has been Submitted by a Publicist, which will result in the post being published. *An Administrator can reject a submitted post. My Post aggregate would then end up looking something like: class Post { void Submit() { this.Status = Submitted; } void Publish() { this.Status = Published; } void Approve() { if (this.Status != Submitted) throw "This post is not pending approval."; this.Status = Published; } void Reject() { if (this.Status != Submitted) throw "This post is not pending approval."; this.Status = Rejected; } } When creating the post, the UI would either be calling Publish or Submit in your API, depending on the context. The API would then check that current user can perform the requested Publish or Submit. Two other options: * *Introduce an Aggregate called PostRequest that Publicists have permission to create and only create a Post when that is approved by an Administrator. *If you want the rules to be more dynamic, i.e. a user just hits 'Publish', whether they are a Publicist or an Administrator and then the outcome is either a published post or a submitted post depending on the rules of the day, then you'd want an orchestration / saga / task layer in between your API and the Aggregate which can interact with User service to decide whether the the first call to the Posts service should be a "Submit" or a "Publish".
{ "language": "en", "url": "https://stackoverflow.com/questions/70275427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Square brackets in keras model output shape I've recently encountered this when looking at a model's summary. I was wondering, what's the difference between [(None, 16)] and (None, 16)? Why does the Input layer have such input shape? Source: model.summary() can't print output shape while using subclass model A: The issue is how you are defining the input_shape. A single element tuple in python is actually a scalar value as you can see below - input_shape0 = 32 input_shape1 = (32) input_shape2 = (32,) print(input_shape0, input_shape1, input_shape2) 32 32 (32,) Since Keras function API Input needs an input shape as a tuple, you will have to pass it in the form of (n,) instead of n It's weird that you get a square bracket because when I run the exact same code, I get an error. TypeError Traceback (most recent call last) <ipython-input-828-b564be68c80d> in <module> 33 34 if __name__ == '__main__': ---> 35 mlp = MLP((16)) 36 mlp.summary() <ipython-input-828-b564be68c80d> in __init__(self, input_shape, **kwargs) 6 super(MLP, self).__init__(**kwargs) 7 # Add input layer ----> 8 self.input_layer = klayers.Input(input_shape) 9 10 self.dense_1 = klayers.Dense(64, activation='relu') ~/anaconda3/lib/python3.7/site-packages/tensorflow/python/keras/engine/input_layer.py in Input(shape, batch_size, name, dtype, sparse, tensor, **kwargs) 229 dtype=dtype, 230 sparse=sparse, --> 231 input_tensor=tensor) 232 # Return tensor including `_keras_history`. 233 # Note that in this case train_output and test_output are the same pointer. ~/anaconda3/lib/python3.7/site-packages/tensorflow/python/keras/engine/input_layer.py in __init__(self, input_shape, batch_size, dtype, input_tensor, sparse, name, **kwargs) 89 if input_tensor is None: 90 if input_shape is not None: ---> 91 batch_input_shape = (batch_size,) + tuple(input_shape) 92 else: 93 batch_input_shape = None TypeError: 'int' object is not iterable Therefore, the right way to do it (which should fix your model summary as well is as below - from tensorflow import keras from tensorflow.keras import layers as klayers class MLP(keras.Model): def __init__(self, input_shape=(32,), **kwargs): super(MLP, self).__init__(**kwargs) # Add input layer self.input_layer = klayers.Input(input_shape) self.dense_1 = klayers.Dense(64, activation='relu') self.dense_2 = klayers.Dense(10) # Get output layer with `call` method self.out = self.call(self.input_layer) # Reinitial super(MLP, self).__init__( inputs=self.input_layer, outputs=self.out, **kwargs) def build(self): # Initialize the graph self._is_graph_network = True self._init_graph_network( inputs=self.input_layer, outputs=self.out ) def call(self, inputs): x = self.dense_1(inputs) return self.dense_2(x) if __name__ == '__main__': mlp = MLP((16,)) mlp.summary() _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_19 (InputLayer) (None, 16) 0 _________________________________________________________________ dense_8 (Dense) (None, 64) 1088 _________________________________________________________________ dense_9 (Dense) (None, 10) 650 ================================================================= Total params: 1,738 Trainable params: 1,738 Non-trainable params: 0 _________________________________________________________________
{ "language": "en", "url": "https://stackoverflow.com/questions/63272292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Visual Studio stating "Microsoft is not a class or namespace name" I am using Visual Studio 2019 and developing in C++. I have installed Microsoft Cognitive services by following this walkthrough and my pakcages.config looks correct. Now when following this tutorial to use cognitive speech, my c++ solution will not build stating "Microsoft is not a class or namespace name" This shows the error and the sample code and the packages.config file code and error screenshot packages.config A: I suggest that you could add speechapi_cxx.h in Properties->VC++ Directories->Include Directories. The path is cognitive-services-speech-sdk-master\quickstart\cpp\windows\from-microphone\packages\Microsoft.CognitiveServices.Speech.1.15.0\build\native\include\cxx_api. Also, you need to add the code using namespace Microsoft::CognitiveServices::Speech::Audio;. Here is the complete code: #include <iostream> #include <speechapi_cxx.h> using namespace std; using namespace Microsoft::CognitiveServices::Speech::Audio; using namespace Microsoft::CognitiveServices::Speech; auto config = SpeechConfig::FromSubscription("real_sub_id", "region"); int main() { std::cout << "Hello World!\n"; auto audioCofig = AudioConfig::FromDefaultMicrophoneInput(); auto recognizer = SpeechRecognizer::FromConfig(config, audioCofig); cout << "Speak " << endl; auto result = recognizer->RecognizeOnceAsync().get(); cout << "RECOGNIZED: Text=" << result->Text; } A: I don't know much about the library you are using, but i am sure that you need to #include something before you can actually use the library.
{ "language": "en", "url": "https://stackoverflow.com/questions/66429583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scrape website that requires button click I am trying to scrape this website. Unfortunately, the data that I want to scrape using rvest is hidden behind a button (the plus symbol). I tried to do it with the rvest package and I use the following code: library(rvest) url <- 'https://transparency.entsoe.eu/generation/r2/actualGenerationPerGenerationUnit/show?name=&defaultValue=true&viewType=TABLE&areaType=BZN&atch=false&dateTime.dateTime=17.03.2017+00:00|UTC|DAYTIMERANGE&dateTime.endDateTime=17.03.2017+00:00|UTC|DAYTIMERANGE&area.values=CTY|10YBE----------2!BZN|10YBE----------2&productionType.values=B02&productionType.values=B03&productionType.values=B04&productionType.values=B05&productionType.values=B06&productionType.values=B07&productionType.values=B08&productionType.values=B09&productionType.values=B10&productionType.values=B11&productionType.values=B12&productionType.values=B13&productionType.values=B14&productionType.values=B15&productionType.values=B16&productionType.values=B17&productionType.values=B18&productionType.values=B19&productionType.values=B20&dateTime.timezone=UTC&dateTime.timezone_input=UTC&dv-datatable_length=100' htmlpage <- html_session(url) %>% read_html() %>% html_nodes(".dv-value-cell") %>>% html_table() The ".dv-value-cell" is extracted from the website using the SelectorGadget (in one of the vignettes of rvest). However, before I can use this code, I still need to open the plus menu. The data inside this sub table doesn't exist before clicking the button. Therefore, the code above will return an empty value. I used the Chrome web development tools described in this question to monitor what happens when I click on the button. According to that information, I see that there is a request to the following url (shortened to only highlight the difference with the original url): https://transparency.entsoe.eu/...&dateTime.timezone_input=UTC&dv-datatable-detail_22WAMERCO000010Y_22WAMERCO000008L_length=10&dv-datatable_length=50&detailId=22WAMERCO000010Y_22WAMERCO000008L As you can see, this is the original url, but there is a small additional request. However, when I try this url in my browser, it doesn't show the desired result. I must be missing something that the website passes additionally. The result of this request according to Chrome is exactly the data that I'm looking for (right-click > copy > copy result). So there should be a way to just download this specific data. I also found this question about a similar problem, but unfortunately the solution is quite specific for this case and misses a general explanation. How can I reproduce this browser request such that I receive the same table? A: If you are not scraping a large set of data. I will suggest to you to use selenium. With selenium actually you can click the button. You can begin with scraping with R programming and selenium. You can also use PhantomJS. It is also like selenium but no browser required. I hope one of them will help.
{ "language": "en", "url": "https://stackoverflow.com/questions/42983649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Using Pandas to pd.read_excel() for multiple worksheets of the same workbook I have a large spreadsheet file (.xlsx) that I'm processing using python pandas. It happens that I need data from two tabs (sheets) in that large file. One of the tabs has a ton of data and the other is just a few square cells. When I use pd.read_excel() on any worksheet, it looks to me like the whole file is loaded (not just the worksheet I'm interested in). So when I use the method twice (once for each sheet), I effectively have to suffer the whole workbook being read in twice (even though we're only using the specified sheet). How do I only load specific sheet(s) with pd.read_excel()? A: Try pd.ExcelFile: xls = pd.ExcelFile('path_to_file.xls') df1 = pd.read_excel(xls, 'Sheet1') df2 = pd.read_excel(xls, 'Sheet2') As noted by @HaPsantran, the entire Excel file is read in during the ExcelFile() call (there doesn't appear to be a way around this). This merely saves you from having to read the same file in each time you want to access a new sheet. Note that the sheet_name argument to pd.read_excel() can be the name of the sheet (as above), an integer specifying the sheet number (eg 0, 1, etc), a list of sheet names or indices, or None. If a list is provided, it returns a dictionary where the keys are the sheet names/indices and the values are the data frames. The default is to simply return the first sheet (ie, sheet_name=0). If None is specified, all sheets are returned, as a {sheet_name:dataframe} dictionary. A: If: * *you want multiple, but not all, worksheets, and *you want a single df as an output Then, you can pass a list of worksheet names. Which you could populate manually: import pandas as pd path = "C:\\Path\\To\\Your\\Data\\" file = "data.xlsx" sheet_lst_wanted = ["01_SomeName","05_SomeName","12_SomeName"] # tab names from Excel ### import and compile data ### # read all sheets from list into an ordered dictionary dict_temp = pd.read_excel(path+file, sheet_name= sheet_lst_wanted) # concatenate the ordered dict items into a dataframe df = pd.concat(dict_temp, axis=0, ignore_index=True) OR A bit of automation is possible if your desired worksheets have a common naming convention that also allows you to differentiate from unwanted sheets: # substitute following block for the sheet_lst_wanted line in above block import xlrd # string common to only worksheets you want str_like = "SomeName" ### create list of sheet names in Excel file ### xls = xlrd.open_workbook(path+file, on_demand=True) sheet_lst = xls.sheet_names() ### create list of sheets meeting criteria ### sheet_lst_wanted = [] for s in sheet_lst: # note: following conditional statement based on my sheets ending with the string defined in sheet_like if s[-len(str_like):] == str_like: sheet_lst_wanted.append(s) else: pass A: You can read all the sheets using the following lines import pandas as pd file_instance = pd.ExcelFile('your_file.xlsx') main_df = pd.concat([pd.read_excel('your_file.xlsx', sheet_name=name) for name in file_instance.sheet_names] , axis=0) A: You can also use the index for the sheet: xls = pd.ExcelFile('path_to_file.xls') sheet1 = xls.parse(0) will give the first worksheet. for the second worksheet: sheet2 = xls.parse(1) A: You could also specify the sheet name as a parameter: data_file = pd.read_excel('path_to_file.xls', sheet_name="sheet_name") will upload only the sheet "sheet_name". A: df = pd.read_excel('FileName.xlsx', 'SheetName') This will read sheet SheetName from file FileName.xlsx A: There are various options depending on the use case: * *If one doesn't know the sheets names. *If the sheets name is not relevant. *If one knows the name of the sheets. Below we will look closely at each of the options. See the Notes section for information such as finding out the sheet names. Option 1 If one doesn't know the sheets names # Read all sheets in your File df = pd.read_excel('FILENAME.xlsx', sheet_name=None) # Prints all the sheets name in an ordered dictionary print(df.keys()) Then, depending on the sheet one wants to read, one can pass each of them to a specific dataframe, such as sheet1_df = pd.read_excel('FILENAME.xlsx', sheet_name=SHEET1NAME) sheet2_df = pd.read_excel('FILENAME.xlsx', sheet_name=SHEET2NAME) Option 2 If the name is not relevant and all one cares about is the position of the sheet. Let's say one wants only the first sheet # Read all sheets in your File df = pd.read_excel('FILENAME.xlsx', sheet_name=None) sheet1 = list(df.keys())[0] Then, depending on the sheet name, one can pass each it to a specific dataframe, such as sheet1_df = pd.read_excel('FILENAME.xlsx', sheet_name=SHEET1NAME) Option 3 Here we will consider the case where one knows the name of the sheets. For the examples, one will consider that there are three sheets named Sheet1, Sheet2, and Sheet3. The content in each is the same, and looks like this 0 1 2 0 85 January 2000 1 95 February 2001 2 105 March 2002 3 115 April 2003 4 125 May 2004 5 135 June 2005 With this, depending on one's goals, there are multiple approaches: * *Store everything in same dataframe. One approach would be to concat the sheets as follows sheets = ['Sheet1', 'Sheet2', 'Sheet3'] df = pd.concat([pd.read_excel('FILENAME.xlsx', sheet_name = sheet) for sheet in sheets], ignore_index = True) [Out]: 0 1 2 0 85 January 2000 1 95 February 2001 2 105 March 2002 3 115 April 2003 4 125 May 2004 5 135 June 2005 6 85 January 2000 7 95 February 2001 8 105 March 2002 9 115 April 2003 10 125 May 2004 11 135 June 2005 12 85 January 2000 13 95 February 2001 14 105 March 2002 15 115 April 2003 16 125 May 2004 17 135 June 2005 Basically, this how pandas.concat works (Source): *Store each sheet in a different dataframe (let's say, df1, df2, ...) sheets = ['Sheet1', 'Sheet2', 'Sheet3'] for i, sheet in enumerate(sheets): globals()['df' + str(i + 1)] = pd.read_excel('FILENAME.xlsx', sheet_name = sheet) [Out]: # df1 0 1 2 0 85 January 2000 1 95 February 2001 2 105 March 2002 3 115 April 2003 4 125 May 2004 5 135 June 2005 # df2 0 1 2 0 85 January 2000 1 95 February 2001 2 105 March 2002 3 115 April 2003 4 125 May 2004 5 135 June 2005 # df3 0 1 2 0 85 January 2000 1 95 February 2001 2 105 March 2002 3 115 April 2003 4 125 May 2004 5 135 June 2005 Notes: * *If one wants to know the sheets names, one can use the ExcelFile class as follows sheets = pd.ExcelFile('FILENAME.xlsx').sheet_names [Out]: ['Sheet1', 'Sheet2', 'Sheet3'] *In this case one is assuming that the file FILENAME.xlsx is on the same directory as the script one is running. * *If the file is in a folder of the current directory called Data, one way would be to use r'./Data/FILENAME.xlsx' create a variable, such as path as follows path = r'./Data/Test.xlsx' df = pd.read_excel(r'./Data/FILENAME.xlsx', sheet_name=None) *This might be a relevant read. A: There are a few options: Read all sheets directly into an ordered dictionary. import pandas as pd # for pandas version >= 0.21.0 sheet_to_df_map = pd.read_excel(file_name, sheet_name=None) # for pandas version < 0.21.0 sheet_to_df_map = pd.read_excel(file_name, sheetname=None) Read the first sheet directly into dataframe df = pd.read_excel('excel_file_path.xls') # this will read the first sheet into df Read the excel file and get a list of sheets. Then chose and load the sheets. xls = pd.ExcelFile('excel_file_path.xls') # Now you can list all sheets in the file xls.sheet_names # ['house', 'house_extra', ...] # to read just one sheet to dataframe: df = pd.read_excel(file_name, sheet_name="house") Read all sheets and store it in a dictionary. Same as first but more explicit. # to read all sheets to a map sheet_to_df_map = {} for sheet_name in xls.sheet_names: sheet_to_df_map[sheet_name] = xls.parse(sheet_name) # you can also use sheet_index [0,1,2..] instead of sheet name. Thanks @ihightower for pointing it out way to read all sheets and @toto_tico,@red-headphone for pointing out the version issue. sheetname : string, int, mixed list of strings/ints, or None, default 0 Deprecated since version 0.21.0: Use sheet_name instead Source Link A: Yes unfortunately it will always load the full file. If you're doing this repeatedly probably best to extract the sheets to separate CSVs and then load separately. You can automate that process with d6tstack which also adds additional features like checking if all the columns are equal across all sheets or multiple Excel files. import d6tstack c = d6tstack.convert_xls.XLStoCSVMultiSheet('multisheet.xlsx') c.convert_all() # ['multisheet-Sheet1.csv','multisheet-Sheet2.csv'] See d6tstack Excel examples A: If you have saved the excel file in the same folder as your python program (relative paths) then you just need to mention sheet number along with file name. Example: data = pd.read_excel("wt_vs_ht.xlsx", "Sheet2") print(data) x = data.Height y = data.Weight plt.plot(x,y,'x') plt.show() A: pd.read_excel('filename.xlsx') by default read the first sheet of workbook. pd.read_excel('filename.xlsx', sheet_name = 'sheetname') read the specific sheet of workbook and pd.read_excel('filename.xlsx', sheet_name = None) read all the worksheets from excel to pandas dataframe as a type of OrderedDict means nested dataframes, all the worksheets as dataframes collected inside dataframe and it's type is OrderedDict. A: If you are interested in reading all sheets and merging them together. The best and fastest way to do it sheet_to_df_map = pd.read_excel('path_to_file.xls', sheet_name=None) mdf = pd.concat(sheet_to_df_map, axis=0, ignore_index=True) This will convert all the sheet into a single data frame m_df
{ "language": "en", "url": "https://stackoverflow.com/questions/26521266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "362" }
Q: Does valarray have contiguous memory alignment? Does valarray have contiguous memory alignment? I want to pass a valarray to a function (from IPPS), which only takes pointers, by passing &myValarray[0]. But therefore I should be sure, that valarray's memory alignment is contiguous. Thanks! A: Assuming you're asking whether the memory managed by a valarray is guaranteed to be contiguous, then the answer is yes, at least if the object isn't const (C++03, §26.3.2.3/3 or C++11, §26.6.2.4/2): The expression &a[i+j] == &a[i] + j evaluates as true for all size_t i and size_t j such that i+j is less than the length of the non-constant array a.
{ "language": "en", "url": "https://stackoverflow.com/questions/11143109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Drawing a circle on a pictureBox from another winform I have two winforms in my application. One of the forms has a picturebox with a jpg loaded of our building plan. The main form has code that does facial recognition identifying people coming into certain areas. I have been asked to modify this program to show an identified individual's location on the building plan. I have a database that has all the X,Y coordinates of the locations that should map to the building plan image. I have looked around and tried to find some code that will draw a circle on the map at the X,Y coordinates as the person progresses through areas of the building by erasing all the existing circles and updating this new one. So on the map form I put in the following code: public void DrawCircle(int x, int y) { Graphics gf = pictureBox1.CreateGraphics(); gf.DrawEllipse(new Pen(Color.Red), new Rectangle(x, y, 400, 400)); pictureBox1.Refresh(); } Then from the update method (right now a button click for testing) on the main form I call this method on the map form. The method gets called, but the circle doesn't show up on the form. I have tried both Refresh and Invalidate and neither method seems to draw the circle on the image. I haven't done winforms development for years, so I'm sure I am missing some plumbing somewhere. Here is the code on the mainform: LocationMap map = new LocationMap(); public Form1() { InitializeComponent(); //set up signalR UserName = "MovementHub1"; ConnectAsync(); //show the map screen map.Show(); map.WindowState = FormWindowState.Maximized; ... Then in a click event (for testing right now) I have this code: private void button2_Click(object sender, EventArgs e) { map.DrawCircle(340, 258); } Once I get the circle drawn on the other form, then I will remove the code from the click event and move it another event that does the updating on the location. If it's possible, I would like to put a label by the circle that has the person's name. Right now this is a proof of concept, I just need help getting the circle on the form to start with. Thanks. A: I tried It out by myself and came up with that: Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace StackoverflowHelp { public partial class Form1 : Form { Form2 form = new Form2(); public Form1() { InitializeComponent(); form.Show(); } private void Button1_Click(object sender, EventArgs e) { form.DrawCircle(100, 100); } } } Form2.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace StackoverflowHelp { public partial class Form2 : Form { public Form2() { InitializeComponent(); DrawCircle(10, 10); } public void DrawCircle(int x, int y) { Graphics gf = Graphics.FromImage(pictureBox1.Image); gf.DrawEllipse(new Pen(Color.Red), new Rectangle(x, y, 20, 20)); gf.Dispose(); pictureBox1.Refresh(); pictureBox1.Invalidate(); pictureBox1.Update(); } } } Instead of calling CreateGraphics() on the picturebox I created the graphics object using the current image.
{ "language": "en", "url": "https://stackoverflow.com/questions/56482346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PowerShell EWS API | How to download attachments? In the code below, I am able to retrieve the subject of the email but unable to download the attachment. I am not even able to output the name of the attachment. The attachment is a WAV sound file. Import-Module "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll" $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId($v_FolderID) $fiItems = $null $iv = new-object Microsoft.Exchange.WebServices.Data.ItemView(1000) $fiItems = $service.FindItems($folderid, $args[1], $iv) foreach ($Item in $fiItems.Items[0]) { $v_Subject = $Item.Subject foreach($attachment in $Item.Attachments) { $attachment.Load() $attachmentname = $attachment.Name.ToString() $attachmentname $file = New-Object System.IO.FileStream("C:\", [System.IO.FileMode]::Create) $file.Write($attachment.Content, 0, $attachment.Content.Length) $file.Close() } } $iv.offset += $fiItems.Items.Count Out-File -FilePath "C:\EWSSubject.txt" -InputObject $v_Subject``` A: You should first need to create a PropertySet object because the attachment information is not loaded automatically. ## Target Path Folder $TargetPath = "c:\temp\attachments" ## Create a PropertySet with the Attachments metadata $ItemPropetySet = [Microsoft.Exchange.WebServices.Data.PropertySet]::new( [Microsoft.Exchange.Webservices.Data.BasePropertySet]::IdOnly, [Microsoft.Exchange.WebServices.Data.ItemSchema]::Attachments, [Microsoft.Exchange.WebServices.Data.ItemSchema]::HasAttachments ) Then: ## Iterate the items and find messages with attachments foreach ($item in $fiItems.Items) { ## Load the Message attachment metadata using the PropertySet Created $message = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind( $service, $item.Id, $ItemPropetySet) if ($message.HasAttachments) { foreach ($attachment in $message.Attachments) { if ($attachment -is [Microsoft.Exchange.WebServices.Data.FileAttachment]) { $FilePath = Join-Path $TargetPath $attachment.Name $attachment.Load($FilePath) } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/74665413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create R Correlation Matrix with RevoScaleR package (multithreaded) functions in SQL Server I am trying to create correlation matrix using SQL Server 2016 R Services. Since that i will have large amount of data, i want to use the new Rx version of standard R "cor" function. This is the function that i want to use: And this is the Code that i have right now. DROP TABLE IF EXISTS #DummyData CREATE TABLE #DummyData ( [VariableA] VARCHAR(24) ,[VariableB] VARCHAR(24) ,[Value] SMALLINT ) INSERT INTO #DummyData([VariableA], [VariableB], [Value]) VALUES ('A1','B1', 4) ,('A1','B2', 3) ,('A1','B3', 1) ,('A2','B1', 2) ,('A2','B2', 1) ,('A2','B3', 3) ,('A3','B1', 4) ,('A3','B2', 5) ,('A3','B3', 2); EXECUTE sp_execute_external_script @language = N'R' , @script = N' library(reshape) pivotData <- cast(DataIn, VariableA ~ VariableB,fun.aggregate = max) curData <- cor(pivotData, method="spearman") DataOut <- data.frame(row=rownames(curData)[row(curData)[upper.tri(curData)]], col=colnames(curData)[col(curData)[upper.tri(curData)]], corr=curData[upper.tri(curData)]) ' , @input_data_1 = N'SELECT [VariableA], [VariableB], [Value] FROM #DummyData' , @input_data_1_name = N'DataIn' , @output_data_1_name = N'DataOut'; This code gives me the following result: Any idea how can i achieve the same results, but using the MS RevoScaleR package?
{ "language": "en", "url": "https://stackoverflow.com/questions/51520501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can i get sum of each elements in tuple Python For example i have a tuple t = ((1, 1), (1, 1), (1, 1)) How can i get sum of all this elements with only one loop I would like to get 6 A: You can map with sum, and get the sum of the result: sum(map(sum, t)) # 6 Or if you prefer it with a for loop: res = 0 for i in t: res += sum(i) print(res) # 6 A: You can use simple iteration (works in python3.8, I assume it works on older versions as well). t = ((1, 1), (1, 1), (1, 1)) sum_tuples = 0 for a,b in t: sum_tuples += a # First element sum_tuples += b # Second Element print(sum_tuples) # prints 6 A: You could use itertools.chain >>> import itertools >>> t = ((1, 1), (1, 1), (1, 1)) >>> sum(itertools.chain.from_iterable(t)) 6 A: You can loop tuple to sum all. This code is long but it can sum tuple in tuple. t = ((1, 1), (1, 1), (1, 1)) # Tuple in tuple: t = ((1, 1, (1, 1, (1, 1)))) def getsum(var, current = 0): result = current if type(var) == tuple: for i in range(len(var)): x = var[i] result = getsum(x, result) else: result += var return result print(getsum(t))
{ "language": "en", "url": "https://stackoverflow.com/questions/60774862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pycharm keeps giving name 'class' is not defined error I have tried to see every possible solution for this but for some reason none of them have worked. I am doing Learn Python the Hard way exercise 49. I made my own parser and it works when I run it via pycharm, when i open the console or powershell and try to import, it gives this error: Traceback (most recent call last): File "<input>", line 1, in <module> NameError: name 'parse_sentence' is not defined I also tried to see if the problem is in the script, so I copied his work down onto another tab and it gave me the same problem. Here a little bit of my code: class Sentence: def __init__(self, type): self.type = type def subjects(self): nouns = ('door', 'bear', 'princess', 'cabinet') s = self.scan(self.type) for i in s: for k in i: if k in nouns: print k def verbs(self): verbs = ('go', 'stop', 'kill', 'eat', 'open') s = self.scan(self.type) for i in s: for k in i: if k in verbs: print k def objects(self): directions = ('north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back') nouns = ('door', 'bear', 'princess', 'cabinet') s = self.scan(self.type) for i in s: for k in i: if k in directions or k in nouns: print k def get_tuple(self, word): directions = ('north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back') verbs = ('go', 'stop', 'kill', 'eat', 'open') stop_words = ('the', 'in', 'of', 'from', 'at', 'it') nouns = ('door', 'bear', 'princess', 'cabinet') lowercased = word.lower() if lowercased in directions: return ('direction', lowercased) elif lowercased in verbs: return ('verb', lowercased) elif lowercased in stop_words: return ('stop_words', lowercased) elif lowercased in nouns: return ('noun', lowercased) elif lowercased.isdigit(): return ('number', int(lowercased)) else: return ('error', word) def scan(self, sentence): words = sentence.split() return [self.get_tuple(word) for word in words] it is not because of the self.scan, it is in the class I just don't want to post all of the code to not mess the page up. I open console, i type import parser (parser is the name of this file) that works, then it i type myarg = Sentence('let us kill the bear'). gives me the error up above. Samehting when I do his way, thank you so much for reading this in advance. I am on Windows 10, Python 2.7 Here is my error import parser myarg = Sentence('let us kill the bear') Traceback (most recent call last): File "<input>", line 1, in <module> NameError: name 'Sentence' is not defined when doing import paser parser.Sentence() I get : Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'module' object has no attribute 'Sentence' when doing : import parser myarg = parser.Sentence('let us kill the bear') Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'module' object has no attribute 'Sentence' A: If you import import parser then you have to use parser.Sentence() myarg = parser.Sentence('let us kill the bear') If you import from parser import Sentence then you can use Sentence() myarg = Sentence('let us kill the bear') Python first looks for file in "current working directory" ("cwd"). If you run code in different folder then it can import from library module with the same name instead of your file. You can check what file was imported import parser print(parser.__file__) To check current working directory import os print(os.getcwd())
{ "language": "en", "url": "https://stackoverflow.com/questions/41404463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I build a follow system in Firestore I switch from Firebase realtime database to Firestore In the realtime database, I was using this code for the follow system: checkFollowingStatus(user.getUID(), holder.followButton) holder.followButton.setOnClickListener { if(holder.followButton.text.toString() == "Follow") { firebaseUser?.uid.let { it1 -> FirebaseDatabase.getInstance().reference .child("Follow").child(it1.toString()) .child("Following").child(user.getUID()) .setValue(true).addOnCompleteListener { task -> if (task.isSuccessful) { firebaseUser?.uid.let { it -> FirebaseDatabase.getInstance().reference .child("Follow").child(user.getUID()) .child("Followers").child(it.toString()) .setValue(true).addOnCompleteListener { task -> if (task.isSuccessful) { } } } } } } } else { firebaseUser?.uid.let { it1 -> FirebaseDatabase.getInstance().reference .child("Follow").child(it1.toString()) .child("Following").child(user.getUID()) .removeValue().addOnCompleteListener { task -> if (task.isSuccessful) { firebaseUser?.uid.let { it1 -> FirebaseDatabase.getInstance().reference .child("Follow").child(user.getUID()) .child("Followers").child(it1.toString()) .removeValue().addOnCompleteListener { task -> if (task.isSuccessful) { } } } } } } } } private fun checkFollowingStatus(uid: String, followButton: Button) { val followingRef = firebaseUser?.uid.let { it1 -> FirebaseDatabase.getInstance().reference .child("Follow").child(it1.toString()) .child("Following") } followingRef.addValueEventListener(object : ValueEventListener { override fun onDataChange(datasnapshot: DataSnapshot) { if (datasnapshot.child(uid).exists()) { followButton.text = "Unfollow" } else { followButton.text = "Follow" } } override fun onCancelled(p0: DatabaseError) { } }) } It looks in realtime database Like this +Follow    +userId      +Following         +usersId...      +Followers         +usersId... How Can I convert this to Firestore or How can I structure a follow system in Firestore database? A: var hashMap : HashMap<String, Object> = HashMap<String, Object> () hashMap.put("someName", true); and pass this hash map to set method databaseRefernce.addSnapshotListener(new EventListener<DocumentSnapshot or QuerySnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { if (value.exists()) { } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/65054319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Row by row calculation Dumb question, but I am a bit rusty in Python. So I wrote the following code: df = pd.read_csv(mypath ) for index, row in df.iterrows(): if row['Age'] < 2: Total = row['Input'] * 1.2 elif row['Age'] > 8: Total = row['Input'] * 1.1 else: Total = row['Input'] * 0.9 print(Total) I have a table and I am looking to some simple calculations using variables from each row. Example table: Input Age Total ----------------------- 100 5 150 3 So, for now I am wondering how to take each row, do my calculations, and write it down on my total ( for each row). For example for the first row the total should be 90. A: You can use the apply method def age_total(x): if x < 2: return * 1.2 elif x > 8: return x * 1.1 else: return x * 0.9 df['Total']= df['age'].apply(age_total)
{ "language": "en", "url": "https://stackoverflow.com/questions/67872477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring @ConditionalOnBean does not work correctly with @RefreshScope I have following classes: public class ClassA { } @Configuration public class config(){ @RefreshScope @Bean public ClassA classA() { return new ClassA(); } } @Component @ConditionalOnBean(ClassA.class) public ClassB { private final ClassA classA; public ClassB(ClassA classA) { this.classA = classA; } } @Component public class ClassC { private final ClassB classB; public ClassC(ClassB classB) { this.classB = classB; } } I noticed that this randomly fails with Parameter 0 of constructor in ClassC required a bean of type 'ClassB' that could not be found. I have discovered that ComponentScanAnnotationParser can parse classes in arbitrary order (different when I use local build and different with artifactory build) and sometimes tries to create ClassB before ClassA. This obviously does not work because of ConditionalOnBean. All works fine after I remove RefreshScope annotation. Anyone knows if this is expectedBehaviour?
{ "language": "en", "url": "https://stackoverflow.com/questions/72829400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python error in calling the function I have a class have these two methods: def whatIsYourName(self): print 'my name is class A' def whatIsYourName(self, name): print 'my name is {0}, I am class A'.format(name) I can call the second one. But when I call the first one like this: x = myClass() x.whatIsYourName() I got this error: Traceback (most recent call last): File "<interactive input>", line 1, in <module> TypeError: whatIsYourName() takes exactly 2 arguments (1 given) I am using python 2.7 A: Python does not support method overloading. The method defined in the end will overwrite all the methods with same name defined earlier. However, You can make use of Multi Method pattern to achieve this. Please refer Guido's post A: You are trying to overload a method. whatIsYourName(self) is being over-ridden by whatIsYourName(sel,name). If you are a C++/Java programmer, this might sound normal to you, but unfortunately it's not the same with Python. If you want to display a name, try defining it in a constructor and have it printed.
{ "language": "en", "url": "https://stackoverflow.com/questions/21328029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems with Ethernet shield + arduino I am currently trying some simple (ready) programs from Arduino examples regardin the ethernet shield. I am still getting no result. Am always receiving that I am not connected or a blank serial monitor. Does anyone knows why? I think I am connected to the DHCP since i am on the DHCP list of my router <#include <SPI.h> #include <Ethernet.h> #include <EthernetUdp.h> // Enter a MAC address for your controller below. // Newer Ethernet shields have a MAC address printed on a sticker on the shield byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; unsigned int localPort = 8888; // local port to listen for UDP packets IPAddress timeServer(192, 43, 244, 18); // time.nist.gov NTP server const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets // A UDP instance to let us send and receive packets over UDP EthernetUDP Udp; void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // start Ethernet and UDP if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // no point in carrying on, so do nothing forevermore: for (;;) ; } Udp.begin(localPort); } void loop() { sendNTPpacket(timeServer); // send an NTP packet to a time server // wait to see if a reply is available delay(1000); if ( Udp.parsePacket() ) { // We've received a packet, read the data from it Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer //the timestamp starts at byte 40 of the received packet and is four bytes, // or two words, long. First, esxtract the two words: unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); // combine the four bytes (two words) into a long integer // this is NTP time (seconds since Jan 1 1900): unsigned long secsSince1900 = highWord << 16 | lowWord; Serial.print("Seconds since Jan 1 1900 = " ); Serial.println(secsSince1900); // now convert NTP time into everyday time: Serial.print("Unix time = "); // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: const unsigned long seventyYears = 2208988800UL; // subtract seventy years: unsigned long epoch = secsSince1900 - seventyYears; // print Unix time: Serial.println(epoch); // print the hour, minute and second: Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) Serial.print(':'); if ( ((epoch % 3600) / 60) < 10 ) { // In the first 10 minutes of each hour, we'll want a leading '0' Serial.print('0'); } Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) Serial.print(':'); if ( (epoch % 60) < 10 ) { // In the first 10 seconds of each minute, we'll want a leading '0' Serial.print('0'); } Serial.println(epoch % 60); // print the second } // wait ten seconds before asking for the time again delay(10000); } // send an NTP request to the time server at the given address unsigned long sendNTPpacket(IPAddress& address) { // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: Udp.beginPacket(address, 123); //NTP requests are to port 123 Udp.write(packetBuffer, NTP_PACKET_SIZE); Udp.endPacket(); } A: If your ethernet shield is a cheap clone, they are known to be faulty. You will be able to get a DHCP address by plugging it directly into your DHCP server, but you will not get an address if the shield is connected to a switch. You can fix this by soldering 2 x 100 Ohm resistors to the correct pins of the network socket on the bottom of the shield. Alternatively, use a static ip address, or buy a different ethernet shield.
{ "language": "en", "url": "https://stackoverflow.com/questions/22556421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access to elements in a list of list (Rccp) I created a list of list in Rcpp (replicated 3 times) cppFunction('List myfunction(){ List L = rep(List::create(List::create(Named("elmement_1")=1,Named("elmement_2")=4)),3); return L; }') Output [[1]] [[1]]$elmement_1 [1] 1 [[1]]$elmement_2 [1] 4 [[2]] [[2]]$elmement_1 [1] 1 [[2]]$elmement_2 [1] 4 [[3]] [[3]]$elmement_1 [1] 1 [[3]]$elmement_2 [1] 4 Then, how I can access to each element (list) of L and each element inside theses elements ? I would be very grateful if anyone can help Thanks !
{ "language": "en", "url": "https://stackoverflow.com/questions/64648754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Retrieve last level directory name from path I have a string that represents a path ... something like this: /A/B/C/D/E/{id}/{file_name}.ext The path structure could be different but in general I would like to retrieve last directory name (in the example {id}) before the file-name. I would like to use Path java class. Is there a simple and safe way to retrieve last directory name using Path class? A: You could use getName() with File which is available Reference : https://docs.oracle.com/javase/6/docs/api/java/io/File.html#getName%28%29 File f = new File("C:\\Dummy\\Folder\\MyFile.PDF"); System.out.println(f.getName()); Which returns you MyFile.PDF. (or) // Path object Path path = Paths.get("D:\\eclipse\\configuration" + "\\myconfiguration.conf"); // call getName(int i) to get // the element at index i Path indexpath = path.getName(path.getNameCount()-2); // prints the name System.out.println("Name of the file : " + indexpath); Which prints myconfiguration.conf. Hope it helps ! A: Path#getParent returns a path’s parent. You can then use Path#getFileName: path.getParent().getFileName();
{ "language": "en", "url": "https://stackoverflow.com/questions/67696137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Drawing Rectangle with only 2 corners rounded in Qt I am working on an application where I need to fill the color for the Pixmap using Painter. Pixmap is of type rectangle with (bottom edge) 2 rounded corners. Top 2 corners are flat/normal. I tried to use the drawRoundedRect() API of Qt, but it makes all the corners of the rectangle rounded. I need to draw the rectangle with only 2 corners rounded and other two flat. If anyone comes across the situation, please suggest me the solution. Thanks A: You can use stylesheets (on runtime or loading the file qss). You could manage to do it very easily: QString str = "bottom-right-radius: 10px; top-right-radius: 0px...."; box->setStylesheet(str); I suppose the box is a pixmap inside a QLabel ( label->setPixmap(...) ) OR Set the object name to something (the label), and then use the QLabel#name { bottom-right-radius: 10px... } In a stylesheet you load. Check this site out. It helps: http://border-radius.com/ A: You can use QPainterPath for that : QPainterPath path; path.setFillRule( Qt::WindingFill ); path.addRoundedRect( QRect(50,50, 200, 100), 20, 20 ); path.addRect( QRect( 200, 50, 50, 50 ) ); // Top right corner not rounded path.addRect( QRect( 50, 100, 50, 50 ) ); // Bottom left corner not rounded painter.drawPath( path.simplified() ); // Only Top left & bottom right corner rounded A: Also you can use arcTo() to create rounded corners. Showcase: Code: // Position of shape qreal x = 100.0; qreal y = 100.0; // Size of shape qreal width = 300.0; qreal height = 200.0; // Radius of corners qreal corner_radius = 30.0; QPainterPath path; path.moveTo(x + corner_radius, y); path.arcTo(x, y, 2 * corner_radius, 2 * corner_radius, 90.0, 90.0); path.lineTo(x, y + (height - 2 * corner_radius)); path.arcTo(x, y + (height - 2 * corner_radius), 2 * corner_radius, 2 * corner_radius, 180.0, 90.0); path.lineTo(x + (width - 2 * corner_radius), y + height); path.lineTo(x + (width - 2 * corner_radius), y); path.lineTo(x + corner_radius, y); painter.drawPath(path); A: You can separately draw polygon and pies to create rectangle with 2 rounded corners Code: // Position of shape qreal x = 100; qreal y = 100; // Radius of corners qreal border_radius = 30; // Size of shape qreal width = 300; qreal height = 200; QPolygonF myPolygon; myPolygon << QPointF(x, y+border_radius) << QPointF(x+border_radius, y+border_radius) << QPointF(x+border_radius, y) << QPointF(x+width, y) << QPointF(x+width, y+height) << QPointF(x+border_radius, y+height) << QPointF(x+border_radius, y+height-border_radius) << QPointF(x, y+height-border_radius) << QPointF(x, y+border_radius); QPainterPath myPath; myPath.addPolygon(myPolygon); QPainter painter(this); painter.setRenderHints(QPainter::Antialiasing); painter.setPen(Qt::NoPen); QBrush myBrush(QColor(0, 0, 0), Qt::SolidPattern); painter.setBrush(myBrush); // Draw base polygon painter.drawPath(myPath); // Add rounded corners painter.drawPie(x, y, 2*border_radius, 2*border_radius, 90*16, 90*16); painter.drawPie(x, y+height-2*border_radius, 2*border_radius, 2*border_radius, 180*16, 90*16); How does it look like: Main polygon: QPolygonF myPolygon; myPolygon << QPointF(x, y+border_radius) << QPointF(x+border_radius, y+border_radius) << QPointF(x+border_radius, y) << QPointF(x+width, y) << QPointF(x+width, y+height) << QPointF(x+border_radius, y+height) << QPointF(x+border_radius, y+height-border_radius) << QPointF(x, y+height-border_radius) << QPointF(x, y+border_radius); QPainterPath myPath; myPath.addPolygon(myPolygon); // Draw base polygon painter.drawPath(myPath); Corners: // Add rounded corners painter.drawPie(x, y, 2*border_radius, 2*border_radius, 90*16, 90*16); painter.drawPie(x, y+height-2*border_radius, 2*border_radius, 2*border_radius, 180*16, 90*16); A: To extend the answer of Romha Korev. Here an example of a box with only rounded top corners (top left, top right). The rectangles in the corners are calculated based on the main rectangle! qreal left = 5; qreal top = 10; qreal width = 100; qreal height = 20; QRectF rect(left, top, width, height); QPainterPath path; path.setFillRule( Qt::WindingFill ); path.addRoundedRect(rect, 5, 5 ); qreal squareSize = height/2; path.addRect( QRect( left, top+height-squareSize, squareSize, squareSize) ); // Bottom left path.addRect( QRect( (left+width)-squareSize, top+height-squareSize, squareSize, squareSize) ); // Bottom right painter->drawPath( path.simplified() ); // Draw box (only rounded at top)
{ "language": "en", "url": "https://stackoverflow.com/questions/15288708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Select the most recent 5 rows based on date I haven't touched PHP in a while and trying to select the 5 most recent entries in my database and print them to screen. I see mysql command isn't recommended anymore and to use PDO->mysql instead. My query is something like this: SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5; I'm assuming I would have to put the values into an array and create a loop and output the results. <?php $db = new PDO('mysql:dbhost='.$dbhost.';dbname='.$dbname, $user, $pass); while () { print($title[$i], $date[$i], $author[$i]); $i++ } $db = null; ?> I'm stuck filling in the gaps with the above code. Update: The $db = new PDO.... line is reporting an error message: PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] Can't connect to local MySQL server through socket... in /var/... PDO is confirmed to be installed and enabled. My other web apps on the server can connect to the same remote mysql server fine. A: <?php $host = 'localhost'; $db = 'db-name'; $user = 'db-user'; $pw = 'db-password'; $conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); ?> <?php $sql = "SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5"; $query = $conn->prepare($sql); $query->execute(); $row = $query->fetch(PDO::FETCH_ASSOC); $totalRows = $query->rowCount(); ?> <?php do { // print your results here ex: next line echo 'Title: '.$row['title'].' Date: '.$row['date'].' Author: '.$row['author'].'<br>'; } while ($row = $query->fetch(PDO::FETCH_ASSOC)); ?> Don't forget to close and release resources <?php $query->closeCursor(); ?> EDIT I recommend not echoing error messages once you have confirmed your code functions as expected; however if you want to simply use plain text you can do this... You can add this to your connection block... if ($conn->connect_error) { die("Database Connection Failed"); exit; } You can also change your query block... try { $sql = "SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5"; $query = $conn->prepare($sql); $query->execute(); $row = $query->fetch(PDO::FETCH_ASSOC); $totalRows = $query->rowCount(); } catch (PDOException $e) { die("Could not get the data you requested"); exit; } Again, it is recommended that errors not be echoed. Use error checking only for debugging. A: <?php $db = PDO('mysql:dbhost=$dbhost;dbname=$dbname', $user, $pass); $sth = $db->prepare("SELECT id,title,date,author FROM table ORDER BY date LIMIT 5"); $sth->execute(); $result = $sth->fetch(PDO::FETCH_ASSOC); print_r($result); ?> in a loop: while($row = $sth->fetch()) { echo $row['column']; } From the documentation: http://php.net/manual/en/pdostatement.fetch.php
{ "language": "en", "url": "https://stackoverflow.com/questions/33337040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ng:areq : Argument 'AppController' is not a function, got undefined JS: (function () { 'use strict'; var app = angular.module('appModule', [ 'ngRoute', 'winjs' ]); app.controller('AppController', function ($scope) { $scope.splitViewElement = document.getElementById('splitView'); }); })(); HTML <!DOCTYPE html> <html ng-app> <head> <meta content="IE=edge, chrome=1" http-equiv="X-UA-Compatible" /> <title>Index</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum- scale=1" /> <script src="lib/angular/angular.min.js"></script> <script src="lib/angular-route/angular-route.min.js"></script> <link href="lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" /> <script src="lib/jquery/dist/jquery.js"></script> <script src="app/app-main.js"></script> <script type="text/javascript" src="app/device/device-main.js"></script> </script> </head> <body ng-controller="AppController as app"> <div> <win-split-view-pane-toggle split-view="splitViewElement"> </win-split-view-pane-toggle> <win-split-view id="splitView"> <win-split-view-pane> SplitView Navigation Pane <win-split-view-command label="'Home'" icon="'home'" on-invoked="goToHome()"></win-split-view-command> <win-split-view-command label="'Settings'" icon="'settings'" on-invoked="goToSettings()"> </win-split-view-command> </win-split-view-pane> <win-split-view-content>SplitView Content Area </win-split-view-content> </win-split-view> </div> </body> </html> Have included the "app-main.js", that contains the JS code above, Could someone please examine and let me know the reason for the above error. A: You should initialize your app in the ng-app. Like this <html ng-app="appModule"> Then it will work. if the ngApp directive were not placed on the html element then the document would not be compiled, the AppController would not be instantiated See angularjs docs for reference on this https://docs.angularjs.org/api/ng/directive/ngApp
{ "language": "en", "url": "https://stackoverflow.com/questions/35555750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Snakemake overwrites rules' log files when using retries - idiomatic way to make it append? I have a Snakemake workflow in which a rule can seemingly randomly fail. I'm using Snakemake 7.7.0 and have set retries for the rule using the retries directive. The command prints to stdout and stderr, and I want to append both to a logfile, keeping output from failed tries, so I can keep track of the failures. The simplified version of what I have is as follows: rule flaky_rule: input: infile = "{sample}/foo.txt" output: outfile = "{sample}/bar.txt" retries: 3 log: flaky_rule_log = "{sample}/logs/flaky_rule.log" shell: """ flaky_script -i "{input.infile}" -o "{output.outfile}" >> "{log.flaky_rule_log}" 2>&1 """ However, when I run this and the rule fails and is rerun, the logfile appears to be overwritten. For now, my workaround is to set the logfile in a params directive instead, but this of course will get me told off by the linter since I "don't have a logfile set" and feels a bit hackish to me. Is there a more idiomatic way to do this (either in this version or a higher one)? A: Probably too convoluted and not very idiomatic, but here's an option anyway. Run your command as a python subprocess, analysed the output and decide what to do after so many retries. For example: rule flaky_rule: input: infile = "{sample}/foo.txt" output: outfile = "{sample}/bar.txt" params: retries = 3 log: flaky_rule_log = "{sample}/logs/flaky_rule.log" run: import subprocess for retry in range(0, params.retries): p = subprocess.Popen('flacky_script {input} {output} >> "{log.flaky_rule_log}" 2>&1', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = p.communicate() if p.returncode == 0: break if p.returncode != 0: raise Exception('Failed after %s retries' % params.retries) A: Here's a variation based on an answer to a related question. The idea is to specify the path to the log file as a resource. This means that snakemake will not automatically clear it (which can be undesirable in some circumstances, so use with caution): rule flaky_rule: input: infile = "{sample}/foo.txt" output: outfile = "{sample}/bar.txt" resources: flaky_rule_log = lambda wildcards, attempt: f"{wildcards.sample}/logs/flaky_rule_attempt{attempt}.log" retries: 3 shell: """ flaky_script -i "{input.infile}" -o "{output.outfile}" >> "{resources.flaky_rule_log}" 2>&1 """ It would be great if params or logs supported attempt, but right now this is still an open issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/75530584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to install sphinx4? For the vast majority of you this will probably be straightforward, but I need help installing the sphinx4 speech recognition software. In particular, using cygwin to do so. 1) how does one set the environmental path variable to the java sdk (I had to install NetBeans) 2) Does one need to install ant if the ant libraries are already present in NetBeans? 3) Is there a better way to import the sphinx jars into my .java project in NetBeans than through using Cygwin? I don't know where I've been going wrong and could use any and all help A: For setting up of environment variables. 1) Right-click the My Computer icon on your desktop and select Properties. 2) Click the Advanced tab. 3) Click the Environment Variables button. 4) Under System Variables, click New. 5) Enter the variable name as JAVA_HOME. 6) Enter the variable value as the installation path for the Java Development Kit. If your Java installation directory has a space in its path name, you should use the shortened path name (e.g. C:\Progra~1\Java\jre6) in the environment variable instead. Note for Windows users on 64-bit systems Progra~1 = 'Program Files' Progra~2 = 'Program Files(x86)' 7 )Click OK. 8) Click Apply Changes. 9) Close any command window which was open before you made these changes, and open a new command window. There is no way to reload environment variables from an active command prompt. If the changes do not take effect even after reopening the command window, restart Windows. 10) If you are running the Confluence EAR/WAR distribution, rather than the regular Confluence distribution, you may need to restart your application server. Does one need to install ant if the ant libraries are already present in NetBeans? No. You don't need to install it again. Is there a better way to import the sphinx jars into my .java project in NetBeans than through using Cygwin? Using Cygwin(linux environment in Windows) definately works , but unsure about any other method.
{ "language": "en", "url": "https://stackoverflow.com/questions/17710236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JDialog inside a wrapper class does not appear I have a login form which is an instance of JDialog class. but it doesn't appear inside the JFrame. I implemented it inside the Application before as a method and it worked. but after wrapping it inside the Login class it does not work also there is not any error. what is the problem? public class Application extends JFrame { JDialog loginForm = null; public Application() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setExtendedState(JFrame.MAXIMIZED_BOTH); setMinimumSize(new Dimension(800, 400)); setVisible(true); loginForm = (JDialog) new Login(); } public static void main(String[] args) { try { UIManager.setLookAndFeel("com.alee.laf.WebLookAndFeel"); WebLookAndFeel.setDecorateDialogs(true); } catch (Exception e) { } Application app = new Application(); } } public class Login extends JDialog { private JButton loginButton = null; private JButton cancelButton = null; private JTextField userNameField = null; private JPasswordField userPassField = null; public void Login() { //... //... setSize(new Dimension(300, 200)); setResizable(false); setLocationRelativeTo(null); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setTitle("Login"); setVisible(true); setAlwaysOnTop(true); } class EventHandler implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == loginButton) { String username = userNameField.getText(); String password = Security.getSha256(userPassField.getText()); if(User.login(username, password)) { // Login Successful } else { // Login Failed. Alert error } } else if(e.getSource() == cancelButton) { System.exit(0); } } } } A: Just change public void Login() to public Login() Login is not a method, it is a constructor.
{ "language": "en", "url": "https://stackoverflow.com/questions/16670530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why window.open() opens in the same window? I write following code` <a href="b.html" class="popup">Holiday</a> <script> a.popup.click(function(event) { event.preventDefault(); window.open($(this).attr('href')); }); </script> It'll open b.html in a new window, but opens in the same, why? I include JQuery like this` <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"/> Which is the latest version? Can it be a reason? A: a.popup.click will throw an error because a is not defined. You are trying to use the jQuery click method, so you need to create a jQuery object that references the element you are trying to select. jQuery("a.popup").click(your_function) A: You can achieve opening in a different tab functionality in your case by simply specifying target="_blank" for your anchor tag as <a href="b.html" target="_blank" class="popup" > Holiday </a> A: You please try using the following code, it works, and you can choose your title and set different parameters that are suitable for you: $(document).ready(function(event) { $('a.popup').on('click', function(event) { var params = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes"; event.preventDefault(); window.open($(this).attr('href'), "Title", params); }); }); A: Just change this part <a href="b.html" target="_blank" class="popup" > jsFiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/19344591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Dax for % of columntotal I've got a tablereport with on the rows product category and on the columns years. In the valuesection, I want to show the number of sales. This works fine. But now I also want to show the % of columntotal for the product categories. I use dax: Measure := count(factSales[salesnr])/calculate(count(factSales[salesnr]);all(factSales)) But this yields the percentage of grand total over all years. I want the percentage of columntotal for every seperate year. A: The ALL(Table) function tells Power Pivot to ignore any filters applied over the whole table. Therefore, you're telling Power Pivot to count all the rows of the factsales table regarless of the Category or Year being filtered on the pivot table. However, in your case, what you want is the sum for ALL the categories on each year. Since you want the sum of ALL the categories you must use `ALL(factsales[categories]). In this way, you're ignoring only the filters for the categories and not the filters for the years. Based on the previous explanation the dax formula would be: Measure := count(factSales[salesnr]) / calculate(count(factSales[salesnr]);all(factsales[categories]))
{ "language": "en", "url": "https://stackoverflow.com/questions/37732968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cordova - Error code 1 for command | Command failed for I'm new on cordova, so if my question is not relevant, forgive me. i have a cordova project in my Windows 7 x64 machine. Yesterday i was build my cordova app via cordova build android --release. But i need to add new plugin cordova-plugin-zip to update my cordova project. What i did to add this plugin to my cordova app; * *I installed a git application to my win7 x64 env. *npm install -g git i wrote this command on cmd. *I Opened Windows Environment Variables/Path Window and added ;C:\Program Files (x86)\Git\bin;C:\Program Files (x86)\Git\cmd *add plugin via this command cordova plugin add https://github.com/apache/cordova-plugin-file.git *then added other plugin cordova plugin add https://github.com/MobileChromeApps/zip.git (Everything fine till this step) *Then i run on cmd cordova build android --release Unfourtunately it throws following error; BUILD FAILED C:\android\sdk\tools\ant\build.xml:720: The following error occurred while execu ting this line: C:\android\sdk\tools\ant\build.xml:734: Compile failed; see the compiler error o utput for details. Total time: 7 seconds C:\hascevher\platforms\android\cordova\node_modules\q\q.js:126 throw e; ^ Error code 1 for command: cmd with args: /s,/c,ant,release,-f,C:\hascevher\platf orms\android\build.xml,-Dout.dir=ant-build,-Dgen.absolute.dir=ant-gen ERROR building one of the platforms: Error: cmd: Command failed with exit code 1 You may not have the required environment or OS to build this project Error: cmd: Command failed with exit code 1 at ChildProcess.whenDone (C:\Users\Hddn\AppData\Roaming\npm\node_modules\cor dova\node_modules\cordova-lib\src\cordova\superspawn.js:134:23) at ChildProcess.emit (events.js:110:17) at maybeClose (child_process.js:1015:16) at Process.ChildProcess._handle.onexit (child_process.js:1087:5) When i try to create a new helloworld cordova project and adding android platform then from cmd cordova build android it creates sample app? So what is wrong with my other application? Any help greatly appricated. * *OS: Windows 7 x64 *Cordova v 5.1.1 *Ant version 1.9.4 Plugins On Cordova Project: * *cordova-plugin-file *cordova-plugin-zip *org.apache.cordova.console *org.apache.cordova.device *org.apache.cordova.inappbrowser Full Windows Environment Variables/Path: C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;%C_EM64T_REDIST11%bin\Intel64;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files (x86)\Java\jdk1.7.0_75\bin;C:\cordova\apache-ant-1.9.4\bin;C:\android\sdk\tools;C:\android\sdk\platform-tools;C:\Program Files\nodejs\;C:\Program Files (x86)\Git\bin;C:\Program Files (x86)\Git\cmd A: Delete platforms/android folder and try to rebuild. That helped me a lot. (Visual Studio Tools for Apache Cordova) A: Delete all the apk files from platfroms >> android >> build >> generated >> outputs >> apk and run command cordova run android A: I removed android platforms and installed again then worked. I wrote these lines in command window: cordova platform remove android then cordova platform add android A: I found answer myself; and if someone will face same issue, i hope my solution will work for them as well. * *Downgrade NodeJs to 0.10.36 *Upgrade Android SDK 22 A: I have had this problem several times and it can be usually resolved with a clean and rebuild as answered by many before me. But this time this would not fix it. I use my cordova app to build 2 seperate apps that share majority of the same codebase and it drives off the config.xml. I could not build in end up because i had a space in my id. com.company AppName instead of: com.company.AppName If anyone is in there config as regular as me. This could be your problem, I also have 3 versions of each app. Live / Demo / Test - These all have different ids. com.company.AppName.Test Easy mistake to make, but even easier to overlook. Spent loads of time rebuilding, checking plugins, versioning etc. Where I should have checked my config. First Stop Next Time! A: I had the same error code but different issue Error: /Users/danieloram/desktop/CordovaProject/platforms/android/gradlew: Command failed with exit code 1 Error output: Exception in thread "main" java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.0 To resolve this issue I opened the Android SDK Manager, uninstalled the latest Android SDK build-tools that I had (24.0.3) and installed version 23.0.3 of the build-tools. My cordova app then proceeded to build successfully for android. A: In my case it was the file size restriction which was put on proxy server. Zip file of gradle was not able to download due this restriction. I was getting 401 error while downloading gradle zip file. If you are getting 401 or 403 error in log, make sure you are able to download those files manually. A: Faced same problem. Problem lies in required version not installed. Hack is simple Goto Platforms>platforms.json Edit platforms.json in front of android modify the version to the one which is installed on system. A: I'm using Visual Studio 2015, and I've found that the first thing to do is look in the build output. I found this error reported there: Reading build config file: \build.json... SyntaxError: Unexpected token The solution for that was to remove the bom from the build.json file Then I hit a second problem - with this message in the build output: FAILURE: Build failed with an exception. * What went wrong: A problem was found with the configuration of task ':packageRelease'. File 'C:\Users\Colin\etc' specified for property 'signingConfig.storeFile' is not a file. Easily solved by putting the correct filename into the keystore property
{ "language": "en", "url": "https://stackoverflow.com/questions/31089647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Breaking Ruby class for DRY I have some classes like these: class Word def initialize (file_name) load_file(file_name) end def pick_first_word(score) #get first word end private def load_file(file_name) #load the file end end class MyClass < SomeOther def initialize (file_name) @word = Word.new(file_name) end def pick @word.pick_first_word end #some other code end dosomething = MyClass.new("words.txt") dosomethingelse = MyClass.new("movies.txt") So I have a class for Word that reads in a file and picks first word. Just like that I want to have another class, say Movies, that will have its own implementation of load_file and pick_first_word. I want this controlled by the type of file that I send to MyClass. Question What is a good way to change the initialize method in MyClass so that it initiates the correct class based on the type of file I send. I can do it by if/else on the file name but that doesn't seem very scalable. Is there a better way to do this than changing initialize method for MyClass to this? def initialize (file_name) if (file_name == "word.txt") @word = Word.new(file_name) else @word = Movie.new(file_name) end This implementation doesn't seem very scalable. A: It's all a matter of tradeoffs -- in this case, you want just enough complexity to handle a reasonable number of cases. If there are only two options, I think that if statement looks just fine. A 'case' statement (aka a switch statement) can be DRYer, and you may want to explicitly say "movie.txt", e.g. @word = (case file_name when "word.txt" Word when "movie.txt" Movie else raise "Unknown file name #{file_name}" end).new(file_name) or extract a class_for_file_name method if you don't like putting a case statement in parens, even though it's pretty fun. If your set of polymorphic classes gets bigger, you might get more mileage out of a lookup table: class_for_file_name = { "word.txt" => Word, "movie.txt" => Movie, "sandwich.txt" => Sandwich, } @word = class_for_file_name[file_name].new(file_name) And of course, maybe you're oversimplifying and you really want to switch on the file extension, not the file name, which you could get with File.extname(file_name). You could also get even fancier and ask each concrete class whether it handles this file name; this feels more OO -- it puts the knowledge about foos inside the Foo class -- but is arguably more complicated: class Word def self.good_for? file_name file_name == "word.txt" end end class Movie def self.good_for? file_name file_name == "movie.txt" end end ... def class_for_file_name file_name [Word, Movie].detect{|k| k.good_for? file_name} end BTW this problem more or less fits the design pattern called Abstract Factory; you may want to look it up and see if any of its analyses inspire you. A: Try the FileMagic library. gem install ruby-filemagic Example: require 'filemagic' type = FileMagic.new.file file_name
{ "language": "en", "url": "https://stackoverflow.com/questions/16065822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: GameplayKit's nextIntWithUpperBound() failing in playground The below code works great in an iOS project, but fails in an iOS playground. Any idea why, other than "it's probably a bug"? Note: you need to open the playground debug area to see the message: "overloads for 'subscript' exist with these partially matching parameter lists: (Int), (Range), (Range), (Self.Index)" import GameplayKit import UIKit let countries = ["france", "germany", "italy"] let randomIndex = GKRandomSource.sharedRandom().nextIntWithUpperBound(3) let chosenCountry = countries[randomIndex].uppercaseString print(chosenCountry) Again, that same code works just fine in a regular iOS project. It looks like something is confused about Int and UInt, because if I typecast randomIndex as Int it works fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/34274893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to create a Role in Loopback/Node.Js I created this method to create an Admin Role. I have to check in user table if the admin field is set to 0 or 1 of the current user to detect if it's a normal user or an admin. Problem is when I console.log('obj',objUser) I get this : obj Promise { _bitField: 0, _fulfillmentHandler0: undefined, _rejectionHandler0: undefined, _promise0: undefined, _receiver0: undefined } This is what I've built so far : Role.registerResolver('Admin', function(role, context, cb) { //Q: Is the user logged in? (there will be an accessToken with an ID if so) var userId = context.accessToken.userId; if (!userId) { //A: No, user is NOT logged in: callback with FALSE return process.nextTick(() => cb(null, false)); } var user = app.models.user; var objUser = user.findById(userId); console.log('obj',objUser) if(objUser.admin==1){ return cb(null, true); } else{ return cb(null, false); } }); Do you have any idea what's wrong am I doing. Any help would be appreciated. Thank you. A: you should read about javascript Promises, it's crucial to understand javascript in general and async programming. Also, check the async/await
{ "language": "en", "url": "https://stackoverflow.com/questions/56873074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to output group claims in B2C from ADFS as an identity provider I'm using ADFS as an IdP for Azure B2C through OpenID Connect. Login works and B2C sends UPN from ADFS as socialIdpUserId claim in JWT token. But group claims from ADFS do not work. How to receive group claims in JWT? Here is the setup: ADFS claim rule: domain security groups and upn c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"] => issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn", "http://schemas.xmlsoap.org/claims/Group"), query = ";userPrincipalName,tokenGroups(longDomainQualifiedName);{0}", param = c.Value); Client permissions are set to openid and allatclaims New group claim type definition in TrustFrameworkBase policy in ClaimsSchema: <ClaimsSchema><ClaimType Id="group"> <DisplayName>group</DisplayName> <DataType>string</DataType> <DefaultPartnerClaimTypes> <Protocol Name="OAuth2" PartnerClaimType="group" /> <Protocol Name="OpenIdConnect" PartnerClaimType="group" /> <Protocol Name="SAML2" PartnerClaimType="http://schemas.xmlsoap.org/claims/Group" /> </DefaultPartnerClaimTypes> </ClaimType></ClaimsSchema> Output group claim definition in TechnicalProfile in TrustFrameworkExtensions policy: <OutputTokenFormat>JWT</OutputTokenFormat><OutputClaims> <OutputClaim ClaimTypeReferenceId="socialIdpUserId" PartnerClaimType="UPN" /> <OutputClaim ClaimTypeReferenceId="group" PartnerClaimType="group" /> </OutputClaims> Output group claim definition in TechnicalProfile in SignUpOrSignIn policy file <TechnicalProfile Id="PolicyProfile"> <DisplayName>PolicyProfile</DisplayName> <Protocol Name="OpenIdConnect" /> <OutputClaims> <OutputClaim ClaimTypeReferenceId="socialIdpUserId" /> <OutputClaim ClaimTypeReferenceId="group" /> <OutputClaim ClaimTypeReferenceId="authmethod" /> <OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub"/> <OutputClaim ClaimTypeReferenceId="identityProvider" /> </OutputClaims> <SubjectNamingInfo ClaimType="sub" /> </TechnicalProfile> But there is no group claim comes with JWT token! Why? A: Here is how to issue group claims out of B2C: 1. Define a new claim type in for groups in the Base policy file. This definition should be at the end of < ClaimsSchema > element (yes, the man who wrote about stringCollection was write!) <ClaimType Id="IdpUserGroups"> <DisplayName>Security groups</DisplayName> <DataType>stringCollection</DataType> <DefaultPartnerClaimTypes> <Protocol Name="OAuth2" PartnerClaimType="groups" /> <Protocol Name="OpenIdConnect" PartnerClaimType="groups" /> <Protocol Name="SAML2" PartnerClaimType="http://schemas.xmlsoap.org/claims/Group" /> </DefaultPartnerClaimTypes> </ClaimType> *Use this new defined claim in the < OutputClaims > in the extenstion policy in < ClaimsProvider > definition for ADFS <OutputClaims> <OutputClaim ClaimTypeReferenceId="socialIdpUserId" PartnerClaimType="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" /> <OutputClaim ClaimTypeReferenceId="IdpUserGroups" PartnerClaimType="http://schemas.xmlsoap.org/claims/Group" /> <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="SAML fmdadfs4.local"/> <OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="SAML ADFS4 fmdadfs4.local" /> </OutputClaims> *Use the same claim in the < OutputClaims > dfinition in relyng party definition under < RelyngParty > elemnt in your SignIn policy file <OutputClaims> <OutputClaim ClaimTypeReferenceId="socialIdpUserId" /> <OutputClaim ClaimTypeReferenceId="IdpUserGroups" /> <OutputClaim ClaimTypeReferenceId="identityProvider" /> <OutputClaim ClaimTypeReferenceId="userPrincipalName" PartnerClaimType="userPrincipalName" /> *Issue group claims from ADFS as it is shown here A: Looks like OP simply has the partnerclaimtype misspelled. Not certain because you may have mapped something non-standard, but I'm thinking you just need to change your PartnerClaimType from group to groups. <ClaimType Id="groups"> <DisplayName>Groups</DisplayName> <DataType>stringCollection</DataType> <DefaultPartnerClaimTypes> <Protocol Name="OpenIdConnect" PartnerClaimType="groups" /> </DefaultPartnerClaimTypes> <UserHelpText>List of group memberships</UserHelpText> </ClaimType> * *Once you define the ClaimType, you don't need to specify the PartnerClaimType anywhere else - unless you're overriding the value. *I'd also consider using the DefaultValue="" attribute so you can check your policy is properly executing the output claim. OutputClaim ClaimTypeReferenceId="groups" DefaultValue="no groups assigned
{ "language": "en", "url": "https://stackoverflow.com/questions/52312521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Misplaced sense of an ASP PlaceHolder control I have a simple div on html, something like: <div class="warning"> <h3>Please make sure:</h3> <asp:PlaceHolder id="phWarnings" runat="server"></asp:PlaceHolder> <br /> <a href="javascript:void(0)" onClick="$('#warning').hide()">Okay</a> </div> The PlaceHolder is being populated with a couple of radio buttons, a covering div, some h4 and p elements. However, when the page shows up, the whole div (along with its children contents) are completely outside the warning div. I thought I was messing up the div structure in codebehind so I just commented out everything and did this: phWarnings.Controls.Add(new LiteralControl("Meh")); Guess what? Yeah, the string "Meh" was outside the warning div too. The HTML (on view source) option shows this: <div class="warning"> <h3>Please make sure:</h3> <br /> <a href="javascript:void(0)" onClick="$('#warning').hide()">Okay</a> </div> Meh I have done the similar things other times but never faced this problem. I was hoping you guys could shed some light on why placeholder decided to go out of parent div or how to avoid it. removing the class from warning div etc doesn't seem to work. Any idea why this is happening please? A: Things don't just happen, they happen for a reason. If they look as if they just happen, then that just means you don't know the reason... which is why you are asking. So... The problem has to be with either your html or your css. As you don't give us much to go on, there isn't much that anyone can say. You could put a page up, and provide a link to that, for people to look at the html and the css. No reason you can't do that. Things to look out for in your css? floats that haven't been cleared for example. Things to look out for in the Html? Unclosed tags. You can diagnose the above kind of problem by right clicking on the offending area and doing "Inspect Element" when viewing the page in either Google Chrome or FireFox? Are you assigning css classes using jquery or similar? Probably not, given your inline js code in the a tag... All the above or a combination thereof are possible candidates, but in the absence of a page to look at, your not going to get much help. A: I may not be correct but what i interpreted from the description is you are appending some HTML from code behind into your place holder. If it is possible you can append the elements into your div through jquery. $('div.warning').append("your content") A: Just guessing here, are you overriding the page's render method? And ff you try and change the containing div to runat="server" what happens?
{ "language": "en", "url": "https://stackoverflow.com/questions/5309921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Projection of mongodb subdocument and get subdocument as class in c# Hi. I have a Collection named "Level" with this class structure : public class Level { [BsonId] public string Id {get; set;} public string Name { get; set; } public int Number { get; set; } public int TotalScore { get; set; } public int QuestionCount { get; set; } public IEnumerable<ConnectingQuestion> ConnectingQuestions { get; set; } } public class ConnectingQuestion { [BsonId] public string Id { get; set; } public int QuestionNumber { get; set; } public string Description { get; set; } public string Type { get; set; } public string Title { get; set; } } and collection structure like this : { "_id" : "64e850f95322e01e88f131a2", "Name" : "First Level", "Number" : NumberInt(1), "TotalScore" : NumberInt(2690), "QuestionCount" : NumberInt(40), "ConnectingQuestions" : [ { "_id" : "5a130570738634297478fb43", "QuestionNumber" : NumberInt(1), "Description" : "desc", "Type" : "sc", "Title" : "title1", }, { "_id" : "5a130570738634297478fb76", "QuestionNumber" : NumberInt(2), "Description" : "desc", "Type" : "sc", "Title" : "title2", }, { "_id" : "5a130570738634297478fb23", "QuestionNumber" : NumberInt(3), "Description" : "desc", "Type" : "sc", "Title" : "title3", } ] } { "_id" : "59e850f95322e01e88f131c1", "Name" : "Second Level", "Number" : NumberInt(2), "TotalScore" : NumberInt(8000), "QuestionCount" : NumberInt(20), "ConnectingQuestions" : [ { "_id" : "5a130570738634297478fa56", "QuestionNumber" : NumberInt(1), "Description" : "desc", "Type" : "sc", "Title" : "title1", }, { "_id" : "5a130570738634297478fb66", "QuestionNumber" : NumberInt(2), "Description" : "desc", "Type" : "sc", "Title" : "title2", }, { "_id" : "5a130570738634297478fe32", "QuestionNumber" : NumberInt(3), "Description" : "desc", "Type" : "sc", "Title" : "title3", } ] } i need to write Query in c# that first select level with specified id and in selected level, select and return "ConnectingQuestion" subcollection with certain "QuestionNumber" in type of ConnectingQuestion class and not BsonDocument. A pseudo-query like this: ConnectingQuestion cq = MongoDB.Levels.find(level.id == "59e850f95322e01e88f131c1" && level.ConnectingQuestions.QuestionNumber == 2).Projection(level.ConnectingQuestions).SingleOrDefault(); A: Here are two possible solutions - there may be simpler ones... Version 1: Using find() and project() only plus some BSON magic var collection = new MongoClient().GetDatabase("test").GetCollection<Level>("test"); var projection = Builders<Level>.Projection.ElemMatch(level => level.ConnectingQuestions, q => q.QuestionNumber == 2); var bsonDocument = collection // filter out anything that we're not interested in .Find(level => level.Id == "59e850f95322e01e88f131c1") .Project(projection) .First(); // get first (single!) item from "ConnectingQuestions" array bsonDocument = bsonDocument.GetElement("ConnectingQuestions").Value.AsBsonArray[0].AsBsonDocument; // deserialize bsonDocument into ConnectingQuestions instance ConnectingQuestion cq = BsonSerializer.Deserialize<ConnectingQuestion>(bsonDocument); Version 2: Using the aggregation framework ($filter needs MongoDB >= v3.2) var collection = new MongoClient().GetDatabase("test").GetCollection<Level>("test"); var cq = collection.Aggregate() // filter out anything that we're not interested in .Match(level => level.Id == "59e850f95322e01e88f131c1") // filter the ConnectingQuestions array to only include the element with QuestionNumber == 2 .Project<Level>("{ 'ConnectingQuestions': { $filter: { input: '$ConnectingQuestions', cond: { $eq: [ '$$this.QuestionNumber', 2 ] } } } }") // move the first (single!) item from "ConnectingQuestions" array to the document root level .ReplaceRoot(q => q.ConnectingQuestions.ElementAt(0)) .FirstOrDefault();
{ "language": "en", "url": "https://stackoverflow.com/questions/47659837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I want to pin down Elasticsearch during Ubuntu 18.04 to 20.04 upgrade I'm trying to upgrade my ubuntu 18.04 to 20.04 and don't want Elasticsearch version to change. I ran the below playbook - block: - debug: msg: "This server is running Ubuntu 18.04 LTS and will be upgraded to 20.04 LTS." - name: "Excluding Elasticsearch version from being upgraded" dpkg_selections: name: elasticsearch selection: hold - name: "Remove the EOL message of the day if one exists" file: path: "{{ item }}" state: absent with_items: - /etc/update-motd.d/99-esm - /run/motd.dynamic - name: "Upgrade all packages to the latest version, take a glass of water" apt: update_cache=yes upgrade=full - name: "Ensure update-manager-core is installed" apt: name=update-manager-core state=present - name: "Check if a reboot is needed on all servers" register: reboot_required_file stat: path: /var/run/reboot-required # get_md5: no - name: "Reboot the server if kernel updated" reboot: msg: "Reboot initiated by Ansible for kernel updates" connect_timeout: 5 reboot_timeout: 300 pre_reboot_delay: 0 post_reboot_delay: 30 test_command: uptime when: reboot_required_file.stat.exists - name: "Run do-release-upgrade non-interactively, grab a cup of coffee this will take a while" command: do-release-upgrade -f DistUpgradeViewNonInteractive - name: Reboot the server. reboot: - name: "Removing elasticsearch from Hold" dpkg_selections: name: elasticsearch selection: install when: ansible_distribution == 'Ubuntu' and ansible_distribution_version == '18.04' I got the below error FAILED! => {"changed": true, "cmd": ["do-release-upgrade", "-f", "DistUpgradeViewNonInteractive"], "delta": "0:00:03.862558", "end": "2022-11-24 20:03:37.481173", "msg": "non-zero return code", "rc": 1, "start": "2022-11-24 20:03:33.618615", "stderr": "", "stderr_lines": [], "stdout": "Checking for a new Ubuntu release\nPlease install all available updates for your release before upgrading.", "stdout_lines": ["Checking for a new Ubuntu release", "Please install all available updates for your release before upgrading."]}
{ "language": "en", "url": "https://stackoverflow.com/questions/74605149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can you get the name of a resx string accessed through dot notation using some sort of reflection? I have language resource files that I typically access using dot notation like so: MyStrings.This_is_a_test_string However, I now need to get two language versions of the same string in error handling. The reason is the local string is shown to the user while the English string is written to the log file. I can call the function below using a statement such as: ----- begin code ----- strCustomErrorMsg = GetCustomErrorMsgStrings(MyStrings.ResourceManager.BaseName, "This_is_a_test_string") Public Function GetCustomErrorMsgStrings(strResource As String, strProperty As String) As String Dim rm As ResourceManager Dim strLocal As String Dim strEnglish As String Dim strCustomErrorMsg As String rm = New ResourceManager(strResource, Assembly.GetExecutingAssembly()) strLocal = rm.GetString(strProperty, Thread.CurrentThread.CurrentUICulture) SetLanguage("en") strEnglish = rm.GetString(strProperty, Thread.CurrentThread.CurrentUICulture) SetLanguage(g_strLanguage) strCustomErrorMsg = "Local Text: " & strLocal & "||||" & vbNewLine & "English: " & strEnglish GetCustomErrorMsgStrings = strCustomErrorMsg End Function ----- endcode ----- The problem is I want to continue to use the strongly typed resx class and dot notation such as MyStrings.This_is_a_test_string so Visual Studio catches non existent resource strings in real-time. For the strProperty parameter, is there any way I can do something like passing MyStrings.This_is_a_test_string.GetName.ToString() which will reflect the name "This_is_a_test_string" back to me? My concern is I will make typos when entering the literal strings such as "This_is_a_test_string" for the strProperty parameter and maintenance will become more difficult. Thanks for the help. Matthew A: If your only concern is that you will make typos when entering the literal string then just use NameOf(MyStrings.This_is_a_test_string).
{ "language": "en", "url": "https://stackoverflow.com/questions/70195057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you create a new column based on Max value of 1 column and Category of another? I am working with a bunch of data for my job creating status reports on the documents that we are working through that we then assign to an area. We decided to use PowerBI as an interactive way to see where everything is at. Using Power BI Desktop I've created a new table that excludes documents that are not ready for QC but we have several different statuses. Instead of creating a new table for each status type (since some can be grouped together) I would like to create a new column that has the grouped status value's Max for each area. The higher the Status Value the further it is from being complete. EX: Record: Area: Status Value: Max Status Value: 152385 A 1 2 354354 B 2 3 131322 B 3 3 132136 A 2 2 213513 A 1 2 351315 B 2 3 If anyone knows how to get the Max Status Value column that would greatly help. I did find another post (https://community.powerbi.com/t5/Desktop/LOOKUPVALUE-return-min-max-of-values-found/td-p/657534) that was similar but I'm still new to DAX and could not figure out how to apply it to my situation. A: This post actually helped me answer the question. https://community.powerbi.com/t5/Power-Query/Maxifs-Power-Query/m-p/1693606 The only difference I made was getting rid of the true/false portion to receive my results. Thus my result was: Max Status Value = VAR vMaxVal= CALCULATE ( MAX ( 'Table'[Status Value] ), ALLEXCEPT ( 'Table', 'Table'[Area] ) ) RETURN vMaxVal
{ "language": "en", "url": "https://stackoverflow.com/questions/67131507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Input field set as 'Value=' instead of 'value=' I have a project written in C# MVC using Razor templates. On one of my pages I have several input fields that contain numeric values. The Razor code that sets the values of these input fields looks like this: @Html.Editor(Model.DesignParams[i].ParamId, new { htmlAttributes = new { @Value = Model.DesignParams[i].DefaultValue, @class = "form-control text-right", @type = "text", id = "_" + Model.DesignParams[i].ParamId, uomid = Model.DesignParams[i].UOMId, measureid = Model.DesignParams[i].MeasureId } }) The above code works fine using FireFox and Chrome and generates an input field that looks like this: <input type="text" uomid="MBH" name="HeatOfRejection" measureid="HeatLoad" id="_HeatOfRejection" class="form-control text-right text-box single-line" value="5000.0"> But the same Razor code, identical @Model values viewed with IE generates this: <input Value="5000" class="form-control text-right text-box single-line" id="_HeatOfRejection" measureid="HeatLoad" name="HeatOfRejection" type="text" uomid="MBH" value="" /> As you can see, there is a difference between the value= attribute generated for IE in that the value attribute that gets my actual value begins with an uppercase 'V' and the lowercase value is an empty string. I'm stumped on this... Can anyone tell me why this is happening and possibly how to handle it? This difference effects jQuery's ability to return the input's value with: var value = $(inputfield).attr("value"); Maybe .val() will retrieve the input field value, but this is going to require a rewrite of core jQuery code that supports this page and others, so I wanted to ask if anyone can tell me why this 'Value=' gets created for IE only and if there is a way of overcoming the problem. Update: Changing @Value to @value (or just value) results in an empty value attribute in Firefox and IE: <input type="text" value="" uomid="MBH" name="HeatOfRejection" measureid="HeatLoad" id="_HeatOfRejection" class="form-control text-right text-box single-line"> A: You are "capitalising" the value html attribute. Change this to lower case... @Value = Model.DesignParams[i].DefaultValue as below ... @value = Model.DesignParams[i].DefaultValue IE is not the smartest of web browsers and there's definitely something wrong in the way Trident (they're parsing engine) validates elements' attributes as seen in these threads... https://github.com/highslide-software/highcharts.com/issues/1978 Highcharts adds duplicate xmlns attribute to SVG element in IE Also, as already noted somewhere else. What's the need for the Editor extension method? Isn't it simpler to just use TextBoxFor instead? @Html.TextBoxFor(model => model.DesignParams[i].ParamId , new { @class = "form-control text-right" , uomid = Model.DesignParams[i].UOMId , measureid = Model.DesignParams[i].MeasureId }) A: As StuartLC points out, you are trying to get Html.Editor to do something it wasn't designed to do. What happens when you pass a @value or @Value key to the htmlAttributes is that the rendering engine produces an attribute with that name in addition to the value attribute it's already generating: <input type="text" name="n" value="something" value="somethingElse" /> or <input type="text" name="n" value="something" Value="somethingElse" /> In both cases, you're giving the browser something bogus, so it can't be expected to exhibit predictable behavior. As alluded above, Html.Editor has functionality to generate the value attribute based on the expression argument you pass to it. The problem is that you are using that incorrectly as well. The first argument to Html.Editor() needs to be an expression indicating the model property that the editor should be bound to. (e.g. the string value "DesignParams[0].ParamId") Nowadays, the preferred practice is to use the more modern EditorFor that takes a lambda function, as StuartLC showed in his post: @Html.EditorFor(model => model.DesignParams[i].ParamId, ...) A: You shouldn't be using invalid Html attributes in this way. Use the data- attributes in Html 5. Also, your use of @Html.Editor(Model.DesignParams[i].ParamId (assuming ParamId is a string) deviates from the helper's purpose, which is to reflect the property with the given name off the Model, and use the value of this property as the Html value attribute on the input. (MVC will be looking for a property on the root model with whatever the value of ParamId is, which seems to silently fail FWR) I would do the defaulting of Model.DesignParams[i].ParamId = Model.DesignParams[i].DefaultValue in the Controller beforehand, or in the DesignParams constructor. @Html.EditorFor(m => m.DesignParams[0].ParamID, new { htmlAttributes = new { // Don't set value at all here - the value IS m.DesignParams[0].ParamID @class = "form-control text-right", @type = "text", id = "_" + Model.DesignParams[i].ParamId, data_uomid = Model.DesignParams[i].UOMId, data_measureid = Model.DesignParams[i].MeasureId } Note that this will give the input name as DesignParams[0].ParamID, which would be needed to post the field back, if necessary. Here's a Gist of some example code (The underscore will be converted to a dash) Use data() in jQuery to obtain these values: var value = $(inputfield).data("uomid"); A: Editor works with metadata. then you need to more about this, http://aspadvice.com/blogs/kiran/archive/2009/11/29/Adding-html-attributes-support-for-Templates-2D00-ASP.Net-MVC-2.0-Beta_2D00_1.aspx But the easiest way is go with @model Namespace.ABCModel @using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.TextBoxFor(model => model.DesignParams[i].ParamId, new { @class = "form-control text-right", uomid = Model.DesignParams[i].UOMId, measureid = Model.DesignParams[i].MeasureId }) }
{ "language": "en", "url": "https://stackoverflow.com/questions/27559582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Should I use public $var or should I use __construct()? I'm new to PHP OOP, and I think public $var and __construct() are exactly the same. What's the difference? Which one should I use? A: They are completely different things: one declares a class property, and the other is the name of the class constructor. There is no such thing as "one or the other" here. I suggest re-reading all about classes and objects in your PHP book, or the manual. A: public $var is not a constructor, which __construct() is. I hope you meant something else. As stated in the manual, there's two kinds of constructors: class Bar { public function Bar() { // "old" style constructor } } class Foo { function __construct() { // new style constructor } } A: public $var; Declares a variable that will be accessible to the outside world. function __construct () { /* Do stuff */ } Defines the "magic" constructor method. This method will be invoked when a new instance is created (i.e. when you create a new object). This method is what accepts and handles any arguments that are passed when creating a new object. The key difference is that one defined a variable (property) and one defines a function (method).
{ "language": "en", "url": "https://stackoverflow.com/questions/8151950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Casting from double to decimal rounds columns in Scala Spark I have a dataframe that looks like this when I print it using df.show(): |---id---|----val_dbl----| | 1| 1.378332E-7| | 2| 2.234551E-7| | 3| 4.03E-7| |--------|---------------| with the schema df.printSchema() |-- id: integer |-- val_dbl: double Then I cast val_dbl to decimal: df.withColumn('val_dec', col('val_dbl').cast(DecimalType(18,7)) But then I get this when I print: |---id---|----val_dec----| | 1| 1.38E-7| | 2| 2.23E-7| | 3| 4.03E-7| |--------|---------------| |-- id: integer |-- val_dec: decimal(18,7) But it should look like: |---id---|----val_dec----| | 1| 1.378332E-7| | 2| 2.234551E-7| | 3| 4.030000E-7| |--------|---------------| |-- id: integer |-- val_dec: decimal(18,7) How come it isn't printing out the full value? Is it actually rounding, or is this just for convenience? And how can I print the full decimal values? I can't imagine it is actually rounding.
{ "language": "en", "url": "https://stackoverflow.com/questions/71667400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent SQL Injection when using MVC's bundling We have an MVC 5 site and currently we are using bundles for our css and java script which is all working just fine. The issue is that when doing so, it creates something like: /bundles/stylesheet?v=_NMyDE-CcoALPkYZqbmiXkI3LfoWnS1GFeEZNVMaBT81 We also use a third party site to verify that our site is trusted and secure and the other day it flagged us for the fact that using the above with '+and+'b'<'a on the end returns a 200 response instead of a 500. So i guess i have two questions, is this a security flaw in MVC's bundles that is susceptible to SQL injection and if so, is there a workaround or fix? A: The v parameter sent in that web request is just used as a way to help the browser know when to request a new resource--commonly called "cache busting." The number that MVC puts in the bundle links will change any time the files used in the bundle are changed, but the server doesn't even pay any attention to the parameter at all when the actual request is made. Because of this, the auditing software sees a pattern that indicates it can send "anything" to the server, and it never gets checked to see if it is valid. In some cases, this can be indicative that their sql injection "got through," but in this case it's a false positive. The bundling framework doesn't touch SQL at all, so there's absolutely no way that this represents a SQL injection vulnerability. For more information, see the "Bundle Caching" section of this article.
{ "language": "en", "url": "https://stackoverflow.com/questions/25123734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Error: ORA-02000: missing ALWAYS keyword i use Oracle version 11g and i want to ad HR db but when i try to create Table this error appear . CREATE TABLE regions ( region_id NUMBER GENERATED ALWAYS BY DEFAULT AS IDENTITY START WITH 5 PRIMARY KEY, region_name VARCHAR2( 50 ) NOT NULL ); how can i resolve this issue without changing my oracle version? A: Identity has been introduced as part of Oracle 12c and not available in 11g, so for auto-increment ID prior to 12c you can use this post Developers who are used to AutoNumber columns in MS Access or Identity columns in SQL Server often complain when they have to manually populate primary key columns using sequences in Oracle. This type of functionality is easily implemented in Oracle using triggers. Create a table with a suitable primary key column and a sequence to support it. CREATE TABLE departments ( ID NUMBER(10) NOT NULL, DESCRIPTION VARCHAR2(50) NOT NULL); ALTER TABLE departments ADD ( CONSTRAINT dept_pk PRIMARY KEY (ID)); CREATE SEQUENCE dept_seq; Create a trigger to populate the ID column if it's not specified in the insert. CREATE OR REPLACE TRIGGER dept_bir BEFORE INSERT ON departments FOR EACH ROW WHEN (new.id IS NULL) BEGIN SELECT dept_seq.NEXTVAL INTO :new.id FROM dual; END; / A: In Oracle version pre 12c, you should use a SEQUENCE and TRIGGER to handle your auto-number ID Table CREATE TABLE regions ( region_id NUMBER(10) NOT NULL, region_name VARCHAR2(50) NOT NULL ); ALTER TABLE regions ADD ( CONSTRAINT regions_pk PRIMARY KEY (ID)); Sequence: CREATE SEQUENCE regions_seq; Trigger: CREATE OR REPLACE TRIGGER regions_id_generate BEFORE INSERT ON regions FOR EACH ROW WHEN (new.region_id IS NULL) BEGIN SELECT regions_seq.NEXTVAL INTO :new.region_id FROM dual; END; / When you do an insert, just specify a NULL value for your region_ID column, and Oracle will attribute it the next integer number in the sequence A: Im sorry, but maybe the server/database you are trying to connect to is 12c and yours/client doesnt support the feature. (I believe the IDENTITY definition is introduced in 12c) Maybe try to use SEQUENCE instead. (Sequence is an object that is not bound to a specific table and can be used anywhere to get new unique numbers. Because of this you should create a trigger to set the value to your column)
{ "language": "en", "url": "https://stackoverflow.com/questions/63771011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to not switch to the first or last "li element" when they are next in line? I have a pagination bar and it will switch to the next button if you click the "next" or "prev" arrow buttons. I wrote some code to stay on the current "page" number if the next item in the list is ".next" or ".prev", but it is not working. What am I missing? $(document).ready(function() { var pageItem = $(".pagination li").not(".prev,.next"); var prev = $(".pagination li.prev"); var next = $(".pagination li.next"); pageItem.click(function() { $('li.active').removeClass("active"); $(this).addClass("active"); }); // stay on current button if next or prev button is ".next" or ".prev" next.click(function() { if($('li.active').next() != next) { $('li.active').removeClass('active').next().addClass('active'); } }); prev.click(function() { if($('li.active').prev() != prev) { $('li.active').removeClass('active').prev().addClass('active'); } }); }); <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <nav> <ul class="pagination"> <li class="prev"> <a href="#"><span>&laquo;</span></a> </li> <li class="active"><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li class="next"> <a href="#"><span>&raquo;</span></a> </li> </ul> </nav> A: jQuery selectors return an Array object, objects cannot be deemed equal unless they are derived from each other. i.e. var a = [] var b = [] console.log(a==b); //would output false If you changed you code to select the item in the array you would get the actual DOM node $('li.active').next()[0] != next[0] A: All you need to check the class name, Please check below updated code $(document).ready(function() { var pageItem = $(".pagination li").not(".prev,.next"); var prev = $(".pagination li.prev"); var next = $(".pagination li.next"); pageItem.click(function() { $('li.active').removeClass("active"); $(this).addClass("active"); }); // stay on current button if next or prev button is ".next" or ".prev" next.click(function() { if($('li.active').next().attr('class') != 'next') { $('li.active').removeClass('active').next().addClass('active'); } }); prev.click(function() { if($('li.active').prev().attr('class') != 'prev') { $('li.active').removeClass('active').prev().addClass('active'); } }); }); <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <nav> <ul class="pagination"> <li class="prev"> <a href="#"><span>&laquo;</span></a> </li> <li class="active"><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li class="next"> <a href="#"><span>&raquo;</span></a> </li> </ul> </nav>
{ "language": "en", "url": "https://stackoverflow.com/questions/31488607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating jar from command prompt giving error I have tried the example as the same as written as answer from this link'How to create a .jar file using the terminal' to create a jar file from command prompt. But I am getting an error 'no main manifest attribute , in Helloworld.jar'. What will be the problem? Please help.I done the same as explained in that method. A: Solved it using instead 'jar cfe HelloWorld.jar HelloWorld HelloWorld.class' of 'jar cfm HelloWorld.jar Manifest.txt HelloWorld.class'. Thanks guys!!
{ "language": "en", "url": "https://stackoverflow.com/questions/26426738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dialog outside iframe I have a little problem with a JavaScript dialog. I have a button and a dialog into the iframe with the next code $( "#correcto" ).dialog({ width: 600, closeOnEscape: true, autoOpen: false, draggable: false, modal: true, show: { effect: "blind", duration: 200 }, hide: { effect: "blind", duration: 200 } }); And the button with this code: $( "#comprobar" ).click(function() { $( "#correcto" ).dialog( "open" ); }); The code works, but open the dialog into the iframe and the overlay and modal only show/work into the iframe and looks really weird. I want to know if there are some code to open the dialog outside the iframe. I found another thread with a similar question and I try to initialize the dialog in the main page (the parent) and use parent. in the button code but it doesn't work. A: You can't. Or should not. You can't do it, because iframe is a window context, in theory it should not know about its parent (even if in practice it does). * *What should happen if you open the contents of the iframe in an independent window? If it's a simple action like: "I don't need this workflow", then don't use an iframe, you don't need it. *Are parent and iframe in the same domain? If the answer is no, you can't do it. If you need it in any case, and they are both in the same domain, and you can't implement it without using an iframe... * *Write the code of your dialog in the parent window window.showDialog = function (){} *Call this code with top.showDialog() or parent.showDialog() top in most browsers related to most parent window... top will be broken if your parent also will be shown in iframe... It's better to use parent instead...
{ "language": "en", "url": "https://stackoverflow.com/questions/22999608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to properly specialize std::swap for my types? After I've managed to overload std::swap for my class type now I want to specialize it rather than overload it since the standard allows adding template specializations to namespace std. Here is my example: class Foo{ public: Foo(){ std::cout << "Foo()\n"; } Foo(Foo const&){ std::cout << "Foo(Foo const&)\n"; } Foo(Foo&&){ std::cout << "Foo(Foo&&)\n"; } Foo& operator=(Foo const&){ std::cout << "operator=(Foo const&)\n"; return *this; } Foo& operator=(Foo&&){ std::cout << "operator=(Foo&&)\n"; return *this; } ~Foo(){ std::cout << "~Foo()\n"; } }; class VecFoo; namespace std{ template <> void swap<VecFoo>(VecFoo&, VecFoo&); } class VecFoo{ Foo* pFoo_ = new Foo[10]; template<> friend void std::swap<VecFoo>(VecFoo&, VecFoo&); }; template <> void std::swap<VecFo>(VecFoo& lhs, VecFoo& rhs){ std::cout << "template <> void std::swap(VecFoo&, VecFoo&)\n"; std::swap(lhs.pFoo_, rhs.pFoo_); } int main(){ VecFoo vf1, vf2; using std::swap; swap(vf1, vf2); } * *I don't know why it doesn't compile and I get an error: /usr/include/c++/10/type_traits|2195| required by substitution of ‘template<class ... _Cond> using _Require = std::__enable_if_t<std::__and_< <template-parameter-1-1> >::value> [with _Cond = {std::__not_<std::__is_tuple_like<VecFoo> >, std::is_move_constructible<VecFoo>, std::is_move_assignable<VecFoo>}]’| So what is the problem here and how could I correctly specialize it? * *P.S: please don't argue about RAII that I am not achieving in my class VecFoo and the memory leak there because it is not that my problem here. A: This is pretty simple really. You don't need the template but you do need to be in the correct namespace. namespace std { void swap(VecFoo& lhs, VecFoo& rhs) { std::cout << "void swap(VecFoo&, VecFoo&)\n"; //do your custom swap here!!! } } A: std::move requires the class to be move-assignable and move-constructible, but the class VecFoo is not any of them. You added a bunch of method to support these constraints in the class Foo, which didn't requires any (you are swapping pointers). Also, there is a typo in the swap declaration: it says std::swap<VecFo> instead of std::swap<VecFoo>. Finally, I would recommend NOT using friend. Just add a method swap to the class and put the logic there.
{ "language": "en", "url": "https://stackoverflow.com/questions/66953901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to print a float value in vertex shader I try to write a small program in OpenGL ES 2.0. But i found i quit hard to inspect the variable in shader language. For example i want to know the value in ver vertex shader. I will pass the value to fragment shader and put the value as the Red in glFragColor. But i found it quit hard to pass the value. If i declare the value using varying, then the value will change. Here is the code, the log is the value i want to print. public static final String VERTEX_SHADER = "attribute vec4 position;\n" + "attribute vec2 inputTextureCoordinate;\n" + "\n" + "uniform float texelWidthOffset; \n" + "uniform float texelHeightOffset; \n" + "\n" + "varying vec2 centerTextureCoordinate;\n" + "varying vec2 oneStepLeftTextureCoordinate;\n" + "varying vec2 twoStepsLeftTextureCoordinate;\n" + "varying vec2 oneStepRightTextureCoordinate;\n" + "varying vec2 twoStepsRightTextureCoordinate;\n" + "varying float log;\n" + "\n" + "void main()\n" + "{\n" + "log = -0.1;\n" + "gl_Position = position;\n" + "vec2 firstOffset;\n" + "vec2 secondOffset;\n" + // "if (sqrt(pow(position.x, 2) + pow(position.y, 2)) < 0.2) {\n" + // "log = -position.x;\n" + "if (position.x < 0.3) {\n" + "log = 0.7;\n" + "firstOffset = vec2(3.0 * texelWidthOffset, 3.0 * texelHeightOffset);\n" + "secondOffset = vec2(3.0 * texelWidthOffset, 3.0 * texelHeightOffset);\n" + "} else {\n" + "firstOffset = vec2(texelWidthOffset, texelHeightOffset);\n" + "secondOffset = vec2(texelWidthOffset, texelHeightOffset);\n" + "log = -0.1;\n" + "}\n" + "\n" + "centerTextureCoordinate = inputTextureCoordinate;\n" + "oneStepLeftTextureCoordinate = inputTextureCoordinate - firstOffset;\n" + "twoStepsLeftTextureCoordinate = inputTextureCoordinate - secondOffset;\n" + "oneStepRightTextureCoordinate = inputTextureCoordinate + firstOffset;\n" + "twoStepsRightTextureCoordinate = inputTextureCoordinate + secondOffset;\n" + "}\n"; public static final String FRAGMENT_SHADER = "precision highp float;\n" + "\n" + "uniform sampler2D inputImageTexture;\n" + "\n" + "varying vec2 centerTextureCoordinate;\n" + "varying vec2 oneStepLeftTextureCoordinate;\n" + "varying vec2 twoStepsLeftTextureCoordinate;\n" + "varying vec2 oneStepRightTextureCoordinate;\n" + "varying vec2 twoStepsRightTextureCoordinate;\n" + "varying float log;\n" + "\n" + "void main()\n" + "{\n" + "if (log != -0.1) {\n" + "gl_FragColor.rgba = vec4(log, 0.0, 0.0, 1.0);\n" + // "return;\n" + // "}\n" + "} else { \n" + "lowp vec4 fragmentColor;\n" + "fragmentColor = texture2D(inputImageTexture, centerTextureCoordinate) * 0.2;\n" + "fragmentColor += texture2D(inputImageTexture, oneStepLeftTextureCoordinate) * 0.2;\n" + "fragmentColor += texture2D(inputImageTexture, oneStepRightTextureCoordinate) * 0.2;\n" + "fragmentColor += texture2D(inputImageTexture, twoStepsLeftTextureCoordinate) * 0.2;\n" + "fragmentColor += texture2D(inputImageTexture, twoStepsRightTextureCoordinate) * 0.2;\n" + "\n" + "gl_FragColor = fragmentColor;\n" + // "gl_FragColor.rgba = vec4(0.0, 1.0, 0.0, 1.0);\n" + // "}\n" + "}\n"; Or is there any better method to do this. A: When comparing floating point values, instead of doing this : if (log != -0.1) You should allow a little delta/tolerance on the value to account for floating point precision and the eventual value "change" you may get from passing it as a varying. So you should do something like : if (abs(log - (-0.1)) >= 0.0001) Here the 0.0001 I chosen is a bit arbitrary ... It has to be a small value ... Another example with == Instead of : if (log == 0.7) do if (abs(log - 0.7) <= 0.0001) However here you probably also have another issue: * *The vertex shader executes for each 3 vertex of all your triangles (or quads) *So for a specific triangle, you may set different values (-0.1 or 0.7) for log for each vertex *Now the problem is that in the fragment shader the GPU will interpolate between the 3 log values depending on which pixel it is rendering ... so in the end you can get any value in [-0.1,0.7] interval displayed on screen :-( To avoid this kind of issue, I personally use #ifdefs in my shaders to be able to switch them between normal and debug mode, and can switch between the two with a keypress. I never try to mix normal and debug displays based on if tests, especially when the test is based on a vertex position. So in your case I would first create a specific debug version of the shader, and then use 0.0 and 1.0 as values for log, like this what you will see are red gradients, the more red the color is, the closer you are to the case you want to test.
{ "language": "en", "url": "https://stackoverflow.com/questions/32556551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Report design not valid. Field not found Jasper Reports Im trying to create a basic jasper report with JRBeanCollectionDataSource. In there im having a list of objects inside the javabean. public class Course { private int id; private List<Student> students; } Student object looks like public class Student { private String name; private int id; } I want to print student information inside my report. This is how my jrxml looks like <subDataset name="dataset1" uuid="09015d96-ad5a-4fed-aa9e-19d25e02e205"> <field name="students" class="java.util.List"> <fieldDescription><![CDATA[students]]></fieldDescription> </field> </subDataset> <field name="id" class="java.lang.Integer"/> <field name="students" class="java.util.List"/> <field name="name" class="java.lang.String"/> <componentElement> <reportElement x="200" y="0" width="400" height="20"/> <jr:list xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd" printOrder="Vertical"> <datasetRun subDataset="dataset1"> <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{students})]]></dataSourceExpression> </datasetRun> <jr:listContents height="20" width="400"> <textField> <reportElement x="0" y="0" width="100" height="20"/> <box leftPadding="10"> <topPen lineWidth="1.0"/> <leftPen lineWidth="1.0"/> <bottomPen lineWidth="1.0"/> <rightPen lineWidth="1.0"/> </box> <textElement/> <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression> </textField> </jr:listContents> </jr:list> </componentElement> But when i run this im getting net.sf.jasperreports.engine.design.JRValidationException: Report design not valid : 1. Field not found : name Report design not valid : 1. Field not found : name Im a beginner to jasper reports can anyone please tell me what am i doing wrong here. Thanks A: You have to define the fields before using it. In your jrxml, you have three field defined students in the subDataSet, id and students. But you haven't defined name and using it in your jrxml and that's why you are getting this exception. Try defining name, like <field name="name" class="java.lang.String"/> A: Try with a subreport. I launched your example in my local database without any problem. This is my list of student objects: private List<Student> getList(){ List<Student> students = new ArrayList<Student>(); Connection con = ....; //Retrieve your connection the way you want ResultSet rs = con.createStatement().executeQuery("select name, id from students order by id"); while (rs.next()){ students.add(new Student(rs.getString(1), rs.getInt(2))); } con.close(); return students; } This is how I passed my JRBeanCollectionDataSource object from my Java program: Map<String, Object> params = new HashMap<String, Object>(); params.put("SUBREPORT_DATASOURCE", new JRBeanCollectionDataSource(getList())); String jasperPath = "....."; //where you have your compiled jasper report file JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, params, new JREmptyDataSource(1)); This is the xlm main report "reportStudent.jrxml": <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="reportStudent" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20"> <property name="ireport.zoom" value="1.0"/> <property name="ireport.x" value="0"/> <property name="ireport.y" value="0"/> <parameter name="SUBREPORT_DATASOURCE" class="net.sf.jasperreports.engine.JRDataSource" isForPrompting="false"> <defaultValueExpression><![CDATA[]]></defaultValueExpression> </parameter> <background> <band splitType="Stretch"/> </background> <detail> <band height="125" splitType="Stretch"> <subreport> <reportElement x="0" y="0" width="555" height="125"/> <dataSourceExpression><![CDATA[$P{SUBREPORT_DATASOURCE}]]></dataSourceExpression> <subreportExpression><![CDATA["./reportStudent_subreport1.jasper"]]></subreportExpression> </subreport> </band> </detail> </jasperReport> And this is the one for the subreport "reportStudent_subreport1.jrxml": <?xml version="1.0" encoding="UTF-8"?> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="reportStudent_subreport1" language="groovy" pageWidth="555" pageHeight="802" columnWidth="555" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0"> <property name="ireport.zoom" value="1.771561000000001"/> <property name="ireport.x" value="0"/> <property name="ireport.y" value="0"/> <field name="id" class="java.lang.String"/> <field name="name" class="java.lang.String"/> <background> <band splitType="Stretch"/> </background> <columnHeader> <band height="20" splitType="Stretch"> <staticText> <reportElement x="66" y="0" width="100" height="20"/> <textElement/> <text><![CDATA[id]]></text> </staticText> <staticText> <reportElement x="212" y="0" width="100" height="20"/> <textElement/> <text><![CDATA[name]]></text> </staticText> </band> </columnHeader> <detail> <band height="20" splitType="Stretch"> <textField> <reportElement x="66" y="0" width="100" height="20"/> <textElement/> <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression> </textField> <textField> <reportElement x="212" y="0" width="100" height="20"/> <textElement/> <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression> </textField> </band> </detail> </jasperReport> This is for just one list of students. You can iterate inside the main report and print your course id and students subreport in the detail band with just a little changes. Hope it helps to start with. A: Fount out the issue. name attribute should defined inside the subdataset. Otherwise it wont work <subDataset name="dataset1" uuid="09015d96-ad5a-4fed-aa9e-19d25e02e205"> <field name="name" class="java.lang.String"/> </subDataset>
{ "language": "en", "url": "https://stackoverflow.com/questions/30952574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Matplotlib labeling x-axis with time stamps, deleting extra 0's in microseconds I am plotting over a period of seconds and have time as the labels on the x-axis. Here is the only way I could get the correct time stamps. However, there are a bunch of zeros on the end. Any idea how to get rid of them?? plt.style.use('seaborn-whitegrid') df['timestamp'] = pd.to_datetime(df['timestamp']) fig, ax = plt.subplots(figsize=(8,4)) seconds=MicrosecondLocator(interval=500000) myFmt = DateFormatter("%S:%f") ax.plot(df['timestamp'], df['vibration(g)_0'], c='blue') ax.xaxis.set_major_locator(seconds) ax.xaxis.set_major_formatter(myFmt) plt.gcf().autofmt_xdate() plt.show() This produces this image. Everything looks perfect except for all of the extra zeros. How can I get rid of them while still keeping the 5? A: I guess you would want to simply cut the last 5 digits out of the string. That's also what answers to python datetime: Round/trim number of digits in microseconds suggest. import numpy as np import matplotlib.pyplot as plt from matplotlib.dates import MicrosecondLocator, DateFormatter from matplotlib.ticker import FuncFormatter x = np.datetime64("2018-11-30T00:00") + np.arange(1,4, dtype="timedelta64[s]") fig, ax = plt.subplots(figsize=(8,4)) seconds=MicrosecondLocator(interval=500000) myFmt = DateFormatter("%S:%f") ax.plot(x,[2,1,3]) def trunc_ms_fmt(x, pos=None): return myFmt(x,pos)[:-5] ax.xaxis.set_major_locator(seconds) ax.xaxis.set_major_formatter(FuncFormatter(trunc_ms_fmt)) plt.gcf().autofmt_xdate() plt.show() Note that this format is quite unusual; so make sure the reader of the plot understands it.
{ "language": "en", "url": "https://stackoverflow.com/questions/53565088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: stripe checkout.session returned data.payment_intent is null When I create a checkout.session with stripe the returned data.payment_intent is null I filled in every required field and the payment works. But without the payment_intent. const url = await stripe.checkout.sessions .create( { line_items: [ { price_data: { product_data: { name: productName, description: productDescription, images: [ 'randomimage-url', ], }, currency: 'eur', unit_amount: priceInCents, }, quantity: 1, }, ], payment_intent_data: { application_fee_amount: feeAmount, setup_future_usage: 'on_session' }, mode: 'payment', success_url: 'http://localhost:3000/payment', cancel_url: 'http://localhost:3000', }, { stripeAccount: stripeExpressUserId, } ) A: This is expected behavior with API version 2022-08-01. A change was made with this API version so that a Payment Intent is not created when a Checkout Session is initially created, but is instead created when the Checkout Session is confirmed. You can read more about this and the other changes introduced with this API version here: https://stripe.com/docs/upgrades#2022-08-01
{ "language": "en", "url": "https://stackoverflow.com/questions/73393228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UITableView edit cell without changing underlying core data I have a tableview of dates that are calculated based on stored week periods from core data. The tableview shows the results for each calculation: Example: Today's date - 80 weeks (the 80 comes from core data) So tableview would show date for 80 weeks prior to today. There are about a dozen of these dates listed in the tableview, different depending on the core data value. If I want to allow the user to "override" the date that is presented, how can I do that? So if they tapped the result in the tableview, I could take them to a view controller with a date picker, but how do I return that back into the tableview with the other items? I'm assuming I'd have to make sure the tableview didn't reload on viewWillAppear as well.. A: You could attach the extraneous date to the object that you are representing in the table view. Give it a new property overrideDate and check that first when configuring your cell. Alternatively, if this is what you want, change the Core Data number based on the chosen date and save it. Depending on your setup (e.g. Fetched Results Controller with delegate enabled and implemented, like in the standard Xcode template), the table view should update correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/19772171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to handle minimize/maximize buttons in tkinter I've researched a lot about this topic, but nothing seems to be helpful. I want to get a callback when I press the minimize/maximize (- button) on my tkinter window. Like when I click on the close button, I can get a callback like this: # Function for callback def on_closing(): print("User clicked close button") root.destroy() # Callback self.root.protocol("WM_DELETE_WINDOW", self.on_closing) Like this I can callback a function when someone clicks on the close (X) button. So my question is, isn't there a similar protocol for minimize/maximize buttons as well for calling back? A: You wont be able to use a protocol like with the X button. You can bind to the '<Map>' and '<Unmap>' events like this. import tkinter as tk def catch_minimize(event): print("window minimzed") def catch_maximize(event): print("window maximized") root = tk.Tk() root.geometry("400x400") root.bind("<Unmap>", catch_minimize) root.bind("<Map>", catch_maximize) root.mainloop()
{ "language": "en", "url": "https://stackoverflow.com/questions/72678069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do regex implementations actually need a split() function? Is there any application for a regex split() operation that could not be performed by a single match() (or search(), findall() etc.) operation? For example, instead of doing subject.split('[|]') you could get the same result with a call to subject.findall('[^|]*') And in nearly all regex engines (except .NET and JGSoft), split() can't do some things like "split on | unless they are escaped \|" because you'd need to have unlimited repetition inside lookbehind. So instead of having to do something quite unreadable like this (nested lookbehinds!) splitArray = Regex.Split(subjectString, @"(?<=(?<!\\)(?:\\\\)*)\|"); you can simply do (even in JavaScript which doesn't support any kind of lookbehind) result = subject.match(/(?:\\.|[^|])*/g); This has led me to wondering: Is there anything at all that I can do in a split() that's impossible to achieve with a single match()/findall() instead? I'm willing to bet there isn't, but I'm probably overlooking something. (I'm defining "regex" in the modern, non-regular sense, i. e., using everything that modern regexes have at their disposal like backreferences and lookaround.) A: The purpose of regular expressions is to describe the syntax of a language. These regular expressions can then be used to find strings that match the syntax of these languages. That’s it. What you actually do with the matches, depends on your needs. If you’re looking for all matches, repeat the find process and collect the matches. If you want to split the string, repeat the find process and split the input string at the position the matches where found. So basically, regular expression libraries can only do one thing: perform a search for a match. Anything else are just extensions. A good example for this is JavaScript where there is RegExp.prototype.exec that actually performs the match search. Any other method that accepts regular expression (e. g. RegExp.prototype.test, String.prototype.match, String.prototype.search) just uses the basic functionality of RegExp.prototype.exec somehow: // pseudo-implementations RegExp.prototype.test = function(str) { return RegExp(this).exec(str); }; String.prototype.match = function(pattern) { return RegExp(pattern).exec(this); }; String.prototype.search = function(pattern) { return RegExp(pattern).exec(this).index; };
{ "language": "en", "url": "https://stackoverflow.com/questions/9756920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Responsive navigation has scroll bar? I've been messing with a bootstrap theme for Wordpress and when I shrink down the navigation it turns into a scroll bar. This is odd because it should be overlaying. The website is: http://sendtohim3dprinting.co.uk/ and this is how it looks: I can't quite figure it out. These are the CSS changes I made: .navbar { height: 110px; background: #2476bf; } .collapse.navbar-collapse { max-width: 850px; height: 110px ; } .menu-item a { height: 110px; width: 200px; } li.menu-item.menu-item-object-page a, .menu-item-type-custom, .menu-item-type-custom.menu-item-object-custom.menu-item-2413 a { text-align: center; line-height: 90px; font-family: 'Pacifico', cursive ; font-size: 1.5em; } .collapse.navbar-collapse { float: right; } And the original CSS for the nav bar is extremely long but can be found here I've not encountered this kind of issue before in regards to the scroll bar. Any help would be appreciated. A: Just add overflow: hidden to your .nav > li class. Like this one: nav > li { position: relative; display: block; overflow: hidden; } A: If your goal is to hide the horizontal scroll bar as in the image above, you can try: <style type="text/css"> body { overflow-x:hidden; } </style>
{ "language": "en", "url": "https://stackoverflow.com/questions/32171133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Out of HeapSpace with Matrix library I'm trying to apply a Kalman Filter to sensor readings using Java, but the matrix manipulation library I'm using is giving me a heapspace error. So, does anyone know of a matrix manipulation library for the JVM with better memory allocation characteristics? It would seem that this one -- http://code.google.com/p/efficient-java-matrix-library/ -- is "efficient" only in name. The data set has 9424 rows by 2 columns, all values are doubles (timestamp and one dimension out of 3 on readings from a sensor). Many thanks, guys! A: 1) The Kalman filter should not require massive, non linear scaling amounts of memory : it is only calculating the estimates based on 2 values - the initial value, and the previous value. Thus, you should expect that the amount of memory you will need should be proportional to the total amount of data points. See : http://rsbweb.nih.gov/ij/plugins/kalman.html 2) Switching over to floats will 1/2 the memory required for your calculation . That will probably be insignificant in your case - I assume that if the data set is crashing due to memory, you are running your JVM with a very small amount of memory or you have a massive data set. 3) If you really have a large data set ( > 1G ) and halving it is important, the library you mentioned can be refactored to only use floats. 4) For a comparison of java matrix libraries, you can checkout http://code.google.com/p/java-matrix-benchmark/wiki/MemoryResults_2012_02 --- the lowest memory footprint libs are ojAlgo, EJML, and Colt. Ive had excellent luck with Colt for large scale calculations - but I'm not sure which ones implement the Kalaman method.
{ "language": "en", "url": "https://stackoverflow.com/questions/9611689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to backup Ec2 linux instances along with users Is there a way to backup users along with software created in AWS. context:I am currently learning ansible and shutting down those instances created after some time..Everyday i have to recreate again users,,install anisble after relaunching those instances A: The natural way to backup EC2 instances is through snapshots. You can also create custom AMI which will simplify launching new instances with all the per-installed software of yours, along with its users and all the settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/70418502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FB Like to status on my page I want to add a Like button to my page, but Like should belong to the fan page status, not to page I'm on it. My idea is that I want to automatically add a link to a new article from WordPress to Facebook, and then I want the same like I have on Facebook, to have the amount of likes be synchronized. Is it possible and how? A: You can specify the href attribute for a like button. For example, this like button would like the Facebook page for Facebook: <div class="fb-like" data-href="http://facebook.com/facebook" data-send="true" data-width="450" data-show-faces="true"></div> A: You should probably use the URL from the status ID. You can find this by right-clicking on the "... Hours ago" link on every Facebook status (gray color). This will now be the same post_object.
{ "language": "en", "url": "https://stackoverflow.com/questions/9162104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Error while creating URI with com.sun.jersey.api.client.WebResource adding String value to path Using com.sun.jersey.api.client.Client,ClientResponse and WebResource. Client client = this.client; WebResource webResource = null; ClientResponse response = null; String url = ""; url = "https://test.com/rest/V1/cart/" + quoteId + "/items"; webResource = client.resource(url); String jsonString = "{\"cartItem\":{\"quote_id\":" + quoteId + ",\"id\": " + id+ ",\"qty\":" + qty + "}}"; ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser parser = factory.createParser(jsonString); JsonNode actualObj = mapper.readTree(parser); response = webResource.header("Authorization", "Bearer " + this.token).type("application/json") .post(ClientResponse.class, actualObj); I have error Illegal character in path at index 52: https://test.com/rest/V1/cart/"IerwexsKLchKYmZ1ryKZkor9RdfJ2Dp3"/items I am passing quoteId as parameter String quoteId="IerwexsKLchKYmZ1ryKZkor9RdfJ2Dp3"; How to remove quotes for quoteId from URL? Thank you.
{ "language": "en", "url": "https://stackoverflow.com/questions/54253540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: fsockopen(): SSL: Connection reset by peer in codeigniter email send Getting error while sending email in my codeigniter project from live ubuntu 16.04 server. (On localhost it works fine.) My smtp configuration is: $config = Array( 'protocol' => 'smtp', 'smtp_host' => 'ssl://smtp.googlemail.com', 'smtp_port' => 465, 'smtp_user' => '[email protected]', // change it to yours 'smtp_pass' => 'password', // change it to yours 'mailtype' => 'html', 'charset' => 'iso-8859-1', 'wordwrap' => TRUE ); $this->load->library('email', $config); $this->email->set_newline("\r\n"); It's work fine on my local server. but when I host it on live server I got the error. How do I solve this error? Please help. A PHP Error was encountered Severity: Warning Message: fsockopen(): SSL: Connection reset by peer Filename: libraries/Email.php Line Number: 1990 Backtrace: File: /var/www/project/company/application/libraries/SendEmail.php Line: 26 Function: send File: /var/www/project/company/application/controllers/Login.php Line: 207 Function: send File: /var/www/project/company/index.php Line: 315 Function: require_once A PHP Error was encountered Severity: Warning Message: fsockopen(): Failed to enable crypto Filename: libraries/Email.php Line Number: 1990 Backtrace: File: /var/www/project/company/application/libraries/SendEmail.php Line: 26 Function: send File: /var/www/project/company/application/controllers/Login.php Line: 207 Function: send File: /var/www/project/company/index.php Line: 315 Function: require_once A PHP Error was encountered Severity: Warning Message: fsockopen(): unable to connect to ssl://smtp.googlemail.com:465 (Unknown error) Filename: libraries/Email.php Line Number: 1990 Backtrace: File: /var/www/project/company/application/libraries/SendEmail.php Line: 26 Function: send File: /var/www/project/company/application/controllers/Login.php Line: 207 Function: send File: /var/www/project/company/index.php Line: 315 Function: require_once Thanks. A: I have had this error yesterday. The Error caused by SSL which has a problem on the server. So, I changed the SSL method to TLS to avoid the problem SSL. Configure your config with these rules. $config['protocol'] = "smtp"; $config['smtp_host'] = "smtp.gmail.com"; $config['smtp_port'] = "587"; $config['smtp_user'] = "*[email protected]*"; $config['smtp_pass'] = "*yourpassword*"; $config['smtp_timeout'] = "4"; $config['charset'] = "utf-8"; $config['newline'] = "\r\n"; $config['smtp_crypto'] = "tls"; // This is an important part of changing to TLS $config['validate'] = TRUE; It's Works for me, Email is sent via TLS protocol. Maybe this is not the best solution for security.
{ "language": "en", "url": "https://stackoverflow.com/questions/57656383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Generating WSDL files I want to implement a WSDL service. To generate its codes, I use from different tools. When I use SoapUI, the generated file's method is as below: ******************************************************* <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/"> <soapenv:Header> <tem:AuthenticationHeader> <tem:TicketID>?</tem:TicketID> </tem:AuthenticationHeader> </soapenv:Header> <soapenv:Body> <tem:GetInfo> <tem:sNo>?</tem:sNo> <tem:source>?</tem:source> </tem:GetInfo> </soapenv:Body> </soapenv:Envelope> and when I use https://app.boomerangapi.com/ on Chrome, this method will be: <x:Envelope xmlns:x="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/"> <x:Header> <tem:AuthenticationHeader> <tem:TicketID>?</tem:TicketID> </tem:AuthenticationHeader> </x:Header> <x:Body> <tem:GetInfo> <tem:sNo>?</tem:sNo> <tem:source>?</tem:source> </tem:GetInfo> </x:Body> </x:Envelope> Why the generated methods are different in namespaces?! What can be the problem in the source of this service?! A: Those two SOAP bodies are exactly the same. A namespace prefix in an element tag is just a symbolic shorthand for a namespace URI. An XML document can define a namespace prefix using an attribute that starts with xmlns:: xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" That attribute means “all names in this element and its descendants starting with soapenv: are actually names associated with the URI http://schemas.xmlsoap.org/soap/envelope/.” The following namespace definition is exactly the same thing; it just specifies a different prefix to use as shorthand for the same URI: xmlns:x="http://schemas.xmlsoap.org/soap/envelope/" So, the only difference is that the two XML documents is how they refer to the “http://schemas.xmlsoap.org/soap/envelope/” URI: * *The first document specifies that elements starting with soapenv: are associated with that URI. *The second document specifies that elements starting with x: are associated with that URI. The notation is different, but the meaning is the same. They literally have identical content.
{ "language": "en", "url": "https://stackoverflow.com/questions/67034808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Use switch-case construction to count how many times a number has been typed Create a C-program that counts how many times each of the numbers 0-4 have been typed. Use a switch-case construction. Use default to count the number of other characters. Print the amount of times a certain number has been typed. Here is my code: int main() { int a; int num_0 = 0; int num_1 = 0; int num_2 = 0; int num_3 = 0; int num_4 = 0; int num_other = 0; printf("Input something\n"); while ((a = getchar()) != EOF) { switch (a) { case 0: num_0++;break; case 1: num_1++;break; case 2: num_2++;break; case 3: num_3++;break; case 4: num_4++;break; default: num_other++;break; }; } printf("0 has been typed %d", num_0);printf(" times\n"); printf("1 has been typed %d", num_1);printf(" times\n"); printf("2 has been typed %d", num_2);printf(" times\n"); printf("3 has been typed %d", num_3);printf(" times\n"); printf("4 has been typed %d", num_4);printf(" times\n"); printf("other characters have been typed %d", num_other);printf(" times\n"); return 0; } No matter what I input, all the numbers including 0,1,2,3,4 were counted as other characters. Could someone tell me why my code didn't work. A: switch (a) will compare the code of a. If you typed digits, it should be; case '0': num_0++;break; case '1': num_1++;break; ... switch on character values not integers (int value of 0 is not 0, for example in ASCII it is 48, but let's not use the value directly, so it's fully portable) Maybe a better thing to do would be to create a table instead: int count[10] = {0}; .... a -= '0'; // removes the offset if ((a >= 0) && (a < 10)) // check bounds { count[a]++; } A: Your answer is in man getchar (emphasis mine) fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error. getc() is equivalent to fgetc() except that it may be implemented as a macro which evaluates stream more than once. getchar() is equivalent to getc(stdin). After that, the numerical representation of a character need not be the same as the character value (and mostly, is not), i.e., a character 0 ('0') does not have the numerical value of 0, in ASCII encoding, it has a decimal value of 48. So, to count a character '0', you should set the case values to '0', not 0. A: a = getchar() When you are reading characters, the value gets stored in variable is the ASCII value. When you type 1 the value getting stored in a is 49. switch (a) { case 1: num_0++; break; } In this code you are comparing with ASCII value 49(ASCII value for 1) with ASCII value 1 and comparison return false. Similarly all the conditions give false and goes to default case. A: There are some mistake in your code . 1) You are taking input through getchar() function , so it takes character in the input . 2) Take the input variable 'a' as char not int . 3) Mark single quotes in case options like case '1' because you are taking input as a character so you must mark single quotes .
{ "language": "en", "url": "https://stackoverflow.com/questions/48379589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: HTML code is getting send in email instead of rendered view Wordpress I have added an action to send email after every post update, in email logs I can see proper view is getting sent, but I don't understand why gmail is showing html code of template instead of rendered view. Functions.php $email_body = file_get_contents(get_stylesheet_directory(). '/email/template2.php'); $headers = 'From: Test <[email protected]>'; $headers .= "Content-Type: text/html"; $title = wp_strip_all_tags( get_the_title( $post->ID ) ); if ( get_post_type( $post->ID ) === 'property' ) { wp_mail( $emails, $title, $email_body, $headers ); } html template: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body leftmargin="0" marginwidth="0" topmargin="0" marginheight="0" offset="0"> <div style="background-color: #f5f5f5; width:100%; -webkit-text-size-adjust:none !important; margin:0; padding: 70px 0 70px 0;"> <table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%"> <tr> <td align="center" valign="top"><table border="0" cellpadding="0" cellspacing="0" width="600" id="template_container" style=" -webkit-box-shadow:0 0 15px rgba(0,0,0,0.2) !important; box-shadow:0 0 15px rgba(0,0,0,0.2) !important; -webkit-border-radius:6px !important; border-radius:6px !important; background-color: #fdfdfd; border: 1px solid #ccc; -webkit-border-radius:6px !important; border-radius:6px !important;"> <tr> <td align="center" valign="top"><!-- Header --> <table border="0" cellpadding="0" cellspacing="0" width="600" id="template_header" style="background-color:#075E86; color: #ffffff; -webkit-border-top-left-radius:6px !important; -webkit-border-top-right-radius:6px !important; border-top-left-radius:6px !important; border-top-right-radius:6px !important; border-bottom: 0; font-family:Arial; font-weight:bold; line-height:100%; vertical-align:middle;"> <tr> <td><h1 style="color: #ffffff; margin:0; -webkit-border-top-left-radius:6px !important; -webkit-border-top-right-radius:6px !important; border-top-left-radius:6px !important; border-top-right-radius:6px !important; padding: 28px 24px; text-shadow: 1px 1px 1px rgba(0,0,0,.2); display:block; font-family:Arial; border:1px solid rgba(0,0,0,.2); font-size:30px; font-weight:bold; border-bottom:0; text-align:left; line-height: 150%; -webkit-box-shadow: inset 0px 1px 0px 0px rgba(255,255,255,.5); -moz-box-shadow: inset 0px 1px 0px 0px rgba(255,255,255,.5); box-shadow: inset 0px 1px 0px 0px rgba(255,255,255,.5);"> <a style="color: #FFFFFF; text-decoration:none;" href="'.site_url().'" target="_blank"> Propery status update </a></h1></td> </tr> </table> <!-- End Header --></td> </tr> <tr> <td align="center" valign="top"><!-- Body --> <table border="0" cellpadding="0" cellspacing="0" width="600" id="template_body"> <tr> <td valign="top" style=" background-color: #fdfdfd; -webkit-border-radius:6px !important; border-radius:6px !important; "><!-- Content --> <td valign="top"><div style=" color: #555; font-family:Arial; font-size:14px; line-height:150%; text-align:left; "> <br/> <br/><center><img src="images/image-5.png" height="60px"><br><br><br> Thanks for being a "Submit All Offers" property agent!<br />&nbsp;This email is to notify you that we have recently noticed that you've submitted an offer for property <a href='[post_url]'><b>[title]</b></a>, thereby now the status of the property has been changed to <b>[status]</b>. <table cellspacing="0" cellpadding="0" style="width: 100%; vertical-align: top;" border="0"> <tr> <br><br><br></td></center> <!-- End Body --></td> </tr> <tr> <td align="center" valign="top"><!-- Footer --> <table border="0" cellpadding="10" cellspacing="0" width="600" id="template_footer" style=" border-top:0; -webkit-border-bottom-left-radius:6px; border-bottom-left-radius:6px; webkit-border-bottom-right-radius:6px; border-bottom-right-radius:6px; overflow:hidden "> <tr> <td valign="top" style="background:#eee;-webkit-box-shadow: inset 0px -1px 0px 0px rgba(0,0,0,.1); -moz-box-shadow: inset 0px -1px 0px 0px rgba(0,0,0,.1); box-shadow: inset 0px -1px 0px 0px rgba(0,0,0,.1);"><table border="0" cellpadding="10" cellspacing="0" width="100%"> <tr> <td colspan="2" valign="middle" id="credit" style=" border:0; color: #c1d46b; font-family: Arial; font-size:12px; line-height:125%; text-align:center; "><p><a style="color: #666;text-decoration:none;" href="'[url]'" target="_blank">[site_name]</a></p></td> </tr> </table></td> </tr> </table> <!-- End Footer --></td> </tr> </table></td> </tr> </table> </div> </body> </html> In post SMTP logs, I can check proper view is generating, but in gmail inbox, HTML Code is coming in email body, can anyone help?
{ "language": "en", "url": "https://stackoverflow.com/questions/69392460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Keytool create a trusted self signed certificate I am trying to use the (java) keytool to create a self signed certificate but when I attempt to use it I get the following exception (see bottom for entire exception). ...<5 more exceptions above this> Caused by: sun.security.validator.ValidatorException: No trusted certificate found at sun.security.validator.SimpleValidator.buildTrustedChain(SimpleValidator.java:304) at sun.security.validator.SimpleValidator.engineValidate(SimpleValidator.java:107) at sun.security.validator.Validator.validate(Validator.java:203) at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172) at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:841) ... 22 more I know that I can by-pass this with this code: import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); (source) But I am not interested in this solutions because I think that it creates a security hole. (please correct me if I am wrong). Can anyone point me in the right direction? I am testing locally at the moment right now so it is pretty easy to change things. I have access to the server code, client code and to the .keystore file. Update I was attempting to use one .keystore file for both the client and server but in hopes of simplifying my issues I have created server.keystore (see below) and client.truststore (see below). I am reasonably confident that the certicates are correct but if someone could verify I would be grateful. server.keystore hostname[username:/this/is/a/path][711]% keytool -list -keystore server.keystore -v Enter keystore password: Keystore type: JKS Keystore provider: SUN Your keystore contains 1 entry Alias name: hostname Creation date: Feb 4, 2010 Entry type: PrivateKeyEntry Certificate chain length: 1 Certificate[1]: Owner: CN=hostname, OU=hostname, O=hostname, L=hostname, ST=hostname, C=hostname Issuer: CN=hostname, OU=hostname, O=hostname, L=hostname, ST=hostname, C=hostname Serial number: 4b6b0ea7 Valid from: Thu Feb 04 13:15:03 EST 2010 until: Wed May 05 14:15:03 EDT 2010 Certificate fingerprints: MD5: 81:C0:3F:EC:AD:5B:7B:C4:DA:08:CC:D7:11:1F:1D:38 SHA1: F1:78:AD:C8:D0:3A:4C:0C:9A:4F:89:C0:2A:2F:E2:E6:D5:13:96:40 Signature algorithm name: SHA1withDSA Version: 3 ******************************************* ******************************************* client.truststore hostname[username:/this/is/a/path][713]% keytool -list -keystore client.truststore -v Enter keystore password: Keystore type: JKS Keystore provider: SUN Your keystore contains 1 entry Alias name: mykey Creation date: Feb 4, 2010 Entry type: trustedCertEntry Owner: CN=hostname, OU=hostname, O=hostname, L=hostname, ST=hostname, C=hostname Issuer: CN=hostname, OU=hostname, O=hostname, L=hostname, ST=hostname, C=hostname Serial number: 4b6b0ea7 Valid from: Thu Feb 04 13:15:03 EST 2010 until: Wed May 05 14:15:03 EDT 2010 Certificate fingerprints: MD5: 81:C0:3F:EC:AD:5B:7B:C4:DA:08:CC:D7:11:1F:1D:38 SHA1: F1:78:AD:C8:D0:3A:4C:0C:9A:4F:89:C0:2A:2F:E2:E6:D5:13:96:40 Signature algorithm name: SHA1withDSA Version: 3 ******************************************* ******************************************* Update I thought it could be useful to include the entire exception: javax.xml.soap.SOAPException: java.io.IOException: Could not transmit message at org.jboss.ws.core.soap.SOAPConnectionImpl.callInternal(SOAPConnectionImpl.java:115) at org.jboss.ws.core.soap.SOAPConnectionImpl.call(SOAPConnectionImpl.java:66) at com.alcatel.tpapps.common.utils.SOAPClient.execute(SOAPClient.java:193) at com.alcatel.tpapps.common.utils.SOAPClient.main(SOAPClient.java:280) Caused by: java.io.IOException: Could not transmit message at org.jboss.ws.core.client.RemotingConnectionImpl.invoke(RemotingConnectionImpl.java:192) at org.jboss.ws.core.client.SOAPRemotingConnection.invoke(SOAPRemotingConnection.java:77) at org.jboss.ws.core.soap.SOAPConnectionImpl.callInternal(SOAPConnectionImpl.java:106) ... 3 more Caused by: org.jboss.remoting.CannotConnectException: Can not connect http client invoker. sun.security.validator.ValidatorException: No trusted certificate found. at org.jboss.remoting.transport.http.HTTPClientInvoker.useHttpURLConnection(HTTPClientInvoker.java:368) at org.jboss.remoting.transport.http.HTTPClientInvoker.transport(HTTPClientInvoker.java:148) at org.jboss.remoting.MicroRemoteClientInvoker.invoke(MicroRemoteClientInvoker.java:141) at org.jboss.remoting.Client.invoke(Client.java:1858) at org.jboss.remoting.Client.invoke(Client.java:718) at org.jboss.ws.core.client.RemotingConnectionImpl.invoke(RemotingConnectionImpl.java:171) ... 5 more Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1584) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:848) at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106) at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495) at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:877) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1089) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1116) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1100) at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:402) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:170) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:857) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230) at org.jboss.remoting.transport.http.HTTPClientInvoker.useHttpURLConnection(HTTPClientInvoker.java:288) ... 10 more Caused by: sun.security.validator.ValidatorException: No trusted certificate found at sun.security.validator.SimpleValidator.buildTrustedChain(SimpleValidator.java:304) at sun.security.validator.SimpleValidator.engineValidate(SimpleValidator.java:107) at sun.security.validator.Validator.validate(Validator.java:203) at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172) at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:841) ... 22 more A: You mustn't do that. A keystore is strictly private. If you leak it to anybody you have fatally compromised security. There is no point in doing this kind of thing just to get it working, because it isn't working - it is just a security breach. You have to do it right: export from the server's keystore into the client's truststore, and from the client's keystore if any to the server's keystore. A: You would need to "establish trust" between your server and client (I'm assuming you only need to do server-side authentication). This is because you use self-signed certs. That involves importing your server's cert into the client trust store: On the server side: keytool -keystore <keystore file> -alias <alias> -export -file <certfilename>.cert Copy the .cert file over to the client side and then: keytool -keystore <truststore file> -alias <alias> -import -file <certfilename>.cert A: You can't share the keystore between client and server, because the keystore contains the private key. When authenticating, the client skips the certificates with private keys. As said above you need to deploy a truststore on client side. The certificates in a keystore don't behave the same way, depending on how you generated or imported them. An imported certificate's entry type (seen when verbosely listing the whole keystore with -list -v) is "trustedCertEntry". A generated certificate's entry type is "PrivateKeyEntry". When you export a certificate, you only export its public key, and an optional reference to its issuer. Seems like you need to export the self-signed certificate in your keystore as a trusted certificate in your truststore (names make sense here). I wouldn't do that, because SSL/TLS implementations probably don't support it. From a real world perspective it's like deploying the ultimately secret private key from Verisign on some obscure Web server to sign casual pages, while the only purpose of this private key is to remain in a safe and sign other certificates. SSL/TLS implementors probably won't pollute their code with such a use case, and anyways, the "KeyUsage" certificate extension may restrict a certificate usage to signing, preventing encipherment. That's why I suggest to rebuild a chain of certificates for your test. The keytool documentation contains an interesting part about creating a chain (-gencert command) but it's a very skeletal example which doesn't cover the keystore-truststore relationship. I've enhanced it to simulate a third-party certification authority. A temporary store their-keystore.jks represents a certificate-emitting authority. I feed it with a certificate chain of ca2 -> ca1 -> ca with ca being considered as a root certificate. The chain appears with each non-root certificate (namely ca1 and ca2) referencing their issuer as Certificate[2]. Please note that every certificate is "PrivateKeyEntry". Then I feed the my-keystore.jks with those certificates in order: ca, ca1, ca2. I import ca with the -trustcacerts option which means it becomes a root certificate. In my-keystore.jks each imported certificate now is "trustedCertEntry" which means there is only the public key. The issuing relationship only appears in the "Issuer" field but it's OK because the trust relationship mattered most at the time of the import. At this point my-keystore.jks simulates an environment containing some trusted certificates, like a fresh JRE. The their-keystore.jks simulates the owners of those certificates, who have the power to sign certificate requests. So do I : I create a self-signed certificate e1 in my-keystore.jks, get it signed by ca2 (through their-keystore.jks) and import the signed result back into my-keystore.jks. e1 is still a "PrivateKeyEntry" (because its private key remains in my-keystore.jks) but now I've built the following chain : e1 -> ca2 -> ca1. It seems that ca1 -> ca is implicit with ca being a certification authority. To build the truststore I just import certificates ca, ca1 and ca2 the same way I did for my-keystore.jks. Please note I don't import e1, as I expect the SSL/TLS client to validate it against ca2. I think this gets rather close of how things work in real world. What's nice here is you have full control on the certificates, and no dependency on JRE's cacerts. Here is the code putting what I say in practice. Seems to work with Jetty (client and server) as long as you disable certificate revocation list (a topic left for another day). #!/bin/bash rm their-keystore.jks 2> /dev/null rm my-keystore.jks 2> /dev/null rm my-truststore.jks 2> /dev/null echo "====================================================" echo "Creating fake third-party chain ca2 -> ca1 -> ca ..." echo "====================================================" keytool -genkeypair -alias ca -dname cn=ca \ -validity 10000 -keyalg RSA -keysize 2048 \ -ext BasicConstraints:critical=ca:true,pathlen:10000 \ -keystore their-keystore.jks -keypass Keypass -storepass Storepass keytool -genkeypair -alias ca1 -dname cn=ca1 \ -validity 10000 -keyalg RSA -keysize 2048 \ -keystore their-keystore.jks -keypass Keypass -storepass Storepass keytool -genkeypair -alias ca2 -dname cn=ca2 \ -validity 10000 -keyalg RSA -keysize 2048 \ -keystore their-keystore.jks -keypass Keypass -storepass Storepass keytool -certreq -alias ca1 \ -keystore their-keystore.jks -keypass Keypass -storepass Storepass \ | keytool -gencert -alias ca \ -ext KeyUsage:critical=keyCertSign \ -ext SubjectAlternativeName=dns:ca1 \ -keystore their-keystore.jks -keypass Keypass -storepass Storepass \ | keytool -importcert -alias ca1 \ -keystore their-keystore.jks -keypass Keypass -storepass Storepass #echo "Debug exit" ; exit 0 keytool -certreq -alias ca2 \ -keystore their-keystore.jks -keypass Keypass -storepass Storepass \ | keytool -gencert -alias ca1 \ -ext KeyUsage:critical=keyCertSign \ -ext SubjectAlternativeName=dns:ca2 \ -keystore their-keystore.jks -keypass Keypass -storepass Storepass \ | keytool -importcert -alias ca2 \ -keystore their-keystore.jks -keypass Keypass -storepass Storepass keytool -list -v -storepass Storepass -keystore their-keystore.jks echo "====================================================================" echo "Fake third-party chain generated. Now generating my-keystore.jks ..." echo "====================================================================" read -p "Press a key to continue." # Import authority's certificate chain keytool -exportcert -alias ca \ -keystore their-keystore.jks -keypass Keypass -storepass Storepass \ | keytool -importcert -trustcacerts -noprompt -alias ca \ -keystore my-keystore.jks -keypass Keypass -storepass Storepass keytool -exportcert -alias ca1 \ -keystore their-keystore.jks -keypass Keypass -storepass Storepass \ | keytool -importcert -noprompt -alias ca1 \ -keystore my-keystore.jks -keypass Keypass -storepass Storepass keytool -exportcert -alias ca2 \ -keystore their-keystore.jks -keypass Keypass -storepass Storepass \ | keytool -importcert -noprompt -alias ca2 \ -keystore my-keystore.jks -keypass Keypass -storepass Storepass # Create our own certificate, the authority signs it. keytool -genkeypair -alias e1 -dname cn=e1 \ -validity 10000 -keyalg RSA -keysize 2048 \ -keystore my-keystore.jks -keypass Keypass -storepass Storepass keytool -certreq -alias e1 \ -keystore my-keystore.jks -keypass Keypass -storepass Storepass \ | keytool -gencert -alias ca2 \ -ext SubjectAlternativeName=dns:localhost \ -ext KeyUsage:critical=keyEncipherment,digitalSignature \ -ext ExtendedKeyUsage=serverAuth,clientAuth \ -keystore their-keystore.jks -keypass Keypass -storepass Storepass \ | keytool -importcert -alias e1 \ -keystore my-keystore.jks -keypass Keypass -storepass Storepass keytool -list -v -storepass Storepass -keystore my-keystore.jks echo "=================================================" echo "Keystore generated. Now generating truststore ..." echo "=================================================" read -p "Press a key to continue." keytool -exportcert -alias ca \ -keystore my-keystore.jks -keypass Keypass -storepass Storepass \ | keytool -importcert -trustcacerts -noprompt -alias ca \ -keystore my-truststore.jks -keypass Keypass -storepass Storepass keytool -exportcert -alias ca1 \ -keystore my-keystore.jks -keypass Keypass -storepass Storepass \ | keytool -importcert -noprompt -alias ca1 \ -keystore my-truststore.jks -keypass Keypass -storepass Storepass keytool -exportcert -alias ca2 \ -keystore my-keystore.jks -keypass Keypass -storepass Storepass \ | keytool -importcert -noprompt -alias ca2 \ -keystore my-truststore.jks -keypass Keypass -storepass Storepass keytool -list -v -storepass Storepass -keystore my-truststore.jks rm their-keystore.jks 2> /dev/null A: I don't get it. Are you using the server key store with the client? What is your use case exactly? Are you trying to setup mutual authentication? If yes, you're on the wrong path here. You'll need a client key store (for the client's self-signed certificate and private key) and a client trust store (for the server's "stand-alone" self-signed certificate i.e. without its private key). Both are different from the server key store. A: Springboot 2.1.5 , java 1.8, keytool(it is part of JDK 8) these are the steps to follow to generate the self signed ssl certifcate in spring boot 1. Generate self signed ssl certificate keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650 ex: D:\example> <here run the above command> if it is not working then make sure that your java bin path is set at environment variables to the PATH variable as C:\Program Files\Java\jdk1.8.0_191\bin 2. after key generation has done then copy that file in to the src/main/resources folder in your project 3. add key store properties in applicaiton.properties server.port: 8443 server.ssl.key-store:classpath:keystore.p12 server.ssl.key-store-password: test123 # change the pwd server.ssl.keyStoreType: PKCS12 server.ssl.keyAlias: tomcat 3. change your postman ssl verification settings to turn OFF go to settings and select the ssl verification to turn off now verify the url ( your applicaiton url) https://localhost:8443/test/hello
{ "language": "en", "url": "https://stackoverflow.com/questions/2200176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: gRPC node-js method not called when protocol specifies void parameter type I have just recent started experimenting with gRCP and currently trying to see how it works using node-js to create a simple example . However after creating the protocol to be used between both client and server . One of my rpc method is not been called . I have added below the specific method that is not been called along side the message specification in the .proto file .I have also provided a sample of both client side call and server side handler below. .proto service WeatherService{ rpc RetrieveAllWeather (void) returns (Temp); } message void{} message Temp{ string msg =1; } server.js // .... server configuration server.addService(weather_proto.WeatherService.service, { "RetrieveAllWeather":RetrieveAllWeather, "RetrieveWeatherByQuery":RetrieveWeatherByQuery, "SaveWeatherToFile":SaveWeatherToFile, } ); server.bindAsync( "127.0.0.1:4000", grpc.ServerCredentials.createInsecure(), (err,port)=>{ if(err){ console.error(err); process.exit(1); } console.log("Listening on port "+port) server.start(); } ); function RetrieveAllWeather(call,callback){ console.log(call); console.log("working"); callback(null,"call"); } client.js const client = new weather_proto.WeatherService( "127.0.0.1:4000",grpc.credentials.createInsecure() ); client.RetrieveAllWeather({},(err,res)=>{ if(err){ return err; } console.log("working"); console.log(JSON.stringify(res)); }); It seems because I am trying to specify the RetrieveAllWeather to accept nothing as payload and send a json {msg:"call"} but it is not working while other method that I created are working . A: It seems that using the void message naming convention was the cause of the bug , when I switch to using a Capitiized name for the message spec it started working . All I did was to change from message void{} to message Void{}
{ "language": "en", "url": "https://stackoverflow.com/questions/69356765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: After opening multiple pages with Puppeteer I get blank pages I apologize if I duplicated the topic, but everything I've tried so far doesn't help. I am trying to scraping some details data from each links from ads. After opened few links, I get each next time blank page without any data. Also, if I stop script and start it again I can't do it(because I received blank page on the start) and need to wait few minutes. This is code and can you please said me where I made mistake. Thank you :) const puppeteer = require("puppeteer-extra"); (async () => { const browser = await puppeteer.launch({ headless: false, args: [ "--no-sandbox", "--disable-setuid-sandbox", "--disable-infobars", "--window-position=0,0", "--ignore-certifcate-errors", "--ignore-certifcate-errors-spki-list", '--user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3312.0 Safari/537.36"', ], }); const page = await browser.newPage(); await page.goto( "https://www.ebay-kleinanzeigen.de/s-immobilien/01309/c195l23973" ); const banner = (await page.$("#gdpr-banner-accept")) !== null; if (banner) { await Promise.all([page.click("#gdpr-banner-accept")]); } let isBtnDisabled = false; while (!isBtnDisabled) { const productsHandles = await page.$$(".ad-listitem.lazyload-item"); for (const producthandle of productsHandles) { try { link = await page.evaluate( (el) => el.querySelector("a.ellipsis").href, producthandle ); const eachPage = await browser.newPage(); await eachPage.goto(link, { waitUntil: "networkidle0", }); await eachPage.waitForSelector("#viewad-price", { visible: true, }); const price = await eachPage.$eval( "#viewad-price", (price) => price.textContent ); console.log(price); eachPage.close(); } catch (error) { console.log(error); } } await page.waitForSelector("#srchrslt-pagination > div", { visible: true }); const is_disabled = (await page.$( "#srchrslt-pagination > div > div.pagination-nav > .pagination-next" )) === null; isBtnDisabled = is_disabled; if (!is_disabled) { await Promise.all([ page.click(".pagination-nav > .pagination-next"), page.waitForNavigation({ waitUntil: "networkidle2" }), ]); } } await browser.close(); })();
{ "language": "en", "url": "https://stackoverflow.com/questions/71286322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hide tableview header that contains a search bar under navbar? I have a search bar in the tableview header. I want to offset the position of the search bar that it looks hidden under the nav bar until the user pulls down on the tableview to reveal a search bar. I have looked everywhere to find this but cannot. Can someone please point me in the right direction and or show me how do create this effect in iOS 9 and objective-c. Thank you A: // search is hidden in TableView by default For swift self.TableView.setContentOffset(CGPointMake(0,self.searchController.searchBar.frame.size.height), animated: false) For Objective c [[self staffTableView] setContentOffset:[CGPointMake(0, frameHeight)] animated:YES]; When you pullDown it will reveal you searchbar(added in the headerview) Hope this will help you to solve your problem. it was working for me. A: Swift 3: let point = CGPoint(x: 0, y:(self.navigationController?.navigationBar.frame.size.height)!) self.tableView.setContentOffset(point, animated: true) This is for regular navigation bar. For search controller: Replace navigationController and navigationBar with karthik's y coordinate.
{ "language": "en", "url": "https://stackoverflow.com/questions/37420621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add textboxes dynamically in a form, using Jade template engine My requirement is a simple one , but no definite answer is available for this one on the net. I have a combobox in my jade page which takes numbers as input.I want the same page to refresh and have as many textboxes as the number specified. I know this requires Ajax, but I am not able to figure out how it can be used in Jade.Any suggestions would be greatly appreciated. A: This can be done without using ajax with help of jQuery. Define jade like this input.addTxtBox(type='text') #rows and then in javascript jQuery(document).ready(function() { // initiate layout and plugins $('.addTxtBox').keyup(function (e) { var value = $('.addTxtBox').val(); var str = '<input type="text">'; for(var i=0; i < parseInt(value) ; i++){ $("#rows").append(str); } }); }); check this jsfiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/26443702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Write an LLVM Pass in C I am trying to write an LLVM Pass in C, but I can only find information on how to do this in C++. If anyone has any references or knowledge on this topic, I would greatly appreciate it! Thank you! A: You should take a look at llvm-c-kaleidoscope where you can learn by example how to use the llvm-c interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/16794985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Paste image via ajax to laravel controller i'm trying to send a form with an image (file) via ajax to a laravel backend. currently i'm trying to get it work with form data, but all i can get are the params but not the file... I'm just outputting the content in console later on the ajax will be used On the save click the currently displaed image should also be replaced with the uploaded one $(document).ready(function() { $('a[data-action=edit]').on('click', function() { $('.box-tools').addClass('hide'); $(this).closest(".box-primary").find('dl.view-data, .box-tools').addClass('hide'); $(this).closest(".box-primary").find('.spinner, form.form-data').removeClass('hide'); }); $('a[data-action=cancel]').on('click', function() { $('.box-tools').removeClass('hide'); $(this).closest(".box-primary").find('.box-tools, dl.view-data').removeClass('hide'); $(this).closest(".box-primary").find('.spinner, form.form-data').addClass('hide'); }); $('a[data-action=save]').on('click', function() { var form = $(this).closest('form.form-data'), formData = new FormData(), formParams = form.serializeArray(); $.each(form.find('input[type="file"]'), function(i, tag) { $.each($(tag)[0].files, function(i, file) { formData.append(tag.name, file); }); }); $.each(formParams, function(i, val) { formData.append(val.name, val.value); }); console.log(formData); console.log(formParams); // alert($(this).closest('form.form-data').serialize()); // alert($(this).closest('.box-primary').attr('id')); $('.box-tools').removeClass('hide'); $(this).closest(".box-primary").find('.box-tools, dl.view-data').removeClass('hide'); $(this).closest(".box-primary").find('.spinner, form.form-data').addClass('hide'); }); $('#file').on('change', function() { var file = document.getElementById("file"); $('.file-name > span[data-text]').html(file.value); $('a[data-action=remove-file]').removeClass('hide'); }); $('a[data-action=remove-file]').on('click', function() { $('a[data-action=remove-file]').addClass('hide'); }); }); .box.box-primary { border-top-color: #00acd6; } .box { -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; -webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 0 5px rgba(0, 0, 0, 0.2); box-shadow: 0 0 2px rgba(0, 0, 0, 0.25); border-top: 3px solid #dddddd; } .box { position: relative; background: #ffffff; border-top: 2px solid #c1c1c1; margin-bottom: 20px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; width: 100%; box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1); } .hide { visibility: hidden; } .file-wrapper input[type="file"] { cursor: pointer; font-size: 100px; height: 100%; filter: alpha(opacity=1); -moz-opacity: 0.01; opacity: 0.01; position: absolute; right: 0; top: 0; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box box-primary" id="profile-picture"> <div class="box-header"> <h3 class="box-title">Profilbild</h3> <div class="box-tools block-action permanent pull-right"> <a href="javascript:void(0)" class="btn btn-default" data-action="edit"> EDIT </a> </div> </div> <div class="box-body"> <div class="text-center"> <div class="small spinner hide"> <div>Loading…</div> </div> </div> <dl class="dl-horizontal view-data"> <dt></dt> <dd class="text-right"> <img class="img-rounded profile" alt="Avatar" src="/img/no-avatar.png"> </dd> </dl> <form class="form-horizontal hide form-data" role="form"> <input type="hidden" name="_token" value="b4AniUckmBZqImpPqFbVhkDWlUwKQ7oiUKDXwAyE"> <div class="form-group"> <label class="col-sm-3 control-label">Neues Profilbild</label> <div class="col-sm-9"> <div class="file-field clearfix" style="margin-top:3px"> <div class="file-wrapper"> <input type="file" id="file" name="file"> <button class="btn btn-default btn-sm" data-action="change-file">Profilbild hochladen</button> </div> <div class="file-name"> <span data-text=""></span> <a href="javascript:void(0)" data-action="remove-file" class="remove-file btn btn-link btn-sm pull-right hide"> <i class="glyphicon glyphicon-remove"></i> </a> </div> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-8"> <a href="javascript:void(0)" class="btn btn-primary" data-action="save">Speichern</a> <a href="javascript:void(0)" class="btn btn-default" data-action="cancel">Zurück</a> </div> </div> </form> </div> </div> A: First you need to add attribute enctype="multipart/form-data" to your form tag like this: <form class="form-horizontal hide form-data" role="form" enctype="multipart/form-data"> And formData can't be inspected in console window you should use this way for (var pair of formData.entries()) { console.log(pair[0]+ ', ' + pair[1]); } Finally to submit your data use ajax call $.ajax({ url: window.location.pathname, type: 'POST', data: formData, success: function (data) { alert(data) }, cache: false, contentType: false, processData: false });
{ "language": "en", "url": "https://stackoverflow.com/questions/51862798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: validates combination of attributes I have two attributes (hours and days) in my model (auction). I have business logic on the combination of hours and days. For example auction duration = days*24 + hours I also have some basic validation on hours and days: class Auction < ActiveRecord::Base validates :days,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true } validates :hours,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true } I would like to incorporate my business logic into the validation, such that hour and days cannot both be zero. Is there a way to do this with an ActiveRecord validation? I know there are other ways to do this w/out an AR validation. Right now I am creating a new instance of my model. Validating days and hours as above. Then I have a model method that "manually" does the validation and removes the instance if it doesn't pass. I know this is not the best way to do this def compute_end_time # assumes that days and hours are already valid time = self.days*24 + self.hours if time > 1 self.end_time = time.hours.from_now.utc self.save else # Auction duration too short (i.e. zero) self.delete end end A: You need to write a private validate function something like this. class Auction < ActiveRecord::Base validates :days,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true } validates :hours,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true } validate :days_and_hours private def days_and_hours if !(days && hours) errors.add_to_base("Days and hours can not be zero. Thank you.") end end end A: You can check for a value greater than 0 by using the numericality validator: validates :auction_duration, :numericality => { :greater_than => 0 } More info is at: http://guides.rubyonrails.org/active_record_validations_callbacks.html#numericality A: So my final solution was an extension of @rharrison33: validates :days,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true } validates :hours,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true } validate :days_and_hours def days_and_hours # It may not validate days and hours separately before validating days_and_hours, # so I need to make sure that days and hours are both not NIL before trying to compute 'time' # I also only want to compute end_time if it has not been computed yet if (!self.days.nil? && !self.hours.nil?) if (self.end_time.nil?) # if end_time has not yet been computed if (self.days == 0 && self.hours == 0) self.errors[:base] << "Days and hours can not be zero." else time = self.hours + self.days*24 self.end_time = time.minutes.from_now.utc self.setStatus # validate status after end time is set end end end end
{ "language": "en", "url": "https://stackoverflow.com/questions/13262579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i seperate joomla sub menus in different modules I have 3 level menus and i need to display each sub menu in diferrent modules. ie, This is a 3 level menu, i need to display main menu in MODULE_ONE, and second level in MODULE_TWO and third level in MODULE_THREE position correspondingly, with out the tree structure . The modules three modules are in different position. How can i implement this in joomla 2.5. I have check and been able to display on second level but not possible to display 3rd level. please reply if there is a thank you. A: You can display 3 levels in 3 modules from the same menu, of course the second level's content will be determined by the first level selection; this will apply also to the third level. However, please note that mod_menu used to have inadequate cache support, so by all means DO DISABLE the cache on the modules, else they won't work or will work funny (not showing the current page highlighted... changing the second menu "20" when you click on the first menu "3" ...) A: Try the Splitmenu configuration of RocketTheme's RokNavMenu Here's a discussion on how to accomplish that.
{ "language": "en", "url": "https://stackoverflow.com/questions/14500691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't drop table after creating table with wrong engine I'm trying to drop a table containing several hundred thousand column-based records. Normally when creating the database I use a column-based engine (infinidb) but in this case I forgot to include the ENGINE statement. So the database is pretty much unusable for my needs. Now I have a database full of tables that are taking forever to drop (it's been two hours and nothing has happened). I tried the ALTER TABLE table ENGINE=INFINIDB command but again, it's taking forever (see above re: two hours). EDIT: The first command I tried was DROP TABLE. It hung with every single table. Then I tried the ALTER command in case that was faster for some reason, but it wasn't. Is there another way to get rid of this database? E.g. manually going into the /mysql/ directory and deleting the database? I guess I could just rename it and leave it, but I'd rather get rid of it entirely so it's not taking up space. A: First of all you said Can't drop table. But in post you mentioned ALTER TABLE table ENGINE=INFINIDB. But DROP != ALTER it is two different things. So you can do following: * *CREATE new table with same structure but engine you need. *copy(UPDATE) data from old table to the one you just created. *DROP old table. *RENAMErename new one to old name A: It turned out that another process (a website) was using this database and had a couple of queries that got 'stuck' in the SQL server and caused the table to hang due to the database using the wrong engine, which I'm assuming was InnoDB since I didn't specify an engine when I initially used the "CREATE TABLE table1 AS SELECT * FROM table2" command. We finally managed to wipe the database and start over. Thanks for your help.
{ "language": "en", "url": "https://stackoverflow.com/questions/37970417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python: How to find the highest number in a column of data I have csv and txt files and I want to analyze them and find the highest number in a specific column. For example I want to know the highest number (in all the rows) in column 5. This what I have so far but I don't know how to figure out how to search a specific column. `import csv #opening csv file = open("Scoring.csv","r") csv = csv.reader(file) csv_1=[] rows = [] for in_line in file: row = [float(each) for each in in_line.split()] rows.append(row) file.close() # this'll happen at the end of the script / function / method anyhow columns = zip(*rows) for index, row in enumerate(rows): print "In row %s, Max = %s, Min = %s" % (index, max(row), min(row)) for index, column in enumerate(columns): print "In column %s, Max = %s, Min = %s" % (index, max(column), min(column)) A: If the following code for index, column in enumerate(columns): print "In column %s, Max = %s, Min = %s" % (index, max(column), min(column)) you provided gives you correct answers and I understand you correctly, than getting min value (for example) from specific column should be easy enough, along the lines of min(columns[index_of_column]), for example: min(columns[4]) For max value in column, replace min() with max(). And, remember, index_of_column is zero based (first column has index of 0, so 5th column would have an index of 4). So, to get both min and max value, you would do: print "In column %s, Max = %s, Min = %s" % (5, max(columns[4]), min(columns[4]))
{ "language": "en", "url": "https://stackoverflow.com/questions/43920583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show night / day icon (with php) using sunset / sunrise What is the best method / script to echo an image after sunset and before sunrise with php. if (date("H:i") > date_sunset(time(), SUNFUNCS_RET_STRING, 51.29, 4.49, 90.7, 2)) { $icon = "icon_night"; } else { $icon = "icon_day"; } if (date("H:i") > date_sunrise(time(), SUNFUNCS_RET_STRING, 51.29, 4.49, 90.7, 2)) { $icon = "icon_night"; } else { $icon = "icon_day"; } echo $icon; I wanted to return a day and night icon. A: You're comparing current time to each of sunrise / sunset independently meaning you'll get some odd results. This should work for determining which one to show $now = date("H:i"); $sunrise = date_sunrise(time(), SUNFUNCS_RET_STRING, 51.29, 4.49, 90.7, 2) $sunset = date_sunset(time(), SUNFUNCS_RET_STRING, 51.29, 4.49, $icon = ($now > $sunrise && $now < $sunset) ? 'icon_day' : icon_night' // Will echo icon_day or icon_night echo $icon; Displaying an actual icon instead of text is a very different question. If that's what you're trying to get at more information is required (do you have icons? where are you showing them? what have you tried)
{ "language": "en", "url": "https://stackoverflow.com/questions/57299535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Correlations with alternating second component in R (I think this one's fairly straightforward but it's not coming to me, as I'm not terribly comfortable using loops in R.) I'd like to run a series of cor() where one element of the function is the same column, but the second alternates to the next column over. For example, cor(data$V1, data$V2) and then cor(data$V1, data$V3), etc. I can't just run a correlation matrix and use use="complete.obs" because every comparison has a different number of cases missing. How can I easily do this in a loop? A: lapply(mtcars[,-1], cor, mtcars[,1]) # [[1]] # [1] -0.852162 # [[2]] # [1] -0.8475514 # [[3]] # [1] -0.7761684 # [[4]] # [1] 0.6811719 # [[5]] # [1] -0.8676594 # [[6]] # [1] 0.418684 # [[7]] # [1] 0.6640389 # [[8]] # [1] 0.5998324 # [[9]] # [1] 0.4802848 # [[10]] # [1] -0.5509251 A: Actually, dumb answer, still can do a correlation matrix but using use="pairwise.complete.obs A: If there is no missing values, you can just do: set.seed(100) mat = data.frame(matrix(runif(1000),ncol=100)) colnames(mat) = paste0("V",1:100) cor(mat[,1],mat[,2:100]) If there are missing values: set.seed(100) mat = matrix(runif(1000),ncol=100) mat[sample(length(mat),100)] <- NA mat = data.frame(matrix(runif(1000),ncol=100)) colnames(mat) = paste0("V",1:100) cor(mat[,1],mat[,2:100],use="p")
{ "language": "en", "url": "https://stackoverflow.com/questions/60759459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How would I convert a valid Javascript JSON into a dictionary in Swift 2? I am trying to create a dictionary from this JSON in an variable of type [String: AnyObject]. I am using Alamofire to make the request. However, the responseJSON response handler doesn't work since it is not a 'valid' JSON object in Swift. How can I go about tackling this? A: Your text is not valid JSON (you can check this here), as it's missing quotation marks around attribute strings. While it might be a JavaScript object, that's not synonymous with valid JSON. NSJSONSerialization (which is surely what's backing that function) will correctly reject the input. You should fix your JSON - preferably at the source. You could do it by post-processing with string editing functions in Swift, but this is a bad idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/36847446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting code coverage in Sonar but no test results (.Net) I'm re-using reports in my sonar config: sonar.gallio.mode=reuseReport sonar.gallio.reports.path=gallio-report.xml sonar.gallio.coverage.reports.path=results.xml I've previously run Gallio and OpenCover and can confirm that both completed successfully and that Sonar is able to retrieve the files (I've checked the log produced by the -X flag thoroughly). When I view the project in the sonar dashboard, I see code coverage, but not test results: Kindly ignore the low code coverage percentage, I'm running a small subset of tests while I figure this out. I should see something that reflects the results I saw when I ran Gallio: 14 run, 13 passed, 1 failed (1 error), 0 inconclusive, 0 skipped I'm happy to include the gallio-report.xml if that's helpful, but it's 103kb so clearly it contains plenty of data, and I think this is more likely to be a configuration issue. I'm running OpenCover 4.0.1118 and Gallio 3.2.750 (tests are written with NUnit). Any thoughts why I don't see any test results? A: Chances are that you don't have the test sources in your .NET solution, so when SonarQube tries to import the test execution results, it can't find to which files they should be attached. In the .NET sample solution, you can see that there is a test project (Example.Core.Tests) which contains the sources of the test classes.
{ "language": "en", "url": "https://stackoverflow.com/questions/18640406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Add a menu to a java swing application I'm working on a Java swing application, and I want to get a menu like that: I created the first menu (on the top) using a JMenuBar and JMenuItems, but I don't know how to create the second one. Thanks in advance A: You could try making a JToolBar and then add buttons to it. A: You should use JTabbedPane and for each element one tab. UPDATE: Here you find a simple example of tabs with icons A: One option is to just horizontally align buttons. But make it your own horizontal menu component with dynamic itens and a flexible interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/23705777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to open partial view with $window.open()? How can i set url in $window.open() .. something like this $window.open("/account/something") ? I tried this but i get always default page without anything. A: You can simply use $window.open('/controller-Name/action-method-Name');}; Which will find the action method and return the view. If problem still persist, debug your action method once.
{ "language": "en", "url": "https://stackoverflow.com/questions/31243461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how do I subtract -1 if a specific char is not found within a string I need some hints on how to program this, this method is for a hangman game guessCh is the letter user has guessed while secretCh is the letters in the secret word, they come from a while() loop one at a time. But what I need is instead of just if (guessCh != secretCh) wich don´t work cause the secret word consist of severall letters so it will subtract points from all those letters within the secret word, that it should not subtract from. Only if the guessCh char is not found in any of the secretCh letters / or within the secret word should it subtract -1. I seem to be stuck on this, I know it´s simple... but throw me a bone. I´ve already spent to much time on this. private void nTurns(char guessCh, char secretCh) { //Create an array that stores already used letters if (guessCh != secretCh) { nTurnsLeft--; } } A: You could do an ArrayList of the characters found in your secret. Then use .contains(Char c) method from the ArrayList An Example: ArrayList<Char> secret = new ArrayList<Char>(); secret.add('w'); secret.add('o'); secret.add('r'); secret.add('l'); secret.add('d'); if(secret.contains(new Char('x')) { System.out.println("Found"); } else { System.out.println("Not Found"); } A: I think this might be homework, so gtgaxiola's answer could be something the teacher doesn't want to see. Here is how to implement the equivalent of .contains() on a normal array of chars so you don't have to change too much in your current code. char[] secretCh = new char[]{'s', 'e', 'c', 'r', 'e', 't'}; char guessCh = 'e'; boolean found = false; for(int i = 0; i < secretCh.length; i++) { // loop through each character in the secretCh array if (secretCh[i] == guessCh) { found = true; break; } } if (found) System.out.println("guessCh is a letter in the secret word."); A: The String object already has this functionality built in. All you really need is something like this: if(secretStr.indexOf(guessCh) < 0) nTurnsLeft--; indexOf returns the index of the location of the char guessCh inside the String secretStr. If guessCh is not found, then indexOf returns -1;
{ "language": "en", "url": "https://stackoverflow.com/questions/12555239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java charAt() Method Crashes in For Loop The following code should read 5 strings from a .dat file and then print each individual character from each of the strings. File file = new File("tictactoe.dat"); Scanner scan = new Scanner(file); String str = ""; int x; for ( x = 0; x < numGames; x++) { str = scan.nextLine(); for (int i = 0; i < str.length(); i++) { out.println(str.charAt(i)); } } But the program throws a StringIndexOutOfBoundsException. There's nothing wrong with the Scanner, as tests have shown that it picks up each line in my file fine. But when attempting to get and then print a certain character in each string, the program crashes. Strangely, outside of the loop charAt() works without error. Why does calling the method within the loop cause the progam to crash? UPDATE: I made some ridiculous mistake copying the code I was using. Please see updated code above. Also, the program "crashes" due to a StringIndexOutOfBoundsException, which I am not catching. A: I would have expected the error to be StringIndexOutOfBoundsException as you are printing the first letter from the first line and the second letter from the second line, etc. As you don't check whether such a letter exists, there comes a point where the line is not that long. If that is not the cause I would * *read the exception post it in the question. *step through your code with your debugger to find the bug in your code. A: you have confused number of lines, with number of characters in each line File file = new File("tictactoe.dat"); Scanner scan = new Scanner(file); String str = ""; int x; int y; for ( x = 0; x < numGames; x++) { str = scan.nextLine(); for (y = 0; y<str.length(); y++) { out.println(str.charAt(y)); } } A: There's something strange in your logic. Assuming the DAT is: 12345 67890 abcde fghij klmno Your code will print: 1 7 c i o After all, you invoke "scanLine" numGames times and grab the X position on each new line. A: Your loop isn't doing what you want it to do. You say: ... and then print each individual character from each of the strings. But what it's actually doing is getting line 1, and printing only the first character from that line, then getting the second line and printing the second character, third line and third character, and so on. If you're printing each character on a separate line, you need to have a second loop inside your first one that iterates through the characters in the string in order to print all their individual characters. char[] characters = str.toCharArray(); for (int i = 0; i < characters.length; i++) { System.out.println(characters[i]); } Or even better, if you use a for-each loop: for (char c : str.toCharArray()) { System.out.println(c); }
{ "language": "en", "url": "https://stackoverflow.com/questions/12605978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: reduce image size in memory After an image was downloaded by the browser, am I correct to think that even if the image is resized smaller with css, the memory footprint is still the same as the image remains untouched in the browser's memory ? If so, is there a way to actually decrease the size of the image so that it takes less memory and also, does not affect display performance too much during scrolling/paning operations ? ps: this question may not make a lot of sense for a "traditional" web page, but is very important (for me, at least) in the context of a single page web application displaying many images of different sizes because pages and browser memory are not "refreshed" when displaying new pages. ps2: i do not have access to the server, so server-side resizing is a no-go A: You could rescale server side with something like imagemagick http://www.imagemagick.org/script/index.php This has bindings for many different programming languages A: CSS scaling does usually not reduce the memory footprint. I think it might actually increase it, because the browser has to buffer/cache the scaled version and the original version of the image. I think you could use the Canvas API to effectively draw a smaller version of the image and use that instead. Also take a look at this question. Plus, if you know the effective, final size of the image, you could of course do that on the web server and cache the smaller version. This should offer some degree of downwards compatibility.
{ "language": "en", "url": "https://stackoverflow.com/questions/14019095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Gradle Kotlin DSL: Extract contents from dependency How do I convert the following snippet (based on the one by Peter Niederwieser) to Kotlin? configurations { assets } dependencies { assets 'somegroup:someArtifact:someVersion' } task extractApi(type: Sync) { dependsOn configurations.assets from { // use of closure defers evaluation until execution time configurations.assets.collect { zipTree(it) } } into "$buildDir/assets/" } A: I haven't experience with the Kotlin DSL, but apparently the extractApi task could be re-written as val assets by configurations.creating dependencies { assets("somegroup", "someArtifact", "someVersion") } tasks { val extractApi by creating(Sync::class) { dependsOn(assets) from(assets.map { zipTree(it) }) into("$buildDir/api/") } }
{ "language": "en", "url": "https://stackoverflow.com/questions/54833503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to include apostrophe in character set for REGEXP_SUBSTR() The IBM i implementation of regex uses apostrophes (instead of e.g. slashes) to delimit a regex string, i.e.: ... where REGEXP_SUBSTR(MYFIELD,'myregex_expression') If I try to use an apostrophe inside a [group] within the expression, it always errors - presumably thinking I am giving a closing quote. I have tried: - escaping it: \' - doubling it: '' (and tripling) No joy. I cannot find anything relevant in the IBM SQL manual or by google search. I really need this to, for instance, allow names like O'Leary. A: Thanks to Wiktor Stribizew for the answer in his comment. There are a couple of "gotchas" for anyone who might land on this question with the same problem. The first is that you have to give the (presumably Unicode) hex value rather than the EBCDIC value that you would use, e.g. in ordinary interactive SQL on the IBM i. So in this case it really is \x27 and not \x7D for an apostrophe. Presumably this is because the REGEXP_ ... functions are working through Unicode even for EBCDIC data. The second thing is that it would seem that the hex value cannot be the last one in the set. So this works: ^[A-Z0-9_\+\x27-]+ ... etc. But this doesn't ^[A-Z0-9_\+-\x27]+ ... etc. I don't know how to highlight text within a code sample, so I draw your attention to the fact that the hyphen is last in the first sample and second-to-last in the second sample. If anyone knows why it has to not be last, I'd be interested to know. [edit: see Wiktor's answer for the reason] btw, using double quotes as the string delimiter with an apostrophe in the set didn't work in this context. A: A single quote can be defined with the \x27 notation: ^[A-Z0-9_+\x27-]+ ^^^^ Note that when you use a hyphen in the character class/bracket expression, when used in between some chars it forms a range between those symbols. When you used ^[A-Z0-9_\+-\x27]+ you defined a range between + and ', which is an invalid range as the + comes after ' in the Unicode table.
{ "language": "en", "url": "https://stackoverflow.com/questions/57542826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Tracking user/client activity in react and .net web app I am trying to track all CRUD activities on my web app. I am using React and .NET with MySql. Idea is that if someone edits let's say client data (phone number, address, etc...), I want to have something like an activity log where I will see WHO edited that client and WHAT he edit. Let's say You are an admin, and you go to list off all clients, then U click on one and get redirected to the preview page of that client. On the bottom, you will see the activity log.
{ "language": "en", "url": "https://stackoverflow.com/questions/72627994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create array from dynamically created input field id's What I need to do is retreive all the values of the input fields and store them in the database after pressing a submit button. Here is what I'm doing: I retrieve an unknown number of rows from the query, I created an ID dynamically for every input field that can be filled. (so if I get 5 rows, I have 10 input fields, if I get 10 rows, 20 input fields) This piece: <input class="goals" type="number" id="'.$row[SCHE_WED].'_'.$row[SCHE_LAND_ID1].'" value="" maxlength="3" '.$active.'/> How do I get all the id="'.$row[SCHE_WED].'_'.$row[SCHE_LAND_ID1].'"'s into an array? I already tried input name="". (but when using an array, while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) it doesn't like name="" so I changed that to id="") What I used in another form with the name="" for an input field is this: $fields = array('','','','',''); // Add all your field names to an array $data = array(); foreach ($fields as $field) { if (isset($_POST[$field])) { $data[$field] = $_POST[$field]; ${$field} = $_POST[$field]; } } But I don't know how or can find how to put the dynamically generated id's in something similar for my code (see below). if (sqlsrv_has_rows($stmt)) { while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) { $dateconvert = $row[SCHE_DATE]; $converted = date("d-m-yy", strtotime($dateconvert)); echo ' <tr> <td style="text-align:center"; colspan="15">Wedstrijd en plaats gegevens voor wedstrijd '.$row[SCHE_WED].'</td> </tr> <tr> <td></td> <td>Stad: '.$row[Stdn_stad].'</td> <td></td> <td>Inwoners Stad: '.$row[STDN_INWNR_CAP].'</td> <td></td> <td>Stadion naam: '.$row[STDN_NAAM].'</td> <td></td> <td>Capaciteit Stadion: '.$row[STDN_CAP].'</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td>Datum: '.$converted.'</td> <td></td> <td>Tijd: '.$row[SCHE_TIME].'</td> <td></td> <td style="text-align:right";>Thuis: '.$row[SCHE_LAND1].'</td> <td> - </td> <td>Uit: '.$row[SCHE_LAND2].'</td> <td></td> <td><input class="goals" type="number" id="'.$row[SCHE_WED].'_'.$row[SCHE_LAND_ID1].'" value="" maxlength="3" '.$active.'/></td> <td> - </td> <td><input class="goals" type="number" id="'.$row[SCHE_WED].'_'.$row[SCHE_LAND_ID1].'" value="" maxlength="3" '.$active.'/></td> <td></td> <td>Totokruisje: <input class="goals" type="number" id="toto_'.$row[SCHE_WED].'" value="" maxlength="3" '.$active.'/></td> <td></td> </tr> '; } } echo ' <tr> <td colspan="15"></td> </tr> </table> </div> '; ?> A: One idea is you can create two input arrays for the goal+team combo. You could repeat this combo for as many goals as you need. <input type="text" name="teams[]" value="" /> <input type="number" name="goals[]" value="" /> Then when your form submits, you have two arrays: $_POST['teams'] and $_POST['goals']. You can use the index to match teams to goals like: foreach($_POST['teams'] as $key => $team) { echo $team; $goal = $_POST['goals'][$key]; echo $goal; } And process as needed. You can add the form elements dynamically with jQuery like this: http://jsfiddle.net/6G7yB/6/ Hope this helps Edit: You can also do something like this: http://www.php.net/manual/en/reserved.variables.post.php#87650
{ "language": "en", "url": "https://stackoverflow.com/questions/23170955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to auto run a dotnet command when opening a solution in visual studio I am interested to run dotnet watch test when opening a solution with my unit tests in visual studio 2017. Is there a way to run that just after the solution is open without doing it manually? A: Visual Studio Task Runner can run any arbitrary CMD command when a project/solution is opened. Prerequisites: Command Task Runner extention. * *Add Foo.cmd with a target command to your project having dotnet watch package installed. It could have one line of code: dotnet watch run Make sure the file is properly encoded to UTF-8 without BOM. *After Command Task Runner extention install, Add to Task Runner option should be accessible from context menu of *.cmd files. Press it and choose per-project level. As a result, commands.json should appear in the project. *Go to VS View -> Other Windows -> Task Runner Explorer. Set up the binding for the Foo command in the context menu: Bindings -> Project Open (the window refresh could help to see a recently added command). *Re-open the solution and check a command execution result in Task Runner Explorer. How it could look:
{ "language": "en", "url": "https://stackoverflow.com/questions/44127882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Django REST api I'm using Django's rest framework and currently set up I have a url /api/course/ which shows a list of courses that are already in the database. Courses have a Lecture foreign key and I want to make it so that you can access each course's lectures. Currently I've set it up so that /api/lectures takes you to all the lectures. router.register(r'course', views.CourseViewSet) router.register(r'lecture', views.LectureViewSet) However, I'm not sure how to set it up so that when you look at course Math, you only get Math lectures.. Thanks! Edit: My models: class Lecture(models.Model): title = models.CharField(max_length=128, unique=True, null=True) recordings = models.ForeignKey(Recording, null=True) keywords = models.ForeignKey(Keyword, null=True) def __str__(self): return self.title class Course(models.Model): title = models.CharField(max_length=128, unique=True) lecturer = models.CharField(max_length=128) lectures = models.ForeignKey(Lecture, null=True) def __str__(self): return self.title A: So here is the answer; You can use detail route for such situations; http://www.django-rest-framework.org/api-guide/routers/ go through DRF routing documentation; class CourseViewSet(ModelViewSet): @detail_route(methods=['get']) def lectures(self, request, pk=None): # code to get all lectures of your current course # pk will be course id(ex: id of Maths course) data = {} # serialize the data return Response(data) so your url will be like; /courses/id/lectures
{ "language": "en", "url": "https://stackoverflow.com/questions/33810462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Print monitor modification and redirection to another printer port I'm trying to modify the data being printed to an Epson POS printer before it is printed. I'm currently doing this by using a print monitor instead of the Epson port in the printer port config. In the WritePort() routine for the monitor, I am writing the modified data to COM1 directly. This does send the data to the printer, but it is not doing the negotiation with the printer that is done if the Epson port is selected instead of the port monitor. Is there a way to send the data from my monitor through the Epson port in order to get the real driver to kick in? It seems to be a monitor as well as it shows up in the list returned from EnumMonitors(). I've seen similar questions asked, but I've been unable to find the answer on any forum. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/13352189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }