_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d12101
train
In MVP, it is the responsibility of the View to know how to capture the click, not to decide what to do on it. As soon as the View captures the click, it must call the relevant method in the Presenter to act upon it: ------------------- View -------------------- button1.setOnClickListener(new OnClickListener({ presenter.doWhenButton1isClicked(); })); ------------------ Presenter ---------------- public void doWhenButton1isClicked(){ // do whatever business requires } I have a series of articles on architectural patterns in android, part 3 of which is about MVP. You might find it helpful. A: OnClick should call a Presenter method. You should do your business in presenter and if you need to update the ui you should define a method in your View and call it from presenter. You need a method for your View ex: public void showCounterCount(final int totalClicks){ counterTextView.setText("Total clicks so far: "+totalClicks); } Also you need a method and a variable in your Presenter: int totalClicks = 0; public void onCounterButtonClicked(){ totalClicks++; mView.showCounterCount(totalClicks); } And refactor your code like this: counterButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mPresenter.onCounterButtonClicked(); } }); For more complex and clean architecture you can do your use case business in interactors. (In your example incrementing a counter value is a use-case for your application) You can define an interactor and increment your counter value there. CounterInteractor: public CounterInteractor{ public int incrementCounter(int currentCounter){ return currentCounter+1; } } And refactor your presenter like below: int totalClicks = 0; CounterInteractor mCounterInteractor = new CounterInteractor(); public void onCounterButtonClicked(){ totalClicks = mCounterInteractor.incrementCounter(totalClicks); mView.showCounterCount(totalClicks); } With this approach you separate your business logic totally from presenters and re use your use-case concepts without duplicating code in presenters. This is more clean approach. You can also check this git repo for different MVP Approaches. https://github.com/googlesamples/android-architecture/tree/todo-mvp-clean/ Good luck. Edit: Here's my lightweight wikipedia client project source: https://github.com/savepopulation/wikilight I'm trying to implement MVP. (MVP + Dagger2 + RxJava)
unknown
d12102
train
It might not be the prettiest code... but it works! <?php $dsn = "sqlsrv:Server=localhost;Database=blog"; $conn = new PDO($dsn, "*****", "*******"); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $id = $_GET['postID']; $sql = "SELECT * FROM blog_posts WHERE blogID=:id"; $stmt = $conn->prepare($sql); $stmt->execute (array($id)); $metta = $stmt->fetch(PDO::FETCH_BOTH); if (isset($_GET['postID'])) { $keywords = $metta['keywords']; $description = $metta['description']; } sqlsrv_close($con); ?> <meta name="description" content="<?= isset($description) ? $description : 'blablabla'; ?>"> <meta name="keywords" content="<?= isset($keywords) ? $keywords : 'blablabla'; ?>">
unknown
d12103
train
One piece of advise I have is for you to start reading screen prompts. When saving a large file with over 65536 rows this kind of warning is displayed. Only you can prevent your own errors. A: You can avoid this by making a copy of the original and filtering on that, then you always have the source if you make an error.
unknown
d12104
train
The third attachment you see empty can possibly be the CID embedded image that web based email clients (like Gmail) can't manage, meanwhile it works with desktop email clients like Outlook. Can you verify this? Please take a look at here
unknown
d12105
train
Session.Abandon() cancels the current session Session.Clear() will just clear the session data and the the session will remain alive more Details: Session.Abandon() method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out(I may add:Session_OnEnd event is triggered) http://msdn.microsoft.com/en-us/library/ms524310.aspx Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.
unknown
d12106
train
You could use comment() so that foo was an attribute of y. For example, try: x <- "foo" y <- 1:5 comment(y) <- x str(y) attr(y, "comment")
unknown
d12107
train
First you must understand the index process, basically your string is passed trough the default analyser if you didn't change the default mapping. HipHop will kept the same Hip Hop is saved separated like Hip, Hop When you do a match query like your example with HipHop vs Hip Hop, this query is passed trough the analyser too and will be separated like: "HipHop, vs, Hip, Hop" and a boolean query that will do a search like this: "match HipHop there?", "match vs there?", "match Hip there?", "match Hop there?" ? If you want a scenario where you have HipHop indexed and the user search for Hip Hop or HipHop vs Hip Hop or HopHip and should return HipHop, you must implement some strategy like: Regex or prefix query: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-regexp-query.html Ngram for partial matching: https://www.elastic.co/guide/en/elasticsearch/guide/current/_ngrams_for_partial_matching.html Synonyms: https://www.elastic.co/guide/en/elasticsearch/guide/current/using-synonyms.html And if you want to keep you terms with space indexed like "Hip Hop" you need to use a not_analyzed mapping.
unknown
d12108
train
if I understand you correctly, then what you are trying to do is to my knowledge not possible with gnuplot. Or at least not in an easy way. And this is the reason why I think you'll have a hard time: You cannot plot different box widths in a single plot. So trying to plot no box on an "non eventful" day and a single column on a day with one event will work just fine. Plotting multiple columns on one day where more than one event occurs in the same plot will fail because: * *You cannot set different box sizes in the same plot *You need to offset the boxes on the same day according to the amount of events There are ways to work around that problem for example plot two boxes of the same color next to each other to "simulate" a single box on one day and then make use of the smaller box width on days with two events. But this will very soon get pretty hairy and hard to maintain. Maybe you want to think about using a different plot style? Take a look at histograms like here. Maybe one of the styles suites your data better. Or you could think about splitting your plot up into multiple plots?
unknown
d12109
train
Obviously neither the "if" nor the "else if" condition are true then. Add let dilutiontext = self.dilution.text let celltext = self.cell.text then set a breakpoint and examine the values. A: Clearly the alerts were skipped if one of the if conditions in the segue function was true. So if there was something that would initially make the statements false and then after going through the alerts it would make them true, the problem would be solved. Therefore I made two more functions each for the if and if else statements in the segue func. func option1() -> Bool { if (self.number1.text?.isEmpty) ?? true || self.number2.text?.isEmpty ?? true || self.number3.text?.isEmpty ?? true || self.number4.text?.isEmpty ?? true || self.dilution.text?.isEmpty ?? true || !(self.number5.text?.isEmpty ?? true) || !(self.number6.text?.isEmpty ?? true) || !(self.number7.text?.isEmpty ?? true) || !(self.number8.text?.isEmpty ?? true) { return false } else { return true } } func option2() -> Bool { if (self.number1.text?.isEmpty) ?? true || self.number2.text?.isEmpty ?? true || self.number3.text?.isEmpty ?? true || self.number4.text?.isEmpty ?? true || self.number5.text?.isEmpty ?? true || self.number6.text?.isEmpty ?? true || self.number7.text?.isEmpty ?? true || self.number8.text?.isEmpty ?? true || self.dilution.text?.isEmpty ?? true { return false } else { return true } } which checked if all the conditions were true and if so returned true, so that the program could move on to the segue func. The segue would check whether the conditions were true, if not, it would go through the alerts-therefore making the option1() or option2() return true- and so the if conditions in the segue func would be true for the program to continue. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { var vc = segue.destination as! SecondViewController if option1() == true { vc.n1 = Int(number1.text!)! vc.n2 = Int(number2.text!)! vc.n3 = Int(number3.text!)! vc.n4 = Int(number4.text!)! vc.dil = Int(dilution.text!)! vc.cn = Int(choose.selectedSegmentIndex) } else if option2() == true { vc.n1 = Int(number1.text!)! vc.n2 = Int(number2.text!)! vc.n3 = Int(number3.text!)! vc.n4 = Int(number4.text!)! vc.n5 = Int(number5.text!)! vc.n6 = Int(number6.text!)! vc.n7 = Int(number7.text!)! vc.n8 = Int(number8.text!)! vc.cn = Int(choose.selectedSegmentIndex) vc.dil = Int(dilution.text!)! } }
unknown
d12110
train
Link to the docs: http://developers.facebook.com/docs/authentication/ There are several flows, but essentially, you provide a link for the client to authenticate at facebook: https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_U‌​RL&scope=publish_stream,manage_pages After authing this redirects to a URL on your site prepared to handle the param code, which you then turn around and send back to facebook for your access_token, which you provide to fb_graph. https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_ur‌​i=YOUR_URLclient_secret=YOUR_APP_SECRET&code=CODE There are other permissions as well, so you might want to check the facebook docs to see if there are more you need. Facebook uses OAuth 2 for auth, and there are several ruby gems you can use to facilitate this process slightly, including the oauth2 gem. A: The app ID you specified must be wrong. please cross check that. A sample appID looks like this APP_ID="162221007183726" Also check whether you have used any call back url. The url should point to a server. Your cannot use your localhost/ local IP there. A similar nice rails plugin for Facebook app using Rails3 is Koala gem https://github.com/arsduo/koala/wiki/Koala-on-Rails http://blog.twoalex.com/2010/05/03/introducing-koala-a-new-gem-for-facebooks-new-graph-api/
unknown
d12111
train
Here's a possible solution using base R (not sure if vectorized enough for you) as.numeric(ave(x, x, FUN = seq)) - 1L ## [1] 0 0 1 0 1 2 1 3 4 2 Or something similar using data.table package library(data.table) as.data.table(x)[, y := seq_len(.N) - 1L, by = x][] # x y # 1: c 0 # 2: b 0 # 3: b 1 # 4: a 0 # 5: a 1 # 6: b 2 # 7: c 1 # 8: b 3 # 9: b 4 # 10: c 2 Or maybe a dplyr option library(dplyr) data.frame(x) %>% group_by(x) %>% mutate(y = row_number() - 1L) # Source: local data frame [10 x 2] # Groups: x # # x y # 1 c 0 # 2 b 0 # 3 b 1 # 4 a 0 # 5 a 1 # 6 b 2 # 7 c 1 # 8 b 3 # 9 b 4 # 10 c 2
unknown
d12112
train
Seems like the file on Server 2008 is Powershell.exe.activation_config. It's located at C:\Program Files(x86)\Common Files\NetApp. Hope this helps! A: Check out your powershell.exe.config file. Do you see the /configuration/startup/requiredRuntime XML element? http://msdn.microsoft.com/en-us/library/a5dzwzc9(v=vs.110).aspx A: Either undo any changes you made to your system that forced PowerShell or other .Net applications to use CLR 4. See here. Or install .Net 3.5 (or 3.0 or 2.0), which will install CLR 2. If you run Windows 8 or 2012 you need do that by changing the Windows features. See here. A: We have now found a solution to the problem: We uninstalled the .NET Framework 4 (since we did not need this on the SharePoint Server). After this we could use the PowerShell for SharePoint again.
unknown
d12113
train
To get the control of the keystrokes from a background app you need to be root. Instead of that, you can use monkeyrunner to make scripts using Python. Another option is to use direct commands in ADB, as stated in this answer. Every option needs to be connected to a computer via USB cable.
unknown
d12114
train
Https Params are immutable. Try that var params = new HttpParams(); for(let address of p.addresses){ params = params.set(address.addLatLng, address.val); } params = params.set('transport_type', p.transport_type) .set('has_return', p.has_return) .set('delay', p.delay); return this.http.post(url, params, {headers: headers}); A: Why use HttpParams?, the sintax for httpClient.post is httpClient.post(url,body,[options]). where body is a object. NOT confussed with params. the httpParams, see https://angular.io/guide/http#url-parameters is used to change the url. Your solucion works because you don't use httpParams in the form of this.http.post(url, params, { headers: headers, params:params }); you can do //A simple object var data= { 'addresses0latitude': 90.64318211857652, 'addresses0longitude': 30.86662599723718, 'addresses1latitude': 90.622619801960056, 'addresses1longitude': 30.91368305099104, 'transport_type', 'motorbike', 'has_return': 0, 'delay': 0 } return this.http.post(url, data, {headers: headers});
unknown
d12115
train
DECLARE @TEMP AS TABLE( [Date] DATETIME, [Status] VARCHAR ) INSERT INTO @TEMP VALUES('29.03.2016 07:30','X') INSERT INTO @TEMP VALUES('29.03.2016 07:31','Y') INSERT INTO @TEMP VALUES('29.03.2016 07:32','Y') INSERT INTO @TEMP VALUES('29.03.2016 07:33','Y') INSERT INTO @TEMP VALUES('29.03.2016 07:34','Y') INSERT INTO @TEMP VALUES('29.03.2016 07:40','X') INSERT INTO @TEMP VALUES('29.03.2016 07:43','Z') INSERT INTO @TEMP VALUES('29.03.2016 07:45','Z') SELECT * FROM @TEMP ;WITH TEMP(n,d,s) AS ( SELECT ROW_NUMBER() OVER(ORDER BY [Date]),[Date],[Status] FROM @TEMP ), StatePeriods(n,T_n,T_d,T_s,TL_n,TL_d,TL_s,TR_n,TR_d,TR_s) AS ( SELECT ROW_NUMBER() OVER(ORDER BY T.d),T.n,T.d,T.s,TL.n,TL.d,TL.s,TR.n,TR.d,TR.s FROM TEMP AS T LEFT JOIN TEMP AS TR ON T.n = TR.n-1 LEFT JOIN TEMP AS TL ON T.n-1 = TL.n WHERE T.s <> TR.s OR T.s <> TL.s OR TR.s IS NULL OR TL.s IS NULL ) SELECT SP1.T_n,SP1.T_d,SP1.T_s,SP1.TL_d,SP1.TL_s,CASE WHEN SP1.T_s = SP3.T_s THEN SP3.TR_d ELSE SP3.T_d END FROM StatePeriods AS SP1 LEFT JOIN StatePeriods AS SP2 ON SP1.n-1 = SP2.n LEFT JOIN StatePeriods AS SP3 ON SP1.n+1 = SP3.n WHERE NOT (SP1.T_s=SP2.T_s AND SP1.TL_s IS NOT NULL AND SP1.TR_s IS NOT NULL) And you can filter first or last row This is a very resource-intensive solution. But you can use temporary tables instead of 'WITH'
unknown
d12116
train
Why you are trying to bold text doing it by hand when you can use built in feature. Modern browsers implements execCommand function that allows to bold, underline etc. on text. You can write just: $('.embolden').click(function(){ document.execCommand('bold'); }); and selected text will be made bold and if it's already bold, the text styling will be removed. A list of commands and a little doc can be found here. (More about browser support here). $(document).ready(function() { $('#jBold').click(function() { document.execCommand('bold'); }); }); #fake_textarea { width: 100%; height: 200px; border: 1px solid red; } button { font-weigth: bold; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="jBold"><b>B</b></button> <div id='fake_textarea' contenteditable> Select some text and click the button to make it bold... <br>Or write your own text </div> A: Copied function from this answer: Get parent element of a selected text Haven't really perfected this and I think this only works on exact selections but it gives you an idea of how to go around this. The click function checks if the parent element of the current selection has the class 'bold', if so it replaces that element with the original selection again. http://jsfiddle.net/XCb95/4/ jQuery(function($) { $('.embolden').click(function(){ var highlight = window.getSelection(); var span = '<span class="bold">' + highlight + '</span>'; var text = $('.textEditor').html(); var parent = getSelectionParentElement(); if($(parent).hasClass('bold')) { $('.textEditor').html(text.replace(span, highlight)); } else { $('.textEditor').html(text.replace(highlight, span)); } }); }); function getSelectionParentElement() { var parentEl = null, sel; if (window.getSelection) { sel = window.getSelection(); if (sel.rangeCount) { parentEl = sel.getRangeAt(0).commonAncestorContainer; if (parentEl.nodeType != 1) { parentEl = parentEl.parentNode; } } } else if ( (sel = document.selection) && sel.type != "Control") { parentEl = sel.createRange().parentElement(); } return parentEl; } A: Something like this should do the trick: var span = ''; jQuery(function($) { $('.embolden').click(function(){ var highlight = window.getSelection(); if(highlight != ""){ span = '<span class="bold">' + highlight + '</span>'; }else{ highlight = span; span = $('span.bold').html(); } var text = $('.textEditor').html(); $('.textEditor').html(text.replace(highlight, span)); }); }); A: Got it, finally: <!DOCTYPE html> <html> <head> <style type="text/css"> .emphasized { text-decoration: underline; font-weight: bold; font-style: italic; } </style> </head> <body> <button type="button" onclick="applyTagwClass(this);" data-tag="span" data-tagClass="emphasized">Bold</button> <div contenteditable="true" class="textEditor"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In malesuada quis lorem non consequat. Proin diam magna, molestie nec leo non, sodales eleifend nibh. Suspendisse a tellus facilisis, adipiscing dui vitae, rutrum mi. Curabitur aliquet lorem quis augue laoreet feugiat. Nulla at volutpat enim, et facilisis velit. Nulla feugiat quis augue nec sodales. Nulla nunc elit, viverra nec cursus non, gravida ac leo. Proin vehicula tincidunt euismod.</p> <p>Suspendisse non consectetur arcu, ut ultricies nulla. Sed vel sem quis lacus faucibus interdum in sed quam. Nulla ullamcorper bibendum ornare. Proin placerat volutpat dignissim. Ut sit amet tellus enim. Nulla ut convallis quam. Morbi et sollicitudin nibh. Maecenas justo lectus, porta non felis eu, condimentum dictum nisi. Nulla eu nisi neque. Phasellus id sem congue, consequat lorem nec, tincidunt libero.</p> <p>Integer eu elit eu massa placerat venenatis nec in elit. Ut ullamcorper nec mauris et volutpat. Phasellus ullamcorper tristique quam. In pellentesque nisl eget arcu fermentum ornare. Aenean nisl augue, mollis nec tristique a, dapibus quis urna. Vivamus volutpat ullamcorper lectus, et malesuada risus adipiscing nec. Ut nec ligula orci. Morbi sollicitudin nunc tempus, vestibulum arcu nec, feugiat velit. Aenean scelerisque, ligula sed molestie iaculis, massa risus ultrices nisl, et placerat augue libero vitae est. Pellentesque ornare adipiscing massa eleifend fermentum. In fringilla accumsan lectus sit amet aliquam.</p> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> function applyTagwClass(self) { var selection = window.getSelection(); if (selection.rangeCount) { var text = selection.toString(); var range = selection.getRangeAt(0); var parent = $(range.startContainer.parentNode); if (range.startOffset > 0 && parent.hasClass(self.attributes['data-tagClass'].value)) { var prefix = '<' + self.attributes['data-tag'].value + ' class="' + self.attributes['data-tagClass'].value + '">' + parent.html().substr(0,selection.anchorOffset) + '</' + self.attributes['data-tag'].value + '>'; var suffix = '<' + self.attributes['data-tag'].value + ' class="' + self.attributes['data-tagClass'].value + '">' + parent.html().substr(selection.focusOffset) + '</' + self.attributes['data-tag'].value + '>'; parent.replaceWith(prefix + text + suffix); } else { range.deleteContents(); range.insertNode($('<' + self.attributes['data-tag'].value + ' class="' + self.attributes['data-tagClass'].value + '">' + text + '</' + self.attributes['data-tag'].value + '>')[0]); //Remove all empty elements (deleteContents leaves the HTML in place) $(self.attributes['data-tag'].value + '.' + self.attributes['data-tagClass'].value + ':empty').remove(); } } } </script> </body> </html> You'll notice that I extended the button to have a couple data- attributes. They should be rather self-explanatory. This will also de-apply to subsections of the selected text which are within the currently-targeted element (everything goes by class name). As you can see, I'm using a class which is a combination of things so this gives you more versatility. A: If you are looking to use the keyboard to bold characters, you can use the following (Mac): $(window).keydown(function(e) { if (e.keyCode >= 65 && e.keyCode <= 90) { var char = (e.metaKey ? '⌘-' : '') + String.fromCharCode(e.keyCode) if(char =='⌘-B') { document.execCommand('bold') } } }) Using keyboard to bold character: A: This code goes thru the content of the textEditor and removes all the span tags. It should do the trick. jQuery(function($) { $('.embolden').click(function(){ $('.textEditor span').contents().unwrap(); var highlight = window.getSelection(); var span = '<span class="bold">' + highlight + '</span>'; var text = $('.textEditor').html(); $('.textEditor').html(text.replace(highlight, span)); }); }); A: Modern browsers utilize the execCommand function that allows you to embolden text very easily. It also provides other styles like underline etc. <a href="#" onclick="emboldenFont()">Bold</a> function emboldenFont() { document.execCommand('bold', false, null); } A: check this is it what u wanted ??? using .toggleclass() (to make all text in text editor class bold only)
unknown
d12117
train
It's not so much that PostgreSQL "preserves" indexes across subqueries, as that the rewriter can often simplify and restructure your query so that it operates on the base table directly. In this case the query is unnecessarily complicated; the subqueries can be entirely eliminated, making this a trivial self-join. SELECT count(*) FROM chromosomal_positions file_1 INNER JOIN chromosomal_positions other_files ON ( file_1.chromosome_id = other_files.chromosome_id AND file_1.position = other_files.position ) WHERE file1.variant_file_id = 1 AND other_files.variant_file_id != 1; so an index on (chromosome_id, position) would be clearly useful here. You can experiment with index choices and usage as you go, using explain analyze to determine what the query planner is actually doing. For example, if I wanted to see if: then I would CREATE INDEX cp_f_c_p ON chromosomal_positions(file_id, chromosome_id , position); -- Planner would prefer seqscan because there's not really any data; -- force it to prefer other plans. SET enable_seqscan = off; EXPLAIN SELECT count(*) FROM ( SELECT * FROM chromosomal_positions WHERE file_id = 1 ) AS file_1 INNER JOIN ( SELECT * FROM chromosomal_positions WHERE file_id != 1 ) AS other_files ON ( file_1.chromosome_id = other_files.chromosome_id AND file_1.position = other_files.position ) and get the result: QUERY PLAN -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Aggregate (cost=78.01..78.02 rows=1 width=0) -> Hash Join (cost=29.27..78.01 rows=1 width=0) Hash Cond: ((chromosomal_positions_1.chromosome_id = chromosomal_positions.chromosome_id) AND (chromosomal_positions_1."position" = chromosomal_positions."position")) -> Bitmap Heap Scan on chromosomal_positions chromosomal_positions_1 (cost=14.34..48.59 rows=1930 width=8) Filter: (file_id <> 1) -> Bitmap Index Scan on cp_f_c_p (cost=0.00..13.85 rows=1940 width=0) -> Hash (cost=14.79..14.79 rows=10 width=8) -> Bitmap Heap Scan on chromosomal_positions (cost=4.23..14.79 rows=10 width=8) Recheck Cond: (file_id = 1) -> Bitmap Index Scan on cp_f_c_p (cost=0.00..4.23 rows=10 width=0) Index Cond: (file_id = 1) (11 rows) (view on explain.depesz.com) showing that while it will use the index, it's actually only using it for the first column. It won't use the rest, it's just filtering on file_id. So the following index is just as good, and smaller and cheaper to maintain: CREATE INDEX cp_file_id ON chromosomal_positions(file_id); Sure enough, if you create this index Pg will prefer it. So no, the index you propose does not appear to be useful, unless the planner thinks it's just not worth using at this data scale, and might choose to use it in a completely different plan with more data. You really have to test on the real data to be sure. By contrast, my proposed index: CREATE INDEX cp_ci_p ON chromosomal_positions (chromosome_id, position); is used to find chromosomal positions with id = 1, at least on an empty dummy data set. I suspect the planner would avoid a nested loop on a bigger data set than this, though. So again, you really just have to try it and see. (BTW, if the planner is forced to materialize a subquery then it does not "preserve indexes on derived tables", i.e. materialized subqueries. This is particularly relevant for WITH (CTE) query terms, which are always materialized).
unknown
d12118
train
You might want to make use of the CQL COPY command to export all your data to a CSV file. Then alter your table and create a new column of type map. Convert the exported data to another file containing UPDATE statements where you only update the newly created column with values converted from JSON to a map. For conversion use a tool or language of your choice (be it bash, python, perl or whatever). BTW be aware, that with map you specify what data type is your map's key and what data type is your map's value. So you will most probably be limited to use strings only if you want to be generic, i.e. a map<text, text>. Consider whether this is appropriate for your use case.
unknown
d12119
train
This is a abuse of the constructor function syntax (it will work without the new) function A(message) { return function(){alert("Make " + message);} } var a = new A("uncertain, divorce the wife say"); var v = a(); //Use ordinary/like Javascript function use A: No,This instance "a" has no object "A" prototype a instanceof A===false
unknown
d12120
train
When you run an application with Windows Scheduler, if that application has dependencies to other files via relative path, then you need to set the start in setting for the task. This sets the path from where execution will begin. Alternatively you can use a command file and have it navigate to the correct directory first. A: Just figured out that the problem was that the program was actually being executed in the wrong folder, in order that the output file wasn't where I thought it would. The output file was being write in the starting folder, not the program's folder.
unknown
d12121
train
Have you tried adding I?&autoplay=1 to the end of the youtube links?
unknown
d12122
train
Try this, it's much simplier: var items = _db.Items.AsQueryable() .AsExpandable(); if (imageFilterType == 1) items=items.OrderByDescending(a=>a.CreatedDate); else items=items.OrderByDescending(a=>a.AbuseCount); items=items.Where(predicate) .Select(x => x) .Join(_db.Users, i => i.UserId, u => u.UserID, (i, u) => new { i, FullName = u.UserType == 1 ? u.FirstName + " " + u.LastName : u.CompanyName, u.UserType, u.UserName }) .Skip(pageIndex) .Take(pageSize) .ToList();
unknown
d12123
train
Try this query: SELECT min(time) as start_time, max(time) as end_time, sum(case when status = 'ON' then 1 else 0 end) as cnt FROM (SELECT time, status, sum(case when status = 'OFF' then 1 else 0 end) over (order by time desc) as grp FROM time_status) _ GROUP BY grp ORDER BY min(time); ->Fiddle
unknown
d12124
train
Since this is a stream, libvlc will not parse it by default (only local files). You need to use a flag to tell libvlc to parse the media even if it is a network stream. Use libvlc_media_parse_with_options with MediaParseFlag set to network (1).
unknown
d12125
train
In Laravel unit tests are located inside tests folder and they have some rules in naming in order to run them. I had the same issue in the past and this is how i solved it: 1) Namespace must be Test\Unit (or if you have a middle folder include that but always inside Tests) 2) the name of the function you build must start with the word test like public function testMyFunction() { // Put your code here }
unknown
d12126
train
You cant get database fields with javascript. You must use php or something like this. Maybe this can help you. Here is the link. choose your database and table, and select your field names, and choose field's type of form (text area, text, radio button groups, etc) and push create. You will have a bootstrap designed form and php insert code writed with medoo (medoo.in). you can use this. create your database first and make form automaticly. Copy code and paste to your pages. Also i offer you to use meddo to connect and use sql with it. There is a sample in that link form.min.php, includes your database and user and pass information.
unknown
d12127
train
UMAP has multiple purposes like clustering, supervised learning and outlier detection. What exactly do you want to do with UMAP? In case of clustering, you can take a look at sklearn cluster evaluation and compare the scores with other algorithms like t-SNE. To look for the structure, you can reduce your data to 2-3 dimensions and use a scatter plot to eye check the results. When you have labeled data, you can try to classify them with (nonlinear) classifiers like a random forest and compare the result score (e.g. accuracy) with other dimension reduction techniques like PCA. Maybe you look for the trustworthiness from sklearn. You can compare the scores of PCA with the score of UMAP or any other dimension reduction algorithm. source
unknown
d12128
train
I had similar problem and solved it adding map in the rjs config like this: map: { '*': { 'kendo.core.min': 'kendo' } } It seems to work :)
unknown
d12129
train
This is currently not possible. Bug 134068 is filed for querying the properties of a window, and bug 134070 is filed for getting events when they change. A: Seems to be possible now that those mentioned bugs were fixed in the last few weeks.
unknown
d12130
train
I seem to have found the solution. I had to add my boost macro names under "Project settings - C/C++ - Additional Include Directories" and "project settings - linker - Additional Library Directories". Somehow the other macros I have made have appeared in those two lists automatically, and I'm not sure why the boost macros were not added automatically too. Now it's working as it should though, so I'll just go with it like this.
unknown
d12131
train
(Not an answer but way too long for a comment. Will delete later if appropriate.) In a clean R session, this works for me: data(Orthodont,package="nlme") mod <- lme4::lmer(distance ~ age*Sex + (1|Subject), data=Orthodont) interactions::sim_slopes(model=mod, pred=age, modx=Sex) sessionInfo() SIMPLE SLOPES ANALYSIS Slope of age when Sex = Female: Est. S.E. t val. p ------ ------ -------- ------ 0.48 0.09 5.13 0.00 Slope of age when Sex = Male: Est. S.E. t val. p ------ ------ -------- ------ 0.78 0.08 10.12 0.00 Warning message: Johnson-Neyman intervals are not available for factor moderators. Here is my sessionInfo(): the important stuff looks the same as yours (lme4 1.1-21, interactions 1.1.0, jtools 2.0.1), but it's certainly not identical ... ?? R Under development (unstable) (2019-05-21 r76566) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 16.04.6 LTS [matrix product and locale info deleted] attached base packages: [1] stats graphics grDevices utils datasets methods base loaded via a namespace (and not attached): [1] Rcpp_1.0.1 magrittr_1.5 splines_3.7.0 MASS_7.3-51.4 [5] tidyselect_0.2.5 munsell_0.5.0 colorspace_1.4-1 lattice_0.20-38 [9] R6_2.4.0 rlang_0.3.4 minqa_1.2.4 plyr_1.8.4 [13] dplyr_0.8.1 tools_3.7.0 grid_3.7.0 gtable_0.3.0 [17] nlme_3.1-140 cli_1.1.0 digest_0.6.19 assertthat_0.2.1 [21] lme4_1.1-21 lazyeval_0.2.2 tibble_2.1.2 numDeriv_2016.8-1 [25] crayon_1.3.4 Matrix_1.2-17 purrr_0.3.2 nloptr_1.2.1 [29] ggplot2_3.1.1 jtools_2.0.1 interactions_1.1.0 glue_1.3.1 [33] pander_0.6.3 compiler_3.7.0 pillar_1.4.1 scales_1.0.0 [37] lmerTest_3.1-0 boot_1.3-22 pkgconfig_2.0.2 A: I solved the problem by detaching lmerTest.
unknown
d12132
train
If the EMR step type is Spark which you mentioned on the step API --steps Type=Spark , as you identified on Step's controller logs, EMR will add the spark-submit command and you do not need to pass the /home/hadoop/spark/bin/spark-submit as arguments of the STEP API. The error was because of two spark-submit's , where it was taking the second one /home/hadoop/spark/bin/spark-submit as argument. Please see : http://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-submit-step.html
unknown
d12133
train
To remove the paste option from the default context menu, use this: func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool { if action != #selector(UIResponderStandardEditActions.paste(_:)) { return true } return false }
unknown
d12134
train
The second alternative in pString accepts the empty string: many' pChar >>= \s -> return (...). Thus many' pString keeps consuming the empty string ad infinitum.
unknown
d12135
train
On seeing the GC cycle pasted above it seems excessive GC operation has been performed which has direct impact on the performance of the application. Excessive GC and Compaction always lead to slow responsive oa application as GC operation is stop the world process. It seems you are using gencon policy (Young/old region). If the young region is small then it will lead to lots of scavenge gc operation. If you need more analysis on the gc logs then load it in GCMV tool to get GC behaviour of your system http://www.ibm.com/developerworks/java/jdk/tools/gcmv/ A: Since your old generation is full, the obvious answer here is that when those files are merged, you need more memory than you currently have assigned the JVM. Try increasing the heap size by running java with -Xmx, for example -Xmx4G to use a 4 GB heap. If you still run into problems despite using a heap you think is large enough, the best way to investigate what fills your heap is to take a heap dump (run jmap -dump:format=b,file=dump.bin <jvm pid>) and analyze it with Eclipse MAT.
unknown
d12136
train
In my manifest permissions look like this: <uses-permission android:name="android.permission.NFC" /> Maybe that's the problem?
unknown
d12137
train
Okay, I'll try to write a complete walk-through. First, it is a common mistake to treat WAV (or, more likely, RIFF) file as a linear structure. It is actually a tree, with each element having a 4-byte tag, 4-byte length of data and/or child elements, and some kind of data inside. It is just common for WAV files to have only two child elements ('fmt ' and 'data'), but it also may have metadata ('LIST') with some child elements ('INAM', 'IART', 'ICMT' etc.) or some other elements. Also there's no actual order requirement for blocks, so it is incorrect to think that 'data' follows 'fmt ', because metadata may stick in between. So let's look at the RIFF file: 'RIFF' |-- file type ('WAVE') |-- 'fmt ' | |-- AudioFormat | |-- NumChannels | |-- ... | L_ BitsPerSample |-- 'LIST' (optional) | |-- ... (other tags) | L_ ... (other tags) L_ 'data' |-- sample 1 for channel 1 |-- ... |-- sample 1 for channel N |-- sample 2 for channel 1 |-- ... |-- sample 2 for channel N L_ ... So, how should you read a WAV file? Well, first you need to read 4 bytes from the beginning of the file and make sure it is RIFF or RIFX tag, otherwise it is not a valid RIFF file. The difference between RIFF and RIFX is the former uses little-endian encoding (and is supported everywhere) while the latter uses big-endian (and virtually nobody supports it). For simplicity let's assume we're dealing only with little-endian RIFF files. Next you read the root element length (in file endianness) and following file type. If file type is not WAVE, it is not a WAV file, so you might abandon further processing. After reading the root element, you start to read all child elements and process those you're interested in. Reading fmt header is pretty straightforward, and you have actually done it in your code. Data samples are usually represented as 1, 2, 3 or 4 bytes (again, in the file endianness). The most common format is a so-called s16_le (you might have seen such naming in some audio processing utilities like ffmpeg), which means samples are presented as signed 16-bit integers in little endian. Other possible formats are u8 (8-bit samples are unsigned numbers!), s24_le, s32_le. Data samples are interleaved, so it is easy to seek to arbitrary position in a stream even for multi-channel audio. Note: this is valid only for uncompressed WAV files, as indicated by AudioFormat == 1. For other formats data samples may have another layout. So let's take a look at a simple WAV reader: stHeaderFields = dict() rawData = None with open("file.wav", "rb") as f: riffTag = f.read(4) if riffTag != 'RIFF': print 'not a valid RIFF file' exit(1) riffLength = struct.unpack('<L', f.read(4))[0] riffType = f.read(4) if riffType != 'WAVE': print 'not a WAV file' exit(1) # now read children while f.tell() < 8 + riffLength: tag = f.read(4) length = struct.unpack('<L', f.read(4))[0] if tag == 'fmt ': # format element fmtData = f.read(length) fmt, numChannels, sampleRate, byteRate, blockAlign, bitsPerSample = struct.unpack('<HHLLHH', fmtData) stHeaderFields['AudioFormat'] = fmt stHeaderFields['NumChannels'] = numChannels stHeaderFields['SampleRate'] = sampleRate stHeaderFields['ByteRate'] = byteRate stHeaderFields['BlockAlign'] = blockAlign stHeaderFields['BitsPerSample'] = bitsPerSample elif tag == 'data': # data element rawData = f.read(length) else: # some other element, just skip it f.seek(length, 1) Now we know file format info and its sample data, so we can parse it. As it was said, sample may have any size, but for now let's assume we're dealing only with 16-bit samples: blockAlign = stHeaderFields['BlockAlign'] numChannels = stHeaderFields['NumChannels'] # some sanity checks assert(stHeaderFields['BitsPerSample'] == 16) assert(numChannels * stHeaderFields['BitsPerSample'] == blockAlign * 8) for offset in range(0, len(rawData), blockAlign): samples = struct.unpack('<' + 'h' * numChannels, rawData[offset:offset+blockAlign]) # now samples contains a tuple with sample values for each channel # (in case of mono audio, you'll have a tuple with just one element). # you may store it in the array for future processing, # change and immediately write to another stream, whatever. So now you have all the samples in rawData, and you may access and modify it as you like. It might be handy to use Python's array() to effectively access and modify data (but it won't do in case of 24-bit audio, you'll need to write your own serialization and deserialization). After you've done with data processing (which may involve upscaling or downscaling the number of bits per sample, changing number of channels, sound levels manipulation etc.), you just write a new RIFF header with correct data length (usually may be computed with a simplified formula 36 + len(rawData)), an altered fmt header and data stream. Hope this helps.
unknown
d12138
train
If you have added additional hooks make sure they adhere to the structure given on the link Additional hooks structure Table 1 lists the inner elements that are supported on Android and the order in which they must appear in your component.wcp Table 1. Order of inner elements for the Android environment Order Inner element 1 CordovaPlugin 2 Activities 3 UserPermissions 4 Receivers 5 Strings 6 ExternalLibraries 7 Libraries Table 2 lists the inner elements that are supported on iOS and the order in which they must appear in the schema. Table 2. Order of inner elements for the iPhone and iPad environments Order Inner element 1 CordovaPlugin 2 Files 3 Libraries Note: Some hooks result in the insertion of properties in the config.xml file or the AndroidManifest.xml file when the associated application component is added to a Worklight project. Every insertion is enclosed in comments that mention the element and application component unique name
unknown
d12139
train
You can use metaprogramming to get variable value because you just call a method: <%= @report.send("variable_#{var}") %>
unknown
d12140
train
Looks like it doesn't work for some reasons or I didn't find the way to make it work. A possible workaround solution would be, if you create a simple pipeline in your source repo, which is triggered on new tag and just runs through or maybe does some validation work if needed. In your target pipeline you create a trigger for it like that: resources: pipelines: - pipeline: myrepo-pipeline source: myrepo-pipeline-build trigger: true If the first pipeline successfully runs, it triggers the actual pipeline.
unknown
d12141
train
If you would start with looking at ultimate source of Unix error code names (/usr/include/errno.h) you'll arrive at the file which contains your error code as #define EINTR 4 /* Interrupted system call */ (Which is this file is left for you to find out, as an exercise ;)) A: The errno values can be different for different systems (even different Unix-like systems), so the symbolic constants should be used in code. The perror function will print out (to stderr ) a descriptive string of the last errno value along with a string you provide. man 3 perror The strerror function simply returns a const char * to the string that perror prints. If 4 is EINTR on your system then you received a signal during your call to read. There are ways to keep this from interrupting your system calls, but often you just need to: while (1) { ssize_t x = read(file, buf, len); if (x < 0) { if (errno == EINTR) { errno = 0; continue; } else { // it's a real error A: If you're getting EINTR, it probably means you've installed a signal handler improperly. Good unices will default to restartable system calls when you simply call signal, but for safety, you should either use the bsd_signal function if it's available, or call sigaction with the restartable flag to avoid the headaches of EINTR.
unknown
d12142
train
http://psacake.com/web/jr.asp contains full instructions, and here's an excerpt: While it may seem odd to think about purposefully causing a Blue Screen Of Death (BSOD), Microsoft includes such a provision in Windows XP. This might come in handy for testing and troubleshooting your Startup And Recovery settings, Event logging, and for demonstration purposes. Here's how to create a BSOD: Launch the Registry Editor (Regedit.exe). Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters. Go to Edit, select New | DWORD Value and name the new value CrashOnCtrlScroll. Double-click the CrashOnCtrlScroll DWORD Value, type 1 in the Value Data textbox, and click OK. Close the Registry Editor and restart Windows XP. When you want to cause a BSOD, press and hold down the [Ctrl] key on the right side of your keyboard, and then tap the [ScrollLock] key twice. Now you should see the BSOD. If your system reboots instead of displaying the BSOD, you'll have to disable the Automatically Restart setting in the System Properties dialog box. To do so, follow these steps: Press [Windows]-Break. Select the Advanced tab. Click the Settings button in the Startup And Recovery panel. Clear the Automatically Restart check box in the System Failure panel. Click OK twice. Here's how you remove the BSOD configuration: Launch the Registry Editor (Regedit.exe). Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters. Select the CrashOnCtrlScroll value, pull down the Edit menu, and select the Delete command. Close the Registry Editor and restart Windows XP. Note: Editing the registry is risky, so make sure you have a verified backup before making any changes. And I may be wrong in assuming you want BSOD, so this is a Microsoft Page showing how to capture kernel dumps: https://web.archive.org/web/20151014034039/https://support.microsoft.com/fr-ma/kb/316450 A: As far as I know, the "Create Dump" command was only added to Task Manager in Vista. The only process I know of to do this is using the adplus VBScript that comes with Debugging Tools. Short of hooking into dbghelp and programmatically doing it yourself. A: You can setup the user dump tool from Microsoft with hot keys to dump a process. However, this is a user process dump, not a kernel dump... A: I don't know of any keyboard short cuts, but are you looking for like in task manager, when you right click on a process and select "Create Dump"?
unknown
d12143
train
From what I can deduce by looking at the code given, first you are loading the data into the list dataList and then you are reversing the entire list using Collections.reverse(dataList); which is an expensive operation. So, a way around is make your own reversing function to reverse the arraylist because the default .reverse() provided by the Collections class is not very efficient. You can try the below code to reverse the list in-place (same ArrayList is used ,hence making it efficient): public ArrayList<Integer> revArrayList(ArrayList<Integer> list) { for (int i = 0; i < list.size() / 2; i++) { Integer temp = list.get(i); list.set(i, list.get(list.size() - i - 1)); list.set(list.size() - i - 1, temp); } return list; }
unknown
d12144
train
Bluetooth P2P connection. Check that
unknown
d12145
train
You didn't mention it but have you added the WebMethodAttribute to the method you have defined on the code behind? You seem to have a method in the code-behind called cbField_Dependent() So just add the attribute like the first line below I think. [WebMethod] public void cbField_Dependent() { // } A: Follow this article, this show step by step method to call web method. http://www.c-sharpcorner.com/UploadFile/63e78b/call-an-Asp-Net-C-Sharp-method-web-method-using-jquery/
unknown
d12146
train
* *It's possible to store images in a database file, usually as binary blobs (which look like instances of NSData in Core Data). If you can provide more info about your model or the code that stores/loads the images, we can be more specific. *"Creating new store" is expected to get logged every time the app is launched in this instance. Even though the SQLite file is persistent on disk, you can't expect data structures in your code to stick around when your app is terminated - you need to create a new persistent store object for your program every time it launches. Think of it like assigning NSInteger x = 10, then expecting to be able to quit and relaunch your program while maintaining that x has the value 10. That's not how programs work - you'd need to reassign x = 10 before you can expect to read x and get 10 back. The variable _persistentStoreCoordinator works the same way here.
unknown
d12147
train
The pg gem you are using 0.13.2 is referencing to a ruby method rb_thread_select, which is not present in 2.2.0+. It was there in the older version of ruby. So you can't use that version of pg in ruby 2.2.0+. Upgrade to a version 0.15.0 +, which doesn't use rb_thread_select
unknown
d12148
train
As you can see from the source for TimeoutHandler, it sets the context in the request to a context with timeout. That means, in your handler you can use the context to see if timeout happened: func MyHandler(w http.ResponseWriter,r *http.Request) { ... if r.Context().Err()==context.DeadlineExceeded { // Timeout happened } }
unknown
d12149
train
Your Javascript contains special characters for XML (< and &). Therefore, it's invalid markup. You need to wrap it in a CDATA section, which will prevent the XML parser from parsing its contents: <script type="text/javascript"> //<![CDATA[ ... //]]> </script> The comments are necessary to prevent the CDATA section from causing Javascript syntax errors in browsers that don't recognize it
unknown
d12150
train
First make certain that you have started up your database properly. There is a fairly substantial thread that has what sounds like it may be your problem here: http://www.progresstalk.com/showthread.php?116855-102B-ODBC-connection-Problem Also something else to look at if you are running over SSL: Change the data source PacketSize setting. The correct setting is 32. PacketSize=32 On Windows this will require a registry edit to make this change. See: http://knowledgebase.progress.com/articles/Article/8500
unknown
d12151
train
You need a GROUP BY and proper JOIN: SELECT pt.module_id, SEC_TO_TIME(SUM(TIMESTAMPDIFF(SECOND, ul.`start_date`, ul.`end_date`))) AS `total_hours` FROM `users_timings_log` ul INNER JOIN `projects_tasks` pt ON ul.type_id = pt.id WHERE `type` = '0' GROUP BY pt.module_id; If you only want one module, then add a WHERE clause for that purpose. I also added table aliases, so the query is easier to write and to read. I should add, the problem with your query is that it did not have proper JOIN conditions for projects_modules. You don't seem to need that table, so removing the table is fine. If you need columns from that table, add the appropriate JOIN conditions.
unknown
d12152
train
For cases involving the AWS SDK, use aws.WriteAtBuffer to download S3 objects into memory. requestInput := s3.GetObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), } buf := aws.NewWriteAtBuffer([]byte{}) downloader.Download(buf, &requestInput) fmt.Printf("Downloaded %v bytes", len(buf.Bytes())) A: I don't know of any way to do this in the standard library, but you can write your own buffer. It really wouldn't be all that hard... EDIT: I couldn't stop thinking about this, and I ended up acidentally the whole thing, enjoy :) package main import ( "errors" "fmt" ) func main() { buff := NewWriteBuffer(0, 10) buff.WriteAt([]byte("abc"), 5) fmt.Printf("%#v\n", buff) } // WriteBuffer is a simple type that implements io.WriterAt on an in-memory buffer. // The zero value of this type is an empty buffer ready to use. type WriteBuffer struct { d []byte m int } // NewWriteBuffer creates and returns a new WriteBuffer with the given initial size and // maximum. If maximum is <= 0 it is unlimited. func NewWriteBuffer(size, max int) *WriteBuffer { if max < size && max >= 0 { max = size } return &WriteBuffer{make([]byte, size), max} } // SetMax sets the maximum capacity of the WriteBuffer. If the provided maximum is lower // than the current capacity but greater than 0 it is set to the current capacity, if // less than or equal to zero it is unlimited.. func (wb *WriteBuffer) SetMax(max int) { if max < len(wb.d) && max >= 0 { max = len(wb.d) } wb.m = max } // Bytes returns the WriteBuffer's underlying data. This value will remain valid so long // as no other methods are called on the WriteBuffer. func (wb *WriteBuffer) Bytes() []byte { return wb.d } // Shape returns the current WriteBuffer size and its maximum if one was provided. func (wb *WriteBuffer) Shape() (int, int) { return len(wb.d), wb.m } func (wb *WriteBuffer) WriteAt(dat []byte, off int64) (int, error) { // Range/sanity checks. if int(off) < 0 { return 0, errors.New("Offset out of range (too small).") } if int(off)+len(dat) >= wb.m && wb.m > 0 { return 0, errors.New("Offset+data length out of range (too large).") } // Check fast path extension if int(off) == len(wb.d) { wb.d = append(wb.d, dat...) return len(dat), nil } // Check slower path extension if int(off)+len(dat) >= len(wb.d) { nd := make([]byte, int(off)+len(dat)) copy(nd, wb.d) wb.d = nd } // Once no extension is needed just copy bytes into place. copy(wb.d[int(off):], dat) return len(dat), nil } A: Faking AWS WriterAt with an io.Writer This isn't a direct answer to the original question but rather the solution I actually used after landing here. It's a similar use case that I figure may help others. The AWS documentation defines the contract such that if you set downloader.Concurrency to 1, you get guaranteed sequential writes. downloader.Download(FakeWriterAt{w}, s3.GetObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), }) downloader.Concurrency = 1 Therefore you can take an io.Writer and wrap it to fulfill the io.WriterAt, throwing away the offset that you no longer need: type FakeWriterAt struct { w io.Writer } func (fw FakeWriterAt) WriteAt(p []byte, offset int64) (n int, err error) { // ignore 'offset' because we forced sequential downloads return fw.w.Write(p) } A: I was looking for a simple way to get io.ReadCloser directly from an S3 object. There is no need to buffer response nor reduce concurrency. import "github.com/aws/aws-sdk-go/service/s3" [...] obj, err := c.s3.GetObject(&s3.GetObjectInput{ Bucket: aws.String("my-bucket"), Key: aws.String("path/to/the/object"), }) if err != nil { return nil, err } // obj.Body is a ReadCloser return obj.Body, nil A: With aws-sdk-go-v2, the codebase-provided example shows: // Example: // pre-allocate in memory buffer, where headObject type is *s3.HeadObjectOutput buf := make([]byte, int(headObject.ContentLength)) // wrap with aws.WriteAtBuffer w := s3manager.NewWriteAtBuffer(buf) // download file into the memory numBytesDownloaded, err := downloader.Download(ctx, w, &s3.GetObjectInput{ Bucket: aws.String(bucket), Key: aws.String(item), }) Then use w.Bytes() as the result. Import "github.com/aws/aws-sdk-go-v2/feature/s3/manager" and other needed components
unknown
d12153
train
It is not possible to have a fully fledged nested function definition in VB.NET. The language does support multi-line lambda expressions which look a lot like nested functions: Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click Dim anim = Sub() Me.Refresh() ... End Sub End Sub There are some notable differences though: * *Cannot have a Handles clause. *Cannot be Implements or Overrides. *The instance of the lambda is named, not the Sub definition. *In this case anim is actually a delegate and not a function. A: It is possible to have a function within a function, called lambda expressions. In your case, however, it is unclear to me how it can be useful. * *Lambda Expressions (Visual Basic) @ MSDN
unknown
d12154
train
I prefer to draw into Bitmaps with System.Drawing.Graphics object. Then you can use your graphics object with "go.DrawImage(...)" to draw the bitmap directly into your winforms and actually give it a scale. https://msdn.microsoft.com/en-us//library/ms142040(v=vs.110).aspx A: I got the solution, thanks for your help. I only need to call refresh/invalidate etc on button click. public partial class ScalingCircle : Form { public Graphics DeviceContexct; // current transformation matrix of main view (offset & scaling) public Matrix mainViewTransform = new Matrix(); public int scale = 1; public ScalingCircle() { InitializeComponent(); DeviceContexct = Graphics.FromHwnd(this.Handle); DeviceContexct = this.CreateGraphics(); } public void ScalingCircle_Paint(object sender, PaintEventArgs e) { DeviceContexct = e.Graphics; DeviceContexct.PageUnit = GraphicsUnit.Pixel; DeviceContexct.Transform = mainViewTransform; ScalingCircle1(scale); } private void ScalingCircle1(int x ) { Pen myPen2 = new Pen(Color.Black, 1); DeviceContexct.Transform = mainViewTransform; Rectangle myRectangle = new Rectangle(50, 50, 100 * x, 100 * x); DeviceContexct.FillRectangle(new SolidBrush(Color.BurlyWood), myRectangle); } private void ScalingCircle_Load( object sender, EventArgs e ) { this.ResizeRedraw = true; } private void button1_Click( object sender, EventArgs e ) { scale += 5; this.Refresh(); } private void button2_Click( object sender, EventArgs e ) { if (scale > 1) { scale -= 5; this.Refresh(); } } } A: You can use transformations for that. The graphics object you use for painting things has a Transformation property of type System.Drawing.Drawing2D.Matrix. Graphics also has the ScaleTransform method. I haven't used it myself, but that is how microsofts Chart does it. https://msdn.microsoft.com/de-de/library/system.drawing.drawing2d.matrix(v=vs.110).aspx https://msdn.microsoft.com/de-de/library/system.drawing.graphics.scaletransform(v=vs.110).aspx
unknown
d12155
train
Here is a basic 3D surface plotting procedure. It seems that your X and Y are just 1D arrays. However, X, Y, and Z have to be 2D arrays of the same shape. numpy.meshgrid function is useful for creating 2D mesh from two 1D arrays. import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = np.array(np.linspace(-2,2,100)) y = np.array(np.linspace(-2,2,10)) X,Y = np.meshgrid(x,y) Z = X * np.exp(-X**2 - Y**2); surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) fig.colorbar(surf, shrink = 0.5, aspect = 5) plt.show()
unknown
d12156
train
You can use the session for this purspose. def open @ticket = Ticket.find(params[:ticket_id]) @ticket.update_attributes(:ticket_status, "closed") session[:close_message] = "Ticket has been closed" redirect_to ticket_path end After that diaplay it in the view like <%= session[:close_message] %> but make sure to clear the session like session[:close_message] = nil after displaying the message to free the memory A: You need to store the message in database if you want it to persist. Say for ex- There is a ticket raised (Ticket model) and someone closes it. The attribute on backend will update attribute status for ticket model. def update tkt = Ticket.where(id: 1) tkt.update_attributes(status: 1) end If this is an ajax call, you can send a response data with message like "Ticket closed " and display it accordingly on html page in the success callback of ajax call. If it's a server call, refresh the page and use the status attribute from Ticket model to create the message. You can use some enums like {0 => "Ticket Open", 1 => "Ticket closed", 2 => "Ticket in progress" } In case messages are not generic and every time some more customization is required, better to create and save the entire message as an attribute in the related model and no need to have enums.
unknown
d12157
train
At the first you try add role to member id, not a member. If no members mention in message, you will get empty mention collection and try get id of undefined, because message.mentions.members.first() of empty collection return undefined. Second, try not use role names, use role ID for this, its more secure. And change your if code from if (statment) then do something to if (!statment) return reject reason this will help avoid unnecessary nesting of code. module.exports = { name: 'mute', description: 'command to mute members', execute(message, args){ if(!message.member.roles.cache.has('2132132131213')) return message.reply('You can`t use mute command') const role = message.guild.roles.cache.get('21321321312'); if (!role) return message.reply('can`t get a role') const member = message.mentions.members.first() if (!member) return message.reply('Pls mention a member') member.roles.add(role).then(newMember => { message.channel.send(`successfully muted member ${member.user}`) }) } }
unknown
d12158
train
You won't be able to use SimRing (Dial Verb with Multiple Nested Number nouns) with that approach, as the first person to pick up the call results in all the other call legs being cancelled. You will need to use the /Calls resource to initiate the calls, and return TwiML that asked the dialed party to press any digit to be connected to the customer. You would then cancel (status=canceled) the other call legs. As you can see SimRing is not the best approach as it tends to tire out the dialed parties with incessant ringing and the voicemail issues you need to guard against as well as the default Calls Per Second (CPS) is 1 per second, so there will be a delay between each outbound call, unless you have Twilio Sales increase the outbound CPS. Once the agent presses a key, you can initiate a Dial Number to the customer. If you need to modify the call once it is established, you should connect the agent to a conference and the customer to the same conference, you anchors the call legs and allows easier manipulation of the call.
unknown
d12159
train
Use re.search and extract your string. Option 1 .*\n(.*{.*}\n) m = re.search('.*\n(.*{.*}\n)', string, re.DOTALL | re.M) print(m.group(1)) 'cable {\n id 3;\n chassis mx2010;\n plate 2c;\n}\n' Regex Details .* # greedy match (we don't capture this) \n # newline ( # first capture group - capture everything inside this .* { # opening brace .* # content within braces (greedy/non-greedy doesn't matter) } # closing brace \n ) Option 2 This one is a bit more flexible, with regards to the positioning of your substring. (cable\s*{.*?}\n?) m = re.search('(cable.*?{.*?}\n?)', string, re.DOTALL | re.M).group(1) print(m.group(1)) 'cable {\n id 3;\n chassis mx2010;\n plate 2c;\n}\n' Regex Details ( # first capture group cable # match "cable" \s* # match 0 or more whitespace char { # opening brace .*? # non-greedy matchall } # closing brace \n? # optional newline )
unknown
d12160
train
One possibility is to poll the results page. When it doesn't return a 404, you load the page. This answer by KyleMit to another question should work in your situation. To adapt his code: const poll = async function (fn, fnCondition, ms) { let result = await fn(); while (fnCondition(result)) { await wait(ms); result = await fn(); } return result; }; const wait = function (ms = 1000) { return new Promise(resolve => { setTimeout(resolve, ms); }); }; (async() => { const url = "/result.html"; let fetchResult = () => fetch(url); let validate = result => !result.ok; let response = await poll(fetchResult, validate, 3000); if (response.ok) location.replace(url); })(); Disadvantages of this approach are: * *Polling increases network traffic *You load the page twice. The advantage is that you can make the results page a parameter, then the user can close the page then come back later and continue waiting.
unknown
d12161
train
Yes, you can use use multiple layouts in single XML using the <include>. Here is a example for that: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/app_background" android:orientation="vertical" > <include layout="@layout/actionbar_main" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical" > <ImageView android:id="@+id/img_rest_pic" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight=".35" android:src="@drawable/upload_image" /> </LinearLayout> </LinearLayout> The actionbar_main.xml file is in different XML: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="?android:attr/actionBarSize" android:background="@drawable/navbar_txt" android:orientation="vertical" > <ImageButton android:id="@+id/ibtn_action_back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:layout_marginLeft="5dp" android:background="@null" android:src="@drawable/navbar_back" /> <ImageButton android:id="@+id/ibtn_action_settings" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignTop="@+id/ibtn_action_back" android:layout_marginRight="5dp" android:background="@null" android:src="@drawable/nacbar_setting" /> <View android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="1dp" android:layout_alignParentBottom="true" android:background="@color/white" /> </RelativeLayout> A: Not sure whether your looking for this alignment but i just gave a shot..... whenever you wish to fix layout at the bottom of screen make sure you use weight property i.e if you want fix button at the bottom of screen then put android:layout_height = "0dp" and layout_weight="1" for other major layout in the xml and to button which has to be fixed at the bottom use android:layout_height="wrap_content" and layout_weight = "0" that's all is the trick (sorry if i have made it hard to understand... just simply saying play with weight and height property) <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#fff" android:orientation="vertical" > <fragment android:id="@+id/adview153613" android:name="com.sentientit.theiWedplanner.Fragadmob" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <RelativeLayout android:id="@+id/RelativeLayout1" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" > <Button android:id="@+id/back" android:layout_width="70dp" android:layout_height="50dp" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="8dp" android:layout_marginTop="3dp" android:layout_x="8px" android:layout_y="3px" android:text="Back" android:textColor="#ffffff" android:textSize="20sp" /> <Button android:id="@+id/home" android:layout_width="50px" android:layout_height="30px" android:layout_alignParentRight="true" android:layout_alignTop="@+id/back" android:layout_marginRight="46dp" android:paddingBottom="12px" android:paddingTop="10px" android:visibility="gone" /> </RelativeLayout> <ScrollView android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="vertical" > <HorizontalScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:id="@+id/table" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > </LinearLayout> </HorizontalScrollView> </ScrollView> <AbsoluteLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0" > <AbsoluteLayout android:layout_width="fill_parent" android:layout_height="61dp" android:layout_x="120dp" android:layout_y="35dp" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="38dp" android:layout_y="30dp" android:text="- Kid Seated" android:textColor="#000000" android:textSize="13dp" android:typeface="serif" > </TextView> <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="6dp" android:layout_y="28dp" > </ImageView> </AbsoluteLayout> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="437dp" android:layout_y="3dp" /> <Button android:id="@+id/button3" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="48dp" android:layout_y="4dp" android:text="Line" android:textSize="20sp" /> <Button android:id="@+id/button1" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="128dp" android:layout_y="4dp" android:text="circle" android:textSize="20sp" /> <Button android:id="@+id/button2" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="212dp" android:layout_y="6dp" android:text="vshape" android:textSize="20sp" /> </AbsoluteLayout> </LinearLayout>
unknown
d12162
train
Change * *setTimeout to setInterval *clearTimeout to clearInterval
unknown
d12163
train
Does ChildClassA also contain a collection, thus you are trying to nest two embedded collections? It looks like it from that stacktrace. This is not possible in Objectify4. I highly recommend the upgrade to 5.
unknown
d12164
train
am I crazy or will never work under any circumstance? Q) Are you crazy? A) Yes. Absolutely. That looks bonkers! Q) Will this never work under any circumstance? A) Oh, there are times this will work. Some observables are synchronous. For example, this will always log a 2, so this works as expected. let convertedView = null; of(1).pipe( map(v => v + 1) ).subscribe(convertedOrder => convertedView = convertedOrder); console.log(convertedView); That's because of(1) is a synchronous observable. This, however, will never work let convertedView = null; of(1).pipe( delay(0), map(v => v + 1) ).subscribe(convertedOrder => convertedView = convertedOrder); console.log(convertedView); This will print null. Even though delay(0) conceptually takes no time, it still uses JSs event loop and therefore doesn't get executed until the current code completes. I think it's best practise to assume all observables are asynchronous. Any code that assume otherwise is likely to be brittle. A: Your store.subscribe is asynchronous and the rest of your code is not. You can resolve it with a Promise like the example below. protected get reportView(): Promise < any > { return new Promise((resolve, reject) => { this.store .pipe(select(fromStore.getTransferOrderConverted), rxjs.take(1)) .subscribe((convertedOrder) => resolve(convertedOrder)); }); } reportView.then(convertedOrder => { // do your stuff }); Also you can get the convertedOrder with Async/Await. But remember, the parent function must be async. const convertedOrder = await reportView(); A: Convert a stream to synchronous isn't a good ideal. However, you can use method toPromise of a subject (subscription) for convert it to a promise and await for resolve. A: Rxjs take(1), first() operator should work absolutely fine These 2 operators takes the latest value from store selector or BehaviourSubject in synchronous way.
unknown
d12165
train
A slight shorter (though marginally more complex) version of @anubhava's answer: jq -r '.asgs[] | .name as $n | (.instances[] | [$n, .id, .az, .state] | @tsv)' file.json This "remembers" each name before producing a tab-separated line for each instance, inserting the correct name in each row. A: You may use this jq: jq -r '.asgs[] | .name + "\t" + (.instances[] | .id + "\t" + .az + "\t" + .state)' file.json test1 i-9fb75dc us-east-1a InService test1 i-95393ba us-east-1a Terminating:Wait test1 i-241fd0b us-east-1b InService test2 i-4bbab16 us-east-1a InService test2 i-417c312 us-east-1b InService A: You can use a generic map to create an extra entry per-instance: jq -r '.asgs[] | [.name] + (.instances[] | map(.)) | @tsv'
unknown
d12166
train
You definitely should use a php framework ! It will help you to organize your code and will bring to you some helpful features like routing which would solve your problem. You will define some roots, each linked to a specific controller and your code will be well organized. I can recommend you Symfony2 : but there are a lot of which are able to do the job : http://www.hongkiat.com/blog/best-php-frameworks/ If your application is small you can have a look to silex which is a light version of Symfony To define your urls, you can use a REST api which is a best practice. I can understand that you find the learning curve of the frameworks difficult but you will not regret it.
unknown
d12167
train
wrong parenthesis solver.Add( solver.Sum(amt[i,j] * Buy[j]) <= n_max[i] )
unknown
d12168
train
I guess you mean the html select box having some page titles displayed and as soon as the user selects one of them the new page showes up. This is not possible with out javascript - the only thing you could do is to add a submit button. <noscript><input type="submit" value="go!"></noscript> This button would only be displayed if javascript is not activated. A: No, you cannot reload a page when a select box changes (if that's your question) without using a scripting language or similar. A: Without a scripting language (that would be JavaScript if you want to be cross-browser), most form elements are "dumb", they hold their state and display user feedback. So if you want to select a new page after selecting it in a form (combo box, list, radio buttons...), you have to add a submit button to send the choice to a server, and have a server side script handling the choice and serving the right page. The good old Web 1.0 way... :-) A: You can't. With HTML only, changing the selected option makes the value of that option to be sent to the server upon submit (either via the Enter key or a submit/button element). You can eventually set up the receiving script to send back a HTTP Redirect based according to the selected option. You shouldn't. This kind of navigation widget implies the use of a mouse: somebody using the keyboard to navigate the page cannot even select the second option at all (as soon as the down arrow is pressed once the onchange() event activates). Do the right thing and add a submit button, with the page change activated by the onsubmit() event.
unknown
d12169
train
Windows line endings consist of two separate characters, a carriage return ('\r') immediately followed by a newline ('\n'). Because they are a combination of two characters, you cannot detect them by looking at only one character at a time. If your code is running on Windows and the file is supposed to be interpreted as text, then open it in text mode (for instance, "r" instead of "rb"), and the line terminators should be automatically translated to single newlines. If you're running on a system that uses single newlines as line terminators (most anything but Windows these days) then no such translation will be performed. In that case, to detect Windows-style line terminators you need to keep track of whether the immediately previous character was a '\r'. When that is so, and the next character read is a '\n', then you've detected a line terminator. But if it should be considered erroneous for Windows-style terminators to be in the file, then consider instead just fixing the file via dos2unix or a similar utility.
unknown
d12170
train
That's not a prompt, it's just a message. Prompting would be: read -p "Please pass a grade: " gr But this get's into conflict with your following gr=$1, so put this into an else block: if [ $# -lt 1 ] then read -p "Please pass a grade: " gr else gr=$1 fi Note that you don't need a semicolon at the line end; it's the line break, which can be substituted by the semicolon. And you don't need an exit to end a script, if you don't want to exit prematurely. A: As you want to prompt the user to input grades until he enters 999, you should use read instead of command line arguments. As bash doesn't have a do-while loop, we can emulate it's behavior using while as shown below: #!/bin/bash read -p "Please pass a grade " gr while [ $gr -ne 999 ]; do if [ $gr -ge 90 ] then echo "A" elif [ $gr -ge 80 ] then echo "B" elif [ $gr -ge 70 ] then echo "C" else echo "Failed" fi read -p "Please pass a grade " gr done exit 0 A: Please try below code. while true do read -p "Please pass a grade:" gr if [ ${gr} -eq 999 ] then exit 0 elif [ ${gr} -ge 90 ] then echo "A" elif [ ${gr} -ge 80 ] then echo "B" elif [ ${gr} -ge 70 ] then echo "C" else echo "Failed" fi done
unknown
d12171
train
Outlook does not expose events that will allow you to expand or collapse the folders in the treeview. You may be able to do this using the Windows API. A: There might be a way to expand (but not to collapse). Basically what you need to do is to go through your sub folders one by one during each step make the sub folder your current folder. I have tested this in Outlook 2010 (VSTO) on addin startup. So if you have the Parent Folder Folder A and its sub folders Folder A1, Folder A2 and Folder A3. In order to expand Folder A do the following: * *Get the active explorer (Globals.thisaddin.application.activeexplorer) *Set the current folder explorer.currentfolder = Folder A *Now loop through all sub folders under Folder A and make each sub folder the current folder: (The code should be something like this) Subfolders = FolderA.Folders For Each folder as outlook .folder in Subfolders Explorer.currentfolder = folder Next Folder This method works for me so hope this would be hopeful
unknown
d12172
train
In short, you can't. map3 doesn't have the correct types to merge map1 and map2 into it. However if it was also a HashMap<String, List<Incident>>. You could use the putAll method. map3 = new HashMap<String, List<Incident>>(); map3.putAll(map1); map3.putAll(map2); If you wanted to merge the lists inside the HashMap. You could instead do this. map3 = new HashMap<String, List<Incident>>(); map3.putAll(map1); for(String key : map2.keySet()) { List<Incident> list2 = map2.get(key); List<Incident> list3 = map3.get(key); if(list3 != null) { list3.addAll(list2); } else { map3.put(key,list2); } } A: create third map and use putAll() method to add data from ma HashMap<String, Integer> map1 = new HashMap<String, Integer>(); HashMap<String, Integer> map2 = new HashMap<String, Integer>(); HashMap<String, Integer> map3 = new HashMap<String, Integer>(); map3.putAll(map1); map3.putAll(map2); You have different type in question for map3 if that is not by mistake then you need to iterate through both map using EntrySet A: Use commons collections: Map<String, List<Incident>> combined = CollectionUtils.union(map1, map2); If you want an Integer map, I suppose you could apply the .hashCode method to all values in your Map. A: HashMap has a putAll method. Refer this : http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
unknown
d12173
train
Yes, you just need to set functionAppScaleLimit to 2. But there are some mechanisms about consumption plan you need to know. I test it in my side with batchSize as 1 and set functionAppScaleLimit to 2(I set WEBSITE_MAX_DYNAMIC_APPLICATION_SCALE_OUT as 2 in "Application settings" of function app instead of set functionAppScaleLimit, they are same). And I test with the code below: import logging import azure.functions as func import time def main(msg: func.QueueMessage) -> None: logging.info('=========sleep start') time.sleep(30) logging.info('=========sleep end') logging.info('Python queue trigger function processed a queue item: %s', msg.get_body().decode('utf-8')) Then I add message to the queue, I sent 10 messages: 111, 222, 333, 444, 555, 666, 777, 888, 999, 000, I sent them one by one. The function was triggered success and after a few minutes, we can see the logs in "Monitor". Click one of the log in "Monitor", we can see the logs show as: I use 4 red boxes on the right of the screenshot above, I named each of the four logs as "s1", "s2", "s3", "s4"(step 1-4). And summarize the logs in excel for your reference: I make cells from "s2" to "s4" as yellow because this period of time refer to the execution time of the function task. According the screenshot of excel, we can infer the following points: 1. The maximum number of instances can only be extended to 2 because we can find it doesn't exist more than two yellow cells in each line of the excel table. So the function can not scale beyond 2 instances as you mentioned in your question. 2. You want to allow both of these queue triggers to run concurrently, it can be implemented. But the instances will be scale out by mechanism of consumption. In simple terms, when one function instance be triggered by one message and hasn't completed the task, and now another message come in, it can not ensure another instance be used. The second message might be waiting on the first instance. We can not control whether another instance is enabled or not. ===============================Update============================== As I'm not so clear about your description, I'm not sure how many storage queues you want to listen to and how many function apps and QueueTrigger functions you created in your side. I summarize my test result as below for your reference: 1. For your question about would the Maximum Burst you described on the premium plan behave differently than this ? I think if we choose premium plan, the instances will also be scale out with same mechanism of consumption plan. 2. If you have two storage queues need to be listen to, of course we should create two QueueTrigger functions to listen to each storage queue. 3. If you just have one storage queue need to be listen to, I test with three cases(I set max scale instances as 2 in all of three cases): A) Create one QueueTrigger function in one function app to listen to one storage queue. This is what I test in my original answer, the excel table shows us the instances will scale out by mechanism of consumption plan and we can not control it. B) Create two QueueTrigger functions in one function app to listen to same storage queue. The result is almost same with case A, we can not control how many instances be used to deal with the messages. C) Create two function apps and create a QueueTrigger function in each of function app to listen to same storage queue. The result also similar to case A and B, the difference is the max instances can be scaled to 4 because I created two function apps(both of them can scale to 2 instances). So in a word, I think all of the three cases are similar. Although we choose case 3, create two function apps with one QueueTrigger function in each of them. We also can not make sure the second message be deal with immediately, it still may be processed to first instance and wait for frist instance complete deal with the first message. So the answer for your current question in this post is setting the functionAppScaleLimit to 2 enough to achieve that? is: If you want both of instances be enabled to run concurrently, we can't make sure of it. If you just want two instances to deal with the messages, the answer is yes.
unknown
d12174
train
You could try this jQuery('div.hidden_fields .poly_id',jQuery(this).parent()).val(...); Remember you can always provide a context to a jQuery Selector jQuery("someselector", context)
unknown
d12175
train
"third person singular" key is repeated twice. A: You have duplicate entries for your keys, third person singular. That is why you only get 5 objects. Change it to third person plural for expected output I guess.
unknown
d12176
train
Create an intermediate layer where you apply mask. Set the background of your view to the desired background, and set background color of the intermediate layer to the color that you wish your mask to appear in. Something like this, view.backgroundColor = UIColor(red: 70/255, green: 154/255, blue: 233/255, alpha: 1) // set background of the view portion that do not include mask let parentLayer = CALayer() parentLayer.frame = view.bounds parentLayer.backgroundColor = UIColor.white.cgColor // sets background of mask view.layer.addSublayer(parentLayer) let mask = CALayer() mask.contents = UIImage(named: "twitter.png")?.cgImage mask.contentsGravity = kCAGravityResizeAspect mask.bounds = CGRect(x: 0, y: 0, width: 100, height: 100) mask.anchorPoint = CGPoint(x: 0.5, y: 0.5) mask.position = CGPoint(x: view.frame.size.width/2, y: view.frame.size.height/2) parentLayer.mask = mask A: This can be achieved by changing the background color of appDelegate's window... let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window!.backgroundColor = UIColor.blue
unknown
d12177
train
You risk printing out and comparing garbage since you don't ensure the strings are nul terminated. You need to do fread(file_md5, 1, md5_length, md5_fd); file_md5[md5_length] = 0; And similar for input_md5. Or to do it properly, use the return value of fread() to add the nul terminator in the proper place, check if fread() fails, Check how much it returned. If you also place your debug output inside quotes, it'll also be easier to spot unwanted whitespace or unprintable characters: fprintf(stdout, "contains '%s'\n", input_md5);
unknown
d12178
train
I will describe POST method in REST. Client send HTTP request via POST method with JSON data. For example, client send some data to create a word "nice". POST http://localhost/word/1 JSON content { "data": { "type": "word", "attributes": { "word": "nice" } } } In PHP you need get a response and convert to array and insert ot DB. Why insert? Because request method is POST.
unknown
d12179
train
Neither of these expressions are legal, they should both fail to compile. C++11, 5.17.1: The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. 5.4: Explicit type conversion (cast notation) [expr.cast] 1 The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type and an xvalue if T is an rvalue reference to object type; otherwise the result is a prvalue. So both expressions violate these constraints. A: shouldn't (long *) p be a rvalue? It is. They're both prvalues and, as such, both statements are ill-formed: [C++03: 5.4/1]: The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is a reference type, otherwise the result is an rvalue. [C++11: 5.4/1]: The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type and an xvalue if T is an rvalue reference to object type; otherwise the result is a prvalue. [..] GCC 4.8 rejects your "legal cast", but Visual Studio has an extension that accepts this (for no apparent reason). A: Why do you think your cast is legal? I'm getting error C2106: '=' : left operand must be l-value on both casts. This shouldn't be legal. If you really want to do it, you have to cast it like this: (long*&)p = &l; // equivalent to *(long**)&p = &l But don't do that unless you know what you are doing. A: The result of a value conversion is an rvalue. You cannot assign to rvalues of fundamental types. In other words, for int a = 10;, a is an lvalue of type int, but (long) a is a temporary rvalue of type long, and you cannot assign to the temporary. Likewise for pointers.
unknown
d12180
train
It's a fairly easy change on a perl file to make this happen. I would only recommend doing this if you don't like the default git-add -p behavior of patching all files. Find your copy of git-add--interactive and open with your favorite editor. Go to the patch_update_cmd subroutine. In there, there is an if statement which tests $patch_mode. Remove the top part of the if statement or set it so that the conditional always evaluates to false. Save and test. An example of what I did to make this work follows. if (0) { @them = @mods; } else { @them = list_and_choose({ PROMPT => 'Patch update', HEADER => $status_head, }, @mods); } Another possible point of change would be at the very bottom of the file. You can change $patch_mode to some false value after the if statement, the effect should be the same. Note you may have some issues if you're using a package manager or something else similar which tracks installed packages, I'm not sure. A: What you could do, is 'git add -p' and add the filenames as commandline arguments. with good tab completion (which only completes dirty files) it's about as effective as picking them from the menu. A: If you don't mind bringing up a gui, just use git gui.
unknown
d12181
train
Hope this might help Controller file public function actionProductcategory($id) { $model=new Product; $this->render('productcategory',array('model'=>$model, 'id'=>$id)); } In View file 'dataProvider'=>$model->SelectedCategoryProducts($id), UPDATE 1 'columns'=>array( 'name', 'model', 'brand', 'price', change them to lowercase which are your original column names A: Pass $id to your view file. $this->render('productcategory',array('model'=>$model,'id'=>$id)); Then pass id to model function in ccgridview function. 'dataProvider'=>$model->SelectedCategoryProducts($id), A: $dataProvider=new CActiveDataProvider('Product', array( 'criteria'=>array( 'select'=>'name,model,price,brand', 'condition'=>'category=:category', 'params'=>array(':category'=>$id), ))); this can retrieve needed data.... first check that data is perfect ... is it right after that take second step....
unknown
d12182
train
That icon indicates that the line is a Find Result from the last time you did a "Find In Files."
unknown
d12183
train
When you're saving workbook, provide full path, otherwise you will save it in a Python folder. I'm pretty sure that's where your Excel workbook with new data resides. wb.save("..\\..\\Decision Tree Classifier TPS\\Decision Tree Classifier TPS\\TestData.xlsx") Also, don't forget to close your workbook when you're done with it. wb.close() Hope this helps!
unknown
d12184
train
Try using an external plugin to parse your dates, something like Datejs A: Frankly, I'm surprised other browsers parse the string correctly, as the string you give to the date object is 1:00 AM1/20/2012. Put the date first and add a space in between. var timeIn = new Date($('#dateIn').val() + ' ' + $('#timeIn').val()); var timeOut = new Date($('#dateOut').val() + ' ' + $('#timeOut').val()); http://jsfiddle.net/mq72k/8/ A: Javascript does not parse string dates very well at all, including ISO8601 formats. You must parse the string yourself. You especially should not expect a minor format like month/day/year to be parsed since it is used by a small minority of the global population. Incidentally, this has nothing to do with jQuery. Edit To reliably parse m/d/y format: function toDate(ds) { var a = ds.split('/'); return new Date(+a[2], (a[0] - 1), +a[1]); } The above assumes a correct date string is supplied. To check that it's a valid date at the same time: function toDate(ds) { var a = ds.split('/'); var d = new Date(+a[2], (a[0] - 1), +a[1]); if (d.getDate() == a[1] && d.getFullYear() == a[2]) { return d; } else { return NaN; // or some other suitable value like null or undefined } }
unknown
d12185
train
Try utilizing .each() , where i is index of element within collection , el is element , el.value is value of input type="range" current element within loop $("input[type=range]").each(function(i, el) { console.log(el.value); }); https://jsfiddle.net/f3x5jfjg/15/ A: Yes, that can be done. You would have to take advantage of the change event, not the click event though. As the ranges are wide, and it's hard to find a match I have set a match by default and used addClass() and removeClass() instead of hide() and show() just to demonstrate how to approach this. Pick any other match, if you can find one, and set your ranges to it. $(document).ready(function () { var ranges = $('div.box > input[type=range]'), table = $('table.table'), hrow = $('tr:has(th)', table), orow = $('tr:has(td)', table); ranges.on('change', function() { //init range object var orange = []; //determine value setting & index for each range ranges.each(function() { var thisrange = {}; thisrange.value = this.value; thisrange.label = $(this).prev('label').text().trim(); thisrange.column = $.inArray( thisrange.label, $('th',hrow).map(function(i,v) { return $(v).text().trim(); }) ); $(this).next('label').text( this.value ); orange.push( thisrange ); }); //hide [remove hightlight] all rows but header orow.removeClass('highlight'); //show [hightlight] rows with values orow.filter(function() { var result = true,that = this; $.each( orange, function(i,v) { result = result && $('td',that).eq(v.column).text().trim() == v.value; }); return result; }).addClass('highlight'); }).change(); }); DEMO NOTE: Some values in the filter columns are non-numeric and would never be set on the range! And some numeric values are out of range. Update Here is a version that will filter just by the changed range. When the page loads it filters by the value of the first range. $(document).ready(function () { var ranges = $('div.box > input[type=range]'), table = $('table.table'), hrow = $('tr:has(th)', table), orow = $('tr:has(td)', table); ranges.on('change', function() { var value = this.value, label = $(this).prev('label').text().trim(), column = $.inArray( label, $('th',hrow).map(function(i,v) { return $(v).text().trim(); }) ); //display the new value $(this).next('label').text( value ); //hide [remove hightlight] all rows but header orow.removeClass('highlight'); //show [hightlight] rows with values orow.filter(function() { return $('td',this).eq(column).text().trim() == value; }).addClass('highlight'); }).eq(0).change(); }); DEMO
unknown
d12186
train
Use event delegation (for dynamically added #searchbutton) $('#searchboxdiv').on('click',"#searchbutton",function(){ * *http://learn.jquery.com/events/event-delegation/ A: Your options: * *Use event delegation. Bind the click to immediate static parent like this : $("#searchboxdiv").on('click', "#searchbutton", function(){ }); *Or, bind it to the document. $(document).on('click', "#searchbutton", function(){ }); *Or, move the existing click after counter++;, ie., inside $("#trail")'s click handler. For more info, see on()
unknown
d12187
train
Try this... A bit lengthy though... I added the rows depending on Dep count instead of Mgr name, as there can be more than one mgr with same name... So Assuming Dep is some sort of Mgr's ID... Sub Macro1() ' Get count of Dep Columns("A:B").Select Selection.Copy Range("F1").Select ActiveSheet.Paste Application.CutCopyMode = False ActiveSheet.Range("$F:$G").RemoveDuplicates Columns:=Array(1, 2), Header _ :=xlYes Range("H2").Select ActiveCell.FormulaR1C1 = "=COUNTIFS(C1,RC[-2])" Range("H2").Select Selection.Copy lRow = Cells(Rows.Count, 6).End(xlUp).Row Range("H2:H" & lRow).Select ActiveSheet.Paste Application.CutCopyMode = False ' Number of rows to add lRow = Cells(Rows.Count, 6).End(xlUp).Row For i = 2 To lRow num = Cells(i, 8).Value If num < 4 Then Range("F" & i & ":" & "G" & i).Copy Range("A1").Select Selection.End(xlDown).Select For j = 1 To 4 - num ActiveCell.Offset(1, 0).Select ActiveSheet.Paste Next End If Next ' Sorting Data ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add2 Key:=Range("A:A") _ , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal With ActiveWorkbook.Worksheets("Sheet1").Sort .SetRange Range("A:D") .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With Columns("F:H").ClearContents Range("A1").Select End Sub Hope this Helps...
unknown
d12188
train
Use this, it ignores onComplete() and onError(): https://github.com/JakeWharton/RxRelay
unknown
d12189
train
It is because mod_rewrite runs in a loop. First rule is doing this: Starting URL: /searchEngine/test Ending URL: /searchEngine/view/index.php Now L flag causes mod_rewrite to loop again. So now your starting URL becomes: Starting URL: /searchEngine/view/index.php Now 1st rule' pattern ^test doesn't match but your 2nd rule is using .* as matching pattern hence redirects to google. You can have your rules as follows to prevent this behavior: RewriteEngine On RewriteRule ^/?test$ view/index.php [NC,L] RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteRule ^ http://google.com [R,L] 2nd rule has this additional condition: RewriteCond %{ENV:REDIRECT_STATUS} ^$ REDIRECT_STATUS is set to 200 after first rule's execution. So 2nd rule will redirect only if first rule hasn't executed first hence it will skip /test. If you're using Apache 2.4+ then you can use END instead of L to end the execution: RewriteEngine On RewriteRule ^/?test$ view/index.php [NC,END] RewriteRule ^ http://google.com [R,L] A: This is happening because of the internal redirection, You can use the END flag instead of L to stop this behaviour : RewriteEngine On RewriteRule ^\/?test$ view/index.php [NC,END] RewriteRule ^(.*)$ http://google.com [NC,L]
unknown
d12190
train
Because HTTP protocol contains not only the IP address, but also the hostname (the URL you type into your browser), which differs between the <cloud_hostname> and localhost. The easiest way to trick it is to create /etc/hosts (there will be some OSX alternative -- search ...) entry redirecting the hostname of your remote machine to localhost. 127.0.0.1 <cloud_hostname> But note that in this case you will not be able to access the remote machine using the hostname!
unknown
d12191
train
From your simple code, I guess you create SQL statement manually. Try using String.format: String query = String.format("SELECT * FROM %s WHERE %s = ?", TABLE_NAME, SEARCH_KEY); Read more at: Local Databases with SQLiteOpenHelper Or try using PreparedStatement like below: PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?"); pstmt.setBigDecimal(1, 153833.00) pstmt.setInt(2, 110592) Please be aware that the parameterIndex (i.e 1 and 2 in above code) start from 1.
unknown
d12192
train
Consider using gulp-debug https://github.com/sindresorhus/gulp-debug it is a plugin that help you see what files are run through your gulp pipeline
unknown
d12193
train
In training_data[i]==row[i]&training_data[9]==1, the operator & has higher precedence than ==. Surround the relational expressions with parentheses before doing the AND: (training_data[i]==row[i]) & (training_data[9]==1)
unknown
d12194
train
Well, for starters, the #options will need to be converted to the value for each radio button. You'll also probably need to add labels for each button as well.
unknown
d12195
train
I don't know any solution using docker-compose.yml. The solution I propose implies create a Dockerfile and execute (creating a shellscript as CMD): ssh-keyscan -t rsa whateverdomain >> ~/.ssh/known_hosts Maybe you can scan /ect/hosts or pass a variable as ENV. A: try to mount it from host to container. . --volume local/path/to/known_hosts:/etc/ssh/ssh_known_hosts in case it didnt work, take a look at some similar case related to ssh key in docker like : this and this
unknown
d12196
train
All this trouble to get YouTube search result data is just a waste of time and effort. Why not try out these options * *YouTube Data API *Selenium + Headless chrome That being said, for the first 20 results, you can get the data from the JavaScript content in the source. The answer to that is given below. After about 1 hr of making sense of the resulting json, it still fails for some queries.YouTube is a very complicated site. The response may vary based on location, browser, search query etc. We are extracting the data from this script tag in the source. Code: from bs4 import BeautifulSoup as bs import requests import re import json headers={ 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' } name=input("Enter video name: ") url='https://www.youtube.com/results?search_query=hello'+name searched=requests.get(url,headers=headers) soup=bs(searched.text,'html.parser') aid=soup.find('script',string=re.compile('ytInitialData')) extracted_josn_text=aid.text.split(';')[0].replace('window["ytInitialData"] =','').strip() video_results=json.loads(extracted_josn_text) #print(item_section=video_results["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][1]) item_section=video_results["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"] for item in item_section: try: video_info=item["videoRenderer"] title=video_info["title"]["simpleText"] url=video_info["navigationEndpoint"]["commandMetadata"]["webCommandMetadata"]["url"] print('Title:',title) print('Url:',url, end="\n----------\n") except KeyError: pass Output: Enter video name: hello Title: New Punjabi Songs 2017-Hello Hello(Ful Song)-Prince Narula-Yuvika Chaudhary-Latest Punjabi Song 2017 Url: /watch?v=mv326-zVpAQ ---------- Title: Alan Walker - The Spectre Url: /watch?v=wJnBTPUQS5A ---------- Title: Hello Hello (Full HD) - Rajvir Jawanda | MixSingh | Josan Bros | New Punjabi Songs 2018 Url: /watch?v=xydupjQSj44 ---------- Title: Bachchan - Hello Hello - Kannada Movie Full Song Video | Sudeep | Bhavana | V Harikrishna Url: /watch?v=oLMMgoug4Uk ---------- Title: Hello Hello latest 2017 16 june punjabi song Url: /watch?v=MqCSsPXw8QU ---------- Title: Hello Hello | + More Kids Songs | Super Simple Songs Url: /watch?v=saDkICxEdgY ---------- Title: 'Gallan Goodiyaan' Full VIDEO Song | Dil Dhadakne Do | T-Series Url: /watch?v=jCEdTq3j-0U ---------- Title: Hello Hello Gippy Grewal Feat. Dr. Zeus Full Song HD | Latest Punjabi Song 2013 Url: /watch?v=IRW2O4QZhgs ---------- Title: Hello Hello | Pataakha | Malaika Arora | Vishal Bhardwaj & Rekha Bhardwaj | Gulzar | Ganesh Acharya Url: /watch?v=RxBAitQLSLA ---------- Title: Hello Hello (Lyrical Audio) Prince Narula ft. Yuvika Chaudhary | Punjabi Lyrical Audio 2017 | WHM Url: /watch?v=v8VIsIvhDoQ ---------- Title: Hello Hello Full Video Song || Bhale Bhale Magadivoi || Nani, Lavanya Tripathi Url: /watch?v=y3FI02OO_kU ---------- Title: Hello hello gaad bahe dhufee na egaa (new comedy hhhhhh) Url: /watch?v=DuRrcTo4rgg ---------- Title: Proper Patola - Official Video | Namaste England | Arjun | Parineeti | Badshah | Diljit | Aastha Url: /watch?v=YmXJp4RtBCM ---------- Title: Official Video: Nikle Currant Song | Jassi Gill | Neha Kakkar | Sukh-E Muzical Doctorz | Jaani Url: /watch?v=uBaqgt5V0mU ---------- Title: Insane (Full Song) Sukhe - Jaani - Arvindr Khaira - White Hill Music - Latest Punjabi Song 2018 Url: /watch?v=mKpPhVVF8So ---------- Title: Radha bole HELLO HELLO-cartoon song mix with step up 2 Url: /watch?v=TFCTgNCzrck ---------- Title: Hello Song | CoCoMelon Nursery Rhymes & Kids Songs Url: /watch?v=fxVMqaViVaA ---------- Title: Bachchan - Hello Hello Unplugged Version | Sudeep | Bhavana | V Harikrishna Url: /watch?v=lvH3kTGJeEQ ---------- Title: Hello Hello! Can You Clap Your Hands? | Original Kids Song | Super Simple Songs Url: /watch?v=fN1Cyr0ZK9M ---------- One last thing that you can try out is to emulate the API used by youtube itself ie. POST request to https://www.youtube.com/results?search_query=yoursearchtext It has a lot of cookie and session values being sent as parameters. You may need to emulate all of them. You may need to use Requests session objects to do that.
unknown
d12197
train
Rust's .find passes the callback the type &Self::Item, and since you are using .iter_mut(), you've created an iterator where each item is &mut T. That means the type passed to your find callback is &&mut T. To get that to typecheck, you can do either vec.iter_mut().find(|&&mut c| c == 2) or vec.iter_mut().find(|c| **c == 2) with the second one being preferable. The error you are getting is because the middle-ground you've chosen by using &c would set c to a value of &mut T, and one of Rust's big rules is that multiple things can't own a mutable reference to an item at the same time. Your non-mutable case works because you are allowed to have multiple immutable references to an item.
unknown
d12198
train
You can do like this <script type="text/javascript"> if ( window.location.href.indexOf ("test") > -1 ) { var myscript = document.createElement ('script'); myscript.src = 'myScriptcc.js'; document.body.appendChild (myscript); } </script>
unknown
d12199
train
If you want to insert this formula =SUMIFS(B2:B10,A2:A10,F2) into cell G2, here is how I did it. Range("G2")="=sumifs(B2:B10,A2:A10," & _ "F2)" To split a line of code, add an ampersand, space and underscore. A: (i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _ (k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx))) From ms support To continue a statement from one line to the next, type a space followed by the line-continuation character [the underscore character on your keyboard (_)]. You can break a line at an operator, list separator, or period. A: In VBA (and VB.NET) the line terminator (carriage return) is used to signal the end of a statement. To break long statements into several lines, you need to Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return). (From How to: Break and Combine Statements in Code) In other words: Whenever the interpreter encounters the sequence <space>_<line terminator>, it is ignored and parsing continues on the next line. Note, that even when ignored, the line continuation still acts as a token separator, so it cannot be used in the middle of a variable name, for example. You also cannot continue a comment by using a line-continuation character. To break the statement in your question into several lines you could do the following: U_matrix(i, j, n + 1) = _ k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _ (k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx))) (Leading whitespaces are ignored.) A: To have newline in code you use _ Example: Dim a As Integer a = 500 _ + 80 _ + 90 MsgBox a
unknown
d12200
train
The solution is simple: you have the wrong argument order in this line: map.put(tempMap,parts[0]); it should say map.put(parts[0],tempMap); You must change the type parameters of your variable declaration accordingly. Where you have Map<Map<String,String>,String> map = new HashMap<>(); you must put Map<String,Map<String,String>> map = new HashMap<>(); Altogether, after these changes I believe you will have the structure you really want to have: a map from parts[0] to the map of the rest of the record fields. I should add that your solution (in addition to your nick :) gives you away as a developer who primarily codes in a dynamic language like Groovy; this style is not a good match for Java's language features. In Java you'd be better off defining a specialized bean class: public class CardHolder { public final String cardNumber, issuingBank, cardSwitch, cardType; public CardHolder(String[] record) { int i = 0; cardNumber = record[i++]; issuingBank = record[i++]; cardSwitch = record[i++]; cardType = record[i++]; } } First, this approach is nicer since your reading loop becomes simpler and more to the point: while ((sCurrentLine = br.readLine()) != null) { final CardHolder ch = new CardHolder(sCurrentLine.split(",")); map.put(ch.cardNumber, ch); } Also this will allow you finer control over other aspects of your record; for example a nice custom toString and similar. Note also that this has hardly resulted in more code: it just got reorganized by the separation-of-concerns principle. (A minor observation at the end: in Java the s-prefix to String variables is not customary because it is redundant in statically-typed languages; rest assured that you will never encounter a bug in Java due to an Integer occuring where a String was expected.) A: You should change, how you have created your Map.. In place of your below declaration: - Map<Map<String,String>,String> map = new HashMap<>(); Rather than this, you should have a : - Map<String, Map<String,String>> map = new HashMap<>(); You should always have an immutable type as a key in your Map.. And after this change, you should change: - map.put(tempMap,parts[0]); to: - map.put(parts[0], tempMap); A: I think you have the arguments in map.put(tempMap,parts[0]); reversed. You are mapping tempMap to the number, where you probably want to be mapping the number to tempMap: map.put(parts[0], tempMap); Using Map<String, Map<String,String>> map = new HashMap<>(); A: You should use Map as value since HashMap equality is based on key value pairs it has.. map.put(parts[0],tempMap); A simple program below will illustrate this fact Map<String, String> tempMap1 = new HashMap<String, String>(); tempMap1.put("issuing_bank", "ICICI"); tempMap1.put("card_switch", "Visa"); tempMap1.put("card_Type", "Debit"); Map<String, String> tempMap2 = new HashMap<String, String>(); tempMap2.put("issuing_bank", "ICICI"); tempMap2.put("card_switch", "Visa"); tempMap2.put("card_Type", "Debit"); System.out.println(tempMap1.equals(tempMap2));//Prints true Output: true So your declaration should like below. Remember you should always use immutable object as key in HashMap. Map<String,Map<String,String>> map = new HashMap<String,Map<String,String>>(); A: That's because you're using a map (the tempMap) as a key. This is wrong.
unknown