Stack Overflow

Subscribe to Stack Overflow feed
most recent 30 from stackoverflow.com 2017-09-23T21:24:57Z
Updated: 2 hours 6 min ago

Need to click on specific link using selenium in Firefox browser

8 hours 8 min ago

I'm using selenium with the Firefox browser. I need to click on the href link associated with the text 'GS-L1' in HTML like what appears below. How can I do that? In spite of various approaches my efforts have always met with "Exception Type : selenium.common.exceptions.NoSuchElementException\nException Detail : Message: Unable to locate element".

<div class="row"> <div class="col-xs-12"> <h3 class="header smaller lighter green" style="font-family:Arial;">Application Health Check</h3> <p></p> <a href="link1" class="btn btn-app btn-primary" title="NDS Level-1 Healthcheck"> <i class="ace-icon fa fa-sitemap bigger-230 faa-vertical animated "></i> NDS-L1 </a> <a href="link2" class="btn btn-app btn-purple" title="GS Level-1 Healthcheck"> <center><i class="ace-icon fa fa-refresh bigger-230 fa-spin fa-3x fa-fw"></i></center> GS-L1 </a> </div> </div>

Here are some of the attempts I've made:

driver = webdriver.Firefox() driver.set_page_load_timeout(30) driver.get("index.htm") driver.maximize_window() driver.find_element_by_id("CID").send_keys("username") driver.find_element_by_name("password1").send_keys("psd") driver.find_element_by_id("submit").click() driver.find_element(By.XPATH,'//a[text()="GS-L1"]')[1].click() driver.find_element_by_xpath('//a[@title="GS Level-1 Healthcheck"][@text="GS-L1"]').click() driver.find_element_by_xpath('//a[@href="http://selfie.standardbank.co.za/GS_HealthCheck.htm"][@title="GS Level-1 Healthcheck"]')[1] driver.find_element_by_xpath('//a[@class="ace-icon fa fa-refresh bigger-230 fa-spin fa-3x fa-fw"][@title="GS Level-1 Healthcheck"]').click() driver.find_element_by_xpath('//a[@href="http://selfie.standardbank.co.za/GS_HealthCheck.htm"]')[1] driver.find_element_by_xpath('//*[@title="GS Level-1 Healthcheck"]').click() driver.find_element_by_xpath("//a[contains(@href,'GS-L1')]").click() driver.find_elements_by_class('ace-icon fa fa-refresh bigger-230 fa-spin fa-3x fa-fw')[0] datentime = driver.findElement(By.className("ace-icon fa fa-refresh bigger-230 fa-spin fa-3x fa-fw")).find_element_by_link_text("GS-L1") driver.find_element_by_link_text("GS-L1")[1].click() driver.implicitly_wait(10) ActionChains(driver).move_to_element(button).click(button) driver.implicitly_wait(10) elem = driver.find_element_by_link_text("GS-L1")[1] elem = driver.find_element_by_link_text("Selfie - Support Automation") driver.implicitly_wait(10) elem.click() click_element = driver.find_element_by_link_text("GS-L1") click_element.click() element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.linkText, "GS-L1")))

How to insert a new Word style into a RMarkdown file

9 hours 1 min ago

Is there a simple way to do this using Knitr without using Pandoc? I tried adding some HTML <DIV Class="newStyle>&nbsp</div> into an .Rmd file, but the style didn't show up in the generated Word .docx.

Thanks, Sue.

pandas - Adding columns to a dataframe using columns from two different dataframes

14 hours 12 min ago

I have three dataframes: problem_data, user_data and submissions_data. The contents of theses dataframes are :

problem_data

problem_id level_type points tags 0 prob_3649 8.0 4000.0 NaN 1 prob_6191 1.0 500.0 NaN 2 prob_2020 6.0 3000.0 NaN 3 prob_313 1.0 500.0 greedy,implementation 4 prob_101 1.0 500.0 constructive algorithms,greedy,math 5 prob_1479 5.0 2500.0 NaN

user_data

user_id rating_combined rank submission_count 0 user_3311 337.8442 2 47 1 user_3028 365.9408 2 63 2 user_2268 293.5780 1 226 3 user_480 493.1192 3 611 4 user_650 511.4106 3 504 5 user_3177 331.1350 2 3

submissions_data

user_id problem_id attempts_range 0 user_232 prob_6507 1 1 user_3568 prob_2994 3 2 user_1600 prob_5071 1 3 user_2256 prob_703 1 4 user_2321 prob_356 1 5 user_1569 prob_6064 1

These dataframes have different number of rows. I want to add columns 'level_type' and 'points' from problem_data and 'rating_combined', 'rank' and 'submission_count' from user_data to submissions_data according to corresponding 'problem_id' and 'user_id'. Basically, I'm preparing my training dataframe which will include all these columns.

What should I do?

How to do parallel processing for Monte Carlo simulation in python

14 hours 12 min ago

I was wondering how do we do Monte Carlo simulations using parallel processing in Python?

Let's say I have a function f which needs two random input parameters (a,b), in MATLAB we simply have to replace the for statement with parfor and start the

Can we do something like that in Python?

iOS 11 UIWebView drop down menus completely broken on iPad - UIPopoverController

14 hours 13 min ago

When using HTML select element, UIWebView presents a native UIPopoverController as dropdown list on iPad (iPhone uses UIPickerView which works fine).

On iOS11 this appears to be completely broken:

  • Clicking outside dropdown to dismiss without selecting an option results in popover being closed and immediately re-presented, occasionally empty
  • When more than one drop down on the page, drop down for new list contains elements from previous list
  • Occassionally drop down appears in top left corner (presumably lost it's source view)
  • Above steps very occasionally result in the following crash:

2017-09-23 09:43:13.190728+0100 Web[1779:86622] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource is not set' *** First throw call stack: ( 0 CoreFoundation 0x000000010d4a01cb __exceptionPreprocess + 171 1 libobjc.A.dylib 0x000000010c8bbf41 objc_exception_throw + 48 2 CoreFoundation 0x000000010d4a5362 +[NSException raise:format:arguments:] + 98 3 Foundation 0x000000010c360089 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193 4 UIKit 0x000000010da742f5 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 1756 5 UIKit 0x000000010da7451a -[UITableView _createPreparedCellForRowAtIndexPath:willDisplay:] + 81 6 UIKit 0x000000010da82137 -[UITableView _heightForRowAtIndexPath:] + 208 7 UIKit 0x000000010dd2b939 -[UISectionRowData heightForRow:inSection:canGuess:] + 259 8 UIKit 0x000000010dd31c1a -[UITableViewRowData heightForRow:inSection:canGuess:adjustForReorderedRow:] + 277 9 UIKit 0x000000010dd36230 -[UITableViewRowData ensureHeightsFaultedInForScrollToIndexPath:withScrollPosition:boundsHeight:] + 964 10 UIKit 0x000000010da51110 -[UITableView _contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:usingPresentationValues:] + 2783 11 UIKit 0x000000010da51b8f -[UITableView _scrollToRowAtIndexPath:atScrollPosition:animated:usingPresentationValues:] + 146 12 UIKit 0x000000010da51a11 -[UITableView scrollToRowAtIndexPath:atScrollPosition:animated:] + 123 13 UIKit 0x000000010de72d11 -[UIWebSelectTableViewController viewWillAppear:] + 247 14 UIKit 0x000000010dabe9b0 -[UIViewController _setViewAppearState:isAnimating:] + 444 15 UIKit 0x000000010dabf245 -[UIViewController __viewWillAppear:] + 147 16 UIKit 0x000000010da8b881 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke + 1088 17 UIKit 0x000000010d926c61 _runAfterCACommitDeferredBlocks + 318 18 UIKit 0x000000010d91530d _cleanUpAfterCAFlushAndRunDeferredBlocks + 280 19 UIKit 0x000000010d945600 _afterCACommitHandler + 137 20 CoreFoundation 0x000000010d442db7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23 21 CoreFoundation 0x000000010d442d0e __CFRunLoopDoObservers + 430 22 CoreFoundation 0x000000010d427324 __CFRunLoopRun + 1572 23 CoreFoundation 0x000000010d426a89 CFRunLoopRunSpecific + 409 24 GraphicsServices 0x00000001124c89c6 GSEventRunModal + 62 25 UIKit 0x000000010d91ad30 UIApplicationMain + 159 26 Web 0x000000010bfb014f main + 111 27 libdyld.dylib 0x0000000110df1d81 start + 1 28 ??? 0x0000000000000001 0x0 + 1

I created a sample application with one line of code which demonstrates the issue:

https://github.com/AshRobinson/BrokenUIWebView

Empty Popover

Does anyone have a workaround for such issue? Is there any way to force iPad to use UIPickerView for dropdowns as per iPhone temporarily?

I have investigated suggestions in other stack overflow posts with no luck, for example:

ios 11 Beta 5 select drop-down list issue

API OMC cTrader with FIX44

14 hours 13 min ago

I'm a freelancer python developer. I have some issues with connecting ctrader with FIX44 using PyFIX when I add the address and port to my client, It have error the code: https://github.com/wannabegeek/PyFIX my code: class Client(FIXEngine): def init(self): FIXEngine.init(self, "h50.p.ctrader.com") self.clOrdID = 0 self.msgGenerator = None

# create a FIX Client using the FIX 4.4 standard self.client = FIXClient(self, "pyfix.FIX44", "TARGET", "SENDER") # we register some listeners since we want to know when the connection goes up or down self.client.addConnectionListener(self.onConnect, ConnectionState.CONNECTED) self.client.addConnectionListener(self.onDisconnect, ConnectionState.DISCONNECTED) # start our event listener indefinitely self.client.start('178.62.43.199', int("5211")) while True: self.eventManager.waitForEventWithTimeout(10.0) # some clean up before we shut down self.client.removeConnectionListener(self.onConnect, ConnectionState.CONNECTED) self.client.removeConnectionListener(self.onConnect, ConnectionState.DISCONNECTED)

That's the error:

2017-09-23 10:56:23,631 Client disconnected 2017-09-23 10:56:23,631 ('178.62.43.199', 5211) has disconnected 2017-09-23 10:56:23,631 Attempting Connection to 178.62.43.199:5211 2017-09-23 10:56:23,740 Connected to ('178.62.43.199', 5211) 2017-09-23 10:56:23,868 Established connection to ('178.62.43.199', 5211) 2017-09-23 10:56:23,869 Connection has been closed [Errno 104] Connection reset by peer 2017-09-23 10:56:23,869 Client disconnected 2017-09-23 10:56:23,869 ('178.62.43.199', 5211) has disconnected 2017-09-23 10:56:23,869 Attempting Connection to 178.62.43.199:5211 2017-09-23 10:56:23,980 Connected to ('178.62.43.199', 5211) ^CTraceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/pyfix/connection.py", line 150, in handle_read msg = self.sock.recv(8192) ConnectionResetError: [Errno 104] Connection reset by peer

I'm from Egypt, and the client is from New Zealand, Is it an issue because of the IPs of Egypt? I will appreciate your help and I hope you reply soon regards,

How to change element in layout dynamically based on position of recyclerview Android?

14 hours 14 min ago

My data set have a element userId. I want to check if the position's userId is equal to userId of previous position,then a TextView set to GONE.

What I tried so far:

final Item item = itemsArray.get(position); if(position - 1 > -1){ if(items.get(position-1).getUserId() == item.getUserId()) { holder.username.setVisibility(View.GONE); } }

But end up,some of the item with same userId their username is gone,but some of them which userId is not same with the previous position's userId the username is gone too.

To make it clear,I attach some image to clearly show what I want.

This is what I want:

But end up,it become like below image,as you see item with different userId,the username also `gone.

So,my question is,how can I check the userId of previous item is same as userId of current position,so it wont end up to the second image I attached.

If have other solution please let me know as well.Thanks in advance.

Google App Engine Python Cloud Storage after deplyoment log shows "ImportError: No module named cloudstorage"

14 hours 14 min ago

I did not set up the local dev server for Cloud storage. I deployed the app and the logs keep showing "ImportError: No module named cloudstorage"

I checked, that the API i enabled and as far as I can tell it is. It just shows "To use this API, you may need credentials. Click "Create credentials" to get started." But ist is listed as enabled on the dashboard.

I created the default Bucket

My app.yaml is this

runtime: python27 api_version: 1 threadsafe: true env_variables: handlers: - url: /.* script: main.app

My main.app is this:

import logging import os from google.appengine.api import app_identity import cloudstorage as gcs import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.write('Hello, World!') bucket_name = os.environ.get('testbgi', app_identity.get_default_gcs_bucket_name()) self.response.headers['Content-Type'] = 'text/plain' #self.response.write('Demo GCS Application running from Version: ' #+ os.environ['CURRENT_VERSION_ID'] + '\n') self.response.write('Using bucket name: ' + bucket_name + '\n\n') app = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True)

Just cop/paste from the tutorial docs to get started with this topic.

Now, when I check the log in the Console dashboard, it shows "ImportError: No module named cloudstorage".

What is going on?

HttpClient posting audio file and reading it at webapi

14 hours 14 min ago

I'm not able figure out what am I doing wrong here, I'm uploading a file via HttpClient and trying to read the file at webapi. Files are written as 0kb, but when I tested it with POSTMAN then it is writing properly this made sure that web api part is correct.

// httpclient sending file. using (var client = new HttpClient()) { client.BaseAddress = new Uri(ConfigurationManager.AppSettings["some-api"]); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data"); MultipartFormDataContent multiPartContent = new MultipartFormDataContent("--whatever--"); var streamContent = new StreamContent(audioFile); streamContent.Headers.TryAddWithoutValidation("Content-Type", "audio/mpeg3"); multiPartContent.Add(streamContent, "rawAudioFile", fileName); await client.PostAsync(Constant.UploadFileApi, multiPartContent); } //web api part, this seems working as I have test with Postman. string root = HttpContext.Current.Server.MapPath("~/App_Data/Uploads"); if(!Directory.Exists(root)) Directory.CreateDirectory(root); var provider = new MultipartFormDataStreamProvider(root); var files = await Request.Content.ReadAsMultipartAsync(provider);

how to clear time out on keyup jquery

14 hours 14 min ago

I want to clear timeout when it was keyup press

$(document).ready(function () { $("#data-lock").click(function () { $(this).animate({bottom: '100vh'}, function () { $(".login-box").addClass("show-login"); setTimeout(function(){ },1000); }); }); });

I Can't Use DISTINCT With SUM in SQL Query

14 hours 14 min ago

I want to collect data from different tables in SQL wit SUM. What I want to do is: I want to multiply the piece and price of the product and add the cargo price next to it but I have to use one of these because the cargo price is on multiple lines. But I can not use distinct as follows:

SELECT SUM((tbl_Product.price * piece) + DISTINCT(tbl_Cargo.cargoprice)) AS total FROM tbl_Order LEFT JOIN tbl_Product ON tbl_Product.productid = tbl_Order.productid LEFT JOIN tbl_Cargo on tbl_Cargo.cargoid = tbl_Order.cargoid WHERE userid = '1'

How can I use DISTINCT in this query?

What's happening in this python code exactly? [on hold]

14 hours 16 min ago

I really can't understand whats happening in this code

n=8 m=[[0/n for i in range(n)] for j in range(n)] print(m)

result1:

[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]

but I have tried

n=8 m=[[0 for i in range(n)] for j in range(n)] print(m)

I know how this comprehension is working but can't understand the above result.

[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]

Why structure member seems to have an overflown value?

14 hours 22 min ago

In the code below, I get A = -1 as output. I guess, it's because I am overflowing the A-member which is of 3 bits. I have two questions in this regard:

  1. Shouldn't the compiler consider the last 3 bits and ignore the rest, for the member A? Why is the value negative ?
  2. If all the bits are considered, why do I get the value of B = 0 as output?

I was expecting A would be having a value of 7 but I am clearly misunderstanding something. Please help.

#include <stdio.h> typedef struct { char A: 3; char B: 3; char C: 3; }my_struct; my_struct new_object = {0}; void main(void) { new_object. A = 63; printf("A = %d\n", new_object.A); printf("B = %d\n", new_object.B); }

Can we declare and initialize a member variable from another member variable in same class

14 hours 29 min ago

i don't know much about class and their member variables. What my doubt is, can we declare and initialize a member variable from another member variable in same class?

like this

class newClass { private $variable1 = 'new1'; private $variable2 = $variable1.'new2'; }

If can't, please help me find an solution for this. Pardon me if this is a wrong question to ask.

HTML textarea show br

14 hours 43 min ago

i have a textarea in HTML. In the textarea the blank line is is looks br.

I try to have the value of the some text. And posting with get. After i received with php. And i changed the value of the some text to variabled i get with get.

Like this :

a<br />b c

Code (post with javascript):

<script type="text/javascript"> function nl2br (str, is_xhtml) { var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>'; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2'); } function menusec(secilen){ var deger = secilen.options[secilen.selectedIndex].value; var urunadi = document.getElementById("okulueua").value; var urunfiyati = document.getElementById("okulueuf").value; var kargofiyati = document.getElementById("okuluekf").value; var aciklama = nl2br(document.getElementById("okulueat").value); alert(aciklama); window.location.href = "okulue.php?menu=" + deger + "&urunadi=" + urunadi + "&urunfiyati=" + urunfiyati + "&kargofiyati=" + kargofiyati + "&aciklama=" + aciklama; } </script>

Code (get with php) :

<?php if (isset($_GET['menu'])) { $secilendeger = filter_input(INPUT_GET, "menu"); $urunadiget = filter_input(INPUT_GET, "urunadi"); $urunfiyatiget = filter_input(INPUT_GET, "urunfiyati"); $kargofiyatiget = filter_input(INPUT_GET, "kargofiyati"); $aciklamaget = filter_input(INPUT_GET, "aciklama"); echo($aciklamaget); ?> <script type="text/javascript"> function br2nl($content){ $content = str_ireplace("<br /> ", "\n", $content); return $content; } function br2nl1($input){ return preg_replace('/<br(\s+)?\/?>/i', "\n", $input); } document.getElementById("menusecme1").style.width = "315px"; document.getElementById("okulueua").value = "<?php echo($urunadiget); ?>"; document.getElementById("okulueuf").value = "<?php echo($urunfiyatiget); ?>"; document.getElementById("okuluekf").value = "<?php echo($kargofiyatiget); ?>"; document.getElementById("okulueat").value = "<?php echo($aciklamaget); ?>"; $('select[name^="ms1"] option[value="<?php echo($secilendeger); ?>"]').attr("selected","selected"); </script>

Code (HTML) :

<input type="text" class="okulueuat" name="okulueua" id="okulueua"> <input type="text" class="okulueua2t" name="okulueua2" value="1000" readonly="yes"> <input type="text" class="okulueuft" name="okulueuf" id="okulueuf"> <input type="text" class="okuluekft" name="okuluekf" value="5" id="okuluekf"> <input type="submit" class="tamamb2" value="Tamam" name="submit"> <input type="button" class="iptalb2" value="İptal" onclick="location='okulul.php'"> <input type="file" name="okuluef[]" class="resimeklec" multiple="multiple"> <textarea id="okulueat" name="okuluea"></textarea>

How can i solve this problem?

I need your help.

Note : I don't have a good English. Pardon me. I hope you understand.

Sending a parameter to JS function using .innerHTML

14 hours 48 min ago

I am attempting to run two different functions which do two separate things. Both need to run when a div is clicked on. The div is generated in the innerHTML function of JavaScript.

This is the method that runs second. It takes one parameter and then generates a div on the page.

//Display larger image: function furtherDetails(mainImage){ var moreInfo = document.getElementById('divpropertyInfo'); moreInfo.innerHTML = '<div id="propInfoDisplay">' + '<img id="image" src="'+mainImage+'" alt="Main Image" />' + '</div>'; }

This is the code that runs that function:

//Create the property div: function createPropertyDiv(mainImage, bedrooms, bathrooms, parkings, price, address, latitude, longitude){ var propertyDiv = document.getElementById('divsearchResults'); propertyDiv.innerHTML += '<div id="divResults" onclick="showMap('+latitude+','+longitude+');furtherDetails('+mainImage+');">' + '<img id="mainImage" src="' + mainImage +'" alt="Main Image" />' + '<p id="numBedrooms">'+ bedrooms +'</p>' + '<img id="bedroomsImage" src="/images/bedrooms.png" />' + '<p id="numBathrooms">'+ bathrooms +'</p>' + '<img id="bathroomsImage" src="/images/bathrooms.png" />' + '<p id="numParking">'+ parkings +'</p>' + '<img id="parkingImage" src="/images/carspots.png" />' + '<p id="Price">'+ price +'</p>' + '<p id="addressHeading">Address: </p>' + '<p id="Address">' + address + '</p>' + '</div>'; }

I am getting the error:

Uncaught SyntaxError: missing ) after argument list

Decimal math wrong result

14 hours 54 min ago

I am trying to make the math code. But I can't do it.

double x = z + ((z * (25.7 - (((z - 400) / 30) * 1.27))) / 100); int d = (int) Math.round(x);

for example if z=910. Real math result is, x =947.401, d = 947 but it doesn't by this code.

Could you help me to solve.

Conditional props in Vue2

16 hours 2 min ago

I have a use case where I may need to pass an object props as props to a child component.

Initially, I had a form and a table contained within a component. This form would take input, an asynchronous request would be performed and the table would be rendered for the user to make a selection. The user could then hit a button and have the table hidden and the form brought back up so parameters could be re-entered. Since the content of the form was dependent on the state of its parent, the last search parameters were still in the form.

The issue arose when I refactored the component to make both the form and the table sub-components of the parent. Now the form would $emit the event to its parent, which would perform the asynchronous operation and pass the result as props to the table. This worked fine, but when the user hits the "return to form" button, the form is re-rendered, thus resetting its state to the initial value.

I tried storing the content of the form in the parent and passing it back to the form as props but that led to the problem of initially setting the values. I didn't want to mutate the props directly, so I tried this approach:

FormContainer.vue <template> <div v-if="formShown"> <form-component :initialValues="formValues" @formSubmitted="displayResults"></form-component> </div> <div v-if="tableShown"> <table-component :results="fetchedResults" @returnToForm="returnToForm"></table-component> </div> </template> <script> export default { data(){ return{ formShown: true, tableShown: false, formValues:{ address1: '', address2: '', address3: '', country: '' }, fetchedResults: [] } }, methods:{ async displayResults(){ this.fetchedResults = await someAsynchronousCall(); this.formShown = false; this.tableShown = true; }, returnToForm(){ this.tableShown = false; this.formShown = true; } } } </script> FormComponent.vue <template> <!--Some form fields here, bound to data(){}, ommitted for brevity--> </template> <script> export default{ props:['initialValues'], data(){ return{ //Original structure /*selectedAddress:{ address1: '', address2: '', address3: '', country: '' }*/ selectedAddress: JSON.parse(JSON.stringify(this.initialValues)) //Object.assign({}, this.initialValues) //tried both of these for deep copy } } } </script>

The problem with this was that when the component was initially created, it is getting passed an empty object (or rather an object with only empty properties, I assume they amount to the same thing), which means my data properties are getting initialized as undefined.

I then tried using a ternary to initialize the data object with the values in the props or an empty string, like this:

data(){ return{ selectedAddress: { address1: this.initialValues.address1 ? this.initialValues.address1 :'', address2: this.initialValues.address2 ? this.initialValues.address2 :'', address3: this.initialValues.address3 ? this.initialValues.address3 :'', country:this.initialValues.country ? this.initialValues.country :'' } } },

But this throws errors saying that selectedAddress is not defined on the instance but is referenced during render. I'm guessing this means that using a ternary to initialize props is wrong.

I then tried to check for props in the mounted(){} lifecycle hook and set the data properties there, like this:

mounted(){ if(!this.initialValues || _.isEmpty(this.initialValues)){ Logger.info(`no props passed, no setup needed`); return; } if(this.initalValues.address1){ Logger.info(`setting address 1`); this.selectedAddress.address1 = this.initalValues.address1; } if(this.initialValues.address2){ Logger.info(`setting address 2`); this.selectedAddress.address2 = this.initalValues.address2; } if(this.initialValues.address3){ Logger.info(`setting address 3`); this.selectedAddress.address3 = this.initalValues.address2; } if(this.initialValues.country){ Logger.info(`setting country`); this.selectedAddress.country = this.initalValues.country; } }

This works for the first run of the form, but this.initialValues is always undefined when the component is mounted. I have inspected the component state and found that initialValues does exist, just not during the mounted life cycle hook. This approach felt 'hacky' anyway.

I'm not really sure where to go from here. I could commit the form data to the store and get it again if the form is remounted, but I don't feel like committing something that should only exist while its parent is mounted is the right approach.

Can anyone guide me to a more Vue way of achieving this?

Ansible Roles Global Variables

16 hours 27 min ago

I use roles to deploy my machines, Roles have vars, but sometimes i have multiple role and i want to put a global variable file in the root folders, so ansible use vars/global.yml and overwrite role/vars/main.yml

#vars/global.yml somevariable: somevalue

But if there is global variable in root folder, Just overwrite role based variable and implement vars/global instead.

├── Playbook.yml ├── ansible.cfg ├── roles │ ├── Ansible-Role-UserProfile │ │ ├── LICENSE │ │ ├── README.md │ │ ├── meta │ │ │ └── main.yml │ │ ├── tasks │ │ │ └── main.yml │ │ ├── templates │ │ │ ├── rm.j2 │ │ │ └── vimrc.j2 │ │ └── vars │ │ └── main.yml └── vars └── global.yml

Is anything comes which suite reusability of roles and variable natively ?

How to append/concatenate strings in mule Transform message?

17 hours 8 min ago

I am trying to concatenate strings in mule Transform message like below, but I am getting the below exception at run time. Could anyone please kindly help me on this? I am new to mule as well.

%dw 1.0 %output application/json --- { references : "" when payload[0].person_id==null otherwise "person/"+payload[0].person_id, }

Exception ::

Root Exception stack trace: com.mulesoft.weave.mule.exception.WeaveExecutionException: Exception while executing: references : "" when payload[0].person_id==null otherwise "person/"+payload[0].person_id, ^ Type mismatch for '+' operator found :string, :number

Pages