_id
stringlengths
2
6
text
stringlengths
4
46k
title
stringclasses
1 value
d10501
Compiling the gist of answers other people have given before: In the development environment your model classes will not be eager loaded. Only when you invoke some code that references a model class, the corresponding file will be loaded. (Read up on 'autoloading' for further detail.) So if you need to do some checks upon startup of the rails server, you can manually invoke Rails.application.eager_load! and after that get a list of all model classes with model_classes = ActiveRecord::Base.descendants For a list of model names associated with their database tables, you might use model_classes.map{ |clazz| [clazz.model_name.human, clazz.table_name] }.sort You can put your code in an arbitrarily named file in the config/initializers directory. All ruby files in that directory will get loaded at startup in alphabethical order. The eager loading will of course take some time and thus slow down server and console start-up in the development environment a bit. Other approaches such as parsing a list of filenames in the app/models directory are not reliable in more complex Rails applications. If in a Rake task, make sure your Application is properly initialized before you send eager_load!. To that end, let your rake task depend on :environment. HTH!
d10502
Don't fight exceptions. If you can't parse a string as an integer, let the ValueError be raised. If the number is out of range, raise a different ValueError. Otherwise, return a value that is guaranteed to be in the requested range. def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int: x = int(str) # May raise if x < low_boundary or x > high_boundary: raise ValueError(f"Value '{x}' is out of range {low_boundary}-{high_boundary}") return x The caller knows better than your function what to do if the string cannot produce an in-range integer, and raising an exception forces them to consider the worst-case scenario, rather than letting them assume the function worked and encountering an error later. As a conventional alternative, you can return None to indicate the lack of a suitable int value. Unlike False, None cannot be confused with 0, but it can still be ignored altogether to cause problems later. (And None by itself doesn't tell you if the string wasn't parseable or if the parsed number was simply out of range.) def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> Optional[int]: try: x = int(str) except ValueError: return None if x < low_boundary or x > high_boundary: return None return x or, to avoid repeating the return None statement: def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> Optional[int]: try: x = int(str) if x < low_boundary or x > high_boundary: raise ValueError except ValueError: return None return x A: def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int | False: number = "".join(filter(str.isdigit, string)) if number: number = int(number) if low_boundary < number < high_boundary: return number return False Note: Using not operator with the output of the function does not distinguish between False and 0 as not False and not 0 will evaluate to True. Here you can differentiate by checking the output with amount is not False condition.
d10503
Use Self join to get next record ;WITH CTE AS ( SELECT ROW_NUMBER() OVER(ORDER BY [Cluster Start Date])RNO,* FROM YOURTABLE ) SELECT C1.ClientID,C1.RefAd1,C1.[Cluster Start Date],C2.[Cluster Start Date] [Cluster End Date] FROM CTE C1 LEFT JOIN CTE C2 ON C1.RNO=C2.RNO-1 * *Click here to view result EDIT : To update the table, you can use the below query ;WITH CTE AS ( SELECT ROW_NUMBER() OVER(ORDER BY [Cluster Start Date])RNO,* FROM #TEMP ) UPDATE #TEMP SET [Cluster End Date] = TAB.[Cluster End Date] FROM ( SELECT C1.ClientID,C1.RefAd1,C1.[Cluster Start Date],C2.[Cluster Start Date] [Cluster End Date] FROM CTE C1 LEFT JOIN CTE C2 ON C1.RNO=C2.RNO-1 )TAB WHERE TAB.[Cluster Start Date]=#TEMP.[Cluster Start Date] * *Click here to view result EDIT 2 : If you want this to be done for ClientId and RefAd1. ;WITH CTE AS ( -- Get current date and next date for each type of ClientId and RefAd1 SELECT ROW_NUMBER() OVER(PARTITION BY ClientID,RefAd1 ORDER BY [Cluster Start Date])RNO,* FROM #TEMP ) UPDATE #TEMP SET [Cluster End Date] = TAB.[Cluster End Date] FROM ( SELECT C1.ClientID,C1.RefAd1,C1.[Cluster Start Date],C2.[Cluster Start Date] [Cluster End Date] FROM CTE C1 LEFT JOIN CTE C2 ON C1.RNO=C2.RNO-1 AND C1.ClientID=C2.ClientID AND C1.RefAd1=C2.RefAd1 )TAB WHERE TAB.[Cluster Start Date]=#TEMP.[Cluster Start Date] AND TAB.ClientID=#TEMP.ClientID AND TAB.RefAd1=#TEMP.RefAd1 * *Click here to view result If you want to do it only for ClientId, remove the conditions for RefAd1 A: Here is the script if you just want the view you described: CREATE VIEW v_name as SELECT ClientId, RefAd1, [Cluster Start Date], ( SELECT min([Cluster Start Date]) FROM yourTable WHERE t.[Cluster Start Date] < [Cluster Start Date] ) as [Cluster End Date] FROM yourtable t
d10504
I suspect you will see this issue in more locations. You could solve this specific issue with 3., but that leaves other locations where you're going to encounter concurrency issues. What I would advise is to implement pessimistic locking. The usual way to do this is to just apply a transaction to the entire HTTP request. With the BeginRequest in your Global.asax, you start a session and transaction. Then, in the EndRequest you commit it. With the Error event, you go the alternative path of doing a rollback and discarding the session. This is quite an accepted manner of applying NHibernate. See for example http://dotnetslackers.com/articles/aspnet/Configuring-NHibernate-with-ASP-NET.aspx. A: I'd go with 3. I believe this in this kind of application it's not so critical if some pages show a slightly outdated value for a while. IIRC, HQL updates do not invalidate the entity cache entry, so you might have to do it manually.
d10505
The scripts which you are able to see is because of the differential loading feature. Angular 8 has a new feature to generate a separate bundle to the older browser and new browsers. You can control which browser you want to support, you can read more about this feature on https://angular.io/guide/deployment#differential-loading
d10506
I prefer the set based answers, but here's one that works anyway [x for x in a if x in b] A: Not the most efficient one, but by far the most obvious way to do it is: >>> a = [1, 2, 3, 4, 5] >>> b = [9, 8, 7, 6, 5] >>> set(a) & set(b) {5} if order is significant you can do it with list comprehensions like this: >>> [i for i, j in zip(a, b) if i == j] [5] (only works for equal-sized lists, which order-significance implies). A: Use set.intersection(), it's fast and readable. >>> set(a).intersection(b) set([5]) A: Can use itertools.product too. >>> common_elements=[] >>> for i in list(itertools.product(a,b)): ... if i[0] == i[1]: ... common_elements.append(i[0]) A: You can use def returnMatches(a,b): return list(set(a) & set(b)) A: You can use: a = [1, 3, 4, 5, 9, 6, 7, 8] b = [1, 7, 0, 9] same_values = set(a) & set(b) print same_values Output: set([1, 7, 9]) A: One more way to find common values: a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] matches = [i for i in a if i in b] A: If you want a boolean value: >>> a = [1, 2, 3, 4, 5] >>> b = [9, 8, 7, 6, 5] >>> set(b) == set(a) & set(b) and set(a) == set(a) & set(b) False >>> a = [3,1,2] >>> b = [1,2,3] >>> set(b) == set(a) & set(b) and set(a) == set(a) & set(b) True A: a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] lista =set(a) listb =set(b) print listb.intersection(lista) returnMatches = set(['5']) #output print " ".join(str(return) for return in returnMatches ) # remove the set() 5 #final output A: Quick way: list(set(a).intersection(set(b))) A: The easiest way to do that is to use sets: >>> a = [1, 2, 3, 4, 5] >>> b = [9, 8, 7, 6, 5] >>> set(a) & set(b) set([5]) A: >>> s = ['a','b','c'] >>> f = ['a','b','d','c'] >>> ss= set(s) >>> fs =set(f) >>> print ss.intersection(fs) **set(['a', 'c', 'b'])** >>> print ss.union(fs) **set(['a', 'c', 'b', 'd'])** >>> print ss.union(fs) - ss.intersection(fs) **set(['d'])** A: Also you can try this,by keeping common elements in a new list. new_list = [] for element in a: if element in b: new_list.append(element) A: A quick performance test showing Lutz's solution is the best: import time def speed_test(func): def wrapper(*args, **kwargs): t1 = time.time() for x in xrange(5000): results = func(*args, **kwargs) t2 = time.time() print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0) return results return wrapper @speed_test def compare_bitwise(x, y): set_x = frozenset(x) set_y = frozenset(y) return set_x & set_y @speed_test def compare_listcomp(x, y): return [i for i, j in zip(x, y) if i == j] @speed_test def compare_intersect(x, y): return frozenset(x).intersection(y) # Comparing short lists a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] compare_bitwise(a, b) compare_listcomp(a, b) compare_intersect(a, b) # Comparing longer lists import random a = random.sample(xrange(100000), 10000) b = random.sample(xrange(100000), 10000) compare_bitwise(a, b) compare_listcomp(a, b) compare_intersect(a, b) These are the results on my machine: # Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms Obviously, any artificial performance test should be taken with a grain of salt, but since the set().intersection() answer is at least as fast as the other solutions, and also the most readable, it should be the standard solution for this common problem. A: Do you want duplicates? If not maybe you should use sets instead: >>> set([1, 2, 3, 4, 5]).intersection(set([9, 8, 7, 6, 5])) set([5]) A: another a bit more functional way to check list equality for list 1 (lst1) and list 2 (lst2) where objects have depth one and which keeps the order is: all(i == j for i, j in zip(lst1, lst2)) A: Using __and__ attribute method also works. >>> a = [1, 2, 3, 4, 5] >>> b = [9, 8, 7, 6, 5] >>> set(a).__and__(set(b)) set([5]) or simply >>> set([1, 2, 3, 4, 5]).__and__(set([9, 8, 7, 6, 5])) set([5]) >>> A: The following solution works for any order of list items and also supports both lists to be different length. import numpy as np def getMatches(a, b): matches = [] unique_a = np.unique(a) unique_b = np.unique(b) for a in unique_a: for b in unique_b: if a == b: matches.append(a) return matches print(getMatches([1, 2, 3, 4, 5], [9, 8, 7, 6, 5, 9])) # displays [5] print(getMatches([1, 2, 3], [3, 4, 5, 1])) # displays [1, 3] A: you can | for set union and & for set intersection. for example: set1={1,2,3} set2={3,4,5} print(set1&set2) output=3 set1={1,2,3} set2={3,4,5} print(set1|set2) output=1,2,3,4,5 curly braces in the answer. A: I just used the following and it worked for me: group1 = [1, 2, 3, 4, 5] group2 = [9, 8, 7, 6, 5] for k in group1: for v in group2: if k == v: print(k) this would then print 5 in your case. Probably not great performance wise though. A: This is for someone who might what to return a certain string or output, here is the code, hope it helps: lis =[] #convert to list a = list(data) b = list(data) def make_list(): c = "greater than" d = "less_than" e = "equal" for first, first_te in zip(a, b): if first < first_te: lis.append(d) elif first > first_te: lis.append(c) else: lis.append(e) return lis make_list()
d10507
You are tring to use xpath as css_selector. Try driver.find_element_by_css_selector("[src='./assets/images/viewdetails.png']").click() Or driver.find_element_by_xpath("//img[@src='./assets/images/viewdetails.png']").click() You can also use explicit wait from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By wait = WebDriverWait(driver, 10) wait.until(ec.element_to_be_clickable((By.CSS_SELECTOR, "[src='./assets/images/viewdetails.png']"))).click() # or wait.until(ec.element_to_be_clickable((By.XPATH, "//img[@src='./assets/images/viewdetails.png']"))).click()
d10508
Use git clone and clone from your bitbucket repository.
d10509
This is actually quite easy to do with awk: pax: awk <input.txt '/^id45678/{$0=substr($0,1,11)"VALUE04"substr($0,19)}1' id12345TEXTVALUE01SOMCODETEXT id23456TEXTVALUE02SOMCODETEXT id34567TEXTVALUE02SOMCODETEXT id45678TEXTVALUE04SOMCODETEXT id56789TEXTVALUE03SOMCODETEXT It just finds lines beginning with id45678 and modifies that part of the line that you want changed. The 1 at the end is simply a command to print the line whether changed or not (it's a "trick" using a truth value 1 to select the (default) action of printing the line). A: Using GNU awk's FIELDWIDTHS for fixed width fields: $ awk ' BEGIN { FIELDWIDTHS="7 4 7 7 4" 3 # set the field widths OFS="" } $1=="id45678" { # when the first field has the given value $3="VALUE04" # replace the third field }1' file # output Column1Col2Column3Column4Col5 id12345TEXTVALUE01SOMCODETEXT id23456TEXTVALUE02SOMCODETEXT id34567TEXTVALUE02SOMCODETEXT id45678TEXTVALUE04SOMCODETEXT id56789TEXTVALUE03SOMCODETEXT A: With GNU sed: sed -E 's/^(id45678....)......./\1VALUE04/' file or shorter: sed -E 's/^(id45678.{4}).{7}/\1VALUE04/' file and with variables: s="id45678" r="VALUE04" sed -E 's/^('"$s"'.{4}).{7}/\1'"$r"'/' file Output: id12345TEXTVALUE01SOMCODETEXT id23456TEXTVALUE02SOMCODETEXT id34567TEXTVALUE02SOMCODETEXT id45678TEXTVALUE04SOMCODETEXT id56789TEXTVALUE03SOMCODETEXT If you want to edit your file "in place" use sed's option -i.
d10510
You said "If there are more than 2 fractional digits". A number cannot "have" 2 fractional digits. You can add an infinite number of fractional digits (0) to a number and the value will not change. You are confusing the actual value with a format string. What you really mean is probably "If 100 times the number is an integer". To do this, you will need an if statement: let formatter = NumberFormatter() formatter.locale = Locale(identifier: "en_US") formatter.usesGroupingSeparator = true formatter.minimumIntegerDigits = 1 formatter.numberStyle = .decimal // this checks if the number has two leading fractional digits that are not zero if (a * pow(10, minimum)).truncatingRemainder(dividingBy: 1) == 0 { formatter.minimumFractionDigits = minimum } else { formatter.minimumSignificantDigits = maximum } return formatter.string(from: self) ?? "-"
d10511
This is the trailing return type. auto is simply a placeholder that indicates that the return type comes later. The reason for this is so that the parameter names can be used in computing the return type: template<typename L, typename R> auto add(L l, R r) -> decltype(l+r) { return l+r; } The alternative is: template<typename L, typename R> decltype(std::declval<L>()+std::declval<R>()) add(L l, R r) { return l+r; } It's likely that a future addition to the language will be to allow leaving out the trailing return type and instead using automatic type deduction as is permitted with lambdas. template<typename L, typename R> auto add(L l, R r) { return l+r; }
d10512
You can use pipe for this: private learningElements: LearningElementDTO[]; constructor(private service: LearningService) { } ngOnInit() { this.loadData().subscribe(reponse => { console.log(this.learningElements[0].name); }); } private loadData(): Observable<LearningElementDTO[]>{ return this.service.getLearningElements().pipe( map((reponse: any) => { this.learningElements = reponse; return response; }) ); } } A: When your console.log is executed, the response hasn't come back yet. You need to move this code into your subscribe function after you assign the server response to your local variable this.learningElements this.service .getLearningElements() .subscribe(response => { this.learningElements = response; console.log(this.learningElements[0].name); });
d10513
Solved it using instead 'jar cfe HelloWorld.jar HelloWorld HelloWorld.class' of 'jar cfm HelloWorld.jar Manifest.txt HelloWorld.class'. Thanks guys!!
d10514
table name "kategori" does not exist on your database, you should check the code if you created the table or not. if created, change the version number of the database, It will call the onUpgrade method and the database will create again.
d10515
You could consider using Cosmos Db sdk or REST API to deploy udf into your collection. sample code: string udfId = "Tax"; var udfTax = new UserDefinedFunction { Id = udfId, Body = {...your udf function body}, }; Uri containerUri = UriFactory.CreateDocumentCollectionUri("myDatabase", "myContainer"); await client.CreateUserDefinedFunctionAsync(containerUri, udfTax); A: Simple answer No, Stored procedures and User Defined Functions are not supported via Azure Resource Management Templates as of today. A: This is now possible.. "type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/userDefinedFunctions", "apiVersion": "2019-08-01", https://learn.microsoft.com/en-us/azure/templates/microsoft.documentdb/2019-08-01/databaseaccounts/sqldatabases/containers/userdefinedfunctions
d10516
To use every number in the first result you can use a for loop. for number in pm_list[0]: print (number) Or if you want to do this for all results: for result in pm_list: for number in result: print (number)
d10517
You can use math.random() to get a random link from the category array, and use a cookie or localStorage to keep track of which links have already been seen. A: Try this: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script type='text/javascript' src='js/jquery.min.js'></script> </head> <body> <p id="category1"></p> <p id="category4"></p> <script> function getRandomInt (min, max) { if (max == 0) return 0; return Math.floor(Math.random() * (max - min + 1)) + min; } $(function () { var link = [ ["category1", [[ "http://www.xyzabcxyz.com/apple", "Apple description comes here"], ["http://www.xyzabcxyz.com/pineapple", "Pineapple description comes here"], ["http://www.xyzabcxyz.com/lemon", "Lemon description comes here"]]], ["category2", [["http://www.xyzabcxyz.com/banana", "Banana description comes here"]]], ["category3", [["http://www.xyzabcxyz.com/apricots", "Apricots description comes here"], ["http://www.xyzabcxyz.com/Berries", "Berries description comes here"]]], ["category4", [["http://www.xyzabcxyz.com/peaches", "Peaches description comes here"]]] ]; $.each(link, function (e,v) { if ($("#" + v[0]).length) { var min = 0; var max = (v[1].length)-1; var i = getRandomInt(min,max); $("#" + v[0]).append('<a target="_blank" href="' + v[1][i][0] +'">' + v[1][i][1] + '</a>'); } }); }); </script> </body> For the random function tks. to Javascript: Generate a random number within a range using crypto.getRandomValues
d10518
There is no way to do this with the AuthComponent because of the way it handles the session keys. You can, however, just save it to the session yourself. The only way to do this is to add to the session when the user logs in: function login() { if ($this->Auth->login($this->data)) { $this->User->id = $this->Auth->user('id'); $this->User->contain(array('Profile', 'Group')); $this->Session->write('User', $this->User->read()); } } Then in your beforeFilter() in your AppController, save a var for the controllers to get to: function beforeFilter() { $this->activeUser = $this->Session->read('User'); } // and allow the views to have access to user data function beforeRender() { $this->set('activeUser', $this->activeUser); } Update: As of CakePHP 2.2 (announced here), the AuthComponent now accepts the 'contain' key for storing extra information in the session. A: As far as I'm aware the Auth component only caches the data from your Users model. You can use that information to retrieve the desired data from the other models, by for example using this in your controller: $group_data = $this->Group->findById($this->Auth->user('group_id')); Or $profile_data = $this->Profile->findByUserId($this->Auth->user('id')); But I don't think you can get it from the Auth component directly, as it doesn't cache the related model data out of the box. A: Two ways: 1) Extend the FormAuthenticate class (see /Controller/Component/Auth) or whatever you use to login and override the _findUser() method and tell the Auth component to use this authorize class. See this page how to do all of that http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html 2) Simply implement a method in the model that will fetch all data you want and call it in the login method of your controller and write the data into the session. IMO it is handy to have such a method because sometimes you need to refresh the session data anyways. Because of your comment on the other answer: You will have to write a method and some code in a model that will return you the data. CakePHP can't read your mind and a database without code. No matter which of both suggested ways you're going to use, you'll have to write code.
d10519
You can use: set(option, value): Sets a config option optionto value, redrawing the calendar and updating the current view, if necessary In order to disable all dates except the 3 selected you can write: instance.set('enable', selectedDates); and, in order to reset you can: instance.set('enable', []); A different approach can be based on Enabling dates by a function: instance.set('enable', [function(date) { if (selectedDates.length >= 3) { var currDateStr = FlatpickrInstance.prototype.formatDate(date, "d/m/Y") var x = selectedDatesStr.indexOf(currDateStr); return x != -1; } else { return true; } }]); The snippet: $('#gig_date_multi').flatpickr({ "mode": "multiple", "locale": 'en', minDate: new Date(), enableTime: true, time_24hr: true, minuteIncrement: 15, onChange: function(selectedDates, dateStr, instance) { var selectedDatesStr = selectedDates.reduce(function(acc, ele) { var str = instance.formatDate(ele, "d/m/Y"); acc = (acc == '') ? str : acc + ';' + str; return acc; }, ''); instance.set('enable', [function(date) { if (selectedDates.length >= 3) { var currDateStr = instance.formatDate(date, "d/m/Y") var x = selectedDatesStr.indexOf(currDateStr); return x != -1; } else { return true; } }]); } }); input[type="text"] { width: 100%; box-sizing: border-box; -webkit-box-sizing:border-box; -moz-box-sizing: border-box; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" href="https://unpkg.com/flatpickr/dist/flatpickr.min.css"> <script src="https://unpkg.com/flatpickr"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> <input type="text" id="gig_date_multi"> A: On a side note, if anyone wants to disable past date as well as time selection in Flatpickr, use Date().getTime() like this: $("input.picker-datetime").flatpickr({ enableTime: true, dateFormat: "Y-m-d H:i", time_24hr: true, minDate: new Date().getTime() });
d10520
I had the same problem. I check my projects dependencies in my solution. I deleted extra and unused dependencies and then, I made the version used for each dependency the same in all projects and the problem solved! My be it works for you, too.
d10521
I didn't realise I had to remove the build directory. Now it imports correctly. For anyone that needs to know you need: extra_link_args=['-framework', 'OpenGL'] Delete the build directory and try it again. It will work.
d10522
To prevent two nodes from overlapping, you should check the newly created node's random position with intersectsNode: to see if it overlaps any other nodes. You also have to add each successfully added node into an array against which you run the intersectsNode: check. Look at the SKNode Class Reference for detailed information.
d10523
You can implement a check before committing the fragment transaction, something as follows. public boolean loadFragment(Fragment fragment) { //switching fragment if (fragment != null) { FragmentTransaction transaction = fm.beginTransaction(); transaction.replace(R.id.main_frame_layout, fragment); if (!fm.isDestroyed()) transaction.commit(); return true; } return false; } A: maybe you can use parentFragmentManager.beginTransaction() instead of childFragmentManager in code will look like dialog.show(parentFragmentManager.beginTransaction(), BaseFragment.TAG_DIALOG) A: Hi you can just use it like this way declare a handler Handler handler = new Handler() and Then put commit in to post delayed of handler // this is a hack to fix fragment has been destroyed issue do not put Transaction.replace // into handler post delayed handler.postDelayed({ // transaction.addToBackStack(null) transaction.commit() },500) Do not place other things in post delayed ie. adding fragment to transaction (or replace transaction.replace(fragment,containerid,tag))
d10524
In Java, you can directly convert the SearchResponse to JSONObject. Below is the handy code. SearchResponse SR = builder.setQuery(QB).addAggregation(AB).get(); JSONObject SRJSON = new JSONObject(SR.toString()); A: You need to use the SearchResponse.toXContent() method like this: SearchResponse response = client.prepareSearch(index).setExplain(true).execute().actionGet(); XContentBuilder builder = XContentFactory.jsonBuilder(); response.toXContent(builder, ToXContent.EMPTY_PARAMS); JSONObject json = new JSONObject(builder.string());
d10525
Solved. I was using an incorrect method of pushing the view controller into the navigation controller. Instead of self.navigationController.viewControllers = [NSArray arrayWithObject:self.myViewController]; Use the following [self.navigationController pushViewController:self.vehicleListViewController animated:YES];
d10526
Ok, I fixed. String target should be out of the function( like put it in main). If not, It will always overwritten.
d10527
Not completely sure what you mean, but I think you are looking for: UPDATE `table` SET `status` = 'new status' WHERE `SNo` = '1'
d10528
The width of a <rect> element isn't a CSS property in SVG, it's only usable as an attribute. It's for example like the size of a <select> element in HTML. You can only set it as an attribute. A: SVG doesn't have a straightforward support for CSS for setting shape dimensions. However there's a workaround for rects, which can also be used to generate horizontal and vertical lines: * *Set width and height to 1, and use CSS transform: scale(width, height) *Don't specify x,y location, and use transform: translate(x, y) E.g. .svg { width: 100px; height: 30px; } .rectangle { transform: scale(30, 10); fill: orange; } .horiz-line { transform: translate(15px,5px) scale(50, 1); fill: red; } .vert-line { transform: translate(10px, 5px) scale(1, 30); fill: blue; } <svg> <rect class="rectangle" width="1" height="1" /> <rect class="horiz-line" width="1" height="1" /> <rect class="vert-line" width="1" height="1" /> </svg> A: In SVG the x, y, width and height of <rect> elements are attributes rather than CSS properties. Only CSS properties can be styled using CSS. A: workaround for symmetric rectangles: rect:hover { stroke-width: 20 !important; } <svg width="100" height="100"> <rect stroke-width="0" fill="blue" stroke="blue" x="30" y="30" width="40" height="40" /> </svg> (darkreader will use different colors for stroke and fill)
d10529
I had the same issue on trying to get the first group from auth_group (Django v. 1.3.5) Group.objects.get(name='First Group') gave the same FeildError. Stangerly this worked: try: Group.objects.get(name="Active Rater") #crazily not working except django.core.exceptions.FieldError as e: group = Group.objects.get(name="Active Rater") #crazily works I have not yet dug into the django code to figure out why.
d10530
If you have a text with one banned word per line, e.g. like this: dog kitten bird ...then you can read it using BannedWords = System.IO.File.ReadAllLines("bannedWords.txt")`; This returns an array of strings, each containing a line of the text file. See here for more information. BTW: if you have lots of banned words, then it might be better to put then into a lookup, as this will make the lookup faster, e.g: // read banned words private ILookup<string, string> BannedWords; // ... BannedWords = File.ReadAllLines("bannedWords.txt").ToLookup(w => w); // check message for banned words if (message.Split(' ').Any(w => bannedWords.Contains(w)) { // message contains a banned word } A: This should do it: var wordsFile = File.ReadAllLines(BANNEDWORDS_PATH); List<string> BannedWords = new List<string>(wordsFile);
d10531
Ok, so i was finally able to register my webhook, following are the steps that i followed 1) first i installed ruby with the help rbenv 2) then i installed twurl using gem install twurl 3) now authorize your app by using the following command twurl authorize --consumer-key key --consumer-secret secret 4) After running the above command on the command prompt you will get output as Go to https://api.twitter.com/oauth/authorize?oauth_consumer_key=xxxxxxxxxxxxx&oauth_nonce=xxxxxxxxxxx&oauth_signature=xxxxxxxxxxxx&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1568986465&oauth_token=xxxxxxx&oauth_version=1.0 and paste in the supplied PIN 5) Just go to the url , twitter page will open with a pin like 9876506 ,just copy the pin and paste in the command line. 6)Then you will get an output of authorization successful in your cmd. 7) Now you have authorized your app. 8) Now before registering the webhook, your call back url that you have given in the details section of your twitter app, should generate a crc token. 9) If your domain is "www.my_domain.com" create an endpoint as "www.my_domain.com/webhook/twitter" and add the following code to generate crc in your web application. def twitterCrcValidation(): crc = request.args['crc_token'] validation = hmac.new(key=bytes(CONSUMER_SECRET, 'utf-8'),msg=bytes(crc, 'utf-8'), digestmod = hashlib.sha256 ) digested = base64.b64encode(validation.digest()) response = { 'response_code':200, 'response_token': 'sha256=' + format(str(digested)[2:-1]) } print('responding to CRC call') return json.dumps(response) 10) Now run the following command to register the webhook, in place of put the name of your environment e.g "prod" twurl -X POST "/1.1/account_activity/all/<environment>/webhooks.json?url=https://www.my_domain.com/webhooks/twitter" 11) After this you will get a json response as the following {"id":"1174326336837472256", "url":"https://www.my_domain.com/webhooks/twitter", "valid":true, "created_timestamp":"2019-09-18 14:16:31 +0000" } 12) Finally your url is registered as webhook. P.S ----Twitter sends crc token to your endpoint in every 24 hours to check whether the url endpoint is alive or not. So your server containing the url endpoint should be in running condition. I deployed my flask app containing the url endpoint on heroku server. So heruko provides you a free server with a single url unlike ngrok. In ngrok you get a new url whenever you run the server, which is not required for twitter. But heroku server sleeps in every 10 minutes if you do not refresh the website. So twitter might have run the crc check on my site and my site was in sleeping condition due to heroku's policy and my webhook id became invalid. You can make your webhook id valid again by running the following command given. twurl -X PUT "/1.1/account_activity/all/prod/webhooks/11743xxxxxxxxxx6.json" then you can get the info about your webhook by running the following command twurl -X GET "/1.1/account_activity/all/webhooks.json" --header authorization:bearer token A: Someone should pay you a beer for this reply. Twitter makes things insanely complicated, LOL. Thanks, it works perfectly. Just a reminder, the env comes from https://developer.twitter.com/en/account/environments. So make sure to create something there in order to put in the POST url.
d10532
You need a double dereference. The first dereference to get the relevant char pointer. The second dereference to get the relevant character. Try: isdigit(str) --> isdigit(str[1][i]) A: Try following, char *secondString = str[1]; int length = strlen(secondString ); for (int i = 0; i < length ; ++i) { if (!isdigit(secondString[i])) return 0; } return 1;
d10533
You are looking for not a word boundary on the left: \Bt See it here on regexr. \B is a zero width assertion that matches when on the left side of a position and of the right side is a word character (or a non word character). So here you have a "t" to the right of \B, so it will only match if on the left of the "t" is also a word character. In other words: It replaces every "t" that is not on the start of a "word". So I tested it now in c#: string[] myStrings = { "ComputerPart", "topaz", "questions" }; Regex reg = new Regex(@"\Bt"); foreach (string str in myStrings) { Console.Out.WriteLine(reg.Replace(str, "success") ); } and it produces exactly the same output than regexr: CompusuccesserParsuccess topaz quessuccessions A: how about: int pos = text.IndexOf("t"); if(pos>0) text = text.Replace("t", "Success"); Do I get your homework credit :-) A: I want more homework credit this time! string readText = File.ReadAllText(path); string[] lines = readText.Split(Environment.NewLine); string output; foreach(string line in lines) { int pos = text.IndexOf("t"); if(pos>0) text = text.Replace("t", "Success"); output += text + Environment.NewLine; } File.AppendAllText(newPath, output); A: I guess this is what you need, string[] inputstrings = { "ComputerPart", "topaz", "questions" };//An array of input strings to manipulate. string output = ""; Regex rgx = new Regex("t");//Regex pattern to match occurence of 't'. foreach (string inputstring in inputstrings)//Iterate through each string in collection. { output = rgx.Replace(inputstring, "success", int.MaxValue, 1);//Replace each occurence of 't' excluding those occurring at position [0] in inputstring. MessageBox.Show(output);//Show output string. } What I've done is : * *Loop through each string in collection. *Match each string against the regular expression for any occurrences of 't'. *The search begins at position 1 in the array of characters derived from each string.So it automatically leaves any occurrence of 't' at start of string. Ideone sample. Hope it helps you.
d10534
Try define column Description for return Series in variable workfromhome: workfromhome = df.loc[df['Description'].str.contains("work from home",na=False), 'Description']
d10535
This is an old question, but still unanswered. So I will add my answer in case people is still curious about it. When your content provider notifies the registered observer using getContext().getContentResolver().notifyChange(URI, "your_uri");, it asks the ContentResponder for it. The return value from that method is the ContentObserver that you registered with the registerContentObserver() method of the content responder, which is what you did in the first case. However, in the second case, you registered the observer in the Cursor using the registerContentObserver() method of the Cursor, so the ContentResponder doesn't know about it. A: If you are setting ContentObserver upon common tables(e.g people, mediaprovider etc) then unfortunately you might not receive any Uri as an argument, it might be blank as it depends upon underneath content provider implementation. To receive an valid Uri upon change, respective ContentProvider has to be modified to notify change along with URI. e.g getContext().getContentResolver().notifyChange(Uri, "your_uri"); // this notifies all the registered ContentObserver with Uri of modified concerned dataset. If you are writing your own ContentProvider then use above mentioned line whenever you perform update, delete or insert operation on your database.
d10536
details below if interested) One way i can think of is using git blame on file, wherever hash matches, remove the lines but seems to be very iterative process and time consuming. Any pointers would be helpful.. Thanks in advance Extra code removed from file which is out of scope of commit A: * *Commit A was added at the end of file *New commits added more code after commit A (below changes from commit A) at the end of file *now when we reverse the changes in commit A (using git apply -R -3), it cleans from start of commit A till end of file because to git, the code was originally added at the end of file A: I would still try git-revert to remove lines in commit A. Next you want to restore the other two files which don’t need revert. git checkout HEAD^ - file1 file2 is the way to recover to the original file content. Finally commit amend to overwrite nicer message than “Revert …”
d10537
Full commented source to a state-machine based approval workflow comes with the MOSS SDK 1.5 in the samples directory. http://www.microsoft.com/downloads/details.aspx?familyid=6D94E307-67D9-41AC-B2D6-0074D6286FA9 -Oisin
d10538
You can have a boolean flag to indicate whether or not saving is allowed and only set it to true when you call the macro that contains your logic for saving the workbook. Add the following code under ThisWorkbook: Public AllowSave As Boolean Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) If Not AllowSave Then MsgBox "You can't save this workbook!" Cancel = True End If End Sub Public Sub CustomSave() ThisWorkbook.AllowSave = True ' TODO: Add the custom save logic ThisWorkbook.SaveAs '.... MsgBox "The workbook has been saved successfully.", , "Workbook saved" ThisWorkbook.AllowSave = False End Sub Note that you'll need to assign the CustomSave macro to the button that will be initiating the custom save. Demo:
d10539
If you want to use the existing properties for the Grid Data, you can use indentL property. <Label text="{i18n>labelDate}" labelFor="datePickerId" design="Bold" > <layoutData> <l:GridData span="L1 M3 S6" indentL="0"/> </layoutData> </Label> Give one column (out of 12) to your label and then indent it to 0 (span value=0 for the Large screen), similarly, you can do it for different screen sizes. A: You have to set labelSpanL/labelSpanM to 1 or 2 to decrease left space, but SimpleForm always align the label to right and put colon ":" between Label and Control. If labelSpan 1 or 2 dont resolve. The only way i know is trying use CSS.
d10540
Refer to Mongoose documentation for providing options to populate field. In the options, you can pass a sort by fieldname.
d10541
You need to have jQuery file in the folder your current page is, also try to get the latest jQuery file you are using quite old, you can download latest here. A: Is Cordova based on jQuery ? If so, you have to include jQuery first. If not, your jQuery file is probably not found. Press Ctrl+u to see the source code, and then click on the link jquery-1.6.4.min.js in the head, and see if it opens your file ?
d10542
The problem is that React is trying to render the posts before the asynchronous fetch returns a result and updates the state. In your render, just check if posts has more than 0 values: //... render() { const { posts } = this.state; if (posts && posts.length) { let post = posts[0]; // for (var key in post) { // console.log(key + ': ' + post[key]); // } let title = post['title'].rendered; let stringbuilder = ''; try { stringbuilder += title + ', '; } catch {} return ( <div> <h1>React Widget</h1> {stringbuilder} </div> ); } // Return null while loading // Or, return useful info like <p>Loading Posts...</p> return null; } //... Also, you should use componentDidMount as componentWillMount has been deprecated.
d10543
You could use this REST API to create a team project. TFS also provide to using C# code to create a team project: public static TeamProject CreateProject() { string projectName = "Sample project"; string projectDescription = "Short description for my new project"; string processName = "Agile"; VssCredentials c = new VssCredentials(new Microsoft.VisualStudio.Services.Common.WindowsCredential(new NetworkCredential("username", "password", "domain"))); VssConnection connection = new VssConnection(new Uri("http://v-tinmo-12r2:8080/tfs/MyCollection"),c); // Setup version control properties Dictionary<string, string> versionControlProperties = new Dictionary<string, string>(); versionControlProperties[TeamProjectCapabilitiesConstants.VersionControlCapabilityAttributeName] = SourceControlTypes.Git.ToString(); // Setup process properties ProcessHttpClient processClient = connection.GetClient<ProcessHttpClient>(); Guid processId = processClient.GetProcessesAsync().Result.Find(process => { return process.Name.Equals(processName, StringComparison.InvariantCultureIgnoreCase); }).Id; Dictionary<string, string> processProperaties = new Dictionary<string, string>(); processProperaties[TeamProjectCapabilitiesConstants.ProcessTemplateCapabilityTemplateTypeIdAttributeName] = processId.ToString(); // Construct capabilities dictionary Dictionary<string, Dictionary<string, string>> capabilities = new Dictionary<string, Dictionary<string, string>>(); capabilities[TeamProjectCapabilitiesConstants.VersionControlCapabilityName] = versionControlProperties; capabilities[TeamProjectCapabilitiesConstants.ProcessTemplateCapabilityName] = processProperaties; //Construct object containing properties needed for creating the project TeamProject projectCreateParameters = new TeamProject() { Name = projectName, Description = projectDescription, Capabilities = capabilities }; // Get a client ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>(); TeamProject project = null; try { Console.WriteLine("Queuing project creation..."); // Queue the project creation operation // This returns an operation object that can be used to check the status of the creation OperationReference operation = projectClient.QueueCreateProject(projectCreateParameters).Result; // Check the operation status every 5 seconds (for up to 30 seconds) Operation completedOperation = WaitForLongRunningOperation(connection, operation.Id, 5, 30).Result; // Check if the operation succeeded (the project was created) or failed if (completedOperation.Status == OperationStatus.Succeeded) { // Get the full details about the newly created project project = projectClient.GetProject( projectCreateParameters.Name, includeCapabilities: true, includeHistory: true).Result; Console.WriteLine(); Console.WriteLine("Project created (ID: {0})", project.Id); } else { Console.WriteLine("Project creation operation failed: " + completedOperation.ResultMessage); } } catch (Exception ex) { Console.WriteLine("Exception during create project: ", ex.Message); } return project; } private static async Task<Operation> WaitForLongRunningOperation(VssConnection connection, Guid operationId, int interavalInSec = 5, int maxTimeInSeconds = 60, CancellationToken cancellationToken = default(CancellationToken)) { OperationsHttpClient operationsClient = connection.GetClient<OperationsHttpClient>(); DateTime expiration = DateTime.Now.AddSeconds(maxTimeInSeconds); int checkCount = 0; while (true) { Console.WriteLine(" Checking status ({0})... ", (checkCount++)); Operation operation = await operationsClient.GetOperation(operationId, cancellationToken); if (!operation.Completed) { Console.WriteLine(" Pausing {0} seconds", interavalInSec); await Task.Delay(interavalInSec * 1000); if (DateTime.Now > expiration) { throw new Exception(String.Format("Operation did not complete in {0} seconds.", maxTimeInSeconds)); } } else { return operation; } } }
d10544
Breaking a string onto a newline without actually adding a character is a word wrap. JTextArea has word wrap. mytextArea.setLineWrap(true);
d10545
Ok. I seem to have found a solution and wanted to share it. The way to do this is to clear out all pending changes before proceeding. So if the SubmitChanges fails I now call this extension method on the datacontext - RejectPendingChanges(). When the next row is processed it now longer tries to resubmit bad data. public static void RejectPendingChanges(this System.Data.Linq.DataContext db){ var chgset = db.GetChangeSet(); if (chgset != null) { foreach (object objToInsert in chgset.Inserts) { db.GetTable(objToInsert.GetType()).DeleteOnSubmit(objToInsert); } //Undo deletes foreach (object objToDelete in chgset.Deletes) { db.GetTable(objToDelete.GetType()).InsertOnSubmit(objToDelete); } ///this._DB.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, chgset.Deletes); db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, chgset.Updates); } }
d10546
Detect selction and keyCode. Hope this will work for you. Only selected value will remove. arr = [08,127,46]; $(document).ready(function(){ document.getElementById('tust').onblur = issueDes; $("input").on("keyup keydown",function (e) { var checkCode = $.inArray( e.keyCode, arr ); if (window.getSelection) { var selectionRange = window.getSelection ().toString (); if((selectionRange.length > 0) && (checkCode != -1)){ var value = $("#tust").val(); $("#tust").val(value.replace(selectionRange,"")) } } if(this.value!='-') while(isNaN(this.value)) this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'').split('').reverse().join(''); }); }); function issueDes() { var currVal = this.value; if(currVal != "" && currVal.indexOf("%") == -1){ $("#tust").val(this.value+"%"); } } demo http://jsfiddle.net/farhanbaloch/awug6h9a/6/
d10547
in normal case input tag text-indent does not work in ie6 and ie7 If we add lineheight:1px it will work all browser Text-indent will work all browser <input type="text" style="text-indent:-100px; display:block; line-height:1px;" value="Test indent" /> Text-indent not will work ie7 and ie6 browser <input type="text" style="text-indent:-100px; display:block;" value="Test indent" /> demo http://jsfiddle.net/KczMR/1/ A: Are you sure that you want 'text-indent' instead of either the 'margin-left' or the 'padding-left' property? The 'text-indent' property is meant to affect only the first line of text in an element. You might have better luck with margin or padding.
d10548
DEMO Try this $(document).on('change', 'select', function () { var value = $(this).val(); var input = $(this).parents('td').next('td').find('input:text'); if (value == 'debit') { total -= parseInt(input.val()); } else if (value == 'credit') { total += parseInt(input.val()); } $('#diff').html('Differance:' + total); }); Hope this helps,Thank you A: $('select#type').on('change', function() { if($(this).val() === "debit"){ //Get the difference between 2 variables and store result in diff $("#diff").val(Math.abs(a - b)) }else if($(this).val() === "credit"){ //perform addition and store value in sum object $("#sum").val(x+y) } }); A: what about something like this? $('select[name="type"]').change(function() { if($(this).val() === 'credit') { $("#amount").val() += $('input[type="text"]').val() } else if($(this).val() === 'debit') { $("#amount").val() -= $('input[type="text"]').val() } }) I use the the change() function to trigger the change. I don't know if this is what you meant, but i hope it helped somehow. A: one issue corrected in more button click handlers. see the changes below: $("#more").click(function() { $(".vtable tr:last").clone().find("input, select").each(function() { $(this).attr({'id': function(_, id) { return id + 1 }}); }).end().appendTo(".vtable"); }); in order to handle the events for dynamically added select and input text, you can achieve it as follows. Note: .on() is used with your table as your are adding rows dynamically with select and input text. for select : $('.vtable').on('change', "select", function (e) { var valueSelected = this.value; alert(valueSelected); }); for input text $('.vtable').on('keyup', "input", function (e) { var valueEntered = this.value; alert(valueEntered ); });
d10549
Returning to css is a good idea in this case: precompile the final version. You can use SimpleLESS or similar compiler to do it. Reducing client-side resources is healthy, especially for mobile/responsive UIs.
d10550
Uncaught ReferenceError: Date is not defined Date is a variable name. You need a string. "Date". And in VS Code it tells me that key is declared but never read. .key doesn't refer to a variable. See also: Dynamically access object property using variable NB: dataJson has no return statement so it isn't going to return anything. See also How do I return the response from an asynchronous call?.
d10551
As a general rule of thumb: When you can do it with the aggregation pipeline, you should. One reason is that the aggregation pipeline is able to use indexes and internal optimizations between the aggregation steps which are just not possible with MapReduce. Aggregation is also a lot more secure when the operation is triggered by user input. When there are any user-supplied parameters to your query, MapReduce forces you to create javascript functions through string concatenation. This opens the door for dangerous Javascript code injection vulnerabilities. The APIs used for creating aggregation pipeline objects (in most programming languages!) usually has fewer such obvious pitfalls. There are, however, still a few cases which can not be done easily or not at all with aggregation. For these cases, MapReduce has still a reason to exist. Another limitation of the aggregation framework is that the intermediate dataset after each aggregation step is limited to 100MB unless you use the allowDiskUse option, which really slows down the query. MapReduce usually behaves a lot better when you need to work with a really large dataset.
d10552
As an avid android user. I think MediaStore is the "Public Link" between the internal Android Media Scanner Application (You can manually invoke it through Spare Parts) and 3rd party applications, like yours. I'm guessing MediaStore is this "public link" based on its android.provider packaging. As providers in android, is how applications provide information to other applications If MediaStore is a ContentProvider, reading information populated by MediaScanner. Then MediaStore is for User media, such as music, video, pictures etc. For ringtones, notifications; I think you are supposed to use android.media.RingtoneManager Also don't hardcode the path "/sdcard/" There is an api call to get it, Environment.getExternalStorageDirectory() http://twitter.com/cyanogen/status/13980762583 ==== The pro is that Media Scanner runs every time you mount the removable storage to the phone, and it also scans the internal memory (if it has any like the HTC EVO & incredible) A: I am no expert in this but as far as my common sense goes, well its the easy way to search for certain types of files. If your app has a library of sorts, then using MediaStore instead of searching all by yourself is more useful, faster and less power consuming. Also you can be assured that those are all the files present in the system. I hope this helps.
d10553
Try this code in ur onCreate protected CharSequence[] Months = { "January", "February", "March", "April", "May","June", "July", "August", "September","October","November","December" }; Button selected_month = ( Button ) findViewById( R.id.button ); selected_month.setOnClickListener(new View.OnClickListener(){ new AlertDialog.Builder( <Classname>.this ) .setTitle( "Months" ) .setSingleChoiceItems( Months, 0, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Toast.makeText(<Classname>.this, Months[which], Toast.LENGTH_SHORT).show(); } }) .setPositiveButton( "OK", new DialogButtonClickHandler() ) .setNegativeButton("No", new DialogButtonClickHandler() ) .create(); });
d10554
There you go .MuiOutlinedInput-notchedOutline { border-color: #fff;//for border color } .MuiSelect-icon { color: #fff;// for icon drop down icon color } .MuiInputLabel-root { color: #fff;// for lable color } For focus just add the parent .Mui-focused selector on these A: const useStyles = makeStyles(theme => ({ select: { borderColor: 'white' }, fomrControl{ margin: theme.spacing(1), minWidth: 120, color: 'white', } }));
d10555
You can try to use the History API with pushState and popState - in order to move from page to page seamlessly. What you're doing is bad and the mistake you're making will be more visible as more elements you put in your page. At the time JS kicks in (and DOM is ready etc) it's already too late to do hide() or .css({display: "none"}) because the page was building and visible. You'll end up having an ugly flashy unstable-looking website/application :( The "other" solution is to hide initially using CSS... but search engines will penalize you for that. Use an overlay A better way is to have a fixed full-size CSS visible overlay element - <div id="loaderOverlay"></div> that overlays your entire page content - and JS-(+CSS3) fadeOut that element instead (by adding a CSS class like) #loaderOverlay{ position: fixed; z-index: 99999; top:0; left:0; right:0; bottom:0; background: #fff; transition: 2s; /* transition timing */ } #loaderOverlay.hide{ /* JS-add this class on DOM ready or window load */ visibility: hidden; opacity: 0; } Triggering the "fadeOut" in jQuery look like: $(window).on("load", function(){ // The overlay is initially visible, we need to hide it! $("#loaderOverlay").addClass("hide"); // CSS3 will animate it nicely }); Now, the fadeIn problem... the **beforeunload** event will kick in at the moment when the page resources are just about to be unloaded. The unloading can last a couple of ms (+ waiting for HTTP requests...), clearly not enough time for an animation of 2s to take place - and the only way I see fit is to target all your links on the page, get the href attribute, prevent the browser to navigate - and navigate only on transitionend (not well supported) or after a 2100ms timeout period: // When we click on some link we want our overlay to show up! // Additionally instead of `"a"` you could make sure it's not an external link, // a #hash anchor etc... $(document).on("click", "a", function(evt) { evt.preventDefault(); // Don't navigate! var href = $(this).attr("href"); // grab the href // Animate-In our overlay $("#loaderOverlay").removeClass("hide"); // wait for CSS3 to animate-in the overlay and than navigate to our next page setTimeout(function() { window.location = href; // Navigate finally }, 2100); }); as you can see the above works for links, but clearly the browser's Back button is not a link in your page, and for that... recurse to the beginning of my answer.
d10556
After reinstalling the python as well as updating all the packages (conda update --all) and changing the PATH file, it seems that the issue is solved in all of my IDE's except PyCharm. It seems that all that remains is an interpreter issue. I will post updates if something else comes into my attention.
d10557
You can use .mask to set the 'flag' values to the .shifted version of itself where 'visit_time' values are notnull. out = df.assign( flag=df['flag'].mask(df['visit_time'].notnull(), df['flag'].shift()) ) print(out) code visit_time flag other counter 0 0 NaT True X 3 1 0 1 days 03:00:12 True Y 1 2 0 NaT False X 3 3 0 0 days 05:00:00 False X 2 4 1 NaT False Z 3 5 1 NaT True X 3 6 1 1 days 03:00:12 True Y 1 7 2 NaT True X 3 8 2 5 days 10:01:12 True Y 0 * *.mask(condition, other) replaces values where condition is True with the values of other in this case other is the value from the previous row. *.assign(…) is a way to update a column while returning a new DataFrame this can be replaced with column assignment df['flag'] = df['flag'].where(…) to modify the DataFrame in place. Creating a column from a string variable. df[name] = df[name].mask(df['visit_time'].notnull(), df[name].shift())) A: You can simply have a shifted dataframe as in: df_previous = df.copy() df_previous.index+=1 Looking like: code visit_time flag other counter 1 0 NaT True X 3 2 0 1 days 03:00:12 False Y 1 3 0 NaT False X 3 4 0 0 days 05:00:00 True X 2 5 1 NaT False Z 3 6 1 NaT True X 3 7 1 1 days 03:00:12 False Y 1 8 2 NaT True X 3 9 2 5 days 10:01:12 True Y 0 Now you can have it merge with original dataframe and assign values with simple vector comparisons: df = df.merge(df_previous[['visit_time', 'flag']], right_index=True, left_index=True, how='left', suffixes=["",'_previous']) df.loc[df.visit_time.notna(), 'flag'] = df.loc[df.visit_time.notna(), 'flag_previous'] Now your dataframe looks like: code visit_time flag other counter visit_time_previous flag_previous 0 0 NaT True X 3 nan nan 1 0 1 days 03:00:12 True Y 1 NaT 1 2 0 NaT False X 3 1 days 03:00:12 0 3 0 0 days 05:00:00 False X 2 NaT 0 4 1 NaT False Z 3 0 days 05:00:00 1 5 1 NaT True X 3 NaT 0 6 1 1 days 03:00:12 True Y 1 NaT 1 7 2 NaT True X 3 1 days 03:00:12 0 8 2 5 days 10:01:12 True Y 0 NaT 1 You can also remove previous columns if you like with: df.drop(list(df.filter(regex = '_previous')), axis = 1) Which will leave you with: code visit_time flag other counter 0 0 NaT True X 3 1 0 1 days 03:00:12 True Y 1 2 0 NaT False X 3 3 0 0 days 05:00:00 False X 2 4 1 NaT False Z 3 5 1 NaT True X 3 6 1 1 days 03:00:12 True Y 1 7 2 NaT True X 3 8 2 5 days 10:01:12 True Y 0 A: for row in df.iterrows(): if row[0] < df.shape[0] - 1: # stop comparing when getting to last row if df.at[row[0], 'visit_time'] == 'NaT' and df.at[row[0] + 1, 'visit_time'] != 'NaT': df.at[row[0] + 1, 'flag'] = df.at[row[0], 'flag'] Before: code visit_time flag other counter 0 0 NaT True X 3 1 0 1 days 03:00:12 False Y 1 2 0 NaT False X 3 3 0 0 days 05:00:00 True X 2 4 1 NaT False Z 3 5 1 NaT True X 3 6 1 1 days 03:00:12 False Y 1 7 2 NaT True X 3 8 2 5 days 10:01:12 True Y 0 After: code visit_time flag other counter 0 0 NaT True X 3 1 0 1 days 03:00:12 True Y 1 2 0 NaT False X 3 3 0 0 days 05:00:00 False X 2 4 1 NaT False Z 3 5 1 NaT True X 3 6 1 1 days 03:00:12 True Y 1 7 2 NaT True X 3 8 2 5 days 10:01:12 True Y 0
d10558
First of all, executing 10 doesn't make sense in real life. How can you execute a number? But, you can execute a command like exec("print(10)"). I don't see the need of creating a my_exec function. It behaves the same as the normal exec. In the interactive shell, everything works differently, so don't try to compare. Basically, exec("print(10)") is the command you are looking for. Another way not using exec is print(10).
d10559
I just tested this with my mobile phone. The user agent that is received by remote servers is both the same when I connect via WLAN and via GPRS (my SIM card is issued by China Mobile). There doesn't seem to be any filtering of user agents. Specifically, my browser's user agent string is: Mozilla/5.0 (webOS/2.1.0; U; en-GB) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 Pre/1.1 I'd say that neither a nor b is true.
d10560
As https://stackoverflow.com/users/13926890/mohit-jain mentioned you need to do this inside your js file, whenever you are invoking your modal either for closing or for opening it. function search_table(rowEle, value){ $(rowEle).each(function(){ var found = 'false'; $(this).each(function(){ if($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0) { found = 'true'; } }); if(found == 'true') { $('#yourIdHere').modal({show:true}); //in case it doesn't work, use this // $('#yourIdHere').modal('show'); } else { $('#yourIdHere').modal({show:false}); //in case it doesn't work, use this //$('#yourIdHere').modal('hide'); } }); }
d10561
This is a trade off since Higher CTR (Click Through Rate) means higher eCPM (estimated cost per mille (impression)) ads. However, with a faster refresh, you get more ad impressions but the CTR drops ad there is less screen time for an individual ad. For banners, I'd say about a 20-30s refresh rate is optimal. I know that for MoPub, you can set values lower than 10, but the minimum is around 10 seconds for refresh rate. You can run a a/b test programmatically on MoPub for two subsets of users, one with an ad unit with 20s and one with an ad unit with 30s and see which one performs better. For MoPub, you can automatically set refresh rate by editing the ad unit in the UI.
d10562
You can use the jQM popup widget with an iFrame. Here is a DEMO The link around the img now links to the popup id. I added a custom data attribute called data-popupurl that has the url for the iFrame and I added a class for a click handler as you will probably have multiple thumbnails on a page (NOTE: the data attribute could just hold the catalog id, or you could use another way to get the url): <a class="popupInfoLink" href="#popupInfo" data-rel="popup" data-position-to="window" data-popupurl="http://www.houzz.com/photos/6147609/T-Fal-I-Hoffmann-Stock-Pot-8-Qt--contemporary-cookware-and-bakeware-"><img src= "http://st.houzz.com/simgs/a1419d6702561831_3-4003/contemporary-cookware-and-bakeware.jpg" width="320" height="300" alt="pot" border="0" /></a> <div data-role="popup" id="popupInfo" data-overlay-theme="a" data-theme="d" data-tolerance="15,15" class="ui-content"> <iframe src="" width="400px" height="400px"></iframe> </div> The script simply responds to a click on the link by reading the url for the popup and then setting the iFrame src to that url. In your case the url would be product.asp?itemid=[catalogid] $( document ).on( "pageinit", "#page1", function() { $(".popupInfoLink").on("click", function(){ var url = $(this).data("popupurl"); $( "#popupInfo iframe" ).attr("src", url); }); }); A: Have a look at the target attribute of the anchor (a) tag. Here is the W3 Schools documentation. <a href="product.asp?itemid=[catalogid]" target="_blank"><img src= "/thumbnail.asp?file=[THUMBNAIL]&maxx=200&maxy=0" width="320" height="300" alt="[name]" border="0"></a> By the way, I strongly urge you not to do this. People don't like that, because they don't have a way of knowing that's the behavior before they do it. If people really want to open it in a new window or tab, then they can right click and do that. Keep one question per post is the Stack Overflow policy. But the best way to learn is by jumping in and doing tutorials. Don't ask questions until you've gotten seriously stuck. Part of learning to program is learning to figure things out on your own. A: So you don't want to pop open a new window, you want a dialog frame to appear overlayed on top of your other content? Have a look at the PopupControlExtender from the Ajax Control Toolkit. I don't know how well it will work in a jQuery Mobile environment, but it's worth a look. Sample code. <asp:Button runat="server" ID="Btn1" Text="Click Here For More Info" /> <ajaxToolkit:PopupControlExtender ID="PopEx" runat="server" TargetControlID="Btn1" PopupControlID="Panel1" Position="Bottom" /> <asp:Panel runat="server" id="Panel1"> Here is some more info! </asp:Panel> Or since you're using jQuery Mobile, why don't you stick with what they already provide for this? Have a look at jQuery Mobile panels or jQuery Mobile popups.
d10563
extend JPanel and add a name property that you want to save and read class MyPanel extends JPanel { public final int i; public final int j; public MyPanel(int i,int j){ super(); this.i = i; this.j = j; } } and for(int i=0;i<8;i++) { for( int j=0;j<8;j++) { jp[i][j]=new MyJPanel(i,j); p.add(jp[i][j]); jp[i][j].addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { MyPanel p = (MyPanel)e.getSource(); // p.i p.j } }); this.allSquares.add(jp[i][j]); // adding panel in arraylist of type Jpanel if(j%2==0&&i%2==0)// code to change background color of panels for chess board { jp[i][j].setBackground(Color.DARK_GRAY); } if(j%2!=0&&i%2!=0) { jp[i][j].setBackground(Color.DARK_GRAY); } } } and on click listener, cast panel to MyPanel MyPanel p = (MyPanel)object; String name = p.name;
d10564
I managed to display a window in the second monitor (placed at the right of the primary) by using the following code: window.Left = System.Windows.SystemParameters.VirtualScreenWidth / 2;
d10565
It looks like you have to pass callback as an option not a html attribute. https://github.com/rajeshwarpatlolla/ionic-datepicker#readme var options = { callback: function (val) { //Mandatory if(typeof(val) === 'undefined') { console.log('Date not selected'); } else { console.log('Selected date is : ', val); self.dateFrom = val; } } }; $scope.openDatePicker = function(){ ionicDatePicker.openDatePicker(options); };
d10566
This could be a solution: procedure Tar_ardemo.qr_ardemoBeforePrint(Sender: TCustomQuickRep; var PrintReport: Boolean); var QR: TquickRep; QB2: TQRBand; QB3: TQRChildBand; QL: TQRLabel; QS : string; begin with artikste do begin close; sql.Clear; sql.add('SELECT * FROM Artikels'); open; first; end; QR := QR_ARDEMO; QB2 := QRBAND2; QB2.HasChild := true; QB2.ChildBand.Height := 23; QL := TQRLabel.Create(QR); QL.Parent := QB2.ChildBand; QL.Left := 100; QL.Top := 1; QL.Width := 81; QL.Height := 23; QL.Caption := 'QRLabeXX'; QB2.ChildBand.HasChild := true; QB2.ChildBand.ChildBand.Height := 23; QL := TQRLabel.Create(QR); QL.Parent := QB2.ChildBand.ChildBand; QL.Left := 100; QL.Top := 1; QL.Width := 81; QL.Height := 23; QL.Caption := 'QRLabeYY'; QB2.ChildBand.ChildBand.HasChild := true; QB2.ChildBand.ChildBand.ChildBand.Height := 23; QL := TQRLabel.Create(QR); QL.Parent := QB2.ChildBand.ChildBand.ChildBand; QL.Left := 100; QL.Top := 1; QL.Width := 81; QL.Height := 23; QL.Caption := 'QRLabeZZ'; end; end. This works (huray). But now the problem is: How do I get an array of childband.chhildband......childband. There is no Childband array like Childband[x]. Or is there one?? As I wrote there could be many Childbands [n]. It has to be dynamic, and... after printing the first childbands, they must be destroyed, before printing the next childbands for the next record (Artikel).
d10567
Your statement The problem with the above method is that you can only set one unit of time ... is not correct. NSCalendarUnit conforms to the RawOptionSetType protocol which inherits from BitwiseOperationsType. This means that the options can be bitwise combined with & and |. In Swift 2 (Xcode 7) this was changed again to be an OptionSetType which offers a set-like interface, see for example Error combining NSCalendarUnit with OR (pipe) in Swift 2.0. Therefore the following compiles and works in iOS 7 and iOS 8: let date = NSDate() let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! // Swift 1.2: let components = cal.components(.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: date) // Swift 2: let components = cal.components([.Day , .Month, .Year ], fromDate: date) let newDate = cal.dateFromComponents(components) (Note that I have omitted the type annotations for the variables, the Swift compiler infers the type automatically from the expression on the right hand side of the assignments.) Determining the start of the given day (midnight) can also done with the rangeOfUnit() method (iOS 7 and iOS 8): let date = NSDate() let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! var newDate : NSDate? // Swift 1.2: cal.rangeOfUnit(.CalendarUnitDay, startDate: &newDate, interval: nil, forDate: date) // Swift 2: cal.rangeOfUnit(.Day, startDate: &newDate, interval: nil, forDate: date) If your deployment target is iOS 8 then it is even simpler: let date = NSDate() let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let newDate = cal.startOfDayForDate(date) Update for Swift 3 (Xcode 8): let date = Date() let cal = Calendar(identifier: .gregorian) let newDate = cal.startOfDay(for: date) A: Here's an example of how you would do it, without using the dateBySettingHour function (to make sure your code is still compatible with iOS 7 devices): NSDate* now = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *dateComponents = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:now]; NSDate* midnightLastNight = [gregorian dateFromComponents:dateComponents]; Yuck. There is a reason why I prefer coding in C#... Anyone fancy some readable code..? DateTime midnightLastNight = DateTime.Today; ;-) A: Swift iOS 8 and up: People tend to forget that the Calendar and DateFormatter objects have a TimeZone. If you do not set the desired timzone and the default timezone value is not ok for you, then the resulting hours and minutes could be off. Note: In a real app you could optimize this code some more. Note: When not caring about timezones, the results could be OK on one device, and bad on an other device just because of different timezone settings. Note: Be sure to add an existing timezone identifier! This code does not handle a missing or misspelled timezone name. func dateTodayZeroHour() -> Date { var cal = Calendar.current cal.timeZone = TimeZone(identifier: "Europe/Paris")! return cal.startOfDay(for: Date()) } You could even extend the language. If the default timezone is fine for you, do not set it. extension Date { var midnight: Date { var cal = Calendar.current cal.timeZone = TimeZone(identifier: "Europe/Paris")! return cal.startOfDay(for: self) } var midday: Date { var cal = Calendar.current cal.timeZone = TimeZone(identifier: "Europe/Paris")! return cal.date(byAdding: .hour, value: 12, to: self.midnight)! } } And use it like this: let formatter = DateFormatter() formatter.timeZone = TimeZone(identifier: "Europe/Paris") formatter.dateFormat = "yyyy/MM/dd HH:mm:ss" let midnight = Date().midnight let midnightString = formatter.string(from: midnight) let midday = Date().midday let middayString = formatter.string(from: midday) let wheneverMidnight = formatter.date(from: "2018/12/05 08:08:08")!.midnight let wheneverMidnightString = formatter.string(from: wheneverMidnight) print("dates: \(midnightString) \(middayString) \(wheneverMidnightString)") The string conversions and the DateFormatter are needed in our case for some formatting and to move the timezone since the date object in itself does not keep or care about a timezone value. Watch out! The resulting value could differ because of a timezone offset somewhere in your calculating chain! A: Swift 5+ let date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date()) A: Yes. You don't need to fiddle with the components of the NSCalendar at all; you can simply call the dateBySettingHour method and use the ofDate parameter with your existing date. let date: NSDate = NSDate() let cal: NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)! let newDate: NSDate = cal.dateBySettingHour(0, minute: 0, second: 0, ofDate: date, options: NSCalendarOptions())! For Swift 3: let date: Date = Date() let cal: Calendar = Calendar(identifier: .gregorian) let newDate: Date = cal.date(bySettingHour: 0, minute: 0, second: 0, of: date)! Then, to get your time since 1970, you can just do let time: NSTimeInterval = newDate.timeIntervalSince1970 dateBySettingHour was introduced in OS X Mavericks (10.9) and gained iOS support with iOS 8. Declaration in NSCalendar.h: /* This API returns a new NSDate object representing the date calculated by setting hour, minute, and second to a given time. If no such time exists, the next available time is returned (which could, for example, be in a different day than the nominal target date). The intent is to return a date on the same day as the original date argument. This may result in a date which is earlier than the given date, of course. */ - (NSDate *)dateBySettingHour:(NSInteger)h minute:(NSInteger)m second:(NSInteger)s ofDate:(NSDate *)date options:(NSCalendarOptions)opts NS_AVAILABLE(10_9, 8_0); A: Just in case someone is looking for this: Using SwiftDate you could just do this: Date().atTime(hour: 0, minute: 0, second: 0) A: In my opinion, the solution, which is easiest to verify, but perhaps not the quickest, is to use strings. func set( hours: Int, minutes: Int, seconds: Int, ofDate date: Date ) -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" let newDateString = "\(dateFormatter.string(from: date)) \(hours):\(minutes):\(seconds)" dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return dateFormatter.date(from: newDateString) } A: func resetHourMinuteSecond(date: NSDate, hour: Int, minute: Int, second: Int) -> NSDate{ let nsdate = NSCalendar.currentCalendar().dateBySettingHour(hour, minute: minute, second: second, ofDate: date, options: NSCalendarOptions(rawValue: 0)) return nsdate! } A: Use the current calendar to get the start of the day for the current time. let today = Calendar.current.startOfDay(for: Date())
d10568
You can resize the font of the xticks: plt.xticks(fontsize=6, rotation=90) A: Solution: plt.plot(x_train.T,"*") plt.xticks(rotation=90) plt.gcf().set_size_inches(30, 10) plt.show() Result:
d10569
You could use the same approach to animate route transitions: You can take a look at the relatebase blog (as well as the jsbin example referred by the blog). Essentially you handle a little state machine in the willTransition action: You abort the original transition and as soon as the user closes the dialog you retry the original transition. Hope it helps!
d10570
Have a look at RotationWheelAndDecelerationBehaviour. there is an example for how to do the deceleration for both linear panning and rotational movement. Trick is to see what is the velocity when user ends the touch and continue in that direction with a small deceleration. A: Well, I'm not a pro but, checking multiple answers, I managed to make my own code with which I am happy. Please tell me how to improve it and if there are any bad practices I used. - (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer { CGPoint translatedPoint = [recognizer translationInView:self.postViewContainer]; CGPoint velocity = [recognizer velocityInView:recognizer.view]; float bottomMargin = self.view.frame.size.height - containerViewHeight; float topMargin = self.view.frame.size.height - scrollViewHeight; if ([recognizer state] == UIGestureRecognizerStateChanged) { newYOrigin = self.postViewContainer.frame.origin.y + translatedPoint.y; if (newYOrigin <= bottomMargin && newYOrigin >= topMargin) { self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, self.postViewContainer.center.y + translatedPoint.y); } [recognizer setTranslation:CGPointMake(0, 0) inView:self.postViewContainer]; } if ([recognizer state] == UIGestureRecognizerStateEnded) { __block float newYAnimatedOrigin = self.postViewContainer.frame.origin.y + (velocity.y / 2.5); if (newYAnimatedOrigin <= bottomMargin && newYAnimatedOrigin >= topMargin) { [UIView animateWithDuration:1.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^ { self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, self.postViewContainer.center.y + (velocity.y / 2.5)); } completion:^(BOOL finished) { [self.postViewContainer setFrame:CGRectMake(0, newYAnimatedOrigin, self.view.frame.size.width, self.view.frame.size.height - newYAnimatedOrigin)]; } ]; } else { [UIView animateWithDuration:0.6 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^ { if (newYAnimatedOrigin > bottomMargin) { self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, bottomMargin + self.postViewContainer.frame.size.height / 2); } if (newYAnimatedOrigin < topMargin) { self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, topMargin + self.postViewContainer.frame.size.height / 2); } } completion:^(BOOL finished) { if (newYAnimatedOrigin > bottomMargin) [self.postViewContainer setFrame:CGRectMake(0, bottomMargin, self.view.frame.size.width, scrollViewHeight)]; if (newYAnimatedOrigin < topMargin) [self.postViewContainer setFrame:CGRectMake(0, topMargin, self.view.frame.size.width, scrollViewHeight)]; } ]; } } } I have used two different animation, one is the default inertia one and the other if for when the user flings the containerView with high velocity. It works well under iOS 7. A: I took the inspiration from the accepted answer's implementation. Here is a Swift 5.1 version. Logic: * *You need to calculate the angle changes with the velocity at which the pan gesture ended and keep rotating the wheel in an endless timer until the velocity wears down because of deceleration rate. *Keep decreasing the current velocity in every iteration of the timer with some factor (say, 0.9). *Keep a lower limit on the velocity to invalidate the timer and complete the deceleration process. Main function used to calculate deceleration: // deceleration behaviour constants (change these for different deceleration rates) private let timerDuration = 0.025 private let decelerationSmoothness = 0.9 private let velocityToAngleConversion = 0.0025 private func animateWithInertia(velocity: Double) { _ = Timer.scheduledTimer(withTimeInterval: self.timerDuration, repeats: true) { [weak self] timer in guard let this = self else { return } let concernedVelocity = this.currentVelocity == 0.0 ? velocity : this.currentVelocity let newVelocity = concernedVelocity * this.decelerationSmoothness this.currentVelocity = newVelocity var angleTraversed = newVelocity * this.velocityToAngleConversion * this.maximumRotationAngleInCircle if !this.isClockwiseRotation { angleTraversed *= -1 } // exit condition if newVelocity < 0.1 { timer.invalidate() this.currentVelocity = 0.0 } else { this.traverseAngularDistance(angle: angleTraversed) } } } Full working code with helper functions, extensions and usage of aforementioned function in the handlePanGesture function. // deceleration behaviour constants (change these for different deceleration rates) private let timerDuration = 0.025 private let decelerationSmoothness = 0.9 private let velocityToAngleConversion = 0.0025 private let maximumRotationAngleInCircle = 360.0 private var currentRotationDegrees: Double = 0.0 { didSet { if self.currentRotationDegrees > self.maximumRotationAngleInCircle { self.currentRotationDegrees = 0 } if self.currentRotationDegrees < -self.maximumRotationAngleInCircle { self.currentRotationDegrees = 0 } } } private var previousLocation = CGPoint.zero private var currentLocation = CGPoint.zero private var velocity: Double { let xFactor = self.currentLocation.x - self.previousLocation.x let yFactor = self.currentLocation.y - self.previousLocation.y return Double(sqrt((xFactor * xFactor) + (yFactor * yFactor))) } private var currentVelocity = 0.0 private var isClockwiseRotation = false @objc private func handlePanGesture(panGesture: UIPanGestureRecognizer) { let location = panGesture.location(in: self) if let rotation = panGesture.rotation { self.isClockwiseRotation = rotation > 0 let angle = Double(rotation).degrees self.currentRotationDegrees += angle self.rotate(angle: angle) } switch panGesture.state { case .began, .changed: self.previousLocation = location case .ended: self.currentLocation = location self.animateWithInertia(velocity: self.velocity) default: print("Fatal State") } } private func animateWithInertia(velocity: Double) { _ = Timer.scheduledTimer(withTimeInterval: self.timerDuration, repeats: true) { [weak self] timer in guard let this = self else { return } let concernedVelocity = this.currentVelocity == 0.0 ? velocity : this.currentVelocity let newVelocity = concernedVelocity * this.decelerationSmoothness this.currentVelocity = newVelocity var angleTraversed = newVelocity * this.velocityToAngleConversion * this.maximumRotationAngleInCircle if !this.isClockwiseRotation { angleTraversed *= -1 } if newVelocity < 0.1 { timer.invalidate() this.currentVelocity = 0.0 this.selectAtIndexPath(indexPath: this.nearestIndexPath, shouldTransformToIdentity: true) } else { this.traverseAngularDistance(angle: angleTraversed) } } } private func traverseAngularDistance(angle: Double) { // keep the angle in -360.0 to 360.0 range let times = Double(Int(angle / self.maximumRotationAngleInCircle)) var newAngle = angle - times * self.maximumRotationAngleInCircle if newAngle < -self.maximumRotationAngleInCircle { newAngle += self.maximumRotationAngleInCircle } self.currentRotationDegrees += newAngle self.rotate(angle: newAngle) } Extensions being used in above code: extension UIView { func rotate(angle: Double) { self.transform = self.transform.rotated(by: CGFloat(angle.radians)) } } extension Double { var radians: Double { return (self * Double.pi)/180 } var degrees: Double { return (self * 180)/Double.pi } }
d10571
This post actually helped me answer the question. https://community.powerbi.com/t5/Power-Query/Maxifs-Power-Query/m-p/1693606 The only difference I made was getting rid of the true/false portion to receive my results. Thus my result was: Max Status Value = VAR vMaxVal= CALCULATE ( MAX ( 'Table'[Status Value] ), ALLEXCEPT ( 'Table', 'Table'[Area] ) ) RETURN vMaxVal
d10572
It seems to ignore the ExchangePattern you set. Have you tried to set it on your JMS URI as activemq:queue:...&exchangePattern=InOut? I am not sure if you also need to define the JMSReplyTo header on the message or if this is done automatically when the exchangePattern is InOut. A: Use the request method on the producer as that is for InOut A: Following code works for me: def sendAndReceiveExtractionDetails(request:String, header: String) : String = { camel.createProducerTemplate() .sendBody("activemq:queue:extractor-jobs?requestTimeout=1400000", ExchangePattern.InOut, request).toString }
d10573
Yes. The JPQL specification even has some examples DELETE FROM Publisher pub WHERE pub.revenue > 1000000.0 A: Just realised that I don't need to consider the Map at all if I just view it from the side of the task, not the quest. DELETE FROM ActiveTask t WHERE t.activeQuest = :quest AND t.task = :taskname
d10574
You are passing .withArgs(3) to the update function. Does that set or influence the value of contentIndex? (e.g maybe loops the array 3 times). As it looks like the array entry is attempting to be retrieved for an index that is not in the array as you only add one item to it. Does this give you a value? //contentIndex value is 0 this.myData[0].reviewWindowExpiry Also think Date.UTC would return a function, try component.myData = [{'reviewWindowExpiry': Date.now()}]; To get the numeric millisecond value.
d10575
I'm not sure if this is the best way to go but, I could manage to make it work like follow. In your user model, make sure you have added :confirmable in devise. devise :database_authenticatable, :registerable, :confirmable, ..., Also you need your user table to have the following fields. t.string "confirmation_token" t.datetime "confirmed_at" t.datetime "confirmation_sent_at" Then in your user controller add the following method. def create_new_account @new_user = User.new(user_params) if @new_user.valid? @new_user.skip_confirmation! @new_user.confirmed_at = nil if @user.save render action: "some_action" else render action: "some_other_action" end end end When and a user creates a new account through that method and email will be send to the new account's email address with a confirmation token. That will forward the new user to a page asking them for there password. The email template that is being send can be fond at app/views/devise/mailer/confirmation_instructions.html.erb And in your routes make sure you have a post request to the controller's action. post "create_new_account" => "users#create_new_account" I'm not an expert on this but the way I understand this, is that you need the confirmation option in Devise to let your new user accounts enter there own password. But since the current admin user is already logged in. You need to skip the confirmation step. Again I'm not 100% sure this is the right way. I would be happy to hear what other people has to say about this.
d10576
there are two things that need to be addressed here. * *You can simply call QDialog.close in the connect method. *In def nextWindow(self): you are trying to connect a local variable quit. So it won't work. You need to define quit as an instance variable (self.quit) self.connect(self.quit, QtCore.SIGNAL('clicked()'), self.close) # this should work Here is the modified code: import sys from PyQt4 import QtGui, QtCore class WindowLV3(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setGeometry(300, 300, 120, 150) self.setWindowTitle('LV3') self.quit = QtGui.QPushButton('Close', self) self.quit.setGeometry(10, 10, 60, 35) self.connect(self.quit, QtCore.SIGNAL('clicked()'), self.close) # this will close entire program class WindowLV2(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.Window3 = WindowLV3() self.setGeometry(300, 300, 120, 150) self.setWindowTitle('LV2') self.quit = QtGui.QPushButton('Close', self) self.quit.setGeometry(10, 10, 60, 35) next = QtGui.QPushButton('Lv3', self) next.setGeometry(10, 50, 60, 35) self.connect(self.quit, QtCore.SIGNAL('clicked()'), self.close) # this should work self.connect(next, QtCore.SIGNAL('clicked()'), self.nextWindow) def nextWindow(self): self.Window3.show() class WindowLV1(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.Window2 = WindowLV2() self.setGeometry(300, 300, 120, 150) self.setWindowTitle('LV1') next = QtGui.QPushButton('Lv2', self) next.setGeometry(10, 50, 60, 35) self.quit = QtGui.QPushButton('Close', self) self.quit.setGeometry(10, 10, 60, 35) self.connect(next, QtCore.SIGNAL('clicked()'), self.nextWindow) def nextWindow(self): self.Window2.show() self.connect(self.quit, QtCore.SIGNAL('clicked()'), self.close) # this should work if __name__ == '__main__': app = QtGui.QApplication(sys.argv) Window1 = WindowLV1() Window1.show() sys.exit(app.exec_())
d10577
You can use row_number(). For instance, if the third column where datetime, then the following gets the most recent row: select t.* from (select t.*, row_number() over (partition by id order by datetime desc) as seqnum from table t ) t where seqnum = 1; A: Try to include in your query count(1) and group by all other columns. Also add having count1) > 1 in your query. Please take a look at the sample: with src as ( select '1' as id,'s1' as descr from dual union all select '1','s1' from dual union all select '2','s2' from dual ) select id,descr,count(*) from src group by id,descr having count(*) > 1
d10578
biometrics API provides BiometricConstants for error handling override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { super.onAuthenticationError(errorCode, errString) //The device does not have a biometric sensor. if (errorCode == BiometricPrompt.ERROR_HW_NOT_PRESENT){ //Do something } } A: I've faced the same problem, imho the short answer is to ignore the deprecation, as long as you only want to support fingerprint authentication in your app. As stated in the google dev blog, since API 28 google comes up with the new biometrics API, which simplifies the whole process of biometrics authentication. They provide a simple builder for the auth-dialog. Additionally, they support face and iris detection, too - imho it is just a matter of time if you want to support it and probably might be worth upgrading it. The only disadvantage I've discovered so far is that if you want to check if e.g. fingerprint hardware is available, you'll have to start the authentication process to check this out and wait for the error callback. The deprecated fingerprint API instead provides methods like isHardwareDetected() or hasEnrolledFingerprints() for this purpose. In this case, you would probably have to re-design your application, if you rely on this information. The reason for the deprecation of those methods is probably, that it only supports fingerprints, therefore it is not a bad idea to upgrade it. Google has also provided the compat 'androidx.biometric:biometric:1.0.0-alpha02' version for the devices below API 28, it seems that by importing this dependency, you could simply switch to USE_BIOMETRIC permission without modifying anything else in your app - you won't be bothered by the warning anymore. Since it is only in alpha stage, I would use it with care. Therefore, as long as you don't use anything from the biometrics API, you could also simply ignore the problem and face it again when you want to support additional biometric authentication methods. EDIT: Now, the beta version of compat library is released, 'androidx.biometric:biometric:1.0.0-beta01'. For more info on this, check here. Now, the stable version of compat library is released on December 18, 2019, 'androidx.biometric:biometric:1.0.1'. For more info on this Click here.
d10579
I think it depends on the version of MySQL. You might as well move the condition to the from clause, where it will only be executed once: SELECT c.* FROM car c.CROSS JOIN (SELECT `count` FROM carfeaturedcounter) x WHERE c.featured = 1 AND x.`count` > 5;
d10580
You don't get a declaration kind-of error because in C, when you do not forward declare a function most compilers assume an extern function that returns an int type. Actually the compiler should warn you about this (most do). Then later on when the compiler actually reaches the function implementation it finds a different return type, in this case a char, and then throws the "conflicting type" error. Just forward declare all the functions to avoid this kind of errors. About what would be the best way somthing like following code woudl yield a similar result: if (n > 9) { return('A' + (n - 10)); } A: Whatever you are doing in the code posted, you are not using double datatype at all, within the function. And from the function return type, it appears you will never see the return value >127. This code highlights some issues:(This is just illustrative) char hexRepresentation(double n){ if(n > 9){//comparing (double>int). Bad. if(n==10) return 'A'; if(n==11) return 'B'; if(n==12) return 'C';//You wrote if(double == int). Bad. if(n==13) return 'D'; if(n==14) return 'E'; if(n==15) return 'F'; } return (char)n; //again unsafe downgrade from 8 bytes double to 1 byte char. } Even if you fix your compiler error, you may not get the desired results always, due to such dangerous usage of datatype in the function. To know why its bad, look here: http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm I would use fabs(n) instead of n everywhere in that function body. And the error "conflicting types for 'hexRepresentation'" will be shown when there exists a prior declaration or definition of the same named function hexRepresentation before this function definition. Also, if you do not declare a function and it only appears after being called, it is automatically assumed to be int by the compiler. So, declare and define your function before main() or declare before main() and define the function anywhere else in the file, but, with the same function prototype. Do: char hexRepresentation(double); //Declaration before main main() { ... } char hexRepresentation(double n){//Definition after main ... } Or char hexRepresentation(double n){ //Declaration and definition before main ... } main() { ... } A: Just create one stack ( for char) which has push and pop functions. I am not returning the value just printing it there in the same function. (have implemented for integral values only) #define max 100 char a[max]; void hex(int n) { while(n>0) { int rem = n%16; if (rem<10) push(rem+'0'); elsif(rem >=10 && rem <16) { switch(rem) { case 10: push('A');break; case 11: push('B');break; case 12: push('C');break; case 13: push('D');break; case 14: push('E');break; case 15: push('F');break; } else n=n/16; } } i=0; while(top>-1) a[i++]=pop(); i=0; while(a[i]!='\0') printf("%c",a[i++]); } Is it helpful ?
d10581
Tthe main parts of your method works with Hibernate EntityManager, as I can see. So you should test this part, or mock it if possible. Also you can mock getTokenByUserToken(userToket). Here you can write several cases. So the possible test cases: * *getTokenByUserToken(usertoken) return null. So your method creates new Token and persist token to DB. The assertion em.createQuery("select token t...."). Here you validate that new token persists to DB *getTokenByUserToken(usertoken) return not persisted in DB token. Here you can expect the exception, when the EntityManager tries to remove this token. It's a good way to find, that some exception cases aren't properly handled in the code *getTokenByUserToken(usertoken) returns existing token (you can insert it to DB before this test for example). Here you test the removing of existing token and creating of the new token.
d10582
If you do not want load config file over http, try to use config.js file. Rename config.json to config.js and change content to this: var config = { "restApiUrl": "https://jboss_host:8443/back/rest/", "ldapAuthentication" : true } Then include config file into index.html in your application: <script type="text/javascript" src="config.js"></script> In angular application you can access to this config via (<any>window).config. For more convenient use create ConfigService like: @Injectable({providedIn: 'root'}) export class ConfigService { getConfig(): Config { // You should create some model of your config too or you can use 'any' return (<any>window).config; } } A: @mpstv thank you for your replay. I was able to solve this, by using the power of java servlet. The solution was adding to the project war the WEB-INF folder ( servlet.class + web.xml ) that will charge the config file from the filesystem and serve it to the angular, while HTTP call.
d10583
use List::MoreUtils qw(natatime); my $input_string = "6;7;8;9;1;17;4;5;90"; my $it = natatime 3, split(";", $input_string); my $output_string; while (my @vals = $it->()) { $output_string .= join(";", @vals)."\n"; } A: Here is a quick and dirty answer. my $input_string = "6;7;8;9;1;17;4;5;90"; my $count = 0; $input_string =~ s/;/++$count % 3 ? ";" : "\n"/eg; A: Don't have time for a full answer now, but this should get you started. $string = "6;7;8;9;1;17;4;5;90"; $Nth_number_of_semicolons_to_replace = 3; my $regexp = '(' . ('\d+;' x ($Nth_number_of_semicolons_to_replace - 1)) . '\d+);'; $string =~ s{ $regexp ) ; }{$1\n}xsmg A: sub split_x{ my($str,$num,$sep) = @_; return unless defined $str; $num ||= 1; $sep = ';' unless defined $sep; my @return; my @tmp = split $sep, $str; while( @tmp >= $num ){ push @return, join $sep, splice @tmp, 0, $num; } push @return, join $sep, @tmp if @tmp; return @return; } print "$_\n" for split_x '6;7;8;9;1;17;4;5;90', 3 print join( ',', split_x( '6;7;8;9;1;17;4;5;90', 3 ) ), "\n"; A: my $string = "6;7;8;9;1;17;4;5;90"; my $Nth_number_of_semicolons_to_replace = 3; my $num = $Nth_number_of_semicolons_to_replace - 1; $string =~ s{ ( (?:[^;]+;){$num} [^;]+ ) ; }{$1\n}gx; print $string; prints: 6;7;8 9;1;17 4;5;90 The regex explained: s{ ( # start of capture group 1 (?:[^;]+;){$num} # any number of non ';' characters followed by a ';' # repeated $num times [^;]+ # any non ';' characters ) # end of capture group ; # the ';' to replace }{$1\n}gx; # replace with capture group 1 followed by a new line A: If you've got 5.10 or higher, this could do the trick: #!/usr/bin/perl use strict; use warnings; my $string = '1;2;3;4;5;6;7;8;9;0'; my $n = 3; my $search = ';.*?' x ($n -1); print "string before: [$string]\n"; $string =~ s/$search\K;/\n/g; print "print string after: [$string]\n"; HTH, Paul
d10584
You are very close. spread funciton from the tidyr package is what you need. library(tidyverse) ICGC_2 <- ICGC %>% spread(submitted_sample_id, methylation_value) %>% remove_rownames() %>% column_to_rownames(var = "probe_id") ICGC_2 X932-01-4D X932-01-6D cg00000029 0.6 0.4 cg00000108 0.3 0.7 cg00000109 0.9 0.1 Data: ICGC <- read.table(text = "submitted_sample_id probe_id methylation_value 1 'X932-01-4D' cg00000029 0.6 2 'X932-01-6D' cg00000029 0.4 3 'X932-01-4D' cg00000108 0.3 4 'X932-01-6D' cg00000108 0.7 5 'X932-01-4D' cg00000109 0.9 6 'X932-01-6D' cg00000109 0.1", header = TRUE, stringsAsFactors = FALSE) A: In base R you can do this: wICGC <- reshape(ICGC, idvar = "probe_id", timevar = "submitted_sample_id", direction = "wide") wICGC <- data.frame(wICGC[,-1], row.names=wICGC[,1]) wICGC # methylation_value.X932.01.4D methylation_value.X932.01.6D # cg00000029 0.6 0.4 # cg00000108 0.3 0.7 # cg00000109 0.9 0.1 A: For a different perspective, you can also use melt in reshape. library(reshape) m <- melt(IGC, id=c("submitted_sample_id", "probe_id")) cast(m, probe_id~submitted_sample_id) > cast(m, probe_id~submitted_sample_id) probe_id X932-01-4D X932-01-6D 1 cg00000029 0.6 0.4 2 cg00000108 0.3 0.7 3 cg00000109 0.9 0.1
d10585
Probably I've found the problem. I look the message in 'original mode' I found in the header that google says 'MISSING ID' and I try to add this code: MailMessage.MsgId := '1234567890@drinkmessage.it'; MailMessage.ExtraHeaders.Values['Message-Id'] := MailMessage.MsgId; Now it seems to work fine. thanks A: Have you tried changing HeloName and MailAgent of IdSMTP? If you use the same domain with PHPMailer, my guess is GMail considers emails coming from your application as spam because it doesn't detect/like the application which is sending them.
d10586
Because it is platform-independent that way. Let's put it this way: They could create a DLL with some specific entry-point, and assume it's always consumed by IIS via ISAPI. But what about the cases where you don't run it on IIS, not via ISAPI, and not on Windows ? That's right, you'd have to program some modules for each and every webserver out there, in order for it to be able to interact with your DLL. Plus you'd need a web-server. You might also need to update all of those modules whenever something changes. And then you need to package it for a boatload of different Linux distros, plus Mac and Windows, and Android and iPhone, etc. And why would you do that ? For that it only runs on IIS and only on Windows ? Bad idea. Nowadays, most servers run Linux, so do most routers and printers, while most mobiles run Android (aka Linux) or iOS, and most TV OSes are Linux-based. If you have a main method, you can create a simple console program, with which can start a web-server on a certain port, which you can then use to forward traffic to (from NGINX/Apache via remote-proxy). Or you can forward SSL traffic directely to that web-server via HAproxy. No IIS or ISAPI required. If you use HAproxy, no NGINX or Apache required, too - because you can forward directely to kestrel. And if it must, it can run inside IIS as well. Maybe that makes IIS integration a little bit more complicated, but it also makes integrating into a Linux/Unix/Mac-environment (or any other, such as mobile phones) so much easier. And as said, most servers use Linux nowadays. Especially if run in containers like Docker/LXC. It would be absolutely breathtakingly monumentally stupid to do anything else but that. Also, it's a silent admission that they (MS) lost in the server space, and are now salvaging what there is to salvage (however, that last sentence is just my opinon, not necessarely a fact). A: Why is it required. * *Point 1: We don't have Global.asax that derives from HttpApplication, the entry point, and the main component that configures everything require to set up the ASP.NET pipeline, even if you have no Global.asax, as soon as a request comes to IIS HttpApplication object is created by the framework that holds HttpRequest, HttpResponse object, in .NET Framework. Similarly in .NET Core, to configure the Request Processing pipeline, anyhow you need to call Startup and provide him all the necessary configurations, which is done by the Main() while creating the Host. *Point 2: ASP.NET Core is cross-platform, and Kestrel is the built-in server that is going to host the app on all platforms except on windows where you can host in-process, so you need to configure Kestrel and tell him to host the App, this is done by the UseKestrel() extension method, at the same time IIS, can also be used as a reverse proxy, obviously, on windows, you will never use reverse proxy as you have the option to host in-process, but if you wish then you can configure using UseIISIntegration() extension method, now you might be thinking, where all these methods are, these are defaults and host.CreateDeafultBuilder() does all these for you. Configuring Logging, DI, Services, reading Configuration from sources like appsettings.json or appsettings.{environment}.json etc are all done while creating the host. Now I think, you got the Idea behind Main().
d10587
Got the answer from the Devexpress Team I can actually use pEditRefreshSum.JSProperties("cpID") = pEditRefreshSum.ID; to set the ID into a custom Property and then get it on js using the following line: form1.hfRaiseEvent.value = s.cpID; in order to get the ID Thanks for your replies. A: I don't think you have assigned anything to the ID of the ASPxEdit. It is null by default. You have to explicitly assign an ID. The ID property is inherited from System.Web.Control. See the MSDN documentation.
d10588
Problem: Currently you're storing your ViewHolder in a class level field, which is being set in getView(), its going to be set to the latest ViewHolder every time ListView is calling getView() and there's absolutely no guarantee in the order of the position the getView() is called for. Its going to get random ViewHolder references, creating problems for you to track position So a class level ViewHolder isn't good solution. Solution: You need to keep track of position related to every check box. Tag the position to checkbox and get it in the listener as follow: mHolder.txtFavorite.setOnCheckedChangeListener(mCheckedChangeListener); mHolder.txtFavorite.setTag(position+""); //tag position as String object Now you can get this position in your listener: public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //Since we set position in form of String, we need to convert String to int int position = Integer.parseInt(buttonView.getTag()); } A: You save position of mHolder.txtFavorite to tag, so you should just read the right position from tag, not from text positionArray.put(htlId.indexOf(mHolder.txtFavorite.getTag()), isChecked);
d10589
try to see output in json instead of html because in my Postman it is displayed correctly. you should set Content type of Response of API to json to avoid any issues like this. If doesn't help please comment with output as json in postman.
d10590
Adding 'f:view contentType="text/html"' solved the problem. Read this in http://www.primefaces.org/faq.html A: <p:column sortBy="#{tup.docTypeAndDirection}" > <f:facet name="header"> <h:outputText value="Document Type"/> </f:facet> <h:outputText value="#{tup.docTypeAndDirection}"/> </p:column> <p:column sortBy="#{tup.partnerEDIAddress}" > <f:facet name="header"> <h:outputText value="Partner Trading Address"/> </f:facet> <h:outputText value="#{tup.partnerEDIQual}:#{tup.partEDIAddr}"></h:outputText> </p:column> </p:dataTable>
d10591
1) Open your terminal 2) Type flutter doctor --android-licenses 3) If you don't see y/n option , continue hitting enter key to read through the license 4) When you get option to press Y/N , press Y to accept every license. A: You should run flutter clean in terminal. Then restart your IDE. It will resolve the issues A: To accept licences run this flutter doctor --android-licenses then y to accept
d10592
By the sounds of it your development environment is a Windows machine I'm guessing, which makes use of back slashes (\) when referencing directory paths. However on UNIX systems (Ubuntu in your case) the system uses forward slashes (/). Good news however, even though the Windows system uses backslashes, running PHP scripts in Windows will recognise both back slashes and forward slashes as the same, so you can use the one without having to change it every time you run the script in a different OS. TL;DR: Use / instead of \. It'll work on both Windows and Ubuntu.
d10593
git log takes zero or more commits as arguments, showing the history leading up to that commit. When no argument is given, HEAD is assumed. For your case, you want to supply the two branch heads you want to compare: git log --graph --oneline currentbranch otherbranch If it doesn't display too much, you can simplify this by using git log --graph --oneline --all which acts as if you had specified every reference in .git/refs as the commits to display. A: I had the same issue and landed here, but no answer helped me to display how two branches are diverging. Eventually I did experiment myself and found this worked. Given branch A and branch B, I want to see where they diverged. git log --oneline --graph --decorate A B `git merge-base A B`^! Note: Don't forget there is ^! at the end. (It excludes the parents of the commit returned by merge-base.) UPDATE The one line command above isn't working in case merge base is more than one. In this case do this: git merge-base A B -a # e.g. output XXXX YYYY git log --oneline --graph --decorate A B --not XXXX^ YYYY^ A: git log --graph --abbrev-commit --decorate --date=relative --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all
d10594
The simplest way to do that, it's to clone a minor part of html. You're cloning everything including the cloned part. After data-bug-item create a div with same name just to identify and clone JUST the form and not all informations inside the div. Example: $("#add_row").on('click', addRow); function addRow() { $("#form-data-bug-item").clone().insertAfter(".data-bug-item"); }; <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script language="javascript" type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script language="javascript" type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <div id="dataBug" class="bug-section"> <div class="row"> <div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12"> <button type="button" class="btn" name="add_row" id="add_row"> <span class="glyphicon glyphicon-plus-sign"></span> Add Row </button> </div> </div> <div class="form-group required data-bug-item"> <div id="form-data-bug-item"> <label class="control-label" for="type"><span class="label label-default">Column & Description:</span></label> <div class="row"> <div class="col-xs-3 col-sm-3 col-md-2 col-lg-2"> <select class="form-control" name="frm_column" id="frm_column" required> <option value="">--Choose--</option> <option value="1">Location</option> <option value="2">Name</option> <option value="3">Year</option> <option value="4">City</option> </select> </div> <div class="col-xs-9 col-sm-9 col-md-10 col-lg-10"> <input class="form-control" type="text" name="frm_descr" id="frm_descr" placeholder="Enter Description" required> </div> </div> </div> </div> </div> Now you just need to clone form-data-bug-item PS: I'm not considering another things on your code, just the solution.
d10595
The value you want out of the event object is called keyCode, not keycode: var canvas = document.getElementById("maincanvas"); var context = canvas.getContext("2d"); var keys = []; var width = 500, height = 400, speed = 3; var player = { x: 10, y: 10, width: 20, height: 20 }; window.addEventListener("keydown", function(e) { keys[e.keyCode] = true; }, false); window.addEventListener("keyup", function(e) { delete keys[e.keyCode]; }, false); /* up - 38 down - 40 left - 37 right - 39 */ function game() { update(); render(); } function update() { if (keys[38]) player.y -= speed; if (keys[40]) player.y += speed; if (keys[37]) player.x -= speed; if (keys[39]) player.x += speed; } function render() { context.clearRect(0, 0, 100, 100) context.fillRect(player.x, player.y, player.width, player.height); } setInterval(function() { game(); }, 1000 / 30); <canvas id="maincanvas"></canvas> A: Another issue you might be running into is that keys is an array and you are treating it like an object. keys[38] is looking for a key at index 38 NOT a key with a value of 38. Set keys = {}; Edit Never mind, I see you are just setting the index at 38. I would say it's a little bit of a weird approach, consider using an object rather than an array.
d10596
perhaps you're lookig for groupby? df.groupby(by=["sls"]).sum() group by docs: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html
d10597
Easy: ListBoxes.Add( new KeyValuePair<string, List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>>("A", new List<KeyValuePair<string, List<KeyValuePair<string, bool>>>> { new KeyValuePair<string,List<KeyValuePair<string,bool>>>("B", new List<KeyValuePair<string,bool>>() { new KeyValuePair<string,bool>("C", true) } ) } ) ); It looks like you could use some helper methods or something. Edit If you create a simple extension method, then the task becomes maybe a bit more readable. public static List<KeyValuePair<TKey, TValue>> AddKVP<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> self, TKey key, TValue value) { self.Add( new KeyValuePair<TKey, TValue>(key, value) ); // return self for "fluent" like syntax return self; } var c = new List<KeyValuePair<string, bool>>().AddKVP("c", true); var b = new List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>().AddKVP("b", c); var a = new List<KeyValuePair<string, List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>>>().AddKVP("a", b); Edit #2 If you define a simple type, then it helps a bit more: public class KVPList<T> : List<KeyValuePair<string, T>> { } public static KVPList<TValue> AddKVP<TValue>(this KVPList<TValue> self, string key, TValue value) { self.Add(new KeyValuePair<string, TValue>(key, value)); return self; } var ListBoxes = new KVPList<KVPList<KVPList<bool>>>() .AddKVP("A", new KVPList<KVPList<bool>>() .AddKVP("B", new KVPList<bool>() .AddKVP("C", true))); Edit #3 One more and I promise I'll stop. If you define "Add" on the type, then you can use implicit initialization: public class KVPList<T> : List<KeyValuePair<string, T>> { public void Add(string key, T value) { base.Add(new KeyValuePair<string,T>(key, value)); } } var abc = new KVPList<KVPList<KVPList<bool>>> { { "A", new KVPList<KVPList<bool>> { { "B", new KVPList<bool> { { "C", true }} }} }};
d10598
Note that GDB 6.4 is 4 years old. You might get better luck with (current) GDB 7.0. It is also possible that the devli executable is corrupt (file just looks at the first few bytes of the executable, but GDB requires much more of the file contents to be self-consistent). Does readelf --all > /dev/null report any warnings?
d10599
I was reaching this problem as well and this seemed to solve my problem. (It builds for me and deploys the application, but then fails to run while still connected. If I stop the connection and restart the app so that it is only running from the phone, it runs perfectly fine.) * *In Xcode, select the folder view in the left pane top menu and select your project in the left pane. *Then in the menu above the main panel, select Build Settings. *In Build Settings, make sure that "All" is selected (not "Basic") *Scroll down to Build Options and set "Bitcode Enabled" to NO.
d10600
Try changing the for loop to: for (; i <= (Number(currentPage) + 4) && i < pages; i++) { That should do the trick for the 10 you want to remove. Hope it works, not sure it will, can't test it right now. If you won't get it working in like 2 hours, I can help you then, when I could test it on my example. Edit: The 10 got removed. We simply changed "less than or equal" to "less than", meaning the last for cycle didn't get executed because we were at the last cycle of the last page already. Now for the 1: var i = (Number(currentPage) > 5 ? Number(currentPage) - 4 : 1) You should change this i declaration. What this code tells us is: If the number of the current page is higher than 5 do: Number(currentPage) - 4 else 1 And because we are using the i variable as a starting point in our for loop, we should change the 1 to 2. So the correct declaration should be: var i = (Number(currentPage) > 5 ? Number(currentPage) - 4 : 2) Second edit: Now for the ... problem: You can probably change i !== 1 to i !== 2 That should fix it, it's the same principle, we are starting for loop from 2, so we have to change it to 2. We are telling it: don't show ... when we are on pages: 1, 2, 3, 4, 5 now.