text
stringlengths
15
59.8k
meta
dict
Q: Why cannot the load part of the atomic RMW instruction pass the earlier store to unrelated location in TSO(x86) memory consistency model? It's known that x86 architecture doesn't implement sequential consistency memory model because of usage of write buffers, so that store->load reordering can take place (later loads can be committed while the earlier stores still reside in write buffers waiting for the commit to L1 cache). In A Primer on Memory Consistency and Coherence we can read about Read-Modify-Write(RMW) operations in Total Store Order(TSO) memory consistency model (which is supposed to be very similar to x86): ... we consider the RMW as a load immediately followed by a store. The load part of the RMW cannot pass earlier loads due to TSO’s ordering rules. It might at first appear that the load part of the RMW could pass earlier stores in the write buffer, but this is not legal. If the load part of the RMW passes an earlier store, then the store part of the RMW would also have to pass the earlier store because the RMW is an atomic pair. But because stores are not allowed to pass each other in TSO, the load part of the RMW cannot pass an earlier store either. Ok, atomic operation must be atomic, i.e. the memory location accessed by RMW can't be accessed by another threads/cores during the RMW operation, but what, if the earlier store passes by load part of the atomic operation is not related to the memory location accessed by RMW? Assume we have the following couple of instructions (in pseudocode): store int32 value in 0x00000000 location atomic increment int32 value in 0x10000000 location The first store is added to the write buffer and is waiting for its turn. Meanwhile, the atomic operation loads the value from another location (even in another cache line), passing the first store, and adds store into the write buffer next after the first one. In global memory order we'll see the following order: load (part of atomic) -> store (ordinal) -> store (part of atomic) Yes, maybe it's not a best solution from the performance point of view, since we need to hold the cache line for the atomic operation in read-write state until all preceding stores from the write buffer are committed, but, performance considerations aside, are there any violations of TSO memory consistency model is we allow for the load part of RMW operation to pass the earlier stores to unrelated locations? A: You could ask the same question about any store + load pair to different addresses: the load may be executed earlier internally than the older store due to out-of-order execution. In X86 this would be allowed, because: Loads may be reordered with older stores to different locations but not with older stores to the same location (source: Intel 64 Architecture Memory Ordering White Paper) However, in your example, the lock perfix would prevent that, because (from the same set of rules): Locked instructions have a total order This means that the lock would enforce a memory barrier, like an mfence (and indeed some compilers use a locked operation as a fence). This will usually make the CPU stop the execution of the load until the store buffer has drained, forcing the store to execute first. A: since we need to hold the cache line for the atomic operation in read-write state until all preceding stores from the write buffer are committed, but, performance considerations aside If you hold a lock L while you do operations S that are of same nature as those prevented by L, that is there exist S' that can be blocked (delayed) by L and S can be blocked (delayed) by L', then you have the recipe for a deadlock, unless you are guaranteed to be the only actor doing that (which would make the whole atomic thing pointless).
{ "language": "en", "url": "https://stackoverflow.com/questions/42820121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Convert address to longitude and latitude I want to do the following - Allow users to input a physical address in ios app. - This address is converted to longitude/latitude - Django server code checks to see nearby locations. How can I do this most efficiently? Should I convert the address to longitude and latitude in ios app and then send the coordinates to django server code, or should I send the address to django server code and then covert address to longitude and latitude? any help would be appreciated! A: According to the Apple's Location Awareness Programming Guide You can achieve this using a CLGeocoder object: CLGeocoder* geocoder = [[CLGeocoder alloc] init]; [geocoder geocodeAddressString:@"Your Address" completionHandler:^(NSArray* placemarks, NSError* error){ for (CLPlacemark* aPlacemark in placemarks) { // Process the placemark. } }]; A CLPlacemark object has a property called location that yields latitude and longitude for the place. A: You can use this function to get (latitude, longitude) tuple on the django side import urllib, urllib2 import simplejson as json def getLatLng( address ): """ Native address format is House Number, Street Direction, Street Name, Street Suffix, City, State, Zip, Country """ TIMEOUT = 3 try: url = "http://maps.google.com/maps/api/geocode/json?address=" + urllib.quote_plus( address.encode('utf-8') ) + "&sensor=false" opener = urllib2.build_opener() req = urllib2.Request( url ) data = json.load( opener.open(req, None, TIMEOUT) ) results = data['results'] if len( results ): location = results[0]['geometry']['location'] return ( location['lat'], location['lng'] ) else: return None except: return None A: Use the below link,this will return json which consist of latitude and longitude for the physical address. http://maps.google.com/maps/api/geocode/json?address=Newyork&sensor=false
{ "language": "en", "url": "https://stackoverflow.com/questions/16694409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Meteor JS meteor pages showing all records on new account create I have found bug in my application. I believe that it's problem with meteor-pages pagination or with some data being cached. I'm also using stardard accounts package for logging and signing up. The problem is that if I have two tabs opened in my browser, and on one of them I log out, create a new account and immediately log out from that new account, then when I change to that second browser tab, and log in on my normal account and switch to one of views I can see all items of BrandCampaignsPagination pagination, which shouldn't happen, instead I should only be able to see my personal campaigns. Everything goes back to normal when I reload my browser tab. Below you can see my pagination: @BrandCampaignsPagination = new Meteor.Pagination Campaigns, availableSettings: filters: true sort: true perPage: 10 templateName: 'campaignPaginate' itemTemplate: 'singleCampaign' navShowFirst: false navShowLast: false maxSubscriptions: 100 divWrapper: false And also controller: class Brands.CampaignsController extends Brands.BaseController action: -> @render "brandsCampaigns#{@params.status.capitalize()}" waitOn: -> Meteor.subscribe 'brandCampaignsProposals', @params.status Meteor.subscribe 'money-package-fxrates' onStop: -> BrandCampaignsPagination.unsubscribe() onRerun: -> BrandCampaignsPagination.unsubscribe() @next() onBeforeAction: -> BrandCampaignsPagination.set filters: userId: Meteor.userId() status: @params.status @next() I even tried onStop and onRerun hooks to force unsubscription on pagination collection but it didn't work. Any ideas? A: I have solution, the problem was with pagination and lack of authentication function, with the extension for pagination posted below everything works like a charm. @BrandCampaignsPagination = new Meteor.Pagination Campaigns, availableSettings: filters: true sort: true perPage: 10 templateName: 'campaignPaginate' itemTemplate: 'singleCampaign' navShowFirst: false navShowLast: false maxSubscriptions: 100 divWrapper: false auth: (skip,subscription) -> alwaysFilters = userId: subscription.userId userPagination = BrandCampaignsPagination.userSettings[subscription._session.id] || {} userFilters = userPagination.filters || {} userSort = userPagination.sort || {} unless _.contains _.values(CampaignStatuses), userFilters.status userFilters.status = CampaignStatuses.PUBLISHED filters = _.extend alwaysFilters, status: userFilters.status options = sort: userSort, skip: skip, limit: @perPage [filters,options]
{ "language": "en", "url": "https://stackoverflow.com/questions/30168521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Aggregate result of sub query to comma separated values How to get get the result of subquery as comma separated values. I have three tables , location and stock_location_type and location_label. I am joining location and stock_location_type and based on the result of SLT.inventory_location_cd , I am querying another table location_label. To do that I am writing following query. select L.stock_catalogue_id, SLT.inventory_location_cd, case when nventory_location_cd = 'base location' then (select related_location_id from location_label where base_location_id = location_id) when nventory_location_cd != 'base location' then (select base_location_id from location_label where related_location_id = location_id) end as "Current Location", * from location L join stock_location_type SLT on L.stock_location_type_id = SLT.stock_location_type_id; These subquueries returns multiple rows. I tried using string_agg and casting related_location_id and base_location_id (as they are UUIDs). But then it complains about group by. If I use group by then it errors out , 'multiple rows returned by subquery'. What am I missing? A: I recreated your set of tables with A location_label table create table location_label(location_id int, location_label varchar); insert into location_label values(1, 'Home'); insert into location_label values(2, 'Office'); insert into location_label values(3, 'Garage'); insert into location_label values(4, 'Bar'); A stock_location_type table create table stock_location_type (stock_location_type_id int, inventory_location_cd varchar); insert into stock_location_type values(1, 'base location'); insert into stock_location_type values(2, 'Not base location'); A location table create table location (stock_catalogue_id int, base_location_id int, related_location_id int, stock_location_type_id int); insert into location values(1,1,2,1); insert into location values(1,2,1,2); insert into location values(1,3,3,1); insert into location values(2,4,3,1); insert into location values(2,3,1,1); insert into location values(2,2,4,2); If I understand your statement correctly you are trying to join location and location_label tables based on the inventory_location_cd column using either base_location_id or location_id. If this is what you're trying to achieve, the following query should do it. By moving the join condition in the proper place select L.stock_catalogue_id, SLT.inventory_location_cd, location_id "Current Location Id", location_label "Current Location Name" from location L join stock_location_type SLT on L.stock_location_type_id = SLT.stock_location_type_id left outer join location_label on ( case when inventory_location_cd = 'base location' then base_location_id else related_location_id end) = location_id ; result is stock_catalogue_id | inventory_location_cd | Current Location Id | Current Location Name --------------------+-----------------------+---------------------+----------------------- 1 | base location | 1 | Home 1 | Not base location | 1 | Home 1 | base location | 3 | Garage 2 | base location | 3 | Garage 2 | base location | 4 | Bar 2 | Not base location | 4 | Bar (6 rows) if you need to aggregate it up by stock_catalogue_id and inventory_location_cd, that can be achieved with select L.stock_catalogue_id, SLT.inventory_location_cd, string_agg(location_id::text, ',') "Current Location Id", string_agg(location_label::text, ',') "Current Location Name" from location L join stock_location_type SLT on L.stock_location_type_id = SLT.stock_location_type_id left outer join location_label on (case when inventory_location_cd = 'base location' then base_location_id else related_location_id end) = location_id group by L.stock_catalogue_id, SLT.inventory_location_cd; with the result being stock_catalogue_id | inventory_location_cd | Current Location Id | Current Location Name --------------------+-----------------------+---------------------+----------------------- 1 | base location | 1,3 | Home,Garage 1 | Not base location | 1 | Home 2 | base location | 3,4 | Garage,Bar 2 | Not base location | 4 | Bar (4 rows) A: You can use the string_agg function to aggregate the values in a comma-separated string. So your sub-queries needs to be rewritten to select string_agg(related_location_id, ', ') from location_label where base_location_id = location_id and select string_agg(base_location_id, ', ') from location_label where related_location_id = location_id
{ "language": "en", "url": "https://stackoverflow.com/questions/66980969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Check if character equals \ in C++ I'm trying to see if a character c equals \ if (c == '\') //do something I don't know exactly how this is called but everything after \ turns in a character string. A: \ backslash is an escape character. Escape sequences are used to represent certain special characters within string literals and character literals. Read here So you should do: if (c == '\\'){ } A: You need escape sequences: \\ backslash byte 0x5c in ASCII encoding Change the code to if (c == '\\') A: Backslash is used as the escape character in C++, as it is in many other languages. If you want a literal backslash, you need to use \\: if (c == '\\') { }
{ "language": "en", "url": "https://stackoverflow.com/questions/37316619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Django Admin - Create an object and Create+Add a many other object (ForeignKey) I have a 'Test'(:a.k.a exam) model that can contain an indeterminate number of questions. I would like to be able to create these tests directly in the Admin part of Django. How should I proceed? Do I have to program the logic from scratch or Django has already thought about this case? class Question(models.Model): question = models.CharField() answer_a = models.Boolean() solution_a = models.Boolean() ... class Test(models.Model): name = models.CharField() ... class TestQuestion(models.Model): """connect many questions to a test""" test_fk = models.ForeignKey(Test) question_fk = models.ForeignKey(Question) A: The Django tutorial explains very well how to do this Part 07: # Admin.py class QuestionsOfTestInline(admin.StackedInline): model = QuestionsOfTest extra = 3 class Test_Admin(admin.ModelAdmin): inlines = [QuestionsOfTestInline] admin.site.register(Test, Test_Admin) This answer was posted as an edit to the question Django Admin - Create an object and Create+Add a many other object (ForeignKey) by the OP Hugo under CC BY-SA 3.0.
{ "language": "en", "url": "https://stackoverflow.com/questions/48363069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gap between ons-toolbar and statusbar iOS I am using the onsenUI framework in combination with Cordova in order to create a hybrid application. For some reason I observe a gap between the toolbar (text) and the iOS statusbar (iPhone 6s, iOS 11) which is larger then should, see the link for an example. example of toolbar To troubleshoot this issue and to be sure the issue in not caused by my own code I took the code of the very simple example of the toolbar reference at https://onsen.io/v2/api/js/ons-toolbar.html to see what happened on the same iPhone (no own css file used) and the same behaviour is observed. I am using Cordova to build the App and used the basis settings for the config.xml which are part of the standard Cordova app template. I am applying version 2.8.2 of Onsen, also tried the CDN version. I am using a real iPhone for testing build via XCode. To confirm it’s not Cordova, I also used plain HTML and also a kitchensick from Framework7 and for both no gap was observed with the same Cordova setup, so something is related with the Onsen setup. The gap is not shown while running the app in a browser. Do anyhow has the same behavior and/or an idea what is going on? A: You have to add viewport-fit=cover to the viewport meta tag of your index.html <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, viewport-fit=cover">
{ "language": "en", "url": "https://stackoverflow.com/questions/47512017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python + Scrapy + JSON : 'NoneType' object has no attribute 'body_as_unicode' I am trying to scrape all the urls from this JSON page with Scrapy in Python: view-source:https://highape.com/bangalore/all-events But whenever I write this code on my Scrapy shell: import json #it works jsonresponse = json.loads(response.body_as_unicode()) I get the following error: Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'NoneType' object has no attribute 'body_as_unicode' This is a portion of that big json file: { "@context":"http://schema.org", "@type":"Event", "name":"Combo Offers at Fill n Chill", "image":"https://highape.com/images/https://res.cloudinary.com/https-highape-com/image/upload/v1536231551/yyfdntyzgsuuctlrqw94.jpg", "url":"https://highape.com/bangalore/events/combo-offers-at-fill-n-chill-QRkdny0WXv", "startDate":"2018-09-07 12:00:00", "endDate":"2018-10-31 00:00:00", "doorTime":"2018-09-07 12:00:00", "description" : "Good food and fine drink are among the finer things life has to offer Fill n Chill has recognized this and therefore brings to you several offers packaged with scrumptious food and plenty of alcohol to wash it down Take a look at this and decide how you want to splurge and indulge1 Individual PassINR 349 2 Mugs of Beer 330ml 2 Domestic Drinks 30ml 1 StarterChoices belowBeer Draught Beer KingfisherDomestic Drinks Mixer Inclusions Served with Water SodaRum Captain Morgan Old MonkVodka Romanov Magi", "location": {"@type":"Place", "name":"Fill &#039;n Chill", "address":"107/2, 80 Feet Road, Srinivagilu Main Rd, Koramangala 4th Block, Koramangala, Bengaluru, Karnataka 560034, India" }, "offers": [ { "@type":"Offer", "name":"Individual Pass - 2 Drinks+1 Food", "price":"349", "priceCurrency":"INR", "validFrom":"2018-09-06 12:52:28", "availability":"http://schema.org/InStock", "url":"https://highape.com/bangalore/events/combo-offers-at-fill-n-chill-QRkdny0WXv" }, { "@type":"Offer", "name":"Pass for 2 people - 4 Drinks +1 Food", "price":"499", "priceCurrency":"INR", "validFrom":"2018-09-06 12:52:28", "availability":"http://schema.org/InStock", "url":"https://highape.com/bangalore/events/combo-offers-at-fill-n-chill-QRkdny0WXv" }, { "@type":"Offer", "name":"Pass for 2 people - 4 Drinks + 2 Food", "price":"599", "priceCurrency":"INR", "validFrom":"2018-09-06 12:52:28", "availability":"http://schema.org/InStock", "url":"https://highape.com/bangalore/events/combo-offers-at-fill-n-chill-QRkdny0WXv" }, { "@type":"Offer", "name":"Entry", "price":"0", "priceCurrency":"INR", "validFrom":"2018-09-06 12:52:28", "availability":"http://schema.org/InStock", "url":"https://highape.com" } ] , "performer": [ { "@type":"Person", "name": "" } ] } I need to scrape URLs like this (it would be quite helpful if you suggest a solution without involving Beautiful Soup) : "url":"https://highape.com/bangalore/events/combo-offers-at-fill-n-chill-QRkdny0WXv"
{ "language": "en", "url": "https://stackoverflow.com/questions/52784129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where does keras actually initialize the dataset? I'm trying to figure out the implementation of SGD in tensorflow, especially how keras/tensorflow actually initializes and dispatches the dataset. In the constructor (__init__ method) of class TensorLikeDataAdapter, self._dataset is initialized by this line https://github.com/tensorflow/tensorflow/blob/r2.5/tensorflow/python/keras/engine/data_adapter.py#L346 self._dataset = dataset I tried to print the value out with this line print('enumerate_epochs self._dataset', list(self._dataset)) and I got <_OptionsDataset shapes: ((None, 2), (None,)), types: (tf.float32, tf.float32)> which seems to indicate that the dataset hasn't yet been actually loaded. At the very begining of the enumerate_epochs method https://github.com/tensorflow/tensorflow/blob/r2.5/tensorflow/python/keras/engine/data_adapter.py#L1196 I added this line def enumerate_epochs(self): print('enumerate_epochs self._dataset', list(self._dataset)) and I got 3 (I set epoch=3) of the actual dataset, which means the dataset has been initialized and randomized somewhere before. I went through the whole data_adapter.py but failed to locate where the dataset is actually initialized. highlight I also tried this line print('data_handler._dataset', data_handler._dataset) for epoch, iterator in data_handler.enumerate_epochs(): and I got data_handler._dataset <_OptionsDataset shapes: ((None, 2), (None,)), types: (tf.float32, tf.float32)> However, this line def _truncate_execution_to_epoch(self): print('_truncate_execution_to_epoch self._dataset', list(self._dataset)) gives 3 (epoch=3) of the actual dataset, which means somewhere just in between the dataset is actually initialized though I couldn't imagine where it could be! I also tried class DataHandler print('DataHandler self._dataset', list(self._dataset)) self._configure_dataset_and_inferred_steps(strategy, x, steps_per_epoch, class_weight, distribute) and I got this error AttributeError: 'DataHandler' object has no attribute '_dataset' Could someone help me to see the light at the end of the tunnel.
{ "language": "en", "url": "https://stackoverflow.com/questions/68506744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: NSUserDefaults and sandboxing under Lion Moving one of my projects to support sandboxing as per Apple's requirements. I use UserDefaults like so: [[NSUserDefaults standardUserDefaults] setObject:@(myNumber) forKey:myNumberKey]; [[NSUserDefaults standardUserDefaults] synchronize]; Everything works as expected until I enable sandboxing. If I have sandboxing enabled the app creates a lock file in it's sandbox directory ( .plist.lockfile) and doesn't create an actual .plist file. What am I doing wrong and how do I store my settings in UserDefaults under sandbox environment? Update: Installed fresh 10.7.3 with the latest Xcode on a separate Mac - the same project compiles and works fine with sandboxing enabled. Also I've tried to run this project on my Mac where the sandbox doesn't work under different user account (freshly created) with exactly the same results - no go. At this point I think the problem is with system configuration on this particular mac. Question is though - is it safe to assume that I'm the only one with this weird problem? Probably not... A: That should work fine. If the preferences system is able to create the lock file, that means your app has appropriate privileges to create files in that directory and has correctly looked up the location where it should put them. Therefore, something else must be going wrong. Is there any Console logging when this occurs? What's the return value of -synchronize? (aside: in general -synchronize is not necessary and will just make your app slower, NSUserDefaults will handle that itself)
{ "language": "en", "url": "https://stackoverflow.com/questions/9268547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What am I doing wrong with my Java code for input validation? So this program is supposed to be a game where a user enters a phrase and another user tries to guess the phrase. I'm having a problem with buying a vowel, however. No matter what I enter at line 41 (, it just goes past the loop. I made the validAnswer(String answer) method in the hopes that it would be useful in the loop but it doesn't look to be much help. I know there is a small thing I'm missing but I'm too new to Java to recognize it yet. What am I doing wrong? I apologize for the long amount of code. import java.util.Scanner; public class PhraseGame { public static void main(String[] args) { // Initialize scanner Scanner stdIn = new Scanner(System.in); // Initialize variables String sPhrase; String answer = "f"; char cGuess = 0; char vGuess = 0; int count = 0; int vowels = 0; int consonants = 0; int spaces = 0; boolean gameOver = false; boolean correct = true; // Start the "fun" game System.out.print("Please enter the phrase to guess at: "); sPhrase = stdIn.nextLine(); // Create the temporary Array char [] tmpArr = new char[sPhrase.length()]; for (int i = 0; i < sPhrase.length(); i++) { tmpArr[i] = sPhrase.charAt(i); } // Gets the number of spaces spaces = initTemplateArray(sPhrase, tmpArr, spaces); printTemplateArray(tmpArr); while (!(endGame(gameOver, spaces, consonants, vowels, sPhrase))) { cGuess = getConsonant(stdIn, cGuess); do { System.out.print("\nWould you like to buy a vowel?: "); answer = stdIn.next(); if (answer == "y") { getVowel(stdIn, vGuess); } else if (answer == "n"){ break; } } while (!validAnswer(answer)); // Updates the array and prints it updateTemplateArray(tmpArr, sPhrase, cGuess, vGuess, count, vowels, consonants); printTemplateArray(tmpArr); // Checks if the game is over endGame(gameOver, spaces, consonants, vowels, sPhrase); } } // returns the number of space characters used in the common phrase public static int initTemplateArray(String sPhrase, char [] tmpArr, int spaces) { for (int i = 0; i < sPhrase.length(); i++) { if (tmpArr[i] != ' ') { tmpArr[i] = '?'; } else { tmpArr[i] = ' '; spaces++; } } return spaces; } public static void printTemplateArray(char [] tmpArr) { System.out.println("\nCommon Phrase"); System.out.println("-------------"); for (int i = 0; i < tmpArr.length; i++) { System.out.print(tmpArr[i]); } } public static boolean isVowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } public static char getConsonant(Scanner stdIn, char cGuess) { do { System.out.println("\nEnter a lowercase consonant guess: "); cGuess = stdIn.next().charAt(0); } while (isVowel(cGuess)); return cGuess; } public static char getVowel(Scanner stdIn, char vGuess) { do { System.out.println("\nEnter a lowercase vowel guess: "); vGuess = stdIn.next().charAt(0); } while (!(isVowel(vGuess))); return vGuess; } public static int updateTemplateArray(char [] tmpArr, String sPhrase, char cGuess, char vGuess, int count, int vowels, int consonants) { for (int i = 0; i < sPhrase.length(); i++) { if (cGuess == sPhrase.charAt(i)) { tmpArr[i] = sPhrase.charAt(i); count++; consonants++; } if (vGuess == sPhrase.charAt(i)) { tmpArr[i] = sPhrase.charAt(i); count++; vowels++; } } return count & vowels & consonants; } public static boolean endGame(boolean gameOver, int spaces, int consonants, int vowels, String sPhrase) { int total = spaces + consonants + vowels; if (total == sPhrase.length()) { return true; } else { return false; } } public static boolean validAnswer(String answer) { if (answer.equalsIgnoreCase("y")) { return true; } else if (answer.equalsIgnoreCase("n")) { return true; } else { return false; } } } A: You need to check for null. public static boolean validAnswer(String answer) { if (answer!=null && (answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("n"))) { return true; } return false; } or an other unconventional way. public static boolean validAnswer(String answer) { if ("y".equalsIgnoreCase(answer) || "n".equalsIgnoreCase(answer))) { return true; } return false; } You need to fix do { System.out.print("\nWould you like to buy a vowel?: "); answer = stdIn.nextLine(); if ("y".equalsIgnoreCase(answer)) { getVowel(stdIn, vGuess); } else if ("n".equalsIgnoreCase(answer)){ break; } } while (!validAnswer(answer));
{ "language": "en", "url": "https://stackoverflow.com/questions/34005518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to keep running RecognizerIntent and get the speech to text string from the mic input string rec = global::Android.Content.PM.PackageManager.FeatureMicrophone; if (rec == "android.hardware.microphone") { var voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech); voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm); voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1500); voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1500); voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 15000); voiceIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 1); voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default); _activity.StartActivityForResult(voiceIntent, 10); } else { throw new Exception("No mic found"); } I'm passing the current activity using "Plugin.CurrentActivity" plugin.What I want to do is continuously run the listener without prompting google speech popup.Listener should not stop until it stop by a button.
{ "language": "en", "url": "https://stackoverflow.com/questions/64318820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to toggle boolean value received from another widget I would like to pass boolean initial boolean values as arguments to a stateful widget and then change its value besides updating the UI. As it stands, I only see the initial value and am not able to toggle the value. The code and the screenshots are as follows: This is the widget from which I'm passing the arguments: class OtherStuff extends StatefulWidget { OtherStuffState createState() => OtherStuffState(); } class OtherStuffState extends State<OtherStuff> { @override Widget build(BuildContext context) { var provider = Provider.of<ModelClass>(context).data; // TODO: implement build return Container( width: double.infinity, height: 150, color: Colors.transparent, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( margin: const EdgeInsets.only(left: 5), child: const Text('Gets more interested with this', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18 )), ), SizedBox(height: 5), Row( children: [ StuffCards('https://static.toiimg.com/thumb/60892473.cms?imgsize=159129&width=800&height=800', false), //passing first value as false SizedBox(width: 10), StuffCards('https://thestayathomechef.com/wp-content/uploads/2016/06/Fried-Chicken-4-1.jpg', true), //passing second value as true SizedBox(width: 10), StuffCards('https://www.foodrepublic.com/wp-content/uploads/2012/03/033_FR11785.jpg', false), //passing third value as false ], ) ], ) ); } } The stateful widget: class StuffCards extends StatefulWidget { final String imageUrl; final bool clickedValue; //receiving the argument StuffCards(this.imageUrl, this.clickedValue); StuffCardsState createState() => StuffCardsState(); } class StuffCardsState extends State<StuffCards> { @override Widget build(BuildContext context) { var clicked = widget.clickedValue; void clickedFav() { setState(() { clicked = !clicked; //toggling the value received }); } // TODO: implement build return Stack( children: [ // Container( // width: 120, // ), Positioned( child: Container( width: 110, height: 120, margin: const EdgeInsets.only(left: 10), decoration: BoxDecoration( color: Theme.of(context).primaryColorDark, borderRadius: const BorderRadius.only( topRight: Radius.circular(100), topLeft: Radius.circular(100), bottomRight: Radius.circular(20), bottomLeft: Radius.circular(20), ) ), child: Padding( padding: const EdgeInsets.only(top: 60), child: Container( width: double.infinity, height: 60, decoration: BoxDecoration( color: Theme.of(context).primaryColorDark, ), child: Column( children: [ Text('Fried Squid', style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white )), Container( width: 75, color: Colors.transparent, child: Text( '₹ 245', style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 20 )), ), Container( width: double.infinity, height: 16, padding: EdgeInsets.only(right: 2, bottom: 1), child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ InkWell( onTap: clickedFav, //The inkwell doesn't seem to respond and update the UI child: clicked ? Icon( Icons.favorite, color: Colors.red, size: 15 ) : Icon( Icons.favorite_border, color: Colors.white, size: 15 ) ) ], ), ) ], ), ), ), ), ), Strangely enough, upon clicking the Inkwell widget, the value does get changed i.e If I click it and if the boolean value is false, it gets changed to true but doesn't change back to false. Also, as stated again, the UI doesn't update. A: Your UI doesn't change because StuffCards('https://static.toiimg.com/thumb/60892473.cms?imgsize=159129&width=800&height=800', false), Will never change. When you call setstate in the StuffCards class, the widget gets a rebuild, but with the same parameters. So you have two options here * *you make a function in the OtherStuffState class that toggles the value, and you pass that function on to the StuffCards class, en you call that function when the ontap event occurs in the InkWell. *you use provider to store the data and you make a function in the modelclass to toggle the card, so you just have to call in the StuffCards class context.read<ModelClass>().toggleCard(cardNumber)
{ "language": "en", "url": "https://stackoverflow.com/questions/70782553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Identify what button triggered new frame Below is my code startBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showTimePickerDialog(view); } }); endBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showTimePickerDialog(view); } }); public void showTimePickerDialog(View v) { DialogFragment newFragment = new TimePickerFragment(); newFragment.show(getFragmentManager(), "timePicker"); } @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { String time = String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute); Log.d("DTAG", "Time Selected:" + time); //How to know here what button triggered the new fragment } How can I know what button triggered the action without setting some new values outside functions? Like startBtnClicked=true;
{ "language": "en", "url": "https://stackoverflow.com/questions/47792495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Deriving Typeable for Text.PrettyPrint.Doc I have an AST type that I want to derive as Typeable, so that I can do Scrap-your-boilerplate generic traversals of it. However, the tree is annotated with messages in the Doc type of the Text.PrettyPrint library from the pretty package. To derive Typeable, there needs to be a typeable instance of Doc. Here's what I've tried and failed: deriving instance Data P.Doc deriving instance Typeable P.Doc gives this error: Can't make a derived instance of `Data P.Doc': The data constructors of `P.Doc' are not all in scope so you cannot derive an instance for it In the stand-alone deriving instance for `Data P.Doc' Or, I try to derive my own instance: instance Typeable P.Doc where typeRep v = typeRep $ show v which gives this error: `typeRep' is not a (visible) method of class `Typeable' Am I doing something wrong? Is there a standard way to derive typeable for types given in other libraries? The thing is, the instance isn't super important. I know that there aren't any parts of my AST stored recursively within a Doc value. But GHC complains if I don't have that instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/27726555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Posting data into JSON format I am working on iPhone application. Here I am trying to post my data with following code : NSDictionary *contactData = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:score] ,@"score", [NSNumber numberWithInt:game_id] ,@"game_id", game_version ,@"game_version", platform ,@"platform", [NSNumber numberWithInt:timestamp] ,@"timestamp", [NSNumber numberWithInt:elapsed_time] ,@"elapsed_time", hash ,@"hash", [NSNumber numberWithInt:level_reached] ,@"level_reached", verification ,@"verification", nil]; [request1 addPostValue:contactData forKey:@"plays[]"]; And I want to generate following format : Array ( [plays] => Array ( [0] => Array ( [score] = 513956 [game_id] = 1 [game_version] = 1.0 [platform] = Web [timestamp] = 1313146039 [elapsed_time] = 400 [hash] = 61e51000143566bfddjfhdeur88cb7b2ad [level_reached] = 5 [verification] = e56a35341c7854dref82ad678cb11593 ) ) [module] => play [action] => save ) How it can be implemented where I have to make changes or where I am making mistakes. Please help me. I am stuck on that. A: Assuming you return valid JSON from your (?) web service, you can use JSONKit to convert from and to JSON. PHP has json_encode and json_decode for this purpose. See here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7074241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: PhoneGap for windows phone 7 I'm interested in developing applications for windows phone 7 with the PhoneGap. I know that there may not have an official version of PhoneGap for windows mobile yet, but I tried to run two projects, but got errors when implementing them. * *1st project: https://github.com/filmaj/phonegap-winphone *2nd project: https://github.com/mrlacey/phonegap-wp7 Errors: * *1st application: Warning message! You are using a project created by previous version of Windows Phone Developer Tools CTP. Your application may not run properly. Please edit the WMAppManifest.xml file under Properties node and insert the following elements between element as shown below. <Capabilities> <Capability Name="ID_CAP_NETWORKING" /> <Capability Name="ID_CAP_LOCATION" /> <Capability Name="ID_CAP_SENSORS" /> <Capability Name="ID_CAP_MICROPHONE" /> <Capability Name="ID_CAP_MEDIALIB" /> <Capability Name="ID_CAP_GAMERSERVICES" /> <Capability Name="ID_CAP_PHONEDIALER" /> <Capability Name="ID_CAP_PUSH_NOTIFICATION" /> <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" /> </Capabilities> * *After inserting those fields, i got many errors on "Errors list". *2nd application output message: C:\Users...\mrlacey-phonegap-wp7-1dcce5b\WP7Gap\WP7Gap\WP7Gap.csproj : error : Unable to read the project file 'WP7Gap.csproj'. C:\Users...\mrlacey-phonegap-wp7-1dcce5b\WP7Gap\WP7Gap\WP7Gap.csproj(135,3): The imported project "C:\Program Files (x86)\MSBuild\Microsoft\Silverlight for Phone\v4.0\Microsoft.Silverlight.WindowsPhone71.Overrides.targets" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk. A: You need https://github.com/phonegap/phonegap-wp7 Please note that this is still not really production ready yet though. We're hoping that it will be there by the time Mango launches though. Note that this is targetting the Mango beta 2 refresh. I'd assume that you're not using that. The one you got from my site looks like a very old version. Get the latest version. I've updated my github profile so you can contact me through there now. A: For the record :) Use the latest lib of phonegap for WP7 from: https://github.com/callback/phonegap/tree/master/lib/windows
{ "language": "en", "url": "https://stackoverflow.com/questions/6945266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Graph algorithm solution done right? I stumbled upon a problem from the last Facebook Hacker Cup (so it's NOT my homework, I just find it very interesting) and I also thought of a curious, but rather good, solution. Could you please check my thought? Here is the task: You are given a network with N cities and M bidirectional roads connecting these cities. The first K cities are important. You need to remove the minimum number of roads such that in the remaining network there are no cycles that contain important cities. A cycle is a sequence of at least three different cities such that each pair of neighbouring cities are connected by a road and the first and the last city in the sequence are also connected by a road. Input The first line contains the number of test cases T. Each case begins with a line containing integers N, M and K, which represent the number of cities, the number of roads and the number of important cities, respectively. The cities are numbered from 0 to N-1, and the important cities are numbered from 0 to K-1. The following M lines contain two integers a[i] and b[i], 0 ≤ i < M, that represent two different cities connected by a road. It is guaranteed that 0 ≤ a[i], b[i] < N and a[i] ≠ b[i]. There will be at most one road between two cities. Output For each of the test cases numbered in order from 1 to T, output "Case #i: " followed by a single integer, the minimum number of roads that need to be removed such that there are no cycles that contain an important city. Constraints 1 ≤ T ≤ 20 1 ≤ N ≤ 10000 1 ≤ M ≤ 50000 1 ≤ K ≤ N Example In the first example, we have N=5 cities that are connected by M=7 roads and the cities 0 and 1 are important. We can remove two roads connecting (0, 1) and (1, 2) and the remaining network will not contain cycles with important cities. Note that in the remaining network there is a cycle that contains only non-important cities, and that there are also multiple ways to remove two roads and satisfy all conditions. One cannot remove only one road and destroy all cycles that contain important cities. Example input 1 5 7 2 0 1 1 2 1 4 0 2 2 4 2 3 3 4 So I thought of it that way: while building the graph, let's have a separate array storing information on how many neighbors does every city have (==how many roads are there connected to the given city). In the example case, city 0 has 2, city 1 has 3 and so on. Let's call this numbers a "city value" of a particular city. After obtaining the whole input, we go through the whole array of city values looking for cities with value 1. When getting to one, it means it can't be in a cycle so we decrement its value, "delete" (without the loss of generality) the road connecting it to its only neighbor and decrement the neighbor's value. After that, we recursively go to the neighbor checking for the same thing, if the value is 1 there - repeat the scheme and recursively go deeper. If it's not - don't touch. After that operation we've cleared all the parts of the graph which are not cycles and can't be a part of one. We also got rid of all the roads removing which didn't make sense whatsoever. So we call another function, this time - working only on the important cities. So we take the vertex 1 - after the use of the function described in the previous paragraph, its value can't be 1 (as it would have already been made zero by the function) so it's either 0 or something >1. In the first case, we don't have to do anything. In the latter, we have to make the value 1 which is done by doing value-1 removals. Similarly to the previous paragraph, after each removal, we decrement the value of both this city and its neighbor also removing the road. We repeat it for all the k important cities summing the value-1's from all of the important cities and that's our answer. Does it make any sense? For all the tests I've tried it worked and I'd like to believe it's correct but I somehow feel there may be a leak somewhere. Could you please check it? Is it any good? If not, why and is there anything correct about this thought process? :) A: Here was an incorrect solution. Counterexample for your solution. Suppose, that one in square is the only one important. Your solution will delete one road. A: If you can prove that the optimal number of cuts is equal to the number of different cycles* that contain an important node, solving the problem is not that hard. You can do a DFS, keep track of visited nodes, and whenever you reach a node that you already visited you got a cycle. To tell whether the cycle contains an important node or not, keep track of the depth at which each node was visited and remember the depth of the last important node in the current branch of the search. If the cycle's start depth is less (i.e. earlier) than the last important node's depth, the cycle contains an important node. C++ implementation: // does not handle multiple test cases #include <iostream> #include <vector> using namespace std; const int MAX = 10000; int n, m, k; vector<int> edges[MAX]; bool seen[MAX]; int seenDepth[MAX]; // the depth at which the DFS visited the node bool isImportant(int node) { return node < k; } int findCycles(int node, int depth, int depthOfLastImp) { if (seen[node]) { if (seenDepth[node] <= depthOfLastImp && (depth - seenDepth[node]) > 2) { // found a cycle with at least one important node return 1; } else { // found a cycle, but it's not valid, so cut this branch return 0; } } else { // mark this node as visited seen[node] = true; seenDepth[node] = depth; // recursively find cycles if (isImportant(node)) depthOfLastImp = depth; int cycles = 0; for (int i = 0; i < edges[node].size(); i++) { cycles += findCycles(edges[node][i], depth + 1, depthOfLastImp); } return cycles; } } int main() { // read data cin >> n >> m >> k; for (int i = 0; i < m; i++) { int start, stop; cin >> start >> stop; edges[start].push_back(stop); edges[stop].push_back(start); } int numCycles = 0; for (int i = 0; i < m; i++) { if (!seen[i]) { // start at depth 0, and last important was never (-1) numCycles += findCycles(i, 0, -1); } } cout << numCycles << "\n"; return 0; } * By 'different' I mean that a cycle isn't counted if all its edges are already part of different cycles. In the following example, I consider the number of cycles to be 2, not 3: A–B | | C–D | | E–F A: My algorithm is based on the following observation: since we don't care about cycles with unimportant nodes only, unimportant nodes can be collapsed. We are collapsing two neighboring unimportant nodes, by replacing them with a single unimportant node with the sum of edges from the original nodes. When collapsing two unimportant nodes we need to handle two special cases: * *Both nodes were connected to the same unimportant node U. This means there was a cycle of unimportant nodes in the original graph; we can ignore the cycle and the new node will be connected to the same unimportant node U with a single edge. *Both nodes were connected to the same important node I. This means there was a cycle of unimportant nodes and the single important node I in the original graph; before collapsing the nodes we need to remove one of the edges connecting them to the important node I and thus removing the cycle; The new node will be connected to the important node I with a single edge. With the above definition of node collapsing, the algorithm is: * *Keep collapsing neighboring unimportant nodes, until there are no neighboring unimportant nodes. All removed edges between important and unimportant nodes, as defined in case (2) above, count towards the solution. *Find the spanning tree of the remaining graph and remove all edges that are not included in the spanning tree. All edges removed in this step count towards the solution. The algorithm runs in O(M) time. I believe I can prove its correctness, but would like to get your feedback before I spend too much time on it :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/9180871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What is the equivalent of Matlab/Octave single type cast function in Python I have received the data from a socket. In Matlab, this data is converted into single precision by the following function data_cal_rx = typecast(data_tcp2, "single"); Now I would like to have the same function in Python. Searching from google and Stack overflow, I saw that the single precision in Python is numpy.float32. So I replace by the following function: import numpy as np data_cal_rx = np.float32(data_tcp2) data_tcp2 in Matlab is an array interger numbers with: class: uint8 dimension: 1x70848 however, when I received data_tcp2 by socket in Python, it is displayed as: ... \x00\x00C\x00 QE\x00 \x04E\x00 'E\x00BE\x00D\x00\x00LE\x00\x00\x10*E\x00`\x00@D\x00\x10+\x00\x00C\x000I\x00\x00A\x00\x16\x00\x13\x00 ... And I got this error from the terminal in python: ValueError: could not convert string to float: It could be a problem with socket in python? Any help or idea would be greatly appreciated. Thank you very much A: As an example, let's start with 32-bit float array: orig = np.arange(5, dtype=np.float32) We'll convert this to a buffer of bytes: data = orig.tobytes() This is shown as: b'\x00\x00\x00\x00\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' Note the initial "b", which indicates this is a bytes object, not a string. If your data is actually a string, see at the bottom of this answer. Now that we've got our buffer of bytes containing the data in the array, we can convert this back to an array of 32-bit floating-point values with: out = np.frombuffer(data, dtype=np.float32) (out is now identical to orig). If data is a string, you need to first cast it to a bytes buffer, which you can do with data = bytes(data, 'latin1') The "latin1" part is the encoding. This encoding seems to not change any data when converting from string to bytes.
{ "language": "en", "url": "https://stackoverflow.com/questions/74112818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rotate an image by 90,180,270 and 360 degrees every time a button is clicked and retain the rotation degree in portrait and landscape mode? I am making an app in android where in an image has to be rotated whenever rotate button is clicked by 90,180,270 and 360 degrees. The rotation has to be the same in portrait and in landscape mode. I am a beginner in Android Programming and I have basic knowledge of Java. Kindly, help me soon. The code that I have used is as below.I can only rotate it 90 degrees once. How do it continue with it? btn_rotate = (ImageButton) findViewById(R.id.btn_rotate); btn_rotate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bitmap bmap = BitmapFactory.decodeResource(getResources(), R.drawable.about_us_ipad_p); Display d = getWindowManager().getDefaultDisplay(); @SuppressWarnings("deprecation") int x = d.getWidth(); @SuppressWarnings("deprecation") int y = d.getHeight(); ImageView imgView = (ImageView) findViewById(R.id.imgViewEdit_Pic); Bitmap scaledBmap = Bitmap.createScaledBitmap(bmap, y, x, true); Matrix matrix = new Matrix(); matrix.postRotate(90, 180, 270); Bitmap rotatedBmap = Bitmap.createBitmap(scaledBmap,0,0,scaledBmap.getWidth(),scaledBmap.getHeight(),matrix,true); imgView.setImageBitmap(rotatedBmap); } }); A: this piece of code may help you and it is self explanatory... public class TestActivity extends Activity { private int rotation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState != null) { rotation = savedInstanceState.getInt("ANGLE"); } final ImageView imageView = (ImageView) findViewById(R.id.imageView); final Button button = (Button) findViewById(R.id.iv_icon); DisplayMetrics metrics = getResources().getDisplayMetrics(); final int width = metrics.widthPixels; final int height = metrics.heightPixels; final Bitmap imageBitmap = BitmapFactory.decodeResource( getResources(), R.drawable.image1); final Bitmap scaledBitmap = Bitmap.createScaledBitmap(imageBitmap, width, height, true); imageView.setImageBitmap(getRotatedBitmap(scaledBitmap)); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { rotation += 90; rotation %= 360; Bitmap bitmap = getRotatedBitmap(scaledBitmap); imageView.setImageBitmap(bitmap); } }); } private Bitmap getRotatedBitmap(Bitmap bitmap) { if (rotation % 360 == 0) { return bitmap; } Matrix matrix = new Matrix(); matrix.postRotate(rotation, bitmap.getWidth() / 2, bitmap.getHeight() / 2); return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight() / 2, matrix, true); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putInt("ANGLE", rotation); super.onSaveInstanceState(outState); } } A: yourimage.setRotation(yourimage.getRotation() + 90); A: In manifest file, lock your screen orientation like this: android:screenOrientation="portrait" or android:screenOrientation="landscape"
{ "language": "en", "url": "https://stackoverflow.com/questions/19902874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error using "Xlmns" in XML document I want to generate below code snippet into xml with c#: <?xml version="1.0" encoding="utf-8" ?> <PrincetonStorageRequest xmlns="http://munichre.com/eai/dss/pct/v1.0" requestId="RequestOut_MAG_Test_02" timestampUtc="2015-02-19T09:25:30.7138903Z"> <StorageItems> and my code is : XmlWriter writer = XmlWriter.Create(fileName); writer.WriteStartDocument(true); writer.WriteStartElement("PrincetonStorageRequest"); writer.WriteAttributeString("xmlns","http://example.com/abc/dss/pct/v1.0"); writer.WriteAttributeString("requestId",name); writer.WriteAttributeString("timestampUtc","2015-02-19T09:25:30.7138903Z"); writer.WriteStartElement("StorageItems"); But I am getting "The prefix " cannot be redefined from " to within the same start element tag. A: From your XML and the error, I believe it's because you are adding a default namespace after adding an element with no namespace declaration, so you're effectively creating an element and then changing its namespace. Try the following code - it stops the error when I test it locally just for the XML I think you're trying to get: XmlWriter writer = XmlWriter.Create(fileName); writer.WriteStartDocument(true); writer.WriteStartElement("PrincetonStorageRequest", "http://example.com/abc/dss/pct/v1.0"); writer.WriteAttributeString("xmlns", "http://example.com/abc/dss/pct/v1.0"); writer.WriteAttributeString("requestId", name); writer.WriteAttributeString("timestampUtc", "2015-02-19T09:25:30.7138903Z"); writer.WriteStartElement("StorageItems"); So when I create the PrincetonStorageRequest element I am specifying a namespace URI. Edit: Just to check, this is the XML that gets created but I did have to add the code to write the end elements: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <PrincetonStorageRequest xmlns="http://example.com/abc/dss/pct/v1.0" requestId="RequestOut_MAG_Test_02" timestampUtc="2015-02-19T09:25:30.7138903Z"> <StorageItems/>
{ "language": "en", "url": "https://stackoverflow.com/questions/30503010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pass parameters in RestClient post request I want to send parameters with a POST request using the RestClient gem (but I don't want to pass the params as JSON). In a GET request, I would have: url = "http://example.com?param1=foo&param2=bar" RestClient.get url How can I pass the same params but in a POST request without passing a JSON ? A: Read ReadMe file of Rest-client git, it has lots of examples showing different types of request. For your answer, try : url = "http://example.com" RestClient.post url,:param1=>foo, :param2=>bar
{ "language": "en", "url": "https://stackoverflow.com/questions/38788306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Flutter : Can anybody help making custom TabController in flutter? I am making an app using flutter(dart). I need to make a tab controller with gradient background colour. I have used the DefaultTabController but couldn't get the way to add decoration or any gradient for App bar.Please find my code below: import 'package:flutter/material.dart'; import 'package:vtech/CustomAppBar.dart'; class Policy extends StatefulWidget { @override _PolicyState createState() => _PolicyState(); } class _PolicyState extends State<Policy> { @override Widget build(BuildContext context) { return MaterialApp( home: DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( backgroundColor: Colors.pink, bottom: TabBar( tabs: [ Tab(icon: Icon(Icons.directions_car)), Tab(icon: Icon(Icons.directions_transit)), Tab(icon: Icon(Icons.directions_bike)), ], ), title: Center(child:Text('POLICY')), ), body: TabBarView( children: [ Icon(Icons.directions_car), Icon(Icons.directions_transit), Icon(Icons.directions_bike), ], ), ), ), ); } } A: The AppBar and TabBar widgets do not allow to set a gradient, just a color. To achieve what you need you can create a custom widget GradientAppBar or GradientTabBar built with a Stack that integrates a Container with a gradient and an AppBar or TabBar. You create the GradientAppBar with parameters that would go to the Container and to the AppBar itself. Here is a working example for Gradient AppBar. Below is a similar example just for the TabBar. import 'package:flutter/material.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new Policy(), ); } } class Policy extends StatefulWidget { @override _PolicyState createState() => _PolicyState(); } class _PolicyState extends State<Policy> { @override Widget build(BuildContext context) { return MaterialApp( home: DefaultTabController( length: 3, child: Scaffold( appBar: GradientAppBar( colors: [Colors.white, Colors.black], begin: Alignment.topCenter, end: Alignment.bottomCenter, elevation: 4.0, bottom: TabBar( indicatorColor: Colors.white, tabs: [ Tab(icon: Icon(Icons.directions_car)), Tab(icon: Icon(Icons.directions_transit)), Tab(icon: Icon(Icons.directions_bike)), ], ), title: Center(child: Text('POLICY')), ), body: TabBarView( children: [ Icon(Icons.directions_car), Icon(Icons.directions_transit), Icon(Icons.directions_bike), ], ), ), ), ); } } class GradientAppBar extends StatefulWidget implements PreferredSizeWidget { // Gradiente properties final AlignmentGeometry begin; final AlignmentGeometry end; final List<Color> colors; // Material property final double elevation; // AppBar properties - Add all you need to change final Widget title; final PreferredSizeWidget bottom; @override final Size preferredSize; GradientAppBar({ Key key, @required this.colors, this.begin = Alignment.centerLeft, this.end = Alignment.centerRight, this.elevation, this.title, this.bottom, }) : preferredSize = new Size.fromHeight( kToolbarHeight + (bottom?.preferredSize?.height ?? 0.0)), super(key: key); //appBar.preferredSize; @override _GradientAppBarState createState() => _GradientAppBarState(); } class _GradientAppBarState extends State<GradientAppBar> { @override Widget build(BuildContext context) { return Stack( children: <Widget>[ Material( elevation: widget.elevation, child: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: widget.begin, end: widget.end, colors: widget.colors, )), ), ), AppBar( backgroundColor: Colors.transparent, elevation: 0.0, bottom: widget.bottom, title: widget.title, ), ], ); } } And here the example for the gradient TabBar. import 'package:flutter/material.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new Policy(), ); } } class Policy extends StatefulWidget { @override _PolicyState createState() => _PolicyState(); } class _PolicyState extends State<Policy> { @override Widget build(BuildContext context) { return MaterialApp( home: DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( bottom: GradientTabBar( colors: [Theme.of(context).primaryColor, Colors.green], begin: Alignment.topCenter, end: Alignment.bottomCenter, tabBar: TabBar( //indicatorColor: Colors.white, tabs: [ Tab(icon: Icon(Icons.directions_car)), Tab(icon: Icon(Icons.directions_transit)), Tab(icon: Icon(Icons.directions_bike)), ], ), ), title: Center(child: Text('POLICY')), ), body: TabBarView( children: [ Icon(Icons.directions_car), Icon(Icons.directions_transit), Icon(Icons.directions_bike), ], ), ), ), ); } } class GradientTabBar extends StatefulWidget implements PreferredSizeWidget { // Gradiente properties final AlignmentGeometry begin; final AlignmentGeometry end; final List<Color> colors; final TabBar tabBar; GradientTabBar({ Key key, @required this.colors, this.begin = Alignment.centerLeft, this.end = Alignment.centerRight, this.tabBar, }) : super(key: key); @override Size get preferredSize => tabBar.preferredSize; @override _GradientTabBarState createState() => _GradientTabBarState(); } class _GradientTabBarState extends State<GradientTabBar> { @override Widget build(BuildContext context) { return Stack( children: <Widget>[ Container( height: widget.preferredSize.height, decoration: BoxDecoration( gradient: LinearGradient( begin: widget.begin, end: widget.end, colors: widget.colors, )), ), widget.tabBar, ], ); } } A: you can try this flexibleSpace: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.centerLeft, end: Alignment.centerRight, colors: [ Colors.red, Colors.blue ], ), ), ), In Appbar appBar: AppBar( title: Center(child: Text("Add Student",),), flexibleSpace: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.centerLeft, end: Alignment.centerRight, colors: [ darkblue, darkpurple ], ), ), ), actions: <Widget>[ IconButton( icon: Icon(Icons.account_circle,color: Colors.white,),), ], ),
{ "language": "en", "url": "https://stackoverflow.com/questions/52753141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wrong characters in some e-mail clients Have you seen an error like this? Using some email clients the characters appear to be different. I used the red squares to highlight the wrong words and the green squares for other words that are ok The difference between them is that the words with special characters that are OK are written in the email template, whereas the wrong ones come from the database. I tried sending this email to Hotmail and Gmail. In Hotmail they look different if they go to the Spam box. The special characters in the red squares are replaced by a '?', the others become a black a symbol Do any of you know what is going on? Do you know how to fix it? Is it a problem in the client or the way the message is being encoded? Thanks in advance A: Try the steps below to see if that could help: 1) From Outlook, click File from the top left > Options > Advanced 2) Scroll down until you see "International Options" 3) Check "Automatically Select Encoding for Outgoing..." 4) Select UTF-8 encoding from the drop down menu. A: Try changing (or setting) the encoding in the html template. If it doesn't help, convert characters to html entities - that works in all email clients.
{ "language": "en", "url": "https://stackoverflow.com/questions/25812790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: crystal report is not printing online http://avas.hexaperkeducation.com/demo/Default.aspx i built this application which print crystal report directly to printer.its working fine on my local system but when i upload it to online server page load keep running . con.Open(); string sql = "select * from Student_Master"; System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(sql, con); DataSet ds = new DataSet(); da.Fill(ds, "Student_Master"); ReportDocument Report = new ReportDocument(); Report.Load(Server.MapPath("CrystalReport.rpt")); Report.SetDataSource(ds); CrystalReportViewer1.ReportSource = Report; CrystalReportViewer1.DataBind(); Report.PrintToPrinter(1, true, 1, 1); A: Which version of crystal reports runtime you are using on server and on local system? Runtime should be 32bit. You need to setup those two properties. Report.PrintOptions.NoPrinter = false; Report.PrintOptions.PrinterName = <printername>; And printer should be available in network via this name. If you are using IIS then application pool also need access to printer. In app pool advanced settings you need to switch boolean prop "Enable 32-bit apps" to true. If this still does not help you can try change Identity to "LocalService" in those advanced settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/37411275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what is wrong in this main.xml? This is my main.xml <com.example.parallax_sample xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res/com.example.parallax_sample" android:id="@+id/scrollView1" android:layout_width="match_parent" android:layout_height="match_parent" android:overScrollMode="never"> <RelativeLayout android:layout_width="match_parent" android:layout_height="1000dp" tools:context=".MainActivity" > <RelativeLayout android:id="@+id/relativeLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" tools:context=".MainActivity" > <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="100dp" android:src="@drawable/teste" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:text="Bottom" android:textColor="#ffffff" android:textSize="18sp" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="Top" android:textColor="#ffffff" android:textSize="18sp" /> </RelativeLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/relativeLayout1" android:text="@string/hello_world" /> </RelativeLayout> </com.example.parallax_sample> when I switch to graphical layout I see nothing (grey screen) ,with the exception stating. Exception raised during rendering: com.android.layoutlib.bridge.MockView cannot be cast to android.view.ViewGroup. I may be wrong but it must be a problem of main.xml only . How can i resolve it. Here is the StackTrace E/AndroidRuntime(15768): FATAL EXCEPTION: main E/AndroidRuntime(15768): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.parallax_sample/com.appkraft.parallax_sample.MainActivity}: android.view.InflateException: Binary XML file line #1: Error inflating class com.example.parallax_sample E/AndroidRuntime(15768): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343) E/AndroidRuntime(15768): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395) E/AndroidRuntime(15768): at android.app.ActivityThread.access$600(ActivityThread.java:162) E/AndroidRuntime(15768): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364) E/AndroidRuntime(15768): at android.os.Handler.dispatchMessage(Handler.java:107) E/AndroidRuntime(15768): at android.os.Looper.loop(Looper.java:194) E/AndroidRuntime(15768): at android.app.ActivityThread.main(ActivityThread.java:5371) E/AndroidRuntime(15768): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime(15768): at java.lang.reflect.Method.invoke(Method.java:525) E/AndroidRuntime(15768): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) E/AndroidRuntime(15768): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) E/AndroidRuntime(15768): at dalvik.system.NativeStart.main(Native Method) E/AndroidRuntime(15768): Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class com.example.parallax_sample E/AndroidRuntime(15768): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:698) E/AndroidRuntime(15768): at android.view.LayoutInflater.inflate(LayoutInflater.java:466) E/AndroidRuntime(15768): at android.view.LayoutInflater.inflate(LayoutInflater.java:396) E/AndroidRuntime(15768): at android.view.LayoutInflater.inflate(LayoutInflater.java:352) E/AndroidRuntime(15768): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:281) E/AndroidRuntime(15768): at android.app.Activity.setContentView(Activity.java:1881) E/AndroidRuntime(15768): at com.appkraft.parallax_sample.MainActivity.onCreate(MainActivity.java:18) E/AndroidRuntime(15768): at android.app.Activity.performCreate(Activity.java:5122) E/AndroidRuntime(15768): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081) E/AndroidRuntime(15768): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307) E/AndroidRuntime(15768): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.parallax_sample" on path: DexPathList[[zip file "/data/app/com.example.parallax_sample-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.parallax_sample-1, /vendor/lib, /system/lib]] E/AndroidRuntime(15768): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53) E/AndroidRuntime(15768): at java.lang.ClassLoader.loadClass(ClassLoader.java:501) E/AndroidRuntime(15768): at java.lang.ClassLoader.loadClass(ClassLoader.java:461) E/AndroidRuntime(15768): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687) A: Your root element on the xml is a custom element. If the graphical layout cannot render that first element, it won't be able to render the rest of them either. A: "com.example.parallax_sample" is the problem, previews for custom view can't be created, though possibly it will work fine when you run it.
{ "language": "en", "url": "https://stackoverflow.com/questions/20469692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do you determine whether a menu item is enabled? A menu item can be enabled or disabled using EnableMenuItem. How do you determine whether an existing item is enabled? A: Whether a menu item is enabled is stored as part of a menu item's state information. The following function reports, whether a menu item (identified by ID) is enabled: bool IsMenuItemEnabled( HMENU hMenu, UINT uId ) { UINT state = GetMenuState( hMenu, uId, MF_BYCOMMAND ); return !( state & ( MF_DISABLED | MF_GRAYED ) ); } A few notes on the implementation: * *A menu item can have both MF_DISABLED and MF_GRAYED states. A disabled item looks just like an enabled item, but is otherwise inactive. Neither disabled nor grayed items can be selected.1) *The MF_ENABLED state equates to 0. As a consequence, it cannot be tested directly, but an expression must be used instead (see GetMenuState). For completeness, here's an implementation using the newer API (GetMenuItemInfo). Both implementations are functionally identical: bool IsMenuItemEnabled( HMENU hMenu, UINT uId ) { MENUITEMINFO mii = { 0 }; mii.cbSize = sizeof( mii ); mii.fMask = MIIM_STATE; GetMenuItemInfo( hMenu, uId, FALSE, &mii ); return !( mii.fState & MFS_DISABLED ); } 1)The distinction between grayed and disabled items is documented under About Menus: Enabled, Grayed, and Disabled Menu Items. This distinction is no longer exposed in the newer APIs (see MENUITEMINFO), where both MFS_DISABLED and MFS_GRAYED have the same value.
{ "language": "en", "url": "https://stackoverflow.com/questions/31208539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why am I getting the error: "cannot read properties of null (reading "style") when I try to integrate Plaid link in JS? My relevant code is as follows function useLink(token){ const handler = Plaid.create({ token: token, onSuccess: (public_token, metadata) => {}, onLoad: () => {}, onEvent: (eventName, metadata) => {}, recievedRedirectUri: window.location.href, }); } But everytime I try to use my link token to pull up link on the frontend, I get the following error from link-unitialize.js: Uncaught TypeError: Cannot read properties of null (reading 'style') I checked the Plaid website and couldn't find this listed as a common error, so I must be doing something very wrong. What is the most likely cause of this?
{ "language": "en", "url": "https://stackoverflow.com/questions/72553222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sort and update list of objects based on variable change I am working on a algorithm which will solve a problem I have, but I am finding myself a little stuck. Here is the scenario: I have an object which contains a variable called order. public class Item { public int Order{get; set;}; public int ID{get; set;}; // not incremented can be any value! } So I have a list of these: List<Item> list = new List<Item>().OrderBy((o) => o.Order); And at any time the order value can be changed. So if I want to change the first an items order value all other order values should update accordingly so there are no duplicates. for (int i = 0; i <= list .Count - 1; i++) { if (list [i].ID == inputID) { list [i].Order = inputNewPosition; } else { if (list [i].Order < inputNewPosition) { list [i].Order --; } else { list [i].Order ++; } } } This fails if I change the last item order to be the first, as this would make the first item order be 0! Can anyone help? Thanks A: Let us look at the four situations for an element in your list (as we iterate through them). If (for terseness) we take old to be the item that is moving's old position and new to be its new position we have the following cases for an item in your list (draw them out on paper to make this clear). * *the current item is the one to be moved: move it directly *the current item's order is < new and < old: don't move it *the current item's order is ≥ new and < old: move it right *the current item's order is ≤ new and > old: move it left *the current item's order is > new and > old: don't move it When we start enumerating, we know the where the item to be moved will end up (at new) but we do not know where it has come from (old). However, as we start our enumeration at the beginning of the list, we know at each step that it must be further down in the list until we have actually seen it! So we can use a flag (seen) to say whether we have seen it yet. So seen of false means < old whilst true means >= old. bool seen = false; for (int i = 0; i < items.Length; i++) { if (items[i].ID == inputID) { items[i].Order = inputNewPosition; seen = true; } } This flag tells us whether the current item is >= old. So now can start shunting stuff around based on this knowledge and the above rules. (So new in the above discussion is inputNewPosition and whether we are before or after old we represent with our seen variable.) bool seen; for (int i = 0; i < items.Count; i++) { if (items[i].ID == inputID) // case 1 { items[i].Order = inputNewPosition; seen = true; } else if (seen) // cases 4 & 5 { if (items[i].Order <= inputNewPosition) // case 4 { items[i].Order--; // move it left } } else // case 2 & 3 { if (items[i].Order >= inputNewPosition) // case 3 { items[i].Order++; // move it right } } } Having said all of that, it is probably simpler to sort the collection on each change. The default sorting algorithm should be quite nippy with a nearly sorted collection. A: Your question isn't very clear, but for the requirements you'd likely be best off doing an event on the object that contains Order, and possibly having a container object which can monitor that. However I'd suspect that you might want to rethink your algorithm if that's the case, as it seems a very awkward way to deal with the problem of displaying in order. That said, what is the problem requirement? If I switch the order of item #2 to #5, what should happen to #3? Does it remain where it is, or should it be #6? A: This is how I solved the problem but I think there might be a more clever way out there.. The object that I need to update are policy workload items. Each one of these has a priority associated. There cannot be a policy workload item with the same priority. So when a user updates the priority the other priorities need to shift up or down accordingly. This handler takes a request object. The request has an id and a priority. public class UpdatePriorityCommand { public int PolicyWorkloadItemId { get; set; } public int Priority { get; set; } } This class represents the request object in the following code. //Get the item to change priority PolicyWorkloadItem policyItem = await _ctx.PolicyWorkloadItems .FindAsync(request.PolicyWorkloadItemId); //Get that item's priority and assign it to oldPriority variable int oldPriority = policyItem.Priority.Value; //Get the direction of change. //-1 == moving the item up in list //+1 == moving the item down in list int direction = oldPriority < request.Priority ? -1 : 1; //Get list of items to update... List<PolicyWorkloadItem> policyItems = await _ctx.PolicyWorkloadItems .Where(x => x.PolicyWorkloadItemId != request.PolicyWorkloadItemId) .ToListAsync(); //Loop through and update values foreach(var p in policyItems) { //if moving item down in list (I.E. 3 to 1) then only update //items that are less than the old priority. (I.E. 1 to 2 and 2 to 3) //items greater than the new priority need not change (i.E. 4,5,6... etc.) //if moving item up in list (I.E. 1 to 3) //items less than or equal to the new value get moved down. (I.E. 2 to 1 and 3 to 2) //items greater than the new priority need not change (i.E. 4,5,6... etc.) if( (direction > 0 && p.Priority < oldPriority) || (direction < 0 && p.Priority > oldPriority && p.Priority <= request.Priority) ) { p.Priority += direction; _ctx.PolicyWorkloadItems.Update(p); } } //finally update the priority of the target item directly policyItem.Priority = request.Priority; //track changes with EF Core _ctx.PolicyWorkloadItems.Update(policyItem); //Persist changes to database await _ctx.SaveChangesAsync(cancellationToken);
{ "language": "en", "url": "https://stackoverflow.com/questions/14880735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: React - Google Maps component not rendering after componentDidMount I'm just having trouble with my Google Maps rendering when a search (with a postcode) happens. It seems like the map is rendering the null map centre, and then not re-rendering after setState in componentDidMount(), as the map is rendered blank/grey but with a hard refresh the map will load with the postcode. I've tried using componentWillMount() without any luck, anyone have any suggestions? This is the code for my search page: class SearchContainer extends Component { constructor(props) { super(props); this.state = { map_centre: null }; } componentDidMount() { const values = queryString.parse(this.props.location.search); axios .get("api/v1/search?postcode=" + values.postcode) .then(response => { var mapCentre = response.data.map_centre; this.setState({ map_centre: mapCentre }); }) .catch(error => console.log(error)); } render() { return ( <div id="map" className="padding-left"> <GoogleMapComponent townCenters={this.state.townCenters} schools={this.state.schools} supermarkets={this.state.supermarkets} hotels={this.state.hotels} airports={this.state.airports} trainStations={this.state.trainStations} map_centre={this.state.map_centre} onMapMounted={this.handleMapMounted} onDragEnd={this.handleMapChange} onZoomChanged={this.handleMapChange} onMarkerClick={this.handleAdspaceShow} googleMapURL={url} loadingElement={<div style={{ height: `100vh`, width: `100%` }} />} containerElement={<div style={{ height: `100vh`, width: `100%` }} />} mapElement={<div style={{ height: `100vh`, width: `100%` }} />} /> <img src={mapSearch} id="map-search-button" onClick={this.toggleSearchInput} /> <input id="map-search-input" className="form-control d-none" type="search" placeholder="Enter new location" aria-label="Search" onChange={this.handlePostcodeChange} onKeyPress={this.handleNewSearch} /> </div> ); } } This is the code for my Google Maps component: const GoogleMapComponent = withScriptjs( withGoogleMap(props => ( <GoogleMap defaultZoom={13} defaultCenter={props.map_centre} onDragEnd={props.onDragEnd} onZoomChanged={props.onZoomChanged} ref={props.onMapMounted} /> )) ); A: defaultCenter will only be used by the map for the initial render, so it will not have any effect if you change this value later. If you use the center prop instead it will work as expected. const GoogleMapComponent = withScriptjs( withGoogleMap(props => ( <GoogleMap defaultZoom={13} center={props.map_centre} onDragEnd={props.onDragEnd} onZoomChanged={props.onZoomChanged} ref={props.onMapMounted} /> )) ); A: Be more specific with the library you are using...you have added the tags "google-maps-react" and "react-google-map" and both are different libraries... google-maps-react = https://github.com/fullstackreact/google-maps-react react-google-map = https://tomchentw.github.io/react-google-maps/ Anyway, I can see 2 options: solution 1: Add a conditional that renders GoogleMapComponent only if map_centre is not null. render() { if(this.state.map_centre){ return ( <div id="map" className="padding-left"> <GoogleMapComponent townCenters={this.state.townCenters} schools={this.state.schools} supermarkets={this.state.supermarkets} hotels={this.state.hotels} airports={this.state.airports} trainStations={this.state.trainStations} map_centre={this.state.map_centre} onMapMounted={this.handleMapMounted} onDragEnd={this.handleMapChange} onZoomChanged={this.handleMapChange} onMarkerClick={this.handleAdspaceShow} googleMapURL={url} loadingElement={<div style={{ height: `100vh`, width: `100%` }} />} containerElement={<div style={{ height: `100vh`, width: `100%` }} />} mapElement={<div style={{ height: `100vh`, width: `100%` }} />} /> <img src={mapSearch} id="map-search-button" onClick={this.toggleSearchInput} /> <input id="map-search-input" className="form-control d-none" type="search" placeholder="Enter new location" aria-label="Search" onChange={this.handlePostcodeChange} onKeyPress={this.handleNewSearch} /> </div>); } return <div> Loading.. </div>; } solution 2: Set a default lat/lng (not null) before you get the response. constructor(props) { super(props); this.state = { map_centre: { lat: -34.397, lng: 150.644 } }; }
{ "language": "en", "url": "https://stackoverflow.com/questions/51617191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why cant I pass a type to a generic method Ok a brief background. I'm trying out various ways to test an API and I'm trying to allow a user to provide a simple CSV file of a API calls that my test framework can iterate over using a generic test method. I'm having trouble passing the type to my generic API call method. Allow me to demonstrate. Given I have a method with the following basic structure public T GetData<T>(Uri uri, HttpStatusCode expectedStatusCode) { var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(uri); myHttpWebRequest.Accept = "application/json"; var response = (HttpWebResponse)myHttpWebRequest.GetResponse(); if (response.StatusCode != expectedStatusCode) Report.Log(ReportLevel.Failure, "ExpectedResponseCode:" + expectedStatusCode.ToString() + " ActualResponseCode:" + response.StatusCode.ToString()); string responseString = ""; using (var stream = response.GetResponseStream()) { var reader = new StreamReader(stream, Encoding.UTF8); responseString = reader.ReadToEnd(); } return JsonConvert.DeserializeObject<T>(responseString); } I can call the above as follows without issue Person person = _apiHelper.GetData<Person>(uri, HttpStatusCode.Ok); However assume I now have a Type that I have acquired as follows Type returnType = Type.GetType(typeString, true, true); why can I not call the GetData method as follows var result = _apiHelper.GetData<returnType>(uri, HttpStatusCode.Ok); Visual studio simply says it cant resolve the symbol A: Just use the JsonConvert.DeserializeType overload that accepts a type parameter instead of the generic one: public object GetData(Type t,Uri uri, HttpStatusCode expectedStatusCode) { .... return JsonConvert.DeserializeObject(responseString,t); } This is a case of the XY problem. You want to deserialize arbitrary types (problem X) and think that somehow, you need pass a generic type at runtime (problem Y), so when you get stuck ,you ask about Y.
{ "language": "en", "url": "https://stackoverflow.com/questions/39791775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Connectivity via a Field Gateway with IoT Central I am building an IoT Solution based on non programmable devices. I can just configure a host where they can connect to send data and receive commands. Now, supposed that I know the messaging protocol of the device, I would like to build a field gateway to apply protocol and identity translation with the IoT Hub behind IoT Central. Is that doable ? If yes, may you drive me to the solution please ? A: AFAIk, this scenario is not implemented yet. Please provide your feedback on the UserVoice. All the feedback you share in these forums will be monitored and reviewed by the Microsoft engineering teams responsible for building Azure. Reference: How to create IoT edge device on IoT central?
{ "language": "en", "url": "https://stackoverflow.com/questions/56018601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: React - Why this function in onClick doesn't work? If I write like this, click button works <Menu.Item key={book.uid} onClick={() => this.changeColor(book)} > But if I write like this: onClick={this.changeName(book)} the click doesn't work. So if the function has arguments, I should use "() => xxx(argument); otherwise, I can just use "this.xxx", right? A: Because doing this.changeName(book) will instantly call the function when rendering. And what your function returns is.. not a function, so when you click, nothing will happen. And () => this.changeColor(book) is an arrow function, it has a similar (but not really) behavior as this syntax : () => { this.changeColor(book) } To avoid this, you could use your first code example or transform your function into a curried one and keep the second syntax in the render : changeName = bookInfo => event => { /* Your code here */ } When called once in the render, this function will return another function receiving the event and set the bookInfo first.
{ "language": "en", "url": "https://stackoverflow.com/questions/54971924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python GDAL does not install on Mac OSX El Capitan I am having several issues when installing pygdal in my Mac OSX El capitan. The procedure is the folowing: * *Install GDAL Libraries from http://www.kyngchaos.com/software/frameworks#gdal_complete *pip install gdal The output is the following: . . . extensions/gdal_wrap.cpp:3085:10: fatal error: 'cpl_port.h' file not found #include "cpl_port.h" ^ 2 warnings and 1 error generated. error: command 'cc' failed with exit status 1 Looks like the installer cannot find the GDAL libraries, or headers (libgdal or gdal-devel in ubuntu). Where are they placed in OSX? FYI, the following /Library/Frameworks/GDAL.framework/Programs is into the $PATH variable. A: I finally (with a little help from Cam_Aust) solved the problem !!! Here is what I did: * *Find the cp_port.h file in your system: sudo find / -name cpl_port.h, My output was: /Library/Frameworks/GDAL.framework/Versions/1.11/Headers/cpl_port.h /opt/local/include/cpl_port.h *Add the resulting folders to your $PATH in your bash init script (~/.bash_login or ~/.zshrc). This worked for me: export PATH=/Library/Frameworks/GDAL.framework/Headers:$PATH *Open a new terminal session or source ~/.zshrc After this, you can now pip install gdal: Collecting gdal Using cached GDAL-2.1.0.tar.gz Installing collected packages: gdal Running setup.py install for gdal ... done Successfully installed gdal-2.1.0 A: After installing the GDAL Libraries from kyngchaos (as mentioned in the question) you should be able to find the python package ready to go. I cheated and used that: export PYTHONPATH=$PYTHONPATH:/Library/Frameworks/GDAL.framework/Versions/2.1/Python/2.7/site-packages
{ "language": "en", "url": "https://stackoverflow.com/questions/37700484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: why does an iOS universal app need to have two different xib files? I'm a newbie of iOS development and I'm confused regarding universal app. We can use the same code, same xib file for iPhone 4(retina) and previous iPhones, but why we should write two different xibs for iPhone and iPad? What's the difference? For iPhone and retina iPhone, we use "point" instead of pixel for the coordinate. Why we can't use the similar method for iPhone and iPad? A: For some simple apps, it is possible to design your iPhone UI and reuse the same xib file for the iPad. Just select your Target in XCode and copy the Main Interface text from iPhone / iPod Deployment Info to iPad Deployment Info. If you're using a Main Storyboard, copy that too. However, the iPad does not simply scale everything up from the 320*480 / 640*960 iPhone screen to the 768*1024 / 1536*2048 iPad screen. @elgarva correctly says that this would look terrible. Instead, the iPad version makes use of your autosizing masks to resize or reposition each view. If all of your views can be considered to be left-middle-right or top-middle-bottom, this may work. If you have anything more complicated, you'll need to design a separate iPad interface. Duplicating your iPhone UI is not just discouraged for aesthetic reasons - iPhones often end up containing a deep and confusing navigation tree for tasks that the iPad can fit on a single screen. A: The main reason, is that if you just scale the elements on the UI to fit the larger screen, it wouldn't look nice... and you don't need to do anything for it to work, it automatically does it for you if your app is iPhone only and installed on an iPad (if the user chooses to). Having a different XIB lets you rearrange your app, and think it so that you can take advantage of the larger screen. You can probably show more information on one iPad view than on 3 different screens on the iPhone... so, your iPhone app could show basic info and expand it when the user taps on it, while your iPad version could show all the information on load, plus extra graphics that look nice but aren't needed, and wouldn't make sense on the iPhone screen. PS: If you're starting a new app, I strongly suggest you using the storyboard if your app won't have a lot of views... it's really easy to get started and it lets you see your app flow at a glance. A: The ratina display just doubles the resolution of original iPhone. If you don't provide separate graphics for retina display, then system just doubles the resolution of resources. The points are related to physical size of screen, which is similar in old and new iPhones. For iPads, the screen size changes. This means that its dimension in points will be different from that of iPhone. A: duplicating the xib file and renaming that as filename~ipad.xib is working great for me in ios6.1
{ "language": "en", "url": "https://stackoverflow.com/questions/10060788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I remove lambda expressions/method handles that are used as listeners? Java 8 has introduced lambda expressions, which is a great thing. But now consider rewriting this code: class B implements PropertyChangeListener { void listenToA(A a) { a.addPropertyChangeListener(this); } void propertyChange(PropertyChangeEvent evt) { switch(evt.getPropertyName()) { case "Property1": doSomething(); break; case "Property2": doSomethingElse(); case "Property1": doSomething; break; break; } void doSomething() { } void doSomethingElse() { } } class A { final PropertyChangeSupport pcs = new PropertyChangeSupport(this); void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } } With lambda expressions and method references, it is no more necessary to have B implement PropertyChangeListner as we can write class B { void listenToA(A a) { // using method reference a.addPropertyChangeListener("Property1", this::doSomething); // using lambda expression a.addPropertyChangeListener("Property2", e -> doSomethingElse()); } void doSomething(PropertyChangeEvent evt) { } void doSomethingElse() { } } class A { final PropertyChangeSupport pcs = new PropertyChangeSupport(this); void addPropertyChangeListener(String name, PropertyChangeListener listener) { pcs.addPropertyChangeListener(name, listener); } void removePropertyChangeListener(String name, PropertyChangeListener listener) { pcs.removePropertyChangeListener(name, listener); } } I think the new code is not only shorter but also cleaner and easier to understand. But after reading the answers given here (duplicate of this one, but I think question and answer are more crisp), I can see no way to implement a method called stopListening() which would remove the listeners again. I am sure that I am not the first one to stumble on this. So has anyone found a nice solution on how to use method handles as shown in this example and still being able to remove the listeners again later? UPDATE That was fast. Building on the answers by Mike Naklis and Hovercraft Full Of Eels, I ended up with this: class B { void listenToA(A a) { a.addPropertyChangeListener("Property1", doSomething); a.addPropertyChangeListener("Property2", doSomethingElse); } final PropertyChangeListener doSomething = evt -> {}; final PropertyChangeListener doSomethingElse = evt -> {}; } A: You can use lambdas and still use variables. For example, if you had: class B { private PropertyChangeListener listener1 = this::doSomething; private PropertyChangeListener listener2 = e -> doSomethingElse(); void listenToA(A a) { // using method reference a.addPropertyChangeListener("Property1", listener1); // using lambda expression a.addPropertyChangeListener("Property2", listener2); } Then it would be easy to remove listener1 or listener2 when and where needed. Also there are other ways, since the PropertyChangeSupport object has a getPropertyChangeListeners() that would allow removal of all listeners in a for loop if need be. class A { final PropertyChangeSupport pcs = new PropertyChangeSupport(this); void addPropertyChangeListener(String name, PropertyChangeListener listener) { pcs.addPropertyChangeListener(name, listener); } void removePropertyChangeListener(String name, PropertyChangeListener listener) { pcs.removePropertyChangeListener(name, listener); } public void removeAllListeners() { for (PropertyChangeListener l : pcs.getPropertyChangeListeners()) { pcs.removePropertyChangeListener(l); } } } A: You can declare your listeners as follows: private final PropertyChangeListener myProperty1Listener = this::doSomething; private final PropertyChangeListener myProperty2Listener = e -> doSomethingElse()); then, you can add your listeners: // using method reference a.addPropertyChangeListener( "Property1", myProperty1Listener ); // using lambda expression a.addPropertyChangeListener( "Property2", myProperty2Listener ); and you can remove them: a.removePropertyChangeListener( "Property1", myProperty1Listener ); a.removePropertyChangeListener( "Property2", myProperty2Listener );
{ "language": "en", "url": "https://stackoverflow.com/questions/42146360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Can a form be invoked on a click event in AngularJS ? I am creating a project to put into practice what I have learned about AngularJS. I created a form, which uses a controller. In the form, I have a button to save the information filled in by the user. After the information is save into the database I would like to call a second form to continue, (this form has its own controller) etc. How can I do that ? A: You can use ng-submit for this: <form ng-submit="goToNextForm()"> <input type="text" ng-model="email"> <button type="submit" value="submit"> </form> And in controller: $scope.goToNextForm = function(){ //code to save data and move to next controller/form here } A: If you're not navigating to a different view, you probably dont need another controller. You can show and hide forms conditionally with ng-if. Ie. say first form is done, you've posted it to the database. You can do something like this $scope.form = 1 <form id="form1" ng-if="form === 1"> //your form html </form> <form id="form2" ng-if="form === 2"> //your form html </form> then when form1 is submitted, you can do $scope.form = 2 in your controller to hide the first form and render the second one If you're set on the different forms having different controllers, you can do something like this <div controller="mainCtrl"> <form controller="form1Ctrl" id="form1" ng-if="form === 1"> //your form html </form> <form controller="form2Ctrl" id="form2" ng-if="form === 2"> //your form html </form> </div> You would set the form variable from the mainCtrl's scope
{ "language": "en", "url": "https://stackoverflow.com/questions/38665129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make Start-Process with Run as administrator should wait till finish i am having a code shown below. When i execute this code i want start-Process should wait. Once it is executed i will be accessing th exit code through $process. But here it is not working properly. $process=Start-Process powershell -Verb runAs "$exePath ${args} " #Run as administrator Write-Output "hello world" Write-Output $process.exitCode
{ "language": "en", "url": "https://stackoverflow.com/questions/56391456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I dynamically label my ggplot within a for loop? I want the title of each of my plots to be labeled by the contents of my list: "namesvector" instead of just "Scatterplot" Also bonus question, par(mfrow = c(2,2)) isnt printing all 4 plots side by side, but individually. par(mfrow = c(2, 2)) namesvector <- list("Start", "Week_1", "Week_3", "Week_5") for (i in 4:ncol(data_3)) { print( ggplot(data_3, aes( y = data_3[, i], x = Biomass, color = Tissue )) + geom_point() + geom_smooth(method = "lm") + labs(title = "Scatterplot", x = "Biomass", y = "Isotopic Signature") ) } A: For printing a variable into your title, you need to use paste(), as explained here: Inserting function variable into graph title in R Does this help you?
{ "language": "en", "url": "https://stackoverflow.com/questions/66305366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Spring Session JDBC - How to catch when the session is destroyed? Since Spring Session JDBC implementation does not support publishing of session events, how can I catch when the session is destroyed? I need to perform some additional logic when user's session has ended, but I couldn't find any other workaround. In the Spring Session docs there isn't any other solution presented.
{ "language": "en", "url": "https://stackoverflow.com/questions/60514668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent saving Excel workbook unless a command button is clicked? I have a command button to save an Excel workbook in a particular format. I want that the users are unable to save the workbook unless they click that command button. To prevent the use of traditional saving options I used the code below: Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) MsgBox "You can't save this workbook!" Cancel = True End Sub How do I prevent traditional saving options but allow saving if the command button is clicked? A: 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:
{ "language": "en", "url": "https://stackoverflow.com/questions/58937488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why there is no element in the list even after populating the list? package collectionwaliclass; import java.util.ArrayList; import java.util.List; public class ArraylistWaliClass { public static List<String> list= new ArrayList<>() ; public static void main(String[] args) { // TODO Auto-generated method stub //list= ; ArraylistWaliClass arraylistWaliClass= new ArraylistWaliClass(); //adding the element to the existing list int counter=0; /*while(counter++<10) { arraylistWaliClass.addElement("new element"+counter, list); }*/ //traversing the list in the arryaList list.forEach((x)-> { System.out.println(x); System.out.println("uff"); }); //deleting the list from the arraylist } public void addElement(String string, List<String> list) { list.add(string); } } A: because of scope definition, you are just adding elements to the parameter List<String> list in public void addElement(String string, List<String> list) { list.add(string); } A: It's working fine if you just un-comment the while loop: Output: new element1 new element2 new element3 new element4 new element5 new element6 new element7 new element8 new element9 new element10 Code: package collectionwaliclass; import java.util.ArrayList; import java.util.List; public class ArraylistWaliClass { public static List<String> list= new ArrayList<>() ; public static void main(String[] args) { // TODO Auto-generated method stub //list= ; ArraylistWaliClass arraylistWaliClass= new ArraylistWaliClass(); //adding the element to the existing list int counter=0; while(counter++<10) { arraylistWaliClass.addElement("new element"+counter, list); } //traversing the list in the arryaList list.forEach((x)-> { System.out.println(x); }); //deleting the list from the arraylist } public void addElement(String string, List<String> list) { list.add(string); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/40211843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Mysql function adding unwanted decimals on addition I am creating a simple MySQL function for addition, the function works well for numbers with up to 10 decimal places, but when I pass A as 17.565714285714 and B as 22.8 I got 40.365714285714006 the function append 006 to the result, what could be a reason and how can I solve it. Mysql version is 8.0.18 DELIMITER $$ CREATE DEFINER=`root`@`localhost` FUNCTION `addition`(`A` DOUBLE, `B` DOUBLE) RETURNS DOUBLE NO SQL BEGIN RETURN A + B; END$$ DELIMITER ;
{ "language": "en", "url": "https://stackoverflow.com/questions/63300592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting root and passing parameter using the same function in angular 2 I am building an Ionic2 app. On click, I am sending parameter and setting a new rootPage in the same function so I can display a different set of tabs on the destination page. viewProjects(item){ this.navCtrl.push(ItemPage,{ item: item }); this.navCtrl.setRoot(Tabs2Page); } Template: <button ion-item (click)="viewItem(item)"> Item </button></div> If I don't send parameter on click, I can successfully go to the target page and new rootPage is set. viewProjects(item){ this.navCtrl.push(ItemPage); this.navCtrl.setRoot(Tabs2Page); } If I only send Parameter and not setRoot, It works I have access to the parameters that I need but new rootPage is not set so I don't have tabs on the page. viewProjects(item){ this.navCtrl.push(ItemPage,{ item: item }); } I'm getting the following error Runtime Error Error in ./ItemPage class ItemPage - caused by: Cannot read property 'name' of undefined I need to be able to setRoot and be able to send parameters on click, any idea how I might be able to do that? Thanks a lot !
{ "language": "en", "url": "https://stackoverflow.com/questions/42936685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Should I lock a variable in one thread if I only need it's value in other threads, and why does it work if I don't? I am aware of this question, but I believe my concerns are very different. I recently created an SDL application, using threading and OpenGL. I have one thread running in a loop, which continually updates the state of the objects I draw to the screen. The states are very simple, it is just a boolean array (when the array value is true, I draw it, when it is false, I don't). Currently, I have no mutex lock on any of my variables and everything is working just fine. Even if only half of the state array was updated between a draw, the framerate is much higher (or at least equal to) the update rate, so it would be acceptable to have a half-updated state. Now, I initially started working on a similar idea to this on an embedded system using interrupts. Every once in a while, an interrupt would trigger, update the state array, and the execution would continue. Now that I'm on a multi-core desktop, and updating the array simultaneously, I'm wondering why nothing bad is happening, since I am technically reading and writing to the same memory location at the same time. * *Is it just by chance, or is there a reason there's no memory access violations happening? *If it is acceptable for the state of the variable to change just before, during, or just after the value is used, should I bother using a mutex lock? Thank you for your help. Edit: Additional information - the array is created dynamically, but when it is created/deleted, I do use a mutex (I figured accessing deleted memory wouldn't be looked kindly upon :P). A: In theory, it's completely invalid (undefined behavior) to access memory like this without some synchronization. In practice, it's moderately safe as long as: * *Only one thread is writing and the others are all reading. *You don't care if the readers don't see some of the changes made until sometime later (possibly much later than the actual time they're written. *You don't care if the readers see out-of-order changes, i.e. they see some changes that were made later without seeing other changes that were made earlier. Issues 2 and 3 are a non-issue on x86, but can occur on nearly every other real-world multi-core/SMP machine. You could mitigate them with some machine-specific asm (or compiler intrinsics) to insert memory barriers at appropriate points. A: The boolean array elements are can be set/read with an atomic operation, there is not need for a mutex. You need a mutex to protect a structure to make sure that it stays consistent. Since your booleans are independent there is no problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/6935208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Authenticating passwords against an LDAP I am a bit confused as to where passwords are stored within an LDAP. Many applications, eg. AD, seem to store passwords to allow users to log onto apps or computers. However, AD is open and can usually be viewed by anyone. So, where is the password? Can I pull passwords out of an LDAP? A: AD stroes the password in an attribute called unicodepwd. This is a one way hash. Even if you can view it,you can not retrieve the password. Also this attribute can not be viewed with regular ldap searches. You have to use ldapi interface to retrieve it. Which means you have to be on the local machine.
{ "language": "en", "url": "https://stackoverflow.com/questions/5798598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: predicate from js to objective C I had a .js file for my screenshot automation with Instruments.app where I was looking up a cell with the following predicate: var classScheduleCell = classScheduleTableView.cells().firstWithPredicate("isEnabled == 1 && NONE staticTexts.value BEGINSWITH 'No classes'").withValueForKey(1, "isVisible"); I want to translate that predicate to an objective C UI test, as the ruby scripts I was using for the screenshots now uses UI testing instead of Instruments. Using the same predicate fails XCUIElement *firstCell = [classScheduleTableView.cells elementMatchingPredicate:[NSPredicate predicateWithFormat:@"isEnabled == 1 && NONE staticTexts.value BEGINSWITH 'No classes'"]]; Looks like I can make the first part of the predicate work changing isEnabled == 1 for enabled == true Any ideas on how to make the other part work? A: I found a solution for this, though is not the most elegant. I couldn't find a way to make a predicate to work as the one I had in UI Automation, so I used a couple of for loops to check the value of the cell labels. NSPredicate *enabledCellsPredicate = [NSPredicate predicateWithFormat:@"enabled == true "]; XCUIElementQuery *enabledCellsQuery = [classScheduleTableView.cells matchingPredicate:enabledCellsPredicate]; int cellCount = enabledCellsQuery.count; for (int i = 0; i < cellCount; i++) { XCUIElement *cellElement = [enabledCellsQuery elementBoundByIndex:i]; XCUIElementQuery *cellStaticTextsQuery = cellElement.staticTexts; int textCount = cellStaticTextsQuery.count; BOOL foundNoClasses = NO; for (int j = 0; j < textCount; j++) { XCUIElement *textElement = [cellStaticTextsQuery elementBoundByIndex:j]; if (textElement.value && [textElement.value rangeOfString:NSLocalizedString(@"No classes", nil) options:NSCaseInsensitiveSearch].location != NSNotFound) { foundNoClasses = YES; break; } } if (foundNoClasses == NO) { [cellElement tap]; break; } } Thanks @joe-masilotti for your help anyway. A: I don't believe your exact predicate is possible with UI Testing. UI Testings vs UI Automation Matching predicates with UI Testing (UIT) behaves a little differently than UI Automation (UIA) did. UIA had more access to the actual UIKit elements. UIT is a more black-box approach, only being able to interact with elements via the accessibility APIs. NOT Predicate Breaking down your query I'm assuming the second part is trying to find the first cell not titled 'No classes'. First, let's just match staticTexts. let predicate = NSPredicate(format: "NOT label BEGINSWITH 'No classes'") let firstCell = app.staticTexts.elementMatchingPredicate(predicate) XCTAssert(firstCell.exists) firstCell.tap() // UI Testing Failure: Multiple matches found As noted in the comment, trying to tap the "first" cell raises an exception. This is because there is more than one match for a text label that starts with "No classes". NONE Predicate Using the NONE operator of NSPredicate leads us down a different path. let predicate = NSPredicate(format: "NONE label BEGINSWITH 'No classes'") let firstCell = app.staticTexts.elementMatchingPredicate(predicate) XCTAssert(firstCell.exists)// XCTAssertTrue failed: throwing "The left hand side for an ALL or ANY operator must be either an NSArray or an NSSet." - This approach can't even find the cell. This is because the elementMatchingPredicate() expects the predict to return a single instance, not an array or set. I couldn't figure out how to make the query select the first element. And once you get an XCUIElement there are no ways to farther restrict it. Different Approach That said I suggest you take a slightly different approach for your test. If your tests are deterministic, and they should be, just tap the first known cell. This means you don't have to worry about ambiguous matchers nor chaining predicates. let firstCell = app.staticTexts["Biology"] XCTAssert(firstCell.exists) firstCell.tap()
{ "language": "en", "url": "https://stackoverflow.com/questions/33349909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android TextView multiline has extra space Multiline TextViews with android:layout_width="wrap_content" automatically take up maximum space as if they become match_parent. Is there any way keep the true wrap_content behavior? Example xml: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/rounded_bg" android:backgroundTint="@color/colorAccent" android:text="Example text" android:textAlignment="center" android:textColor="#fff" android:textSize="28sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:background="@drawable/rounded_bg" android:backgroundTint="@color/colorAccent" android:text="Example text ================" android:textAlignment="center" android:textColor="#fff" android:textSize="28sp" /> <TextView android:layout_width="270dp" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:background="@drawable/rounded_bg" android:backgroundTint="@color/colorAccent" android:text="Example text ================" android:textAlignment="center" android:textColor="#fff" android:textSize="28sp" /> </LinearLayout> * *Single line *Multiline *How I want it to look I want to remove the extra space at the left and right ends of the multiline text. The effect can be done if I manually set the layout_width to some specific value like 270dp, but then it becomes arbitrary. I prefer to keep it as wrap_content. EDIT: The purpose of this is that I want to use a custom background, rounded bg that fits onto the text. I've edited the example xml and the images. A: Try it programmatically in .java file without changing xml file SpannableString s = new SpannableString("your content"); s.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.colorAccent)), 0, s.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); text.setText(s);
{ "language": "en", "url": "https://stackoverflow.com/questions/69592710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Time complexity analysis of search problem I was introduced to an example interview question, where given a 2D array of characters and a word, find the word in the array, where the next character of the word is either to the right or below the previous character, and return a list of the co-ordinates of each character found. I wrote the following code to solve this: co_ords = [] def init_recursion(word, grid): co_ords.clear() return find_word(word, grid, 0, 0, True, 0) def find_word(word, grid, x, y, explore, pos): word_len = len(word) - pos if word_len == 0: return True x_size = len(grid[0]) y_size = len(grid) if word_len > (x_size - x) + (y_size - y): return False try: char_on = grid[y][x] if word[pos] == char_on: co_ords.append((y, x)) if find_word(word, grid, x + 1, y, False, pos + 1): return True elif find_word(word, grid, x, y + 1, False, pos + 1): return True else: co_ords.pop() if word_len - 1 > (x_size - x) + (y_size - y): return False if explore and find_word(word, grid, x + 1, y, True, 0): return True else: return explore and find_word(word, grid, x, y + 1, True, 0) except IndexError: return False # Valid grid and word combinations: grid1 = [ ['c', 'c', 'x', 't', 'i', 'b'], ['c', 'c', 'a', 't', 'n', 'i'], ['a', 'c', 'n', 'n', 't', 't'], ['t', 'c', 's', 'i', 'p', 't'], ['a', 'o', 'o', 'o', 'a', 'o'], ['o', 'a', 'a', 'a', 'o', 'o'], ['k', 'a', 'i', 'c', 'k', 'i'] ] word1 = 'catnip' >>> [(1, 1), (1, 2), (1, 3), (2, 3), (3, 3), (3, 4)] word2 = 'cccc' >>> [(0, 0), (0, 1), (1, 1), (2, 1)] (one choice of many) word3 = 's' >>> [(3, 2)] word4 = 'bit' >>> [(0, 5), (1, 5), (2, 5)] My complexity analysis for this is as follows: Where: * *R = number of rows *C = number of columns *W = characters in word The find_word function will loop through the entire 2D grid RC - W2 times, and for each exploration call, could recuse up to Wlog(W) times attempting to find a match. There would therefore be a total of Wlog(W)(RC - W2) recursive calls at the worst case. Hence my questions: * *One, have I got the complexity analysis of the above correct? *Two, in big O notation (worst case time complexity), how would this be represented? I think that it could be one of the following: * *O(RCW(log(W)) - W3) *O(RCW(log(W))) But I'm not sure which - normally the smaller term would be ignored in big O, however I'm not sure, as W is present in both the n3 and n3log(n) terms. A: I disagree with your search depth being O(Wlog(W)). In the worst case, where every intermediate letter (except the last) matches the word, your recursion will have a branching factor of 2, and will explore 2^W paths. Take, as an example, an extremely large grid, filled entirely with As, and a sole B in the lower right corner, and a search word AAA...AB. You can see how that would explode exponentially (with respect to W). You are correct too, in that you'd ignore the smaller term, so overall I think the time complexity should be O(RC*2^W).
{ "language": "en", "url": "https://stackoverflow.com/questions/70964576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can't convert int pointer array to double pointer array in a function I have a function that is supposed to convert an int pointer array to a double pointer array. It looks like this: double* intToDouble(int len , int*x){ double* y; y =(double*)malloc(len*sizeof(double)); for (int i=0; i<len ; i++){ y[i]=(double)x[i]; } return y; } However, when trying to use it, I get an array full of float 0's . I will also leave here my print array function in case it is relevant. void printDoubleSignal(int len, double* x) { printf("%d: [", len); if (len > 0) { printf("%lf", x[0]); for (int i = 1; i < len; i++) printf(",%lf", x[i]); } printf("]\n"); } This is the result that I get after trying to convert from int to float the array 10: [1,2,3,4,5,0,0,0,0,0] 10: [0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000] EDIT As requested, here is the rest of the code: #include <stdio.h> #include <stdlib.h> #include <complex.h> #include <math.h> int* readSignal(int* len) { int* x; char c; scanf("%d:", len); x = calloc(*len, sizeof(int)); do c = getchar(); while (c != '['); if (*len > 0) { scanf("%d", &x[0]); for (int i = 1; i < *len; i++) scanf(",%d", &x[i]); } do c = getchar(); while (c != ']'); return x; } void printSignal(int len, int* x) { printf("%d: [", len); if (len > 0) { printf("%d", x[0]); for (int i = 1; i < len; i++) printf(",%d", x[i]); } printf("]\n"); } void printDoubleSignal(int len, double* x) { printf("%d: [", len); if (len > 0) { printf("%lf", x[0]); for (int i = 1; i < len; i++) printf(",%lf", x[i]); } printf("]\n"); } int* zeroPad(int len, int* x, int n){ int i; x = (int*)realloc(x, sizeof(int) * n); for (i=len; i<n ; i++){ x[i]=0; } return x; } double* intToDouble(int len , int* x){ double *y; y =(double*)malloc(len*sizeof(double)); for (int i=0; i<len ; i++){ printf("x[%d]=%lf\n",i, x[i]); y[i]=x[i]; printf("y[%d]=%lf\n",i, y[i]); } return y; } int main() { int *x , len=5; double *y; x = readSignal(&len); printSignal(len,x); x = zeroPad(&len,x,10); printSignal(len,x); y = intToDouble(len,x); printDoubleSignal(len ,y); return 0; } EDIT 2 This is the exact text of the input/output (first line is input, the rest is output): 5:[1,2,3,4,5] 5: [1,2,3,4,5] 10: [1,2,3,4,5,0,0,0,0,0] x[0]=-0.000000 y[0]=-0.000000 x[1]=-0.000000 y[1]=-0.000000 x[2]=-0.000000 y[2]=-0.000000 x[3]=-0.000000 y[3]=-0.000000 x[4]=-0.000000 y[4]=-0.000000 x[5]=-0.000000 y[5]=-0.000000 x[6]=-0.000000 y[6]=-0.000000 x[7]=-0.000000 y[7]=-0.000000 x[8]=-0.000000 y[8]=-0.000000 x[9]=-0.000000 y[9]=-0.000000 10: [0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000] A: You forgot to receive the result of zeroPad. The function uses realloc(), so the passed pointer may be invalidated. The function returns the new pointer, so you have to assign that to x. This means that the line in the main() function zeroPad(5,x,10); should be x = zeroPad(5,x,10);
{ "language": "en", "url": "https://stackoverflow.com/questions/65601154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Customize 'at' with extra parameters for the closure? Is it possible to specify some optional parameter(s) to the 'at' closure on the page like this: class ManagerDashboardClientsPage extends Page { static at = { year, geo -> if (year) { GebUtil.selectedYear == year } title.endsWith('Dashboard: Clients') } } so that I can write both at ManagerDashboardClientsPage and at ManagerDashboardClientsPage(2013, 'North East') Currently the first one breaks with No signature of method: page.ManagerDashboardClientsPage$__clinit__closure1.doCall() is applicable for argument types: () values: [] Possible solutions: doCall(java.lang.Object, java.lang.Object), call(), call([Ljava.lang.Object;), call(java.lang.Object), call(java.lang.Object, java.lang.Object), equals(java.lang.Object) groovy.lang.MissingMethodException: No signature of method: page.ManagerDashboardClientsPage$__clinit__closure1.doCall() is applicable for argument types: () values: [] Possible solutions: doCall(java.lang.Object, java.lang.Object), call(), call([Ljava.lang.Object;), call(java.lang.Object), call(java.lang.Object, java.lang.Object), equals(java.lang.Object) at geb.Page.verifyThisPageAtOnly(Page.groovy:165) at geb.Page.verifyAt(Page.groovy:133) at geb.Browser.doAt(Browser.groovy:358) at geb.Browser.at(Browser.groovy:289) at geb.spock.GebSpec.methodMissing(GebSpec.groovy:51) at spec.ManagerDashboardClientsSpec.login as CEO(ManagerDashboardClientsSpec.groovy:16) A: In Groovy you can set default values for optional closure parameters, like so: static at = { year=null, geo=null -> ... } I think that'll clear ya up. :) update Ok, I know you don't need it anymore, but I made this for my own use when I was learning Groovy, and I thought someone might find it helpful: * *{ -> ... } a closure with exactly zero parameters. Groovy will blow up if you call it with params. *{ ... } a closure with one optional parameter, named "it" *{ foo -> ... } a closure with one parameter named "foo" (foo can be any type) *{ foo, bar, baz -> ... } a closure with 3 parameters named "foo", "bar" and "baz" *{ String foo -> ... } You can specify the type of the parameters if you like
{ "language": "en", "url": "https://stackoverflow.com/questions/21740702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: dyld: Library not loaded: @rpath/libswiftContacts.dylib dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib dyld: Library not loaded: @rpath/libswiftCore.dylib. Issue persist I know that theses question have been answered several times, but "dyld: Library not loaded: @rpath/libswiftContacts.dylib" I have not been able to find a proper solution to this error when I am coding a Swift application for XCode 7.2: Here I use Contact & ContactUI Frameworks:: @rpath/libswiftContacts.dylib dyld: Library not loaded: @rpath/libswiftContacts.dylib Referenced from: /var/mobile/Containers/Bundle/Application/C0F2B5CB-628C-4643-9473-648D3099D8FB/HomeMadeFood_User.app/HomeMadeFood_User Reason: image not found I have tried all these actions: * *Restarting Xcode, iPhone, computer *Cleaning & rebuilding *Revoking and creating new certificate/provision profile *Runpath Search Paths is '$(inherited) @executable_path/Frameworks' *Embedded Content Contains Swift Code is 'Yes' *Code Signing Identity is developer *deleting Xcode's Derived Data directory. but I have always got the same error... I tried like this: but i am getting an error like: /Users/mac-jarc/Library/Developer/Xcode/DerivedData/HomeMadeFood_User-bmwdevsopruaqxfrbibhaspidobn/Build/Products/Debug- iphoneos/HomeMadeFood_User.app/Frameworks/Contacts.framework: bundle format unrecognized, invalid, or unsuitable Command /usr/bin/codesign failed with exit code 1 A: In our case, it was clear that there was a bug in the way Xcode was resolving dependencies to our target. Let's me start by saying, the solution was: import PassKit Now, before you raise that eyebrow, here is why this worked: * *We relied on a Swift framework that imports PassKit *We distributed the prebuilt binary to team members *The team observed the crash, just as OP mentioned it *Adding that import in the app target made Xcode embed the required swift libraries Note: Just linking PassKit in the GUI did absolutely nothing. A: Cracked it. Check if the framework you're trying to build or one of it's dependency framework uses any of the Swift standard libraries. If yes, create a NEW key in the build settings ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; A: I had this same error for a couple of weeks: dyld: Library not loaded: @rpath/libswiftContacts.dylib Basically I was able to run and test my app on device. Then about 2 weeks ago, I wasn't able to run the tests on device anymore. Tests were running fine on simulator. I can't think what changed. The error I saw was the one above. I searched Google for ages trying to find a solution, and tried many fixes unsuccessfully. The fix that finally worked was to delete the Derived Data. Once I did this, I was once again able to run the tests on my device. Fix that worked for me: * *Go to Xcode > Preferences > Locations > Derived Data (click on little arrow to open up the folder in finder) e.g. /Users/[username]/Library/Developer/Xcode/DerivedData *Delete the entire DerivedData folder *Clean/Build *Test on device - finally works again A: This error is caused due to invalid certification of Apple. Go to your keychain access. Under "Keychains" select "System" and under "Category" select "Certificates". Check whether the "Apple Worldwide Developer Relations Certification Authority" is valid or not. If not download that certificate from Apple site. It'll solve the problem. A: I know this is old question, but this is what helped me Speaking shortly: EMBEDDED_CONTENT_CONTAINS_SWIFT = YES
{ "language": "en", "url": "https://stackoverflow.com/questions/34986456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Sign up form data is not storing on firebase except the image I'm trying to create sign up form in react-native using Firebase.I've used Fetch Blob and Document Picker libraries for getting image and upload it to firebase. And I'm also trying to save the user's name, email, and password in realtime database. But unfortunately, the user data is not going to save in database except the image is uploaded in the firebase storage. Here is my Firebase Auth Code handleSignupOnPress = () => { const {image, email, password} = this.state; let validation = this.validateData(); console.warn(validation); if (validation == true) { this.toggleLoading(); firebaseService .auth() .createUserWithEmailAndPassword(email, password) .then(() => { // console.warn("User SignUp Successfully"); this.uploadImage(image); }) .catch(error => { this.toggleLoading(); var errorCode = error.code; var errorMessage = error.message; alert(errorMessage); // console.warn("ERROR => ", errorCode, errorMessage); }); } }; Here is image Upload Code // First Uploading image and download Image URI then call saveUserToDB()... uploadImage(uri, mime = 'image/jpeg') { return new Promise((resolve, reject) => { const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri; let uploadBlob = ''; const imageRef = firebaseService .storage() .ref('images') .child(uuid.v4()); fs.readFile(uploadUri, 'base64') .then(data => { return Blob.build(data, {type: `${mime};BASE64`}); }) .then(blob => { uploadBlob = blob; return imageRef.put(blob, {contentType: mime}); }) .then(() => { uploadBlob.close(); const downnloadImageURI = imageRef.getDownloadURL().then(url => { this.setState( { imageURI: url, }, () => { alert('ImageURI ==> ', this.state.imageURI); this.saveUserInfo(); }, ); }); return downnloadImageURI; }) .then(url => { resolve(url); }) .catch(error => { this.toggleLoading(); reject(error); }); }); } Here is code for saving user's data saveUserInfo = () => { const {userName, email, password, imageURI} = this.state; const {navigate} = this.props.navigation; const uid = firebaseService.auth().currentUser.uid; const params = { image: imageURI, username: userName, email: email, password: password, }; //firebaseService.database().ref('/Users').push(params) firebaseService .database() .ref('/Users') .child(uid) .set(params) .then(res => { this.toggleLoading(); navigate('Login'); }) .catch(err => { alert(err); }); }; Here are screenshots of Firebase Console A: Are the "Rules" in database given permission to "Write" * *Go to the firebase console and open your project. *Go to the database and search for "Rules" tab. *Check the rules are set as below { /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */ "rules": { ".read": true, ".write": true } } A: I've solved this issue. The issue was in this piece of code. const downnloadImageURI = imageRef.getDownloadURL().then(url => { this.setState( { imageURI: url, }, () => { alert('ImageURI ==> ', this.state.imageURI); this.saveUserInfo(); }, ); setState was not working and calback was not fired. And I've made it like this way const downnloadImageURI = imageRef.getDownloadURL().then(url => { this.saveUserInfo(url) );}
{ "language": "en", "url": "https://stackoverflow.com/questions/60134931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: getting latitude and longitude of an address in android using gps and without using internet connection I want to know if gps can be used to get the latitude and longitude of an address.I've just began to work on gps on android.My problem is that if the user does not have internet connection, i want him to be able to get the latitude and longitude of an address.Can gps do that or it is only used to get current location.If not are they any other way of getting this done.I;m using google maps and i've also tried to get geocoding as mentioned in some posts,but it does not work. A: From your question, If you are using Google Map and GeoCoder class that means you must have Internet connection. And moreover when you are working with GPS, again you must have Internet Connection. If you are using GPS_PROVIDER then you required open sky type environment and for NETWORK_PROVIDER you can fetch gps details inside a room,but for both provider Internet is must. A: You are missing the point of what GPS is designed to do. Your phone's GPS doesn't do anything with an address. All GPS does is get the latitude/longitude of your current position, nothing more. The phone (via an internet connection) is able to identify your address based on the Latitude/Longitude that the GPS provides by using 3rd party provides (such as Google Maps) It sounds like you just want to get the latitude/longitude of any address, not just for the device's physical location. That does not require GPS at all. But it needs an internet connection in order to access a provider to perform the geocoding. A answer I provided to Does GPS require Internet? is a somewhat related to your issue. The 2nd to last paragraphs are pertinent here as well While it requires a significant amount of effort, you can write your own tool to do the reverse geocoding, but you still need to be able to house the data somewhere as the amount of data required to do this is far more you can store on a phone, which means you still need an internet connection to do it. If you think of tools like Garmin GPS Navigation units, they do store the data locally, so it is possible, but you will need to optimize it for maximum storage and would probably need more than is generally available in a phone. So effectively, you theoretically could write your own tool, cache data locally and query it as needed, but that not something that is easily done.
{ "language": "en", "url": "https://stackoverflow.com/questions/22192767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tomcat maven plugin: Unable to find jdbc By using the tomcat7-maven-plugin I launch my spring web application that needs to connect to a Mysql database. However, when attempting this I get the error "unable to find jdbc". Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is javax.naming.NameNotFoundException: N ame [jdbc/contentDataSource] is not bound in this Context. Unable to find [jdbc]. My pom file includes. <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>9001</port> <path>/webapp</path> <serverXml>./src/main/tomcat/config/server.xml</serverXml> <contextFile>./src/main/tomcat/config/context.xml</contextFile> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <type>jar</type> <version>5.0.8</version> </dependency> </dependencies> </plugin> Context.xml file: <?xml version='1.0' encoding='utf-8'?> <Context> <ResourceLink global="jdbc/contentDataSource" name="jdbc/contentDataSource" type="javax.sql.DataSource"/> </Context> Server.xml includes: <GlobalNamingResources> <Resource name="jdbc/contentDataSource" auth="Container" type="javax.sql.DataSource" driverClassName="org.gjt.mm.mysql.Driver" url="jdbc:mysql://database.lan/databaseName" username="root" password="pass" /> </GlobalNamingResources> web.xml includes at the end: <resource-ref> <res-ref-name>jdbc/contentDataSource</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> </web-app> WEB-INF/applicationContext.xml includes at the beginning: <beans> <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jdbc/contentDataSource" /> <property name="resourceRef" value="true" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"> <ref local="dataSource" /> </property> </bean> Why is JDBC not recognized?
{ "language": "en", "url": "https://stackoverflow.com/questions/40659413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set a text inside a button to drop the shadow in JavaFX So i have a custom button class in controller and i want to make the font which will be Inside of button to drop a shadow. i've tried to use -fx-stroke, but it doesn't seem to change anything. Buttons which i want to use will be generated during the program. i'm not familiar with CSS so i just used some examples. Now i have this mineButton(int x, int y,boolean difficult){ this.x=x; this.y=y; Font s = new Font(13); if (difficult){ this.setMaxSize(35, 35); this.setMinSize(20, 20); this.setPrefSize(20, 20); this.setFont(new Font(8)); } else { this.setMaxSize(35,35); this.setMinSize(33,33); this.setPrefSize(34,34); } this.setStyle("-fx-background-color: -fx-outer-border, -fx-inner-border, -fx-body-color;\n" + " -fx-background-insets: 0, 1, 2;" + " -fx-background-radius: 5, 4, 3;" + " -fx-text-fill: white; -fx-font-weight: bold;" ); } A: You can use the setGraphic method to change the appearance of the Node inside your Button. Here's a documentation with an example about how to do it: Using JavaFX UI Controls - Button. You can then apply CSS to that custom Node of yours. Example: Button button = new Button(); Label label = new Label("Click Me!"); label.setStyle("-fx-effect: dropshadow( one-pass-box , black , 8 , 0.0 , 2 , 0 )"); button.setGraphic(label);
{ "language": "en", "url": "https://stackoverflow.com/questions/28382371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to check the CPU and memory load in percentages of a process then output that to a file? I have searched with no luck. The onlything I am able to find is the entire servers load, which I do not want. I want to specifically check how much CPU and memory a process is using, preferably CPU in percentages and memory in MB. A: You can get the CPU and memory usage of a process using ps. If you know the pid of the process, then a command like this will give you the percentage CPU usage and memory usage in kilobytes: ps -o pcpu,rss -p <pid> You can redirect the output of this to a file in the usual way, and do whatever you want with it. Other variables that you can get in this way can be found in man ps (or here), in the section on Standard Format Specifiers.
{ "language": "en", "url": "https://stackoverflow.com/questions/20505760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Resolution failed exception in Xamarin IOS prism I have an iOS application written in Xamarin and I am getting a Unity Exceptions Resolution Failed exception when I try and run the application in iOS. However this error does not happen when I run the android version of the application. The exception is being thrown while the initalize function from prism is taking place. Here is a snippet from my app.xaml.cs protected override void RegisterTypes(IContainerRegistry containerRegistry) { this.RegisterLocal(containerRegistry); this.RegisterServices(containerRegistry); this.RegisterPagesForNavigation(containerRegistry); } This code all executes and passes. This is the iOS initialization Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); PullToRefreshLayoutRenderer.Init(); LoadApplication(new App(new IosInitializer())); return base.FinishedLaunching(app, options); } public class IosInitializer : IPlatformInitializer { public void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.Register<IUAirshipUpdate, UAirshipUpdate>(); } } This code also executes The exception being thrown is an argument null exception indicating that IModuleCatelog is not present. I do not understand why it is looking for that module and can not find it. The source code on GitHub indicates that class was registered. A: This issue was caused because linker behavior for IOS application was set to full and that causes issues with Unity IOC Container.
{ "language": "en", "url": "https://stackoverflow.com/questions/55543201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is wrong with this JOIN query? I have a list of tenant reports, each link pointing to a report ID. I need this query to select the report information, and some of the information related to the tenant who submit it. This query gets the report information correctly, but returns copies of it with every tenant attached to it: SELECT reports.person_reporting, reports.request_type, reports.details, tenants.office, tenants.email, tenants.alt_email, tenants.office_phone, tenants.personal_cell, tenants.emergency_phone, tenants.address, tenants.building_name FROM reports, tenants WHERE reports.id = '{$id}' AND ( tenants.email = reports.email OR tenants.alt_email = reports.alt_email ) in that AND clause, I need it to match the tenant email address with the one contained in the report with the specified ID. But it's just getting every tenant with an email or alternate email that matches any email or alternate email in the reports (almost all of them, since most of them don't have an alternate email specified). Is there any way for me to do this? update My problem was that there were lots of empty alt_email fields, and it was just picking all of them. The answers below were right in filtering out the empty fields, but I just changed my OR clause to an AND clause, which was more clear about how I wanted to match them anyways: they both have to match because there shouldn't be any duplicate emails in the database. A: You should probably filter out the 'null' emails, like this. AND ( (tenants.email != '' AND tenants.email = reports.email) OR (tenants.alt_email != '' AND tenants.alt_email = reports.alt_email) ) In reality, this seems like it ought to be a left join, i.e.: SELECT reports.person_reporting, reports.request_type, reports.details, tenants.office, tenants.email, tenants.alt_email, tenants.office_phone, tenants.personal_cell, tenants.emergency_phone, tenants.address, tenants.building_name FROM reports LEFT JOIN tenants ON ( (tenants.email != '' AND tenants.email = reports.email) OR (tenants.alt_email != '' AND tenants.alt_email = reports.alt_email) ) WHERE reports.id = '{$id}' This way, you will get the reports with no tenants at least once. A: I'd assume that your problem is that there are a bunch of tenants with alt_email = NULL, and a bunch of reports with alt_email = NULL, and your OR clause will match each report with alt_email = NULL with all the tenants records with alt_email = NULL. You should probably catch the NULL case: WHERE reports.id = '{$id}' AND ( (tenants.email IS NOT NULL AND tenants.email = reports.email) OR (tenants.alt_email IS NOT NULL AND tenants.alt_email = reports.alt_email) )
{ "language": "en", "url": "https://stackoverflow.com/questions/1911868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot remove event from fullcalendar I am using fullcalendar http://fullcalendar.io/ whenever my user creates an event on the calendar by selecting a timeslot, he generates an event object with a unique_id which is then pushed into a hidden field as JSON. select: function(start, end, id, allDay) { // generate unique id function guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } var eventData = { start: start, end: end, unique_id: guid(), block: true, editable: true, backgroundColor: "#469278" }; // console.log(moment(eventData.start["_d"]).format("dddd")); // console.log(moment(eventData.end["_d"]).format("dddd")); $('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true // console.log(eventData); // if (moment(eventData.start["_d"]).format("dddd") != moment(eventData.end["_d"]).format("dddd")) { // $('#calendar').fullCalendar('unselect'); // } // console.log(start); var day = moment(eventData.start["_d"]).format("dddd"); var start_time = moment(eventData.start["_d"]).format("HH:mm"); var end_time = moment(eventData.end["_d"]).format("HH:mm"); var id = moment(eventData.unique_id)["_i"]; // console.log(id); var slot = { day: day, start_time: start_time, end_time: end_time, id: id }; array_dispo.push(slot); $("#dispo_array").val(JSON.stringify(array_dispo)); $('#calendar').fullCalendar('unselect'); }, I am then trying to delete this specific event from the calendar by clicking on it using fullcalendar method http://fullcalendar.io/docs1/event_data/removeEvents/ eventClick: function(event, element) { console.log(event); console.log(event.unique_id); if(confirm('Voulez-vous supprimer cette dispo?')) { $('#calendar').fullCalendar('removeEvents', event.unique_id); } }, Unfortunately the event is never removed from the calendar... Any ideas ? A: Instead of using a custom field unique_id, you should use the field provided for the event: id eventClick: function(event, element) { console.log(event); console.log(event.id); if(confirm('Voulez-vous supprimer cette dispo?')) { $('#calendar').fullCalendar('removeEvents', event.id); } }, events: [{ id: 1, title: 'Some Event', start: new Date(y, m, d + 1, 19, 0), end: new Date(y, m, d + 1, 22, 30), allDay: false }, { [...] Here is an example that works: enter link description here
{ "language": "en", "url": "https://stackoverflow.com/questions/32986879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: best way to serialize json android I'm quite new in android development. I have an app and I'm going with retrofit for the network requests. to handle the response there are some good libraries that I found such as gson , jackson , moshi and som much more. I'm abit confused and I can't decide what I should go with in this particular case. Any help is appreciated.m A: Probably a duplicate question. But since you're new to Android development this article will explain everything to you. https://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/ In short , if your json response is quite small, go with gson otherwise Jackson is better.
{ "language": "en", "url": "https://stackoverflow.com/questions/49229310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Problem with separating UI views from ASP.net Razor using Angular.js routing SOLVED USING DIRECTIVES INSTEAD. I am trying to separate the UI from my ASP.net Web app which currently uses Razor pages (.cshtml) to present views. I would like the Client side views to be entirely handled by Angular.js using the ng-view directive. I have created a view in StudentForm.html which is a form I would like to inject in my Index.html file so I can re-use it later. However, this is not working as expected and I am getting the following error: HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier). (XHR)GET - http://localhost:61424/Views/StudentForm.html * *I've tried moving the file around to a different folder according to my project structure. *I have made sure to include the script reference at the bottom of my .html file where I am trying to inject the view. index.cshtml: <div ng-app="myApp"> <div ng-controller="StudentCtrl"> <!--The view for the form goes here--> <div ng-view></div> </div> </div> <script src="~/Scripts/angular.min.js"></script> <script src="~/Scripts/angular-route.min.js"></script> <script src="~/ScriptsNg/Module/sepView.js"></script> <script src="~/ScriptsNg/Controller/StudentCtrl.js"></script> <script src="~/ScriptsNg/Service/CrudService.js"></script> my app module: (sepView.js): var sepView = angular.module('myApp', ['ngRoute']); sepView.config(function ($routeProvider) { $routeProvider .when('/', { controller: 'StudentCtrl', templateUrl: 'Views/StudentForm.html' }) .otherwise({ redirectTo: '/' }); }); The StudentForm.html just contains the form so I won't include that. StudentCtrl.js: sepView.controller('StudentCtrl', ['$scope', 'CrudService', function ($scope, CrudService) { // Base Url var baseUrl = '/api/StudentAPI/'; $scope.btnText = "Save"; $scope.studentID = 0; $scope.SaveUpdate = function () { var student = { FirstName: $scope.firstName, LastName: $scope.lasttName, Email: $scope.email, Address: $scope.address, StudentID: $scope.studentID } if ($scope.btnText == "Save") { var apiRoute = baseUrl + 'SaveStudent/'; var saveStudent = CrudService.post(apiRoute, student); //Callback to check what kind of response we received: saveStudent.then(function (response) { if (response.data != "") { alert("Data Saved Successfully"); $scope.GetStudents(); $scope.Clear(); } else { alert("Some error"); } }, function (error) { console.log("Error: " + error); }); } CrudService.js: sepView.service('CrudService', function ($http) { var urlGet = ''; this.post = function (apiRoute, Model) { var request = $http({ method: "post", url: apiRoute, data: Model }); return request; } StudentController that returns the view: namespace CRUDOperations.Controllers { public class StudentController : Controller { // GET: Student public ActionResult Index() { return View(); } public ActionResult viewAllStudents() { return View(); } } } https://imgur.com/a/jAfnnT6 This is the project folder structure. I'm having a lot of trouble grasping the leap from using ASP.net routing and views to using Angular.js for routing and views. If anyone could perhaps point me to some articles about this, that might help!
{ "language": "en", "url": "https://stackoverflow.com/questions/57401346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: No longer unable to retrieve data from QIODevice after calling readAll(). Buffer flushed? I've just noticed something when using QNetworkReply that I was unable to find the slightest hint in the Qt documentation for QIODevice::readAll() (which the QNetworkReply inherits this method from). Here is what the documentation states: Reads all remaining data from the device, and returns it as a byte array. This function has no way of reporting errors; returning an empty QByteArray can mean either that no data was currently available for reading, or that an error occurred. Let's say I have the following connection: connect(this->reply, &QIODevice::readyRead, this, &MyApp::readyReadRequest); Ths readyReadRequest() slot looks like this: void MyApp::readyReadRequest() { LOG(INFO) << "Received data from \"" << this->url.toString() << "\""; LOG(INFO) << "Data contents:\n" << QString(this->reply->readAll()); this->bufferReply = this->reply->readAll(); } The surprise came after I called this->bufferReply (which a QByteArray class member of MyApp). I passed it to a QXmlStreamReader and did: while (!reader.atEnd()) { LOG(DEBUG) << "Reading next XML element"; reader.readNext(); LOG(DEBUG) << reader.tokenString(); } if (reader.hasError()) { LOG(ERROR) << "Encountered error while parsing XML data:" << reader.errorString(); } Imagine my surprise when I got the following output: 2017-10-17 16:12:18,591 DEBUG [default] [void MyApp::processReply()][...] Reading next XML element 2017-10-17 16:12:18,591 DEBUG [default] [void MyApp::processReply()] [...] Invalid 2017-10-17 16:12:18,591 ERROR [default] Encountered error while parsing XML data: Premature end of document Through debugging I got that my bufferReply at this point is empty. I looked in the docs again but couldn't find anything that hints removing the data from the device (in my case the network reply) after reading it all. Removing the line where I print the byte array or simply moving it after this->bufferReply = this->reply->readAll(); and then printing the contents of the class member fixed the issue: void MyApp::readyReadRequest() { LOG(INFO) << "Received data from \"" << this->url.toString() << "\""; this->bufferReply = this->reply->readAll(); LOG(INFO) << "Data contents:\n" << QString(this->bufferReply); } However I would like to know if I'm doing something wrong or is the documentation indeed incomplete. Since readAll() doesn't report errors or that data is not available at the given point in time returning an empty byte array is the only thing that hints towards the fact that something didn't work as intended. A: Yes. When you call QIODevice::readAll() 2 times, it is normal that the 2nd time you get nothing. Everything has been read, there is nothing more to be read. This behavior is standard in IO read functions: each call to a read() function returns the next piece of data. Since readAll() reads to the end, further calls return nothing. However, this does not necessarily means that the data has been flushed. For instance when you read a file, it just moves a "cursor" around and you can go back to the start of the file with QIODevice::seek(0). For QNetworkReply, I'd guess that the data is just discarded.
{ "language": "en", "url": "https://stackoverflow.com/questions/46792520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ vector and memoization runtime error issues I encountered a problem here at Codechef. I am trying to use a vector for memoization. As I am still new at programming and quite unfamiliar with STL containers, I have used vector, for the lookup table. (although, I was suggested that using map helps to solve the problem). So, my question is how is the solution given below running into a run time error. In order to get the error, I used the boundary value for the problem (100000000) as the input. The error message displayed by my Netbeans IDE is RUN FAILED (exit value 1, total time: 4s) with input as 1000000000. Here is the code: #include <iostream> #include <cstdlib> #include <vector> #include <string> #define LCM 12 #define MAXSIZE 100000000 using namespace std; /* * */ vector<unsigned long> lookup(MAXSIZE,0); int solve(int n) { if ( n < 12) { return n; } else { if (n < MAXSIZE) { if (lookup[n] != 0) { return lookup[n]; } } int temp = solve(n/2)+solve(n/3)+solve(n/4); if (temp >= lookup[n] ) { lookup[n] = temp; } return lookup[n]; } } int main(int argc, char** argv) { int t; cin>>t; int n; n = solve(t); if ( t >= n) { cout<<t<<endl; } else { cout<<n<<endl; } return 0; } A: I doubt if this is a memory issue because he already said that the program actually runs and he inputs 100000000. One things that I noticed, in the if condition you're doing a lookup[n] even if n == MAXSIZE (in this exact condition). Since C++ is uses 0-indexed vectors, then this would be 1 beyond the end of the vector. if (n < MAXSIZE) { ... } ... if (temp >= lookup[n] ) { lookup[n] = temp; } return lookup[n]; I can't guess what the algorithm is doing but I think the closing brace } of the first "if" should be lower down and you could return an error on this boundary condition. A: You either don't have enough memory or don't have enough contiguous address space to store 100,000,000 unsigned longs. A: This mostly is a memory issue. For a vector, you need contiguous memory allocation [so that it can keep up with its promise of constant time lookup]. In your case, with an 8 byte double, you are basically requesting your machine to give you around 762 mb of memory, in a single block. I don't know which problem you're solving, but it looks like you're solving Bytelandian coins. For this, it is much better to use a map, because: * *You will mostly not be storing the values for all 100000000 cases in a test case run. So, what you need is a way to allocate memory for only those values that you are actually memoize. *Even if you are, you have no need for a constant time lookup. Although it would speed up your program, std::map uses trees to give you logarithmic look up time. And it does away with the requirement of using up 762 mb contiguously. 762 mb is not a big deal, but expecting in a single block is. So, the best thing to use in your situation is an std::map. In your case, actually just replacing std::vector<unsigned long> by std::map<int, unsigned long> would work as map also has [] operator access [for the most part, it should].
{ "language": "en", "url": "https://stackoverflow.com/questions/9029899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: RxJS cancellable HTTP queue I'm trying to implement some sort of queueing with support for cancelling (or not) an ongoing HTTP request. In my head, it looks something like this, but I can't seem to find the "propper tools" for the job :/ * *Click Load More for Item A *Send Http Request for Item A *Click Load More for Item B *Send Http Request for Item B *Click (again) Load More for Item B (while the previous Request was still ongoing) *Should cancel previous Request for Item B *Should Send Http Request for (the new) Item B *Click Load More for Item A (currently an ongoing Request for Item B is active) *It, doesn't matter: Send Http Request for Item A My first idea was to use a takeUntil together with the concatMap and somehow cancel the ongoing request. But then, how can I actually check the items of the queue? It feels like I'm missing a handy operator. // in the service queue.pipe( tap(()=> { how to check and trigger sameItem$.next() }) // using concatMap to process every item from the queue sequentially concatMap((item) => this.httpClient.get(item)).pipe(takeUntil(this.sameItem$)) ).subscribe((x)=> {console.log('response', x)}) // In the component loadMore(item){ this.queueService.queue.next(item); } I was also thinking about using switchMap or concatMap based on "is the item already in the queue?" but I don't even know if this makes any sense :) Also don't mind if the solution goes on a different direction, as long as I can leverage the power of RxJS! A: Assuming you have some kind of id in the item, you could do something like this. queue.pipe( groupBy((item) => item.id), // split queue values into independent obs based on grouping key mergeMap( // process each group obs in parallel (group$) => group$.pipe( switchMap((item) => this.httpClient.get(item)) //cancel prev req in the group if still running ) ) ) .subscribe(console.log); cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/72484869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Change ImageView dynamically from IndoorAtlas I have this following code : public void futureResult() { FutureResult<FloorPlan> result = mIndoorAtlas.fetchFloorPlan(mFloorPlanId); result.setCallback(new ResultCallback<FloorPlan>() { @Override public void onResult(final FloorPlan result) { mFloorplan = result; loadFloorPlanImage(result); } And this : public void loadFloorPlanImage(FloorPlan floorPlan) { BitmapFactory.Options options = createBitmapOptions(floorPlan); final FutureResult<Bitmap> result = mIndoorAtlas.fetchFloorPlanImage(floorPlan, options); result.setCallback(new ResultCallback<Bitmap>() { @Override public void onResult(final Bitmap result) { //updateImageViewInUIThread(result) <-------this is where im getting confused } I have problem with set image in imageview with an instance of indooratlas. Anyone can help me ? A: Again, your question is about generic ImageView use and the source of the image doesn't have much to do with it. Did you check the tutorial I linked in your previous question? It has a section on using ImageViews: http://developer.android.com/training/displaying-bitmaps/display-bitmap.html
{ "language": "en", "url": "https://stackoverflow.com/questions/30234994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing parameter from jsf to bi publisher report I've been trying to solve one tricky problem. How does one pass a parameter, say, an integer from jsf page to the actual bi report? In more detail: [jsf page]---backing bean takes parameter(an id)---?--- bi report with parameter input(id) So far, I tried one approach, which simply was using Javascript to pass the value to the input field and 'click' the search button on the page where bi report is inserted via iframe. The obstacle was same domain policy, couldn't get/set the insides of iframe. Is there any way that a parameter can be passed to BI report? Full scenario: * *User selects a contract *Upon selection, the id of contract is stored in variable in managed bean *When the user clicks the "Info Sheet" button, a new page is loaded with iframe *iframe contains link to different domain *page with BI Report is loaded and there is the input field for contract id that actually needs to be already passed from managed bean. Thanks in advance! A: I believe passing such parameter to IFrame should be done on the page on server. Not with javascript. According to full scenario this is what should have worked but it is not. I believe the managedbean scope is lost and that is why the id is not set on different page. To make this work probably the scope of managed bean should be session not request or view because you go to different page. A: So, after some digging into BI Publisher, found out that parameter can just be passed through url and to iframe. In other words, url should look somewhat like this: "content:port?accessmode&credentials&parameterid".
{ "language": "en", "url": "https://stackoverflow.com/questions/22376206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP flush problem Ok, so I have this PHP script that runs in a nice little infinite loop (with sleeps, don't worry). I use it as a page I can go to from any computer to monitor my database statistics. Every 2 seconds, it gets stats from the DB and displays them on the screen. Now, this works just fine on XAMPP on my Windows machine. I'm trying to get it to work on my linux webserver, running apache2 with PHP 5.3.5, but for some reason it won't actually display anything (it doesn't go to a blank page, it just stays at the page I was at before going to the monitor page, but with the "working" wheel spinning). I feel like this is some sort of caching thing, it doesn't want to display the page until it's finished running the script (although I NEED it to). I use flush() and ob_flush() after every 2 seconds, and I made sure that output_buffering = off and zlib.output_compression = off in my php.ini file. I realize this question seems to have been asked a lot, but I've tried everything I can find on the subject with ultimate failure. NOTE: like I said, this works FINE on my XAMPP install with apache and PHP 5.3.6. My question isn't so much about how to find alternatives, but more with regards to WHY it works there but not on my linux webserver. A: Having php script run for an "infinite" amount of time is almost never appropriate. You can: * *set the page to reload using html (<meta http-equiv="refresh" content="5">) *set it to run and display via a cron script *reload the page regularly using javascript *something else I haven't thought of All of these ways of approaching the problem would save you the type of headaches you're experiencing now. A: Here is what you can do, Have your script write the parameters to the javascript, so you can reload your page every 2 seconds with new parameters. example: <script type='text/javascript'> setTimeout(function() { location.href="http://www.example.com/?jobid=<?php echo $nextJobId ?>"; },2000); </script> so if you need to do a Db offset on each sql query, you can pass that parameter in the url. Having an infinite loop might seem like a good idea, but maybe you should reevalute your code and see if you really need it, or if you can implement it this way
{ "language": "en", "url": "https://stackoverflow.com/questions/5929500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which is the best place to handle the deleted data scenario? I have a WPF application where MVVM model is used. Also, we do have the requirement of showing some data in Dialog() using ShowDialog(). For this purpose, We have a MainWindow call another method in a different class which will actually return an object of type Window. The MainWindow will then show this window by calling the ShowDialog() method. The window class has ViewModel which will have the data that is displayed in the dialog. My problem is How to handle the scenario where in the data is not present in the db ? Should the constructor of the Window() or ViewModel(which one exactly) throw the exception ? If Yes then what type of exception ? Is there any other way of handle this scenario ? A: You aren't laying out the use case so yo aren't going to get the best answer, because the answer DEPENDS on your use case, your domain and your users. That said it's highly unlikely that you want your users to see an exception, even if it is in fact exceptional. Better to either show the dialog with an informative message (ie, "No Items to Display") or just not show it at all. HTH, Berryl
{ "language": "en", "url": "https://stackoverflow.com/questions/13458385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do we do Unit testing for AWS CDK code? And should we? Based on the examples I see, the code assertions are expected json cf template versus the cdk synth generated template. How do we setup expected json cf template? * *If we manually create it, that defeats the purpose of using cdk. *If we just copy paste the cdk synth output, that defeats the purpose of unit testing it. Having said that, is there a purpose on having unit tests for CDK code? Maybe I'm missing the idea here. Please do point it out. A: aws-cdk has a library of testing utilities that are useful for asserting against stacks. The cdk repo uses it itself for a lot of its own unit tests. https://www.npmjs.com/package/@aws-cdk/assert This allows you to do something like // jest test('configurable retention period cannot exceed 14 days', () => { const stack = new MyStack(); expect(stack).to(haveResource('AWS::SomeService::SomeResource', { SomePropertyOnResource: 'some-value-it-should-have' })); }); This is only supported for CDK apps written in typescript as of now, but the plan is to eventually support all languages cdk supports. Whether or not you should do this usually is similar to asking whether you should unit test any codebase. If you have a lot of complex business logic happening that does things like conditionally creating resources or otherwise changing your apps behavior, its probably worth getting some coverage in those places. If your app is essentially a bunch of static declarations without conditionals, loops, etc, maybe you can get by with just running cdk diff when making changes and manually verifying your expected changes. If you're writing custom constructs for reusing in different cdk apps, unit testing those is probably a good idea. Some relevant docs https://docs.aws.amazon.com/cdk/latest/guide/testing.html A: An approach that I use, is to create a different project delegated to use the resources that i expect that have been created. So, from the cdk-init-cluster project, i simply create all the necessary resources using cdk library. Than, after the DEPLOY phase, i run the cdk-init-cluster-test module that is delegated to populate/query/use the resources previously created from the cdk-init-cluster project. This approach, can only help with few type of resources such as: * *S3 bucket *Lambda *AppSync *DynamoDB table The test project is in charge to: * *Populate the DynamoDB table and retrieve the data. *Call the Lambda function with dummy data *Call the lambda function with correct data for verify permission behaviour *Call appsync (that wrap all the resources above) and verify the result Then, i remove the data inserted for test. If no exceptions occurs, the test is passed.
{ "language": "en", "url": "https://stackoverflow.com/questions/60225645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: osx - Linking error, when building POCO library I'm trying to build poco library on osx 10.9 with clang++. I'm running make CXXFLAGS+=-stdlib=libstdc++ CFLAGS+=-stdlib=libstdc++ LDFLAGS+=-stdlib=libstdc++. It've successfully compiled all .o files: ** Compiling src/UUIDGenerator.cpp (release, shared) clang++ -Iinclude -I/Users/croco/Work/poco-1.6.0-all/CppUnit/include -I/Users/croco/Work/poco-1.6.0-all/CppUnit/WinTestRunner/include -I/Users/croco/Work/poco-1.6.0-all/Foundation/include -I/Users/croco/Work/poco-1.6.0-all/XML/include -I/Users/croco/Work/poco-1.6.0-all/JSON/include -I/Users/croco/Work/poco-1.6.0-all/Util/include -I/Users/croco/Work/poco-1.6.0-all/Net/include -I/Users/croco/Work/poco-1.6.0-all/Crypto/include -I/Users/croco/Work/poco-1.6.0-all/NetSSL_OpenSSL/include -I/Users/croco/Work/poco-1.6.0-all/Data/include -I/Users/croco/Work/poco-1.6.0-all/Data/SQLite/include -I/Users/croco/Work/poco-1.6.0-all/Data/ODBC/include -I/Users/croco/Work/poco-1.6.0-all/Data/MySQL/include -I/Users/croco/Work/poco-1.6.0-all/MongoDB/include -I/Users/croco/Work/poco-1.6.0-all/Zip/include -I/Users/croco/Work/poco-1.6.0-all/PageCompiler/include -I/Users/croco/Work/poco-1.6.0-all/PageCompiler/File2Page/include -stdlib=libstdc++ -DNDEBUG -O2 -fasm-blocks -fPIC -c src/UUIDGenerator.cpp -o /Users/croco/Work/poco-1.6.0-all/Foundation/obj/Darwin/x86_64/release_shared/UUIDGenerator.o But when linking, -stdlib flag doesn't used and i receive some errors like this: Undefined symbols for architecture x86_64: "std::basic_string, std::allocator >::data() const", referenced from: Poco::UnicodeConverter::convert(std::basic_string, std::allocator > const&, std::string&) in UnicodeConverter.o "std::basic_string, std::allocator >::length() const", referenced from: Poco::UnicodeConverter::convert(std::basic_string, std::allocator > const&, std::string&) in UnicodeConverter.o What i'm doing wrong? A: Well, my solution is to put -stdlib flag to build/config/Darwin-clang and configure build with required Darwin-clang config.
{ "language": "en", "url": "https://stackoverflow.com/questions/27689882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find and add the node with the same name as a sibling to the find node in c# Trying to find the xml node with a name and add the another new node with the same name as a sibling. Issue: used GetElementsByTagname() method which will give the list of nodes with the name. Looping through the nodes to add a new node with same name as a sibling. It raises an error "The element list has changed. The enumeration operation failed to continue." A: I believe the collection is immutable. You can create a copy of the collection. When you find the elements you want, add them to the collection you have deep cloned. See if you can ToList() the collection to create a copy of your target collection. Also as the code is not in your question, have you considered using InsertAfter() on the parent node or AppendChild() once you have created your elements?
{ "language": "en", "url": "https://stackoverflow.com/questions/50769216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with viewModel and TextField I'm not sure whether it's a SwiftUI bug or it's my fault: When I type some text in a TextField and press the return button on my keyboard (in order to hide my keyboard), the typed text is removed and the TextField is empty again. I've tried this solution on different simulators and on a real device as well. The issue appears every time. I'm using iOS 14.3, Xcode 12.4 TextField view: struct CreateNewCard: View { @ObservedObject var viewModel: CreateNewCardViewModel var body: some View { TextField("placeholder...", text: $viewModel.definition) .foregroundColor(.black) } } ViewModel: class CreateNewCardViewModel: ObservableObject { @Published var definition: String = "" } Main View: struct MainView: View { @State var showNew = false var body: some View { Button(action: { showNew = true }, label: { Text("Create") }) .sheet(isPresented: $showNew, content: { CreateNewCard(viewModel: CreateNewCardViewModel()) }) } } @SwiftPunk: Here is my second question: Let's say my view model has an additional parameter (id): class CreateNewCardViewModel: ObservableObject { @Published var id: Int @Published var definition: String = "" } This parameter needs to be passed when I create the view to my viewModel. For this example let's say we iterate over some elements that have the id: struct MainView: View { @State var showNew = false var body: some View { ForEach(0...10, id: \.self) { index in // <<<---- this represents the id Button(action: { showNew = true }, label: { Text("Create") }) .sheet(isPresented: $showNew, content: { // now I have to pass the id, but this // is the same problem as before // because now I create every time a new viewModel, right? CreateNewCard(viewModel: CreateNewCardViewModel(id: index)) }) } } A: Your issue is here, that you did not create a StateObject in main View, and every time you pressed the key on keyboard you created a new model which it was empty as default! import SwiftUI struct ContentView: View { @State var showNew = false @StateObject var viewModel: CreateNewCardViewModel = CreateNewCardViewModel() // <<: Here var body: some View { Button(action: { showNew = true }, label: { Text("Create") }) .sheet(isPresented: $showNew, content: { CreateNewCard(viewModel: viewModel) }) } } struct CreateNewCard: View { @ObservedObject var viewModel: CreateNewCardViewModel var body: some View { TextField("placeholder...", text: $viewModel.definition) .foregroundColor(.black) } } class CreateNewCardViewModel: ObservableObject { @Published var definition: String = "" }
{ "language": "en", "url": "https://stackoverflow.com/questions/66707506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to compare an EditText to Chronometer? I tried in several ways and I also search a lot but what I found is very confuse to me because I'm relative begginer in Android dev. I didn't know anything about how to use the chronometer, I passed all the day studing it and I know now how to reset the clock (using ElapsedRealTime) but I don't know how to compare the time on chronometer and the time typed by the user. I read that i could use the Handler or run() but I didn't understand how each one works. What I want to do: 1: The user will enter a time in mm:ss (same format as chronometer), lets call this t1 2: The user will enter another time, in mm:ss format too. Lets call this t2 3: A message will be displayed in a TextView, the message will appear after t1 minutes and will stay on the screen for t2 minutes, and it'll repeat forever. The result will be: appear, disappear, appear, disappear... I will place 2 chronometers for it, each one for each time typed. I'm not asking all the code, just how can I compare a time in the chronometer with a time typed in the EditText, I have (or I think I have) everything planned. How can I do it? Is there any other easy way to do it? Hopes I was clear and a sorry for my English. A: I continued my search and I did it, I was thinking about delete this post but I'll post what I did here so others can use it. MyChronometer.setOnChronometerTickListener(new OnChronometerTickListener() { public void onChronometerTick(Chronometer p1) { if (MyChronometer.getText().toString().contains(MyEditText.getText().toString())) { //Do something } } }); I use contains(something) to compare, i don't know why but it didn't work as expected when I used ==something Hope it helps someone.
{ "language": "en", "url": "https://stackoverflow.com/questions/17497691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to remove the FIRST whitespace from a python dataframe on a certain column I extracted a pdf table using tabula.read_pdf but some of the data entries a) show a whitespace between the values and b) includes two sets of values into one column as shown one columns "Sports 2019/2018" and "Total 2019/2018": https://imgur.com/a/MviV6N9 In order for me to use df_1=df1["Sprots 2019/2018"].str.split(expand=True) to split the two values which are separated by a space, I need to remove the FIRST space shown in the first value so that it doesn't split into three columns. I've tried df1["Sports 2019/2018"] = df1["Sports 2019/2018"].str.replace(" ", "") but this removes all the spaces, which would then combine the two values. Is there a way to remove the first whitespace on column "Sports 2019/2018 so that it resembles the values on "Internet 2019/2018'? A: df1["Sports 2019/2018"] = df1["Sports 2019/2018"].str.replace(" ", "", n = 1) n=1 is an argument that will only replace the first character that will find.
{ "language": "en", "url": "https://stackoverflow.com/questions/55306180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RegEx to match only character constants and specific escape sequences I'm trying to match a character constant. I only want single characters and a few escape sequences rather than \ followed by any letter. This is very similar to this question with the added requirement of specific escape characters. Regular expression to match escaped characters (quotes) '(\\\[tvrnafb\\\]|.)' A: I feel dumb, I just had to remove the period in the other answer and add another character class. '(\\[tvrnafb\\]|[^\\'])'
{ "language": "en", "url": "https://stackoverflow.com/questions/14556777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# trim within the get; set; I am total MVC newbie coming from 10 years of webforms. Here is the code I have inherited: namespace sample.Models { public class Pages { public int PageID { get; set; } public string FolderName { get; set; } } } How can I apply a trim function to the "set" portion of this code? Right now it is allowing spaces at the end of foldername and I need to prevent that. Okay I have incorporated the suggestions however the spaces are still getting saved. Here are the UI/ vs Database. The UI is trimming properly but the full value with spaces is stored in the table: A: What about this solution: public class Pages { private string _folderName; public int PageID { get; set; } public string FolderName { get { return _folderName; } set { _folderName = value?.Trim() ?? string.Empty; } } } A: You need a backing field: public class Pages { public int PageID { get; set; } private string _folderName; public string FolderName { get { return _folderName; } set { _folderName = value.Trim(); } } } In the setter method we use the Trim string's method, which Removes all leading and trailing white-space characters from the current String object. For further info regarding this method, please have a look here. A: You may consider writing a custom extension method to call Trim only if the value of your string is not null: public static class CustomExtensions { public static string TrimIfNotNull(this string value) { if (value != null) { value = value.Trim(); } return value; } } And then in your Pages class, something like private string _folderName; public string FolderName { get { return _folderName.TrimIfNotNull(); } set { _folderName = value.TrimIfNotNull(); } } If you're using C#6, as mentioned by Jacob Krall, you can use the null conditional operator directly and not worry about the extension method: public string FolderName { get { return _folderName; } set { _folderName = value?.Trim(); } } A: The shorthand syntax for properties is only for when you want to provide a thin layer of abstraction on top of a field. If you want to manipulate the field within the getter or setter, you need to specify the backing field on your own. namespace sample.Models { public class Pages { public int PageID { get; set; } private string folderName; public string FolderName { get { return folderName; } set { folderName = value.Trim(); } } } } A: public class Pages { public int PageId { get; set; } // you need a backing field then you can customize the set and get code private string folderName; public string FolderName { get { return this.folderName; } // if the fileName can be set to null you'll want to use ?. or you'll get // a null reference exception set { this.folderName = value?.Trim(); } } } A: See the code below. //You can filter the entry before saving it into the database. //About the null issue. You can use this. if(String.IsNullOrEmpty(txtusername.Text)) { throw new Exception("Cannot be blank!"); } //You can filter the entry before saving it into the database txtpageid.Text = book.PageID.Trim(); txtfoldername.Text = book.FolderName.Trim();
{ "language": "en", "url": "https://stackoverflow.com/questions/41368650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Opening a file and selecting specific column in file Hello all I am new to python and really need help I have a set of data as below all large values are column 1 and xx.x are column 2 19600110 28.6 19600111 28.9 19600112 29.2 19600113 28.6 19600114 28.6 19600115 28.4 19600116 28.6 19600117 28.6 stored as station.txt I am trying to get python to only present the first column of data (19600115 etc) which is labelled dates.I opened the file and I am using a for loop to try only open 1st column. I am not sure where I am going wrong any help would be greatly appreciated def load_dates(stations): """loads station dates and excludes station temperature data""" f = open(stations[0] + '.txt', 'r') #create a for loop and open first column of data which are the dates #close the file and return body of dates dates = [] for line in f: dates.append(lines(7)) f.close() return dates A: dates = [] for line in f: dataItem = line.split() #split by while space by default, as a list date = dataItem[0] #index 0 is the first element of the dataItem list dates.append(date) f.close() in summary, you need to split the line string first, then choose the date
{ "language": "en", "url": "https://stackoverflow.com/questions/29640655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: python Code show invalid syntax (folder_name = 'ebert_reviews') I am try to run python code. but it shows invalid syntax (folder_name = 'ebert_reviews') the Code import requests import os ebert_review_urls = ['https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9900_1-the-wizard-of-oz-1939-film/1-the-wizard-of-oz-1939-film.txt', 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9901_2-citizen-kane/2-citizen-kane.txt'] folder_name = 'ebert_reviews' if not os.path.exists(folder_name): os.makedirs(folder_name) for url in ebert_review_urls: response = requests.get(url) with open(os.path.join(folder_name, url.split('/')[-1]) = 'wb') as file: file.write(response.content) os.listdir(folder_name) A: The only problem that I found was " = 'wb'"; so put a comma instead: import requests import os ebert_review_urls = [ 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9900_1-the-wizard-of-oz-1939-film/1-the-wizard-of-oz-1939-film.txt', 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9901_2-citizen-kane/2-citizen-kane.txt'] folder_name = 'ebert_reviews' if not os.path.exists(folder_name): os.makedirs(folder_name) for url in ebert_review_urls: response = requests.get(url) with open(os.path.join(folder_name, url.split('/')[-1]), 'wb') as file: file.write(response.content) print(os.listdir(folder_name))
{ "language": "en", "url": "https://stackoverflow.com/questions/68643301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Nested push animation, but there's no push? I am getting this error when I try to preform a segue... 2012-11-14 20:24:54.133 MyApp[26266:c07] nested push animation can result in corrupted navigation bar 2012-11-14 20:24:54.486 MyApp[26266:c07] Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted. 2012-11-14 20:24:54.487 MyApp[26266:c07] Unbalanced calls to begin/end appearance transitions for <SheetDrillDownViewController: 0xa1bb980>. Here is my setup: Initial view --> next view (UITableView) --> last view (UITable) Each cell pushes to another view until the last view. I do not have a modal segue, i have a push segue... I have the push segues linked from the cell to the next view, each with different names... I have a perform segue line in my selectedRowAtIndex method. I have tried removing that method, with people saying I am double calling the segue, but then the cell when clicked turns blue, and doesn't push to anywhere... How can I fix this error? Thanks. Here is my code: -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath) { [self performSegueWithIdentifier:@"subjectDrillDown" sender:nil]; } } - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { NSLog(@"Attempting to identify segue..."); // Make sure we're referring to the correct segue if ([[segue identifier] isEqualToString:@"subjectDrillDown"]) { NSLog(@"Segue has been identified..."); // Get reference to the destination view controller SubjectDrillDownViewController *vc = [segue destinationViewController]; NSInteger selectedIndex = [[self.tableView indexPathForSelectedRow] row]; NSMutableDictionary *object = [tableDataSource objectAtIndex:selectedIndex]; NSString *key = [object valueForKey:@"key"]; [vc setSelectedItem:key]; NSLog(@"Switching to %@ detail view...",key); NSLog(@"Passing dictionary to %@ view... (Source below)\n\n %@",key,[NSString stringWithFormat:@"%@", [tableDataSource objectAtIndex:selectedIndex]]); [vc setDetailDataSourceDict:[tableDataSource objectAtIndex:selectedIndex]]; } else { NSLog(@"ERROR, DOUBLE CHECK SEGUE'S NAME!"); } } I have seen all of the other Stack Overflow questions, but most of the correct answers don't work for me... EDIT: The next view is able to load, but when I click the back button, there are suddenly two more views... UPDATE: I will try to post the number of times Attempting to identify segue... NSLogs, but my compiler suddenly won't run :( A: You surely don't need to perform segue in didSelectRowAtIndexPath, if you have already configured it like cell -> next view. But, removing the call from there doesn't work for you then you can try the segue from view controller (ctrl+drag from view area) to next view and keep the segue call in didSelectRowAtIndexPath I always use one of the following methods Method 1: Segue from UITableViewCell to Next View Controller -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Nothing } Method 2: Segue from Main View Controller to Next View Controller -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self performSegueWithIdentifier:@"subjectDrillDown" sender:nil]; } The error you are getting is because you have segue and you perform the segue manually when selected - hence, it is resulting in nested push animation Make sure the name of the segue is correct and you are using ONLY one of the above methods
{ "language": "en", "url": "https://stackoverflow.com/questions/13390421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Excel cell values containing times are reported as 12 hour instead of 24 hour with JExcelApi I need to read an Excel document and extract some cell values for further processing. I use JExcelAPI for this. This works well. We need to have a cell containing wall time as a four character string (like "0810" for ten past eight and "1550" for ten to four) which is achived by calculating the time and custom formatting it with the "ttmm" minute pattern. ("t" is 24 hour in the Danish locale. This is in Denmark which currently is GMT+2, and our Windows machines are with English locale) My problem is now that when I read in the cells with cell.getContents() the first cell is correctly "0810" but the second is "0350" instead of "1550". I do not have a deep understanding of jxl so I do not know if that value comes straight from the sheet as generated by Excel when saving or is generated deep down in jxl at runtime. Manipulating the Date stored in the DateCell is also cumbersome as the timezone is wrong, and we have other date cells which does not need this treatment. I was also thinking if we can do the calculations in a field not read, and then convert the contents to a four character string in a field read? So, how can I get the times in the form I need? (Note: I will award a 500 point bounty for the most helpful answer. I just cannot open it yet) A: I did not find a solution. We ended up in coercing the date into the desired text string in Excel itself (in a different cell, and ignoring the date cell when reading the sheet in Java).
{ "language": "en", "url": "https://stackoverflow.com/questions/19562365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to properly refactor router components? I'm building a to-do list app in React. With React-Router it has routes for "/all", "/today", "/week", "/inbox", and custom "/:projectId" tasks. They all render the same component <TaskList /> which accepts a couple of props: * *Project ID, to add tasks to *Project Name, and *Tasks belonging to the respective project I don't know how to properly refactor such code so that it's as efficient and DRY as possible. Here's my current attempt: import { useSelector } from "react-redux"; import { useParams } from "react-router-dom"; import { selectAllTasks, selectTodayTasks, selectWeekTasks, selectProjectTasks } from "../../redux/tasks.module"; import { selectCurrentProject } from "../../redux/projects.module"; import TaskList from "../task-list/task-list.component"; const projectId = 0; // Tasks entered will be added to Inbox export const AllTasks = () => { const tasks = useSelector(selectAllTasks); return <TaskList projectName="All" projectId={projectId} tasks={tasks} />; }; export const TodayTasks = () => { const tasks = useSelector(selectTodayTasks); return <TaskList projectName="Today" projectId={projectId} tasks={tasks} />; }; export const WeekTasks = () => { const tasks = useSelector(selectWeekTasks); return ( <TaskList projectName="Next 7 Days" projectId={projectId} tasks={tasks} /> ); }; export const ProjectTasks = () => { const { projectId } = useParams(); const { text } = useSelector(state => selectCurrentProject(state, projectId)); const tasks = useSelector(state => selectProjectTasks(state, projectId)); return <TaskList projectName={text} projectId={projectId} tasks={tasks} />; }; And here's the page that calls them: import { Switch, Route, useRouteMatch } from "react-router-dom"; import Header from "../../components/header/header.component"; import Sidebar from "../../components/sidebar/sidebar.component"; import { AllTasks, TodayTasks, WeekTasks, ProjectTasks } from "../../components/filters/filters.component"; import useStyles from "./tasks.styles"; const TasksPage = () => { const { path } = useRouteMatch(); const classes = useStyles(); return ( <div className={classes.container}> <Header /> <Sidebar /> <Switch> <Route exact path={`${path}/all`} component={AllTasks} /> <Route exact path={`${path}/today`} component={TodayTasks} /> <Route exact path={`${path}/week`} component={WeekTasks} /> <Route exact path={`${path}/:projectId`} component={ProjectTasks} /> </Switch> </div> ); }; export default TasksPage; What's the most efficient way to structure this? And allow not only the hardcoded routes (i.e. all, today, week, etc.) but also the custom user project routes (/:projectId) to coexist and not have repeating code? Thank you so much.
{ "language": "en", "url": "https://stackoverflow.com/questions/59416396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Issues with downloading PDF file from source iv'e created a method to generate a pdf file from a form, it got saved to the correct path using itexsharp, but the problem is i can't download it. this is my code : private void FillForm(Dictionary<string, string> dic) { var pdfTemplate = HttpContext.Current.Server.MapPath("~/ress/GENE_15_04_2014.pdf"); //_pdfTemplet; var newFile = _newFileName + "_" + Guid.NewGuid() + ".pdf"; _gNewFile = newFile.ToString(); var pdfReader = new PdfReader(System.IO.File.ReadAllBytes(pdfTemplate)); var pfileStream = new FileStream(string.Format(HttpContext.Current.Server.MapPath("~/ress/") + "{0}", newFile), FileMode.Create); var pdfStamper = new PdfStamper(pdfReader, pfileStream); var pdfFormFields = pdfStamper.AcroFields; foreach (var entry in dic) { pdfFormFields.SetField(entry.Key, entry.Value); } pdfStamper.FormFlattening = true; pdfStamper.JavaScript = "this.print(true);\r"; pdfStamper.Writer.CloseStream = false; pdfReader.Close(); pdfStamper.Close(); UPContract.Update(); pfileStream.Close(); pdf.FilePath = string.Format("../Ress/{0}", Path.GetFileName(_gNewFile)); Response.Clear(); byte[] bytes = System.IO.File.ReadAllBytes(string.Format(HttpContext.Current.Server.MapPath("~/ress/") + "{0}", _gNewFile)); Response.ContentType = "application/pdf"; MemoryStream ms = new MemoryStream(bytes); Response.AddHeader("content-disposition", "attachment;filename=" + "fiche abonnement_" + _gNewFile + ".pdf"); Response.Buffer = true; ms.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } A: If you want to pass a file you can skip the byte array and MemoryStream and just use Response.WriteFile(string)
{ "language": "en", "url": "https://stackoverflow.com/questions/37920343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error Coming when passing props from one component to another and vice - versa in react using typescript In react, when I pass information from App component to App2 component as <App2 value = {this.state.name}/> it works well, but when I try to pass information from App2 component to App1 component as <App1 value = {this.state.name2}/> inside the render function of App2 component , it gives an error :- [ts] 'render' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. The code for App1 component is :- import * as React from "react"; import App2 from './App2'; interface IState{ name : string, age : 5; } interface Iprops{ value ? : any } class App extends React.Component<Iprops,IState>{ constructor(props:any) { super(props); this.state = { age : 5, name : "" } this.change = this.change.bind(this); } public change(event : any){ // alert("you have submitted the form"); this.setState({ name : event.target.value }); } public render() { return( <div> <input type="text" value = {this.state.name} onChange = {this.change}/> <App2 value = {this.state.name}/> </div> ) } } export default App; and App2 component code is :- import * as React from "react"; import App from './App' interface Iprops{ value ? : any; } interface Istate{ name2 : string } class App2 extends React.Component<Iprops,Istate>{ constructor(props:any) { super(props); this.state = { name2 : " " } } public change(event : any){ this.setState({name2 : event.target.value}) } public render() { return ( <div> <h4> <input type="text" value = {this.props.value} onChange = {this.change}/> Hello, I am in App3 component. <App value = {this.state.name2}/> </h4> </div> ) } } export default App2; Is there any other method to pass the information vice-versa between components in react using typescript. A: Note, that you have circular dependency between App and App2. Typescript is unable to infer return type of App2#render as it uses App in it's return expression which in turn uses App2 which isn't yet fully defined ... Long story short - declare your render methods as follows: public render(): JSX.Element { // ... } Thanks to this Typescript compiler knows render signature without looking at function contents.
{ "language": "en", "url": "https://stackoverflow.com/questions/51380705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Phpmyadmin Relations between 2 tables I am trying to make relations between a new table and a wordpress woocommerce table "wp_posts" by making a foreign key constraint from the new table to the ID of wp_posts, I managed to make the constraint but it still only returns null to me, it looks like this it should display an ID from wp_posts with that FK but nothing happened.
{ "language": "en", "url": "https://stackoverflow.com/questions/52947231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: toLocaleString thousand separator doesn't appear for Ewe below 100,000 for Firefox I'm on Firefox, and if I set the locale to "ee" to toLocaleString. The thousand separator won't appear below 100,000. (1111).toLocaleString("ee-gh") "1111" (10000).toLocaleString("ee-gh") "10000" (123456).toLocaleString("ee-gh") "123,456" console.log((1111).toLocaleString("ee-gh")); console.log((10000).toLocaleString("ee-gh")); console.log((123456).toLocaleString("ee-gh")); Even with useGrouping set to true (1234).toLocaleString("ee-gh", {useGrouping: true}) "1234" Why does this happen for Ewe? If I set the locale to English, it'll work fine (1234).toLocaleString("en-us") "1,234" console.log((1234).toLocaleString("ee-gh", {useGrouping: true})); A: Locale ee has a minimum grouping digits set to 3 as seen on the CLDR survey tool. You get the grouping separator if it has at least 3 digits on the left side of the first grouping separator.. This is a rare thing and ee is the only locale as of CLDR 38 which a such value. This applies to both Chrome and Firefox. I have something to solve this. Taking advantage of formatting to parts. Grouping separator is recieved by formatting it by million, 4 digit on the left side of the first grouping separator, because 4 is the highest value I can find for the minimum grouping digits, then it groups the non-grouped integer using that symbol every 3 digits. function format_no_minimum_grouping_digits(value_to_format, locale, options) { // Create a number formatter const formatter = new Intl.NumberFormat(locale, options); const formatter_options = formatter.resolvedOptions(); // Check if grouping is disabled if (!formatter_options.useGrouping // The POSIX locale have grouping disabled || formatter_options.locale === "en-US-u-va-posix" // Bulgarian currency have grouping disabled || (new Intl.Locale(formatter_options.locale).language === "bg") && formatter_options.style === "currency") { // If yes format as normal return formatter.format(value_to_format); }; // Otherwise format it to parts const parts = formatter.formatToParts(value_to_format); // Check if the grouping separator isn't applied const groupSym = parts.find(part => part.type === "group") === undefined ? new Intl.NumberFormat(locale, options).formatToParts(10 ** 6)[1].value : undefined; // If the grouping separator isn't applied, group them return parts.map(({type, value}) => (type === "integer" && groupSym) ? value.replace(/\B(?=(\d{3})+$)/g, groupSym) : value).join(''); }
{ "language": "en", "url": "https://stackoverflow.com/questions/63692296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to list out FB friends pictures using Facebook Graph API I'm trying to set up a call that will list out a certain number of a friends pictures for a logged in facebook user. It works to spit out the users' picture, but I cannot get the call for fb friends pictures. I'm sure you guys can solve this easily. Here is the code: <?php if(!isset($_SESSION['logged_in'])) { ?> <?php } else{ if (!class_exists('FacebookApiException')) { require_once('./src/facebook.php' ); } $facebook = new Facebook(array( 'appId' => $appId, 'secret' => $appSecret, )); $fbuser = $facebook->getUser(); echo $fbuser; echo $_SESSION['user_name']; echo '<img src="https://graph.facebook.com/'.$fbuser.'/picture">'; echo '<img src="https://graph.facebook.com/'.$fbuser.'/friends/picture">'; echo '<a href="?logout=1">Log Out</a>'; } ?> A: You first need to get a list of the user friends calling /me?fields=friends. Then, you can only add their id to the picture urls just like you did with the user: <img src="https://graph.facebook.com/{{friend_id}}/picture">
{ "language": "en", "url": "https://stackoverflow.com/questions/15329119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: OOP design skill additional effect in RPG style game Creating a RPG related program, I would like to add various additional effects to my characters skills (damage over time, buff, etc...) So far I did something looking like this (C# Syntax) public class Paladin : Character { public Paladin() { BaseMP = 7080; caster = false; baseGCD = 2.43; aadelay = 2.24; aapotency = AAPotency.Attack; Moveset = new List<IMove>() { new Weaponskill("Fast Blade", "", 150, 150, false, false, baseGCD, null), new Weaponskill("Riot Blade", "Fast Blade", 100, 230, false, false, baseGCD, new RiotBlade_Effect()), new Weaponskill("Goring Blade", "Riot Blade", 100, 240, false, false, baseGCD, new DoT(50, 24)), new Spell("Holy Spirit", 430, 1440, false, 2.5, null), new Ability("Requiescat", 350, true, 60, false, new Requiescat_Effect()), }; } } Weaponskill, Spell and Ability are all implementations of Interface ISkill, which represent one of my characters skills. The last parameter of their constructor is either null if there is no special effect, or should contains the special effect of this skill. To implement them, i thought about a strategy design pattern (or what I believe is a strategy design pattern, first time i try to implement it). public interface IStrategy { void execute(); } public class RiotBlade_Effect : IStrategy { public RiotBlade_Effect() { } public void execute() { } } I got two problems. First, how can the IStrategy implementation can know my Character properties if I need to change them? (for exemple, if I want to lower or increase one of the properties set in Paladin()). Second, how can I handle multiple possible return types for execute(), depending on the effect I'll implement?
{ "language": "en", "url": "https://stackoverflow.com/questions/44440880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to run schedule every 7 minutes my current schedule runs everyFiveMinutes . $schedule->command('booking:cron')->everyFiveMinutes();
{ "language": "en", "url": "https://stackoverflow.com/questions/74821232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get href value in the redirected JSP. I have several href tag, and it redirects to different Jsp. I want to send an integer along with URL. Assume I am in a.jsp, Inside I have an href tag like below <a href='app/b?num=1' class='passid'>Link to b.jsp</a> // Is this correct syntax to pass value <a href='app/c?num=2' class='passid'>Link to c.jsp</a> <a href='app/d?num=3' class='passid'>Link to d.jsp</a> If I click Link to b.jsp , then inside b.jsp ready method I have to take that num value that sends through href tag. $(document).ready(function() { needs to check num equals to 1 or not } A: Like so: $(document).ready(function() { $("a").click(function(){ var href= $(this).attr("href"); var id = href.substring(href.length - 1) alert(id) }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/53011037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert LINQ nvarchar to double I'm trying to sort a column, but the value is stored as nvarchar in the database, how can I convert it to a double so it sorts here? I tried to do Convert.ToDouble(t.PressureChange), but it didn't work... if (column == "PressureChange") { if (sortDirection == "ascending") testResults = testResults.OrderBy(t => t.PressureChange); else testResults = testResults.OrderByDescending(t => t.PressureChange); } A: You could try if (column == "PressureChange") { if (sortDirection == "ascending") { testResults = testResults.OrderBy(t => double.Parse(t.PressureChange)); } else { testResults = testResults.OrderByDescending (t => double.Parse(t.PressureChange)); } } ... but it depends whether that method is supported by LINQ to SQL. To be honest, it sounds like you've got bigger problems in terms of your design: if you're trying to store a double value in the database, you shouldn't be using a varchar field to start with. Fix your schema if you possibly can. EDIT: Note that based on the information on this page about LINQ to SQL and Convert.* it looks like Convert.ToDouble should work, so please give us more information about what happened when you tried it. A: Rather use TryParse to avoid exceptions. In this code I used 0.0 as a default value if it could not parse the string. double temp = 0.0; if (column == "PressureChange") { if (sortDirection == "ascending") testResults = testResults.OrderBy(t => (double.TryParse(t.PressureChange.toString(), out temp) ? temp : 0.0)).ToList(); else testResults = testResults.OrderByDescending(t => (double.TryParse(t.PressureChange.toString(), out temp) ? temp : 0.0)).ToList(); } A: I have not tested it but you can use an extension method like this: public class StringRealComparer : IComparer<string> { public int Compare(string s1, string s2) { double d1; double d2; double.tryParse(s1, out d1); double.TryParse(s2, out d2); return double.Compare(d1, d2); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/10956411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible that library made in visual studio can`t linking to mingw g++? I made static library in visual studio called MyString. (TEST PURPOSE) And trying to linking using cmake tool and set the compiler mingw64. But it seems not working It`s showing me some error called 'skipping incompatible when searching for library' Is that impossible to linking library that made by another compiler? A: There are many challenges mixing different compilers, like: * *Name mangling (the way symbols are exported), especially when using C++ *Different compilers use different standard libraries, which may cause serious problems. Imagine for example memory allocated with GCC/MinGW malloc() being released with MSVC free(), which will not work. With static libraries it is especially hard (e.g. malloc() can be linked to the wrong standard library). With shared libraries there may be possibilities to solve these issues and get it to work, at least when sticking to C. For C++ it may be a lot more challenging.
{ "language": "en", "url": "https://stackoverflow.com/questions/69095567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS - Batch (coalesce) network requests to a particular resource . Cooperation between NSURLSession , NSURLRequest etc I have a highly asynchronous environment and many modules which may request a particular network resource (such as an access token and perhaps indirectly through transitive requests). For instance many places in code could "simultaneously" do calls to send analytics: // module 1 [Analytics sendAnalytics:module1Analytics]; // module 2 [Analytics sendAnalytics:module2Analytics]; ... Analytics requests require a valid access token and the sending code may contain special care for an expired access token that should be renewed +(void)sendAnalaytics:(Analytics)analyticsPayload { //... setup code ... NSURLRequest *analyticsRequest = // Analytics NSURLRequest with a special access token // the network request to send the analytics [[MyNSURLSession dataTaskWithRequest:analyticsRequest completionHandler:^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error)){ if (error == 401) { get new access token // re-send the same request [self sendAnalaytics:analyticsPayload]; } // .... }] resume]; } I don't want to request the same resource simultaneously. I want to batch the call for the same resource if it is already running. // batch this call to only happen once if already running NSURLRequest *accesstoken = ... .... Also the access token should never be cached (using the "NSURLCache" et.al mechanisms. ) There are other request such as the "access token" request which should be batched together (for instance a request for an image). I need to optimize the network access so that I am not doing redundant requests. Is there a builtin mechanism supplied by the NSURL loading system without resorting to collecting the requests myself? A: No. You'd have to add your own wrapper code around NSURLSession to do that. You should probably have an analytics singleton class that handles merging multiple requests where needed, retries, etc. so that all the caller has to do is [MyAnalyticsClass updateAnalyticsWithParameters: @{...}] or whatever. Then, in that call, you should check to see if there's a request in progress. If not, start the request immediately. If so, enqueue the new request. When the current request completes, look through the queue and decide which ones to send, which ones to merge, etc. and start the next one.
{ "language": "en", "url": "https://stackoverflow.com/questions/37319269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Swift UILocalNotification Display On Screen I am trying to display a UILocalNotification on the top of the screen when it is received. I have created a simple notification var notification = UILocalNotification() notification.alertBody = "Hello World!" notification.fireDate = NSDate(timeIntervalSinceNow: 0) UIApplication.sharedApplication().scheduleLocalNotification(notification) This displays like it should in the Notifications section when the user swipes down on the screen, but is there a way to also show a notification on the top of the screen to alert the user when the app is running? A: Implement this in your appdelegate and show an alert : func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/30173252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mozilla flexbox not working with bootstrap row I am using a bootstrap 3 container, inside there is a col-sm-4 and col-sm-offset-4 for centering the form inside. I'd like to vertically center the form with flexbox, it's working in Chrome & Safari, but with mozilla, it's not working. #login { height: 100vh; width: 100%; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } my Container above My html code: <div class="container" id="login"> <div class="row"> <div class="col-sm-4 col-sm-offset-4 centered"> <div class="well"> <form action="login.php" autocomplete="off" id="Login_Form" method="post" name="Login_Form"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i aria-hidden="true" class="fa fa-user fa-fw"></i></span> <input class="form-control" name="Username" placeholder="Nutzername"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i aria-hidden="true" class="fa fa-shield fa-fw"></i></span> <input class="form-control" name="Password" placeholder="Passwort" type="password"> </div> </div> <div class="form-group"> <button class="btn btn-primary full-width-button" name="Submit" value="Login">Anmelden</button> </div> <table class="errormessage_table"> <?php if(isset($msg)){?> <tr> <td class="errormessage"><?php echo $msg;?></td> </tr><?php } ?> </table> </form> </div> </div> </div> </div> like..the container is so small, in safari the container is a lot bigger and not cut off Safari & Chrome Mozilla Firefox Hope someone can help me :) A: To achieve your expected result remove display:flex #login { height: 100vh; width: 100%; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } http://codepen.io/nagasai/pen/zBjkWw
{ "language": "en", "url": "https://stackoverflow.com/questions/38543722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .exe file of c# project using mysql server I am building a C# application which connects to a MySQL database. It is working fine on my development computer. I want to build the application into an 'exe' or executable file which can be run on different computers. Where do I start and how can I build the application so that it runs on another computer. It should still be able to access and modify the database. A: If you see in bin exe must me building There in *.exe.config you can modify connection string It will be easier if you create installer
{ "language": "en", "url": "https://stackoverflow.com/questions/45404384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where can I find dependencies to add to Sails.js application like Vue.js, Vuetify, and lodash? I'm looking for a place to find available dependencies that can be added to a Sails.js application in the assets/dependencies folder. I'm asking because I see that in this project https://github.com/mikermcneil/ration/tree/master/assets/dependencies they have dependencies for these things but I can't seem to find a repository or something similar for dependencies such as these online. A: Found it: https://www.jsdelivr.com/ This place has all the .js files that I was looking for, as well as .css files
{ "language": "en", "url": "https://stackoverflow.com/questions/65621388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difference between $$ and $ what is Difference between "$$" and "$"? $$('#items li').each( function(item) { item.observe('click', function(event) { doSomethingWith(event.target); }); }); ========================== $('items').observe('click', function(event) { if (event.target.tagName === 'LI') { doSomethingWith(event.target); } }); A: See the Prototype.js documentation $ — id (String | Element) — A DOM node or a string that references a node's ID $$(cssRule...) — Takes an arbitrary number of CSS selectors (strings) and returns a document-order array of extended DOM elements that match any of them.
{ "language": "en", "url": "https://stackoverflow.com/questions/21761022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: get listview row onContextItemSelected I'm doing a proyect where i have a view with multiple listview created at runtime, every listview load specifics rows of a database. and i want to implement a contextmenu. The problem is how can i get the row of the listview to retieve the id of the database? How can i get my list adapter inside the contextmenu ? or some other solution. Thanks! here is a part of the code... private void makeView(){ yearsArray = db.getUniqueYears(TABLE_NAME); for (int i = 0; i < yearsArray.size() ; i++){ list = db.getDocByYear(TABLE_NAME, yearsArray.get(i)); custom_adapter = new Document_adapter(this, list); ListView lv = new ListView(this); lv.setAdapter(custom_adapter); lv.setBackgroundResource(R.drawable.title_container_bg); registerForContextMenu(lv); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater mi = getMenuInflater(); mi.inflate(R.menu.doc_options, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); /* */ return super.onContextItemSelected(item); } A: If you set your database up properly you can just do this info.id; in your onContextItemSelected and that gives the database id
{ "language": "en", "url": "https://stackoverflow.com/questions/14449013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: date range picker get current dates in the end range I am using flask to build some small application. I would like to build a form that collects a start date and an end date. Ideally I would like this form data to my database to run some search on date range. I found some example that is fairly close to what I am trying to do. One thing that I cant figure out is in the example the date range is predefined. I would like for at least the end date to be updated with the current date and not a predefined field. <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script> <script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script> <!-- Include Date Range Picker --> <script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" /> <input style="width: 40%" class="form-control" type="text" name="daterange" value="01/01/2015 - 01/31/2015" /> <script type="text/javascript"> $('input[name="daterange"]').daterangepicker( { locale: { format: 'MM-DD-YYYY' }, startDate: '01-01-2013', endDate: '12-31-2013' }, function(start, end, label) { alert("A new date range was chosen: " + start.format('MM-DD-YYYY') + ' to ' + end.format('MM-DD-YYYY')); }); </script> A: Substitute 'moment()' for the hardcoded end date. Example: $('input[name="daterange"]').daterangepicker( { locale: { format: 'YYYY-MM-DD' }, startDate: '2013-01-01', endDate: moment() }, function(start, end, label) { alert("A new date range was chosen: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD')); }); (Also, not sure if this was a copy/paste issue - but you are missing the 'https:' prefix on your script and stylesheet imports.)
{ "language": "en", "url": "https://stackoverflow.com/questions/46736599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }