text
stringlengths
15
59.8k
meta
dict
Q: Swift - UIProgressView is not smooth with NSTimer So I am using an NSTimer to let the user know the app is working. The progress bar is set up to last 3 seconds, but when running, it displays in a 'ticking' motion and it is not smooth like it should be. Is there anyway I can make it more smooth - I'm sure just a calculation error on my part.... If anyone could take a look that would be great. Here is the code: import UIKit class LoadingScreen: UIViewController { var time : Float = 0.0 var timer: NSTimer? @IBOutlet weak var progressView: UIProgressView! override func viewDidLoad() { super.viewDidLoad() // Do stuff timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector:Selector("setProgress"), userInfo: nil, repeats: true) }//close viewDidLoad func setProgress() { time += 0.1 progressView.progress = time / 3 if time >= 3 { timer!.invalidate() } } } A: For continues loader timer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(setProgress), userInfo: nil, repeats: true) and func setProgress() { time += 0.001 downloadProgressBar.setProgress(time / 3, animated: true) if time >= 3 { self.time = 0.001 downloadProgressBar.progress = 0 let color = self.downloadProgressBar.progressTintColor self.downloadProgressBar.progressTintColor = self.downloadProgressBar.trackTintColor self.downloadProgressBar.trackTintColor = color } A: Edit: A simple 3 second UIView animation (Recommended) If your bar is just moving smoothly to indicate activity, possibly consider using a UIActivityIndicatorView or a custom UIView animation: override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) UIView.animateWithDuration(3, animations: { () -> Void in self.progressView.setProgress(1.0, animated: true) }) } Make sure your progressView's progress is set to zero to begin with. This will result in a smooth 3 second animation of the progress. Simple animated progress (Works but still jumps a bit) https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIProgressView_Class/#//apple_ref/occ/instm/UIProgressView/setProgress:animated: func setProgress() { time += 0.1 progressView.setProgress(time / 3, animated: true) if time >= 3 { timer!.invalidate() } } Option with smaller intervals. (Not recommended) Set your timer to a smaller interval: timer = NSTimer.scheduledTimerWithTimeInterval(0.001, target: self, selector:Selector("setProgress"), userInfo: nil, repeats: true) Then update your function func setProgress() { time += 0.001 progressView.setProgress(time / 3, animated: true) if time >= 3 { timer!.invalidate() } } A: It's hard to say exactly what the problem is. I would like to see the output if you put a print line in setProgress to print a timestamp. Is it actually firing every tenth of a second? My guess is that it is not. Why not? Well, the timer schedules a run loop task in the main thread to execute the code in setProgress. This task cannot run until tasks in front of it in the queue do. So if there are long running tasks happening in your main thread, your timer will fire very imprecisely. My first suggestion is that this is perhaps what is happening. Here is an example: * *You start a timer to do something every second. *Immediately after, you start a long running main thread task (for example, you try to write a ton of data to a file). This task will take five seconds to complete. *Your timer wants to fire after one second, but your file-writing is hogging the main thread for the next four seconds, so the timer can't fire for another four seconds. If this is the case, then to solve the problem you would either need to move that main thread work to a background thread, or else figure out a way to do it while returning to the run loop periodically. For example, during your long running main thread operation, you can periodically call runUntilDate on your run loop to let other run loop tasks execute. Note that you couldn't just increment the progress bar fill periodically during the long running main thread task, because the progress bar will not actually animate its fill until you return to the run loop. A: What about proper way for animating changes: animateWithDuration:animations: or CABasicAnimation. You can use this for creating smooth animations
{ "language": "en", "url": "https://stackoverflow.com/questions/31438305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to use variable and changing user defined functions in query I have defined some user defined function in sql server . for example : select dbo.SumItems(1 , 2) will return 3 and select dbo.MaxItems(5 , 3) will return 5 and some other functions may be more complicated. also I keep variables and their formula expressions in a table: IdVar Title Formula ----- ----- --------------------- 1 Sum dbo.SumItems(@a , @b) 2 Max dbo.maxItems(@a , @b) I have my parameters in another table : a b -- -- 1 2 5 3 now i want to join this two tables and get the following result : Parameter a Parameter b Variable Title Result ----------- ----------- -------------- ------ 1 2 Sum 3 1 2 Max 2 5 3 Sum 8 5 3 Max 5 also I have asked my problem from another view here. A: Posted something very similar to this yesterday. As you know, you can only perform such function with dynamic sql. Now, I don't have your functions, so you will have to supply those. I've done something very similar in the past to calculate a series of ratios in one pass for numerous income/balance sheets Below is one approach. (However, I'm not digging the 2 parameters ... seems a little limited, but I'm sure you can expand as necessary) Declare @Formula table (ID int,Title varchar(25),Formula varchar(max)) Insert Into @Formula values (1,'Sum' ,'@a+@b') ,(2,'Multiply','@a*@b') Declare @Parameter table (a varchar(50),b varchar(50)) Insert Into @Parameter values (1,2), (5,3) Declare @SQL varchar(max)='' ;with cte as ( Select A.ID ,A.Title ,ParameterA = A ,ParameterB = B ,Expression = Replace(Replace(Formula,'@a',a),'@b',b) From @Formula A Cross Join @Parameter B ) Select @SQL = @SQL+concat(',(',ID,',',ParameterA,',',ParameterB,',''',Title,''',(',Expression,'))') From cte Select @SQL = 'Select * From ('+Stuff(@SQL,1,1,'values')+') N(ID,ParameterA,ParameterB,Title,Value)' Exec(@SQL) -- Optional To Trap Results in a Table Variable --Declare @Results table (ID int,ParameterA varchar(50),ParameterB varchar(50),Title varchar(50),Value float) --Insert Into @Results Exec(@SQL) --Select * from @Results Returns ID ParameterA ParameterB Title Value 1 1 2 Sum 3 2 1 2 Multiply 2 1 5 3 Sum 8 2 5 3 Multiply 15
{ "language": "en", "url": "https://stackoverflow.com/questions/41003935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to split CSV rows then duplicate that row? I have a CSV file from which I need to generate a new file with new rows. I have some experience in Bash and Python. Example: Source Country A,Place1;Place2;Place3,Other info Country B,Place4;Place5;Place6,Other stuff Country C,Place7;Place8;Place9,Other examples Target Place1,Country A,Other info Place2,Country A,Other info Place3,Country A,Other info Place4,Country B,Other stuff Place5,Country B,Other stuff Place6,Country B,Other stuff So I need to split the 2nd column by the ; delimiter and create a new line based on the rest of the information in the row. A: Assuming its always the second column. Change the columnNumber if its a different column (I'm counting this from 1 and not 0 for ease of use). import csv newData = [] columnNumber = 2 with open('data.csv') as csvfile: line = csv.reader(csvfile, delimiter = ',') for row in line: cStr = row[columnNumber-1].split(';') for i in range(0,len(cStr)): temp = [] for j in range(0, len(row)): if(j==columnNumber-1): temp.append(cStr[i]) else: temp.append(row[j]) newData.append(temp) with open('output.csv', 'w', newline="") as outFile: writer = csv.writer(outFile) writer.writerows(newData) A: Here's a Python 3 solution. Note use of newline='' per csv read/writer documentation: import csv with open('source.csv',newline='') as fin: with open('target.csv','w',newline='') as fout: r = csv.reader(fin) w = csv.writer(fout) # Read original three columns for country,places,other in r: # Write a row for each place for place in places.split(';'): w.writerow([place,country,other]) If still using Python 2, use the following open syntax instead: with open('source.csv','rb') as fin: with open('target.csv','wb') as fout: A: If you have a csv file then the simplest way is to open Excel, then navigate to File>Open and select "All Files" and navigate to the csv file you want to modify. When you open this file, it should give you the option to state what character you want to use as the delimiter, and you can enter ";". There should be a few more options that you just agree to, and then you will have an xls file with the fields split by the ";". In order to get from this to the table you want, I would suggest creating a pivot table. My answer is based on this being a one-off, whereas if you will have to repeat this function it would be better to write something in Excel VBA or Python. Happy to advise further if you get stuck. A: Using Miller (https://github.com/johnkerl/miller) is very simple. Using this command mlr --nidx --fs "," nest --explode --values --across-records -f 2 then reorder -f 2 input.csv you have Place1,Country A,Other info Place2,Country A,Other info Place3,Country A,Other info Place4,Country B,Other stuff Place5,Country B,Other stuff Place6,Country B,Other stuff Place7,Country C,Other examples Place8,Country C,Other examples Place9,Country C,Other examples
{ "language": "en", "url": "https://stackoverflow.com/questions/57874901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what is the best way to check session in codiginator everytime make a new request i know how to use session in codiginator but i am facing the problem with session management and little bit confuse ie how can i check every time a valid session in controller. i do this by using <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Dashboard extends MY_Controller { function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); $this->load->library('session'); $this->load->model('User'); $this->load->model('Enquiry_model'); } public function index() { //$data['status']=$this->Blog_model->status(); $data['main_product']=$this->Enquiry_model->getMainProduct(); $session_data = $this->session->userdata('logged_in'); if(!$session_data) { $this->welcome(); } else { $data['user_data'] = $session_data; $this->load->view('admin1/index1',$data); } } } ?> but facing the problem when i have two website and i use same table to check the user but the different database for both. the problem i am facing when i logedin to first website i automatically logged in to other one. how can i remove or solve this problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/39846604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert spaces to newlines in text file using Python I have a text file which looks like this: 15.9 17.2 18.6 10.5 I want to edit this file in Python so that it looks like this: 15.9 17.2 18.6 10.5 This means that I need to replace the space strings by newline strings and save the text. I tried this but it doesn't work: f = open("testfile.txt", "w") for line in f: if ' ' in line: line2 = line.replace(' ' , '\n') print(line2) for i in line2: f.write(line2(i)) f.close The print for line2 is already working, but I don't get a new text file with spaces replaced by newlines. How can I fix the problem and produce the desired output? A: with open("testfile.txt", "r") as r: with open("testfile_new.txt", "w") as w: w.write(r.read(.replace(' ' , '\n')) A: Example: with open("file1.txt", "r") as read_file: with open("file2.txt", "w") as write_file: write_file.write(read_file.read().replace(" ", '\n')) Content of file1.txt: 15.9 17.2 18.6 10.5 Content of file2.txt: 15.9 17.2 18.6 10.5 NOTE: Or you can use the split and join method instead of replace. write_file.write("\n".join(read_file.read().split())) A: try like this instead f = open("testfile.txt", "r") text=f.read() f.close() f=open("testfile.txt", "w+") text2='' if ' ' in text: text2 = text.replace(' ' , '\n') print(text2) f.write(text2) f.close() A: You can try using string replace: string = string.replace('\n', '').replace('\r', '') Firstly: f.close() is not there. Secondly: try above code. It will replace spaces to new lines. A: Use str.split with str.join Ex: with open("testfile.txt", "r") as infile: data = infile.read() with open("testfile.txt", "w") as outfile: outfile.write("\n".join(data.split()))
{ "language": "en", "url": "https://stackoverflow.com/questions/57387805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Return Link Addresses of Titles on Google SERP I'm trying to get all link addresses that are hyperlinked on titles for a Google Search results page. Also trying to append it to a CSV file which I think I've got pretty straight as of now. from bs4 import BeautifulSoup from urllib.request import Request, urlopen import requests import re import csv #f = open("web_search_terms.txt", "r") terms = ["thanks","for","the help"] terms = [] for line in f: stripped_line = line.strip() terms.append(stripped_line) with open("web_urls.csv", "w") as f_out: writer = csv.writer(f_out) writer.writerow(["Search Term", "URL"]) for t in terms: url = f"https://google.com/search?q={t}" print(f"Getting {url}") html_page = requests.get(url) soup = BeautifulSoup(html_page.content, "html") divs = soup.findAll("div", attrs={"class": "yuRUbf"}) for item in divs: writer.writerow([t, item.get_text(strip=True)]) I'm not able to append the links to the "divs" list though, not sure how to get the hrefs within the class labelled "yuRUbf" Any help would be super appreciated! Thanks so much! A: To get correct response from the Google server, set User-Agent HTTP header. For example: import requests from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0" } url = "https://google.com/search" terms = ["thanks", "for", "the help"] for t in terms: params = {"q": t, "hl": "en"} print(f"Getting {t}") soup = BeautifulSoup( requests.get(url, params=params, headers=headers).content, "html.parser" ) divs = soup.findAll("div", attrs={"class": "yuRUbf"}) for div in divs: print(div.a["href"], div.a.text) print() Prints: Getting thanks https://slovnik.aktuality.sk/preklad/anglicko-slovensky/?q=thanks Preklad slova „ thanks ” z angličtiny do slovenčiny - Slovnik.skhttps://slovnik.aktuality.sk › preklad https://slovnik.aktuality.sk/preklad/anglicko-slovensky/?q=thanks%21 Preklad slova „ thanks! ” z angličtiny do slovenčiny - Slovnik.skhttps://slovnik.aktuality.sk › preklad https://www.merriam-webster.com/dictionary/thanks Thanks | Definition of Thanks by Merriam-Websterhttps://www.merriam-webster.com › dictionary › thanks https://dictionary.cambridge.org/dictionary/english/thanks THANKS | meaning in the Cambridge English Dictionaryhttps://dictionary.cambridge.org › dictionary › thanks https://www.thanks.com/ Thanks: Thank Homehttps://www.thanks.com https://www.dictionary.com/browse/thanks Thanks Definition & Meaning | Dictionary.comhttps://www.dictionary.com › browse › thanks https://www.collinsdictionary.com/dictionary/english/thank Thank definition and meaning | Collins English Dictionaryhttps://www.collinsdictionary.com › dictionary › thank https://www.youtube.com/watch?v=FnpZQoAOUFw THANK YOU and THANKS - How to thank someone in Englishhttps://www.youtube.com › watch Getting for https://www.merriam-webster.com/dictionary/for For | Definition of For by Merriam-Websterhttps://www.merriam-webster.com › dictionary › for https://www.dictionary.com/browse/for For Definition & Meaning | Dictionary.comhttps://www.dictionary.com › browse › for https://dictionary.cambridge.org/dictionary/english/for Meaning of for in English - Cambridge Dictionaryhttps://dictionary.cambridge.org › dictionary › for https://www.macmillandictionary.com/dictionary/british/for FOR (preposition, conjunction) definition and synonymshttps://www.macmillandictionary.com › british › for https://www.collinsdictionary.com/dictionary/english/for For definition and meaning - English - Collins Dictionaryhttps://www.collinsdictionary.com › dictionary › for https://www.thefreedictionary.com/for For - definition of for by The Free Dictionaryhttps://www.thefreedictionary.com › for https://www.learnersdictionary.com/definition/for 1 for - Merriam-Webster's Learner's Dictionaryhttps://www.learnersdictionary.com › definition › for Getting the help https://www.imdb.com/title/tt1454029/ The Help (2011) - IMDbhttps://www.imdb.com › title https://en.wikipedia.org/wiki/The_Help_(film) The Help (film) - Wikipediahttps://en.wikipedia.org › wiki › The_Help_(film) https://www.vanityfair.com/hollywood/2018/09/viola-davis-the-help-regret Viola Davis Regrets Making The Help: “It Wasn't the Voiceshttps://www.vanityfair.com › Hollywood › viola davis https://www.csfd.cz/film/277770-cernobily-svet/prehled/ Černobílý svět (2011) | ČSFD.czhttps://www.csfd.cz › film › prehled https://www.rottentomatoes.com/m/the_help The Help - Rotten Tomatoeshttps://www.rottentomatoes.com › the_help https://www.usatoday.com/story/entertainment/movies/2020/06/08/the-help-isnt-helpful-resource-racism-heres-why/5322569002/ 'The Help' isn't a helpful resource on racism. Here's why - USA ...https://www.usatoday.com › story › movies › 2020/06/08 https://www.amazon.com/Help-Emma-Stone/dp/B004A8ZWVK The Help : Emma Stone, Octavia Spencer, Jessica - Amazon ...https://www.amazon.com › Help-Emma-Stone https://www.amazon.com/Help-Kathryn-Stockett/dp/0399155341 The Help: Stockett, Kathryn: 9780399155345 - Amazon.comhttps://www.amazon.com › Help-Kathryn-Stockett https://www.martinus.sk/?uItem=258803 Kniha: The Help (Kathryn Stockett) - Anglický jazyk - Martinushttps://www.martinus.sk › ...
{ "language": "en", "url": "https://stackoverflow.com/questions/69019141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Programming Google CardDAV in Python I want to obtain my Google contacts through the CardDAV protocol using preferably Python (open to other languages). I've come across the pycarddav library, but it only works with SabreDAV/DAVical servers, not Google for example. How one would go about programming an interface to the Google contacts CardDAV using Python (or other language)? A: Google has just today announced to make CalDAV and CardDAV available for everyone. Google's CardDAV Documentation (also just released today) is probably a good place to start.
{ "language": "en", "url": "https://stackoverflow.com/questions/16844701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CMake: Replace a literal citation mark with an escaped one I have a string containing something like this: Hello "there" happy face! and I want to do a string(REPLACE ...) in CMake so that it becomes: Hello \"there\" happy face! How do I do this? string(REPLACE "\"" "\\"" TARGET "${SOURCE}") does not work A: I came up with the answer to this question while writing it... To get a literal \ in the replace target we need to escape it not just once but twice: \\\\ Then to get a literal " we need to escape that as well \". So to replace a literal \" with an escaped one, we need: \\\\\". That is: string(REPLACE "\"" "\\\\\"" TARGET "${SOURCE}")
{ "language": "en", "url": "https://stackoverflow.com/questions/24563035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone App with Activation Key I am asked by a client to build an iPhone app which works as follow: * *User download the App for free from iTunes *User enter their email address when they first launch the app *They will be emailed activation key *User launch app and then enter this activation key to start using the App. User do not have to pay for this activation key as the only purpose of this is that only employees of my client company can get the activation code and use it. So when they enter their email address activation key will only be sent if email address is from the same company. I know I can use enterprise license to distribute app internally but it is not possible due to various reasons. We do not want to their activation key every time so this will be stored in their settings. Second questions is that if I want to force them to enter their activation key every month then does this violate apple guidelines. I want to ask that if I build app as explained above then will it be rejected? A: This will be rejected. See guideline 17.2 here: https://developer.apple.com/app-store/review/guidelines/ A: simply create a session for 30 days, and expire that session in 30 days... Apple have no issues in expired session plenty of my apps are live with it... Just give a message you need to login to access the application features or something like that when user get logged out due to session expiration. Kudos A: This can be done if the client creates an enterprise app. With the enterprise app the app will have to be downloaded from the client's account and is not subject to Apple's restrictions above.
{ "language": "en", "url": "https://stackoverflow.com/questions/8508850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I find the most recent joda DateTime in map? I have a map that is updated from Firebase Realtime Database, so I don't know the map size in advance. In the map I have a String as key, and a Joda DateTime as value. I don't know how to iterate through the map to return the most recent Datetime. I'll try to explain better: //on returning results from Realtime Database Map<String, DateTime> myMap = new HashMap<>(); if(dataSnapshot.exists){ for(DataSnapshot data:dataSnapshot.getChildren()){ String key = data.getKey(); DateTime dateTime = // I get the data and convert it to Datetime; no problem here; I can do it. myMap.put(key, dateTime); } //outside the Loop //HERE IS WHAT I NEED HELP WITH for(DateTime date:myMap.values()){ // 1 - check if date is after the next date in map // 2 - if it is, then keep it // 3 - if it is not, then remove // 4 - in the end, only one pair of key/value with the most recent date is left } } Can you guys please, help me? Thank you so much EDIT: Sorry, one more thing. I'm using a minimum sdk in Android that doesn't ler me use Java 8. I have to use Java 7 features. A: how to iterate through the map to return the most recent Datetime Java 8+ using Streams: // To get latest key (or entry) String latestKey = myMap.entrySet().stream() .max(Entry::comparingByValue) .map(Entry::getKey) // skip this to get latest entry .orElse(null); // To get latest value DateTime latestValue = myMap.values().stream() .max(Comparator.naturalOrder()) .orElse(null); Any Java version using for loop: Entry<String, DateTime> latestEntry = null; for (Entry<String, DateTime> entry : myMap.entrySet()) { if (latestEntry == null || entry.getValue().isAfter(latestEntry.getValue())) latestEntry = entry; } String latestKey = (latestEntry != null ? latestEntry.getKey() : null); In the above, adjust as needed depending on whether you need latest key, value, or entry (key+value). in the end, only one pair of key/value with the most recent date is left Best way is to replace the map, or at least replace the content, after finding the latest entry. Java 8+ using Streams (replacing map): myMap = myMap.entrySet().stream() .max(Comparator.comparing(Entry::getValue)) .stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue)); Any Java version using for loop (replacing content): Entry<String, DateTime> latestEntry = null; for (Entry<String, DateTime> entry : myMap.entrySet()) { if (latestEntry == null || entry.getValue().isAfter(latestEntry.getValue())) latestEntry = entry; } myMap.clear(); if (latestEntry != null) myMap.put(latestEntry.getKey(), latestEntry.getValue()); A: You can use the .isAfter() method on the DateTime objects in the map values to check if one is after the other. Create a String mostRecentKey variable or something similar and set it to the first key value in the map. Then iterate through myMap.keySet(), comparing each date object value to the most recent one with .isAfter(). At the end, you will have the most recent date. e.g String mostRecentKey; for (String dateKey : myMap.keySet()){ if (mostRecentKey == null) { mostRecentKey = dateKey; } // 1 - check if date is after the next date in map if (myMap.get(dateKey).isAfter(myMap.get(mostRecentKey))) { mostRecentKey = dateKey; } } Then you have the key of the most recent one, and you can choose to delete all entries except that one, save the value or whatever you want. To delete all but the entry you found, refer to this question here: Remove all entries from HashMap where value is NOT what I'm looking for Basically, you can do something like this: myMap.entrySet().removeIf(entry -> !entry.getKey().equals(mostRecentKey)); Edit - Forgot you can't modify a collection you are iterating through, changed method slightly. A: Java 7 solution I'm using a minimum sdk in Android that doesn't ler me use Java 8. I have to use Java 7 features. Map<String, DateTime> myMap = new HashMap<>(); myMap.put("a", new DateTime("2020-01-31T23:34:56Z")); myMap.put("b", new DateTime("2020-03-01T01:23:45Z")); myMap.put("m", new DateTime("2020-03-01T01:23:45Z")); myMap.put("c", new DateTime("2020-02-14T07:14:21Z")); if (myMap.isEmpty()) { System.out.println("No data"); } else { Collection<DateTime> dateTimes = myMap.values(); DateTime latest = Collections.max(dateTimes); System.out.println("Latest date-time is " + latest); } Output from this snippet is in my time zone (tested on jdk.1.7.0_67): Latest date-time is 2020-03-01T02:23:45.000+01:00 We need to check first whether the map is empty because Collections.max() would throw an exception if it is. If you need to delete all entries from the map except that or those holding the latest date: dateTimes.retainAll(Collections.singleton(latest)); System.out.println(myMap); {b=2020-03-01T02:23:45.000+01:00, m=2020-03-01T02:23:45.000+01:00} Is it a little bit tricky? The retainAll method deletes from a collection all elements that are not in the collection passed as argument. We pass a set of just one element, the latest date-time, so all other elements are deleted. And deleting elements from the collection we got from myMap.values() is reflected back in the map from which we got the collection, so entries where the value is not the latest date are removed. So this call accomplishes it. Side note: consider ThreeTenABP If you are not already using Joda-Time a lot, you may consider using java.time, the modern Java date and time API and the successor of Joda-Time, instead. It has been backported and works on low Android API levels too. java.time links * *Java Specification Request (JSR) 310, where java.time was first described. *ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310). *ThreeTenABP, Android edition of ThreeTen Backport *Question: How to use ThreeTenABP in Android Project, with a very thorough explanation. *Oracle tutorial: Date Time explaining how to use java.time. A: You could iterate through entrySet as well, save the latest entry then remove everything and add that one back in. Map<String, DateTime> myMap = new HashMap<>(); .... Entry<String, DateTime> latest = myMap.entrySet().iterator().next(); for(Entry<String, DateTime> date:myMap.entrySet()){ // 1 - use isAfter method to check whether date.getValue() is after latest.getValue() // 2 - if it is, save it to the latest } myMap.clear(); myMap.put(latest.getKey(), latest.getValue());
{ "language": "en", "url": "https://stackoverflow.com/questions/60218775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: getting springboot to support groovy 4.0 (apache packaging) | needed 3.0.0-M2 and more spring-boot > 2.3.1 will grab groovy-bom from codehaus instead of org.apache.groovy packaging, even if you declare org.apache.groovy dependendices I found this means spring-boot > 2.3.1 will not build groovy 4.0 even spring initializr bakes this in... because when you go springboot 2.6.7, initializr is using groovy packaging from org.codehaus. so that limits 2.6.7 to use groovy 3.0.10, as that's the cutoff for groovy to show up in org.apache packaging. and groovy 4.x uses apache packages. here's the gradle initializr created from this URL plugins { id 'org.springframework.boot' version '2.6.7' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'groovy' } group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '11' repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-data-rest' implementation 'org.codehaus.groovy:groovy' testImplementation 'org.springframework.boot:spring-boot-starter-test' } tasks.named('test') { useJUnitPlatform() } A: Support for Groovy 4 is coming in Spring Framework 6 and Spring Boot 3. It’s currently available in Spring Boot 3.0.0-M2 which is published to https://repo.spring.io/milestone. A: you 1st have to change settings.gradle to add the following: pluginManagement { repositories { maven { url 'https://repo.spring.io/milestone' } gradlePluginPortal() } } Then I had to modify my build.gradle as follows: plugins { // id 'org.springframework.boot' version '2.6.7' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'groovy' } plugins { id 'org.springframework.boot' version '3.0.0-M2' } group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = javaSrcVersion targetCompatibility = javaClassVersion repositories { mavenCentral() maven { url("https://repo.spring.io/milestone/")} } dependencies { runtimeOnly('com.h2database:h2') implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-data-rest' // implementation 'org.codehaus.groovy:groovy' implementation("org.apache.groovy:groovy:${groovyVersion}") testImplementation 'org.springframework.boot:spring-boot-starter-test' implementation('com.google.code.findbugs:jsr305:latest.integration') implementation group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2' implementation group: 'jakarta.persistence', name: 'jakarta.persistence-api', version: '3.1.0' implementation group: 'commons-io', name: 'commons-io', version: '2.11.0' testImplementation("org.testng:testng:${testNgVersion}") } tasks.named('test') { useJUnitPlatform() }
{ "language": "en", "url": "https://stackoverflow.com/questions/71888383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I insert an item into a List without bumping the item at that index to the back? I'm trying to Insert an item at the start of a list using foo.Insert(0, bar); but it seems that the item that was at index 0 before is getting bumped to the back of the list instead of moving to index 1. I've tried creating a new List and adding the values in order, but it looks messy/hacky. Is there any clean way of doing this? If so, how? Thank you. A: As already said in comments, insert into List<T> preserve ordering, so described behaviour shouldn't happen. Simple example: var lst = new List<int> {1,2,3,4}; lst.Insert(0,0); lst.Dump();
{ "language": "en", "url": "https://stackoverflow.com/questions/41428330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Throw runtime exception in Closable.close() During my studies to the OCPJP8 I've encountered one question which doesn't have very clear answer to me. Consider following code: public class Animals { class Lamb implements Closeable { public void close() { throw new RuntimeException("a"); } } public static void main(String[] args) { new Animals().run(); } public void run() { try (Lamb l = new Lamb();) { throw new IOException(); } catch (Exception e) { throw new RuntimeException("c"); } } } According to the book correct answer for a question "Which exception will the code throw?" is "Runtime exception c with no suppressed exception". I have check this code in Eclipse and system.out suggest that the book is right. However, I've also modified the code a bit and added the following system.out just before throwing RuntimeException "c" System.out.println(e.getSuppressed().toString()); and the output I've got from this system.out is: [Ljava.lang.Throwable;@75da931b So clearly there is a suppressed exception. In debug mode, I've also found that this suppressed exception is the one frown in close() method. Two questions: 1. Why there is no information in the console about exception throwed in close() method? 2. Is the answer given by the book correct? A: The suppressed exception (RuntimeException-A) was added to the IOException caught in the catch and lost from the stack trace printout as it was not passed as the cause of the RuntimeException-C. So when the RuntimeException-C is printed from the main it has no mention of the IOException or the suppressed RuntimeException-A. And therefore the book's answer is correct because the only exception that is propagated from the main method is RuntimeException-C without cause (IOException), and without any suppressed exceptions (as it was on IOException).
{ "language": "en", "url": "https://stackoverflow.com/questions/33376813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Obscure Javascript difference between IE / Firefox / Opera Within a "cloaked" site, using obj.innerHTML = something to change the contents of a div seems to screw up the div's position in Firefox and Opera. Best way to understand the problem is by seeing the code in action. Go to http://www.guggs.net/index_redirected.htm in IE, Firefox or Opera and everything looks as it should. Hit one of the links in IE and everything is still fine, but in Firefox the page gets misaligned and there's no way of getting it back into shape. Hit one of the links in Opera and the misalignment happens but if you then hit another link the page is OK again and remains so however many links you hit. If however you go straight to http://www.sensetech.me.uk/guggs which is the page behind the "cloak" it's all fine whichever browser you use and however many links you hit. Help ! A: * *validate *I see no difference in F 3.6.10 on Mac *fix at least this: Warning: Expected end of value but found ','. Error in parsing value for 'padding'. Declaration dropped. Source File: /guggs/css.css Line: 39 td { font: 9pt verdana; color:#665544; padding: 0px, 0px, 0px, 5px; } A: Issue resolved. Nothing do with the Javascript ! FireFox and Opera were tripping due to earlier PHP code intended to prevent users coming in through anything other than the index page. Works OK when the site isn't cloaked so I'm not sure exactly what the problem is, but for the moment I've removed the code, which isn't anything like vital. Thanks for your time, people !
{ "language": "en", "url": "https://stackoverflow.com/questions/3895950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does Sage Pay have a PayPal-like IPN? I'm building an events system where users can book & pay for tickets - I'm intending to use Sage Pay Form, and have all transaction data held on their servers (I would collect ticket order, customer name & address on the website, then have them POST it to Sage Pay). The only information I need 'my end' is confirmation that payment has been received, so I can simply mark a ticket as sold (most events will have limited tickets). I've worked with PayPal IPN (& PDT) before, and wondered if Sage Pay offers a similar notification service? A: With the FORM protocol on the REQUEST you indicate the callback url, you will be notified on that URL when the payment is completed. SuccessURL The URL of the page/script to which the user is redirected if the transaction is successful. You may attach parameters if you wish. Sage Pay Form will also send an encrypted field containing important information appended to this URL (see below). You also need to specify the FailureURL, in case the transaction fails. A: Sage Pay also allow confirmation of failed and successful transactions via email if you pass a field *VendorEMail=*[email protected] in your transaction posts. This is listed as an optional field in their integration protocol.
{ "language": "en", "url": "https://stackoverflow.com/questions/7257487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding a new and removing previously selected value using ngModelChange I have a select dropdowd on a row colomn and I'm trying to add a new row with a new select box with the previously selected value removed. I used ngModelChange to call a function that assigns the value selected to my ngModel and removes it from the selection list. The problem is everytime I add a new row the value is removed from all rows. NB: I was unable to create a plunker for my project my grid look like this: <tbody> <tr *ngFor="let row of rows"> <td></td> <td> <select [ngModel]="row.color" (ngModelChange)="onSelectColor(row, $event)"> // value is a string or number <option *ngFor="let obj of availableColors">{{obj}}</option> </select> </td> <td *ngFor="let headItem of headList"><input class="input" type='text' #qty/></td> </tr> </tbody> <button (click)='addRow()'>Add a row</button> my componant I have this: export class ReferenceTableComponent implements OnInit { observable: Observable<any>; //couleurs exp: ['first', 'seconde'] @Input() public datas: Array<string>; public availableColors: Array<string>; //exp: ['1' ,'2', '3'] @Input() public headList: Array<string>; public rows: Array<any> = [{}]; public rowIDs: Array<any> = []; constructor(private injector: Injector) { } ngOnInit() { this.computeAvailableColors(); } addRow() { this.rows.push({}); } computeAvailableColors() { this.availableColors = _.concat([''], this.datas); console.log(_.map(this.rows, 'color')) this.rowIDs = _.map(this.rows, 'color') this.availableColors = _.difference(this.availableColors, this.rowIDs); } onSelectColor(row, color) { row.color = color; this.availableColors = this.availableColors.filter(c => c !== color); } } datas and headlist are injected by my service As you can see the 1st selected color 'BLANC NEIG' was removed from the selection as desired but also from the first row A: I do not really understand what you want to achieve. However If you want to remove the select color from the available colors you just have to something like this: public onSelectColor(row, color) { row.color = color; this.availableColors = this.availableColors.filter(c => c !== color); } That will change all select elements rerendering them without the removed color. If you don not want to remove the color from all the existing selects, then for each select you should have a different array of available colors. I would make the row a angular component itself. constructor(private _cr: ComponentFactoryResolver, private _viewContainerRef: ViewContainerRef) { }; public onSelectColor(row, color) { //workout the new colors const newAvailableColors = this.availableColors.filter(c => c !== color); // Create new row component on the fly const row: ComponentRef<RowComponent> = this._viewContainerRef.createComponent( this._cr.resolveComponentFactory(RowComponent) ); //Add whatever you want to the component row.instance.addColors(newAvailableColors); row.instance.addSelectedColor(color); } The child component should emit an event when that select changes. So the child should have something like this: @Output() public changed = new EventEmitter(); and then when select has change emit the event with the color as you say in the comment. Something like this: this.changed.emit({ color: color, row: row }); And then the parent, when is placing the child component in the html will be able to catch the event. Something like that: (changed)="onSelectColor($event)" Obviously, the onSelectColor has to change its arguments. Now it should be accepting the event. (Create an interface for the event, instead of using any) public onSelectColor(event: any) { //Do the same but retrieving info from the event event.color; event.row; }
{ "language": "en", "url": "https://stackoverflow.com/questions/45083624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Probability outputs of MATLAB LIBSVM I'm using LIBSVM toolbox for Matlab. My problem is a binary classification problem with labels of 1 (True) and 0 (False). When I train my system with this function : svmstruct = svmtrain(TrainTargets, TrainInputs,['-t 2 ' '-g ' SIGMA ' -c ' P ' -q' ' -b 1']); and test my test accuracy with this function : [TestOutputs, ~, ~] = svmpredict(TestTargets, TestInputs, svmstruct,'-b 1 -q'); Now I want use desined SVM model for out sample data. So I use this function : [OUT, ~, Prob_Out] = svmpredict(zeros(size(Outsample_DATA,1),1), Outsample_DATA, svmstruct,'-q -b 1'); For my first trained model (I have trained SVM model with different parameters) I have this Output (Out sample data set is same in both cases) : [Prob_Out OUT] 0.8807 0.1193 0 0.8717 0.1283 0 0.0860 0.9140 1.0000 0.7846 0.2154 0 0.7685 0.2315 0 0.7916 0.2084 0 0.0326 0.9674 1.0000 0.7315 0.2685 0 0.3550 0.6450 1.0000 for second one I have this : 0.4240 0.5760 0 0.4090 0.5910 0 0.7601 0.2399 1.0000 0.5000 0.5000 1.0000 0.4646 0.5354 0 0.4589 0.5411 0 Suppose that I want find class 1 with these probabilities. In first group of data when column 2 is larger than column 1 this sample belongs to class 1 but in second group when column 1 is larger than column 2 the sample belongs to class 1. The structure of these two out sample data is same. What is the problem? Thanks. PS. When I check SVMstruct parameters after training the model in on of these models Label is [0;1] and in another label is [1;0] ! A: As you have already noticed, the difference is due to the different mapping of the labels. LIBSVM uses its own labels internally and therefore needs a mapping between the internal labels and the labels you provided. The labels in this mapping are generated using the order the labels appear in the training data. So if the label of the first element in your training data changes, the label mapping also changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/24825463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Grant appropriate permission to use Symmetric Key in stored proc I created a symmetric key in SQL2012 using the following code (logged in as Windows Admin user): CREATE MASTER KEY ENCRYPTION BY PASSWORD = '34trg45trgf546t'; CREATE CERTIFICATE SSCert01 WITH SUBJECT = 'SS Certificate 01'; CREATE SYMMETRIC KEY SSN_Key_01 WITH ALGORITHM = TRIPLE_DES ENCRYPTION BY CERTIFICATE SSCert01; Once that was done I applied encryption to certain database columns. Still logged in as Admin, I can successfully decrypt columns using the Key: OPEN SYMMETRIC KEY SSN_Key_01 DECRYPTION BY CERTIFICATE SSCert01; SELECT name, surname, CONVERT(nvarchar(50),DECRYPTBYKEY(PasswordEnc)) as DecryptedPassword FROM [tbl_Users]; CLOSE SYMMETRIC KEY SSN_Key_01; I then placed the above code into a Stored Procedure. The problem is that my application access SQL using two Roles, which access the appropriate proc's. When either of these two Roles tries to execute a proc containing the above code, I see this error: Cannot find the certificate 'SSCert01', because it does not exist or you do not have permission. The key 'SSN_Key_01' is not open. Please open the key before using it. When I login as either Role, they cannot see the Key or the Cert. So, can anyone advise WHICH permissions to grant to the roles so that they can use the key/cert within stored procedures (only) to encrypt/decrypt data. The roles shouldn't be allowed to perform any functionality with the key/cert apart from encryption/decryption. I have looked at MSDN/Google and am none the wiser. UPDATE The following code allows the roles to use the proc's, but I am worried that CONTROL is too much access. Can anyone provide some clarity please? GRANT CONTROL ON CERTIFICATE :: SSCert01 TO Role001; GRANT CONTROL ON SYMMETRIC KEY :: SSN_Key_01 TO Role001; A: The way I usually get around this is to set the procedure to execute as owner and then make sure that the owner of the procedure has the correct permissions to perform the decryption, a lot of time the owner of the proc is DBO anyway so no additional configuration needs to be done apart from altering the procedure like so: ALTER PROCEDURE proc_name WITH EXECUTE AS OWNER AS OPEN SYMMETRIC KEY SSN_Key_01 DECRYPTION BY CERTIFICATE SSCert01; SELECT name, surname, CONVERT(nvarchar(50),DECRYPTBYKEY(PasswordEnc)) as DecryptedPassword FROM [tbl_Users]; CLOSE SYMMETRIC KEY SSN_Key_01; This means that you don't have to grant any additional permissions at all to your application role or users.
{ "language": "en", "url": "https://stackoverflow.com/questions/22254762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to add online image in epub3 file? I want to include online images in my EPUB3 file but when i validate it it shows me error "Only audio and video remote resources are permitted".when i include it using javascript it is working fine in Android e reader but images are not shown in iBooks. A: you probably need to save or download images into your android project folder and should access the images. refer this for reference
{ "language": "en", "url": "https://stackoverflow.com/questions/14978640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android ArrayList item in ListView So I have this list which uses values from an ArrayList (and I can't use String[] because the user must add items to the list, and I can't do .add to the String[]). But now I have problems with onItemClick method. I want to get the text from item selected, and my book says the following should work: @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { dodaj.setText(values[arg2]); } But I get the following error: The type of the expression must be an array type but it resolved to ArrayList What should I do to fix it? A: is "values" an ArrayList? if so use dodaj.setText( (String)values.get( arg2 ) ); A: you will have to convert arraylist to array using arraylist.toarray() A: With ArrayList you always use arrayList.get(index); Recommended way is to add a toString() method to your items/Objects so that it returns the preferred field. public Student() { ... ... public String toString() { return firstName + " " + lastName; } } Now you can use arrayList.get(int index). It will print our the output of toString().
{ "language": "en", "url": "https://stackoverflow.com/questions/11924065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get system drives through php? Possible Duplicate: How to get system info in PHP? I am building a simple file browser, I want to know as how to get the system information like the total drives and there names through php script? thanks A: This is gotten from the manual, and is for windows (Since you didn't specify the OS.) using the COM class. Note : This has nothing to do with the client side. <?php $fso = new COM('Scripting.FileSystemObject'); $D = $fso->Drives; $type = array("Unknown","Removable","Fixed","Network","CD-ROM","RAM Disk"); foreach($D as $d ){ $dO = $fso->GetDrive($d); $s = ""; if($dO->DriveType == 3){ $n = $dO->Sharename; }else if($dO->IsReady){ $n = $dO->VolumeName; $s = file_size($dO->FreeSpace) . " free of: " . file_size($dO->TotalSize); }else{ $n = "[Drive not ready]"; } echo "Drive " . $dO->DriveLetter . ": - " . $type[$dO->DriveType] . " - " . $n . " - " . $s . "<br>"; } function file_size($size) { $filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"); return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i] : '0 Bytes'; } ?> Would output something similar to Drive C: - Fixed - Bla - 88.38 GB free of: 444.14 GB Drive D: - Fixed - Blas - 3.11 GB free of: 21.33 GB Drive E: - Fixed - HP_TOOLS - 90.1 MB free of: 99.02 MB Drive F: - CD-ROM - [Drive not ready] - Drive G: - CD-ROM - Usb - 0 Bytes free of: 24.75 MB Drive H: - Removable - [Drive not ready] -
{ "language": "en", "url": "https://stackoverflow.com/questions/8209923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AppCenter build fails with no such module My automatic iOS build on AppCenter fails with the following error (snippet): ViewController.swift:10:8: error: no such module 'MBCircularProgressBar' import MBCircularProgressBar ^ But I don't know what the problem might be. I'm using CocoaPods to import that framework. My Podfile looks like this (removed all other pods): target 'MyApp' do use_frameworks! pod 'MBCircularProgressBar' end And I have a Post Clone script appcenter-post-clone.sh which is recognized in AppCenter that contains: #!/usr/bin/env bash pod repo update pod install EDIT: After moving the offending file down in the list of files to compile, I get the same error for another CocoaPod. So it seems to me that no CocoaPods are being found What is going wrong here? A: Can you check you are building your projects workspace? You'll need to build the workspace in orde to get Cocoapods to work, not the Xcode project.
{ "language": "en", "url": "https://stackoverflow.com/questions/49447433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: query with Pointer<_User> in Swift Parse SDK I have a class called Client and this class have a Pointer<_User>. I'm trying to do that the follow way: query.whereKey("user", equalTo:currentUser) But this way, no data returns in my query. Someone have an idea how can I to do this query? A: You probably need to set the includeKey property on your class, which fetched related objects, e.g. var query = PFQuery(className:"Client") // Retrieve the most recent ones query.orderByDescending("createdAt") // Include the user query.includeKey("user") Source: Parse iOS Guide A: try this query.whereKey("user", equalTo: PFUser.currentUser()!) or query.whereKey("user", equalTo: PFObject(withoutDataWithClassName: "_User", objectId: "\(PFUser.currentUser()!.objectId!)"))
{ "language": "en", "url": "https://stackoverflow.com/questions/39522836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SPXERR_GSTREAMER_NOT_FOUND_ERROR when using mp3 file with Microsoft.CognitiveServices.Speech I have this piece of code throwing the wrror in the title: using (var audioInput = AudioConfig.FromStreamInput(new PullAudioInputStream(new BinaryAudioStreamReader(new BinaryReader(File.OpenRead(audioFile))), AudioStreamFormat.GetCompressedFormat(AudioStreamContainerFormat.MP3)))) using (var recognizer = new SpeechRecognizer(config, sourceLanguageConfig, audioInput)) audioFile is the path to mp3 file with audio to transcribe. I have installed the latest GStreamer gstreamer-1.0-msvc-x86_64-1.17.2.msi for Windows and added it to the User's PATH and set GSTREAMER_ROOT_X86. That did not work. In the docs here https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/how-to-use-codec-compressed-audio-input-streams?tabs=debian&pivots=programming-language-csharp Handling compressed audio is implemented using GStreamer. For licensing reasons GStreamer binaries are not compiled and linked with the Speech SDK. Developers need to install several dependencies and plugins, see Installing on Windows. Gstreamer binaries need to be in the system path, so that the speech SDK can load gstreamer binaries during runtime. If speech SDK is able to find libgstreamer-1.0-0.dll during runtime it means the gstreamer binaries are in the system path. It says it will look for libgstreamer-1.0-0.dll which is no longer included in the latest version (1.17.2) so I went back to gstreamer-1.0-x86-1.14.1 which does have the required dll, but still getting the same error. From Visual Studio 2019 console I can invoke exe files included in that folder so I know the PATH is set correctly. Anyone has an idea what's missing? A: the way i fixed this... (similar to Artur Kędzior) use version 1.14.5 of Gstreamer https://gstreamer.freedesktop.org/pkg/windows/1.14.5/gstreamer-1.0-x86_64-1.14.5.msi - complete setup use version 1.13 of Microsoft.CognitiveServices.Speech (Nuget package) Go to environment variables on your pc and add to the User variable called path the following C:\gstreamer\1.0\x86_64\bin then add a system variable called "GSTREAMER_ROOT_X86_64" (without the quotes) and the value to "C:\gstreamer\1.0\x86_64" you may need to reboot if still having issues. but this is now working for me. A: Got help with it here https://github.com/Azure-Samples/cognitive-services-speech-sdk/issues/764 Basically: * *Do not use the latest version of Gstreamer *Use this one https://gstreamer.freedesktop.org/pkg/windows/1.14.5/gstreamer-1.0-x86_64-1.14.5.msi *Set PATH to bin folder (C:\gstreamer\1.0\x86_64\bin) *Set GSTREAMER_ROOT_X86_64 variable (C:\gstreamer\1.0\x86_64) *Reboot the machine *Set Visual Studio build configuration to x64
{ "language": "en", "url": "https://stackoverflow.com/questions/63358132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sequelize always timeout when row doesn't exist in database i have a get for an user with sequelize on a nodejs server : router.get('/:id', function (req, res) { models.user.find({ where: { id: req.params.id } }).then(function (result) { if (result === null) { res.status(204); } else { res.status(200); res.json(result); } }); }); working perfectly when user exist in database, but when i use an id who doesn't exist this get timeout, like every other find i use. Someone could tell me what I'm doing wrong? A: If your result is null you set the status of the response but don't return anything. Usual way to do this is the call next() to end the route: router.get('/:id', function (req, res, next) { models.Utilisateur.find({ where: { id: req.params.id }, include: [{model: models.Profil, include: [{model: models.Fonctionnalite}], through: {attributes: []}}] }).then(function (result) { if (result === null) { res.status(204); next(); } else { res.status(200); res.json(result); } }); }); or you could just return a json object instead. res.json({error: "not found"});
{ "language": "en", "url": "https://stackoverflow.com/questions/41057465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove maven artifcat completely from SpringSource? I have a local maven repository and installed a custom artifact. It works if i reference it in other projects. But now i want to use a server for a "own maven repository". If i delete the artifact from the local maven repository, i assumed that the project will not build when i do a maven clean and maven force update dependencies. The artifact cannot be found under .m2/ but Spring Source Tool Suite still can add the artifact to new Java Projects. Create New Java Project -> Edit Pom -> Maven Artifact is added, even if i deleted it from local repository .m2/ . How is this possible and how can i delete it completely, to be able to test if now all dependencies are updated from my server with the .m2/settings.xml configuration? A: Your repository is just a directory/file structure. Go to your local repo, find the path (the group id is the path), and delete from the place where you start to see version numbers. When you rebuild, the artifact should be downloaded/replaced from your server/repo.
{ "language": "en", "url": "https://stackoverflow.com/questions/24785327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying To Delay the Appearance of JLabels in a JDialog Hi I've there a little problem: What I want is to delay the appearance of JLabels in a JDialog-Window, in terms of that the first line of JLabels shoud come out and then two seconds later the second line of Jlabels etc. I've tried something with Windowlistener,the doClick()-Method etc., bu every time the Jdialog revalidates all of its panels AT ONCE and shows them without any delaying! Please help me(Just copy the code below and try out)! package footballQuestioner; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; public class attempter { public static void main(String[] args) throws InterruptedException { JDialog dialog = new Punkte(); } } class Punkte extends JDialog { private JPanel screenPanel = new JPanel(new GridLayout(4, 1)); private JButton button = new JButton(); private int i = 1; private class WindowHandler implements WindowListener { @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { } @Override public void windowClosing(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowOpened(WindowEvent e) { button.doClick(1000); button.doClick(1000); button.doClick(1000); button.doClick(); // here im trying to delay the appearance of the // JLabels.... } } private class ButtonHandler implements ActionListener { @Override public void actionPerformed(ActionEvent e) { switch (i) { case 1: settingUpPanel(getPanelFromScreenPanel(i), "Right", new Color( 102, 205, 0)); settingUpPanel(getPanelFromScreenPanel(i), "Wrong", Color.RED); break; case 2: settingUpPanel(getPanelFromScreenPanel(i), "Trefferquote", Color.YELLOW); break; case 3: settingUpPanel(getPanelFromScreenPanel(i), "Ausgezeichnet", Color.BLUE); break; } System.out.println(i); i++; } } public Punkte() { button.addActionListener(new ButtonHandler()); addWindowListener(new WindowHandler()); setModal(true); setResizable(true); setLayout(new BorderLayout()); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); settingUpScreenPanel(); add(screenPanel); setSize(1200, 1000); centeringWindow(); setVisible(true); } private void settingUpScreenPanel() { JPanel titlePanel = new JPanel(new GridBagLayout()); JPanel rightWrongCountPanel = new JPanel(new GridLayout(1, 2)); JPanel shareOfRightQuestions = new JPanel(new GridBagLayout()); JPanel grade = new JPanel(new GridBagLayout()); settingUpPanel(titlePanel, "Result", Color.BLACK); // settingUpPanel(rightWrongCountPanel, // "Right: "+numberOfRightAnsers+"/6",new Color(102,205,0)); // settingUpPanel(rightWrongCountPanel, // "Wrong: "+(6-numberOfRightAnsers)+"/6", Color.RED); // settingUpPanel(shareOfRightQuestions, // "Trefferquote: "+(numberOfRightAnsers*100/6)+"%",Color.YELLOW); // settingUpPanel(summaSummarum, // getBufferedImage("footballQuestioner/Strich.png")); // settingUpPanel(grade,"Aushezeichnet", Color.BLUE); borderingJPanel(screenPanel, null, null); titlePanel.setOpaque(false); rightWrongCountPanel.setOpaque(false); shareOfRightQuestions.setOpaque(false); grade.setOpaque(false); screenPanel.add(titlePanel); screenPanel.add(rightWrongCountPanel); screenPanel.add(shareOfRightQuestions); screenPanel.add(grade); } private void settingUpPanel(JComponent panel, String string, Color color) { Font font = new Font("Rockwell Extra Bold", Font.PLAIN, 65); JPanel innerPanel = new JPanel(new GridBagLayout()); JLabel label = new JLabel(string); label.setForeground(color); label.setFont(font); innerPanel.add(label); innerPanel.setOpaque(false); panel.add(innerPanel); panel.validate(); panel.repaint(); } public JPanel getPanelFromScreenPanel(int numberOfPanel) { JPanel screenPanel = (JPanel) getContentPane().getComponent(0); JPanel labelPanel = (JPanel) screenPanel.getComponent(numberOfPanel); return labelPanel; } public void centeringWindow() { Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); int x; int y; x = (int) (dimension.getWidth() - getWidth()) / 2; y = (int) (dimension.getHeight() - getHeight()) / 2; setLocation(x, y); } public void borderingJPanel(JComponent panel, String jPanelname, String fontStyle) { Font font = new Font(fontStyle, Font.BOLD + Font.ITALIC, 12); if (jPanelname != null) { panel.setBorder(BorderFactory.createTitledBorder(BorderFactory .createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY, Color.WHITE), jPanelname, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, font)); } else if (jPanelname == null || fontStyle == null) { panel.setBorder(BorderFactory.createTitledBorder(BorderFactory .createEtchedBorder(EtchedBorder.LOWERED, Color.BLACK, Color.WHITE))); } panel.setOpaque(false); } } A: This is a really good use case for javax.swing.Timer... This will allow you to schedule a callback, at a regular interval with which you can perform an action, safely on the UI. private class WindowHandler extends WindowAdapter { @Override public void windowOpened(WindowEvent e) { System.out.println("..."); Timer timer = new Timer(2000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JPanel panel = getPanelFromScreenPanel(1); panel.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; for (int index = 0; index < 100; index++) { panel.add(new JLabel(Integer.toString(index)), gbc); } panel.revalidate(); } }); timer.start(); timer.setRepeats(false); } } Now, if you wanted to do a series of actions, separated by the interval, you could use a counter to determine the number of "ticks" that have occurred and take appropriate action... private class WindowHandler extends WindowAdapter { @Override public void windowOpened(WindowEvent e) { System.out.println("..."); Timer timer = new Timer(2000, new ActionListener() { private int counter = 0; private int maxActions = 10; @Override public void actionPerformed(ActionEvent e) { switch (counter) { case 0: // Action for case 0... break; case 1: // Action for case 1... break; . . . } counter++; if (counter >= maxActions) { ((Timer)e.getSource()).stop(); } } }); timer.start(); } } Take a look at How to use Swing Timers for more details
{ "language": "en", "url": "https://stackoverflow.com/questions/25025666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Convert IIFE module to something importable by RollupJS I am using RollupJS as a bundler, and it can read CommonJS (via a plugin) or ES6 modules. But this module seems to be in UMD format, and I am looking for a quick way I can edit it (without replacing a lot of lines) so that it is in commonJS or ES6 format. What do folks suggest? I show the top and the bottom of a 5,000 line .js file. @module vrlinkjs **/ (function (mak) { mak.MessageKindEnum = { Any : -1, Other : 0, AttributeUpdate : 1, Interaction : 2, Connect : 3, ObjectDeletion : 4 }; /** Decodes AttributeUpdate messages into an EnvironmentalStateRepository object. @class EnvironmentalStateDecoder @constructor @augments StateDecoder @param {WebLVCConnection} webLVCConnection Connection to a WebLVC server **/ mak.EnvironmentalStateDecoder = function(webLVCConnection) { mak.StateDecoder.apply(this, arguments); }; mak.EnvironmentalStateDecoder.prototype = Object.create(mak.StateDecoder.prototype, { constructor : { value : mak.EnvironmentalStateDecoder }, /** Decodes a AttributeUpdate message into an EntityStateRepository object. @method decode @param {Object} attributeUpdate WebLVC AttributeUpdate message @param {EntityStateRepository} stateRep State repository to be updated **/ decode : { value : function( attributeUpdate, stateRep ) { // if(this.webLVCConnection.timeStampType == mak.TimeStampType.TimeStampAbsolute && // attributeUpdate.TimeStampType == mak.TimeStampType.TimeStampAbsolute) { // } else { // stateRep.timeStampType = mak.TimeStampType.TimeStampRelative; // } stateRep.timeStampType = mak.TimeStampType.TimeStampRelative; var curTime = 0.0; // if (stateRep->timeStampType() == DtTimeStampAbsolute) // { // // Use timestamp as time of validity // curTime = pdu.guessTimeValid(myExConn->clock()->simTime()); // } // else // { // // Use receive time as time of validity // curTime = myExConn->clock()->simTime(); // } curTime = this.webLVCConnection.clock.simTime; if(attributeUpdate.ProcessIdentifier != undefined) { stateRep.entityIdentifier = attributeUpdate.EntityIdentifier; } if(attributeUpdate.Type != undefined) { stateRep.entityType = attributeUpdate.Type; } if(attributeUpdate.ObjectName != undefined) { stateRep.objectName = attributeUpdate.ObjectName; } if(attributeUpdate.GeometryRecords != undefined) { stateRep.GeometryRecords = attributeUpdate.GeometryRecords; } if(attributeUpdate.EnvObjData != undefined) { if(attributeUpdate.EnvObjData.VrfObjName != undefined) { stateRep.marking = attributeUpdate.EnvObjData.VrfObjName; } } } } }); ..... } (this.mak = this.mak || {})); UPDATE I used the ES6 module solution from estus (below), which I really like. It solved the rollup bunding issue, but there is still a runtime error. But there is a little more that needs to be done. I am getting this error with chrome. I have two varients of the HTML main.html file, one uses the bundle and the other just imports my es6 modules. The error occurs even when I am not using rollup and creating and using the bundle. Uncaught TypeError: Cannot set property objectName of [object Object] which has only a getter at mak$1.ReflectedEntity.mak$1.ReflectedObject [as constructor] (vrlink.mjs:818) at new mak$1.ReflectedEntity (vrlink.mjs:903) at mak$1.ReflectedEntityList.value (vrlink.mjs:1358) at mak$1.WebLVCMessageCallbackManager.<anonymous> (vrlink.mjs:1155) at mak$1.WebLVCMessageCallbackManager.processMessage (vrlink.mjs:1745) at mak$1.WebLVCConnection.drainInput (vrlink.mjs:2139) at SimLink.tick (SimLink.js:34) This seems to be the offender when converting from IIFE modules to ES6. It says that there is no setter. The code is not my creation, but it seemed like it should not have be a major effort to convert IIFE to ES6. The offending snippet is: mak.VrfBackendStateRepository = function (objectName) { /** Unique string identifying entity @property objectName @type String **/ this.objectName = objectName; //error generated on this line! If you are wondering what this is, it is a object called mak.webLVConnection, which is created by this function in the IIFE code: /** Represents a connection to a WebLVC server. clientName and port are required. webLVCVersion is optional (current version supported by the WebLVC server will be in effect). serverLocation is optional ( websocket connection will be made to the host servering the javascript ) @class WebLVCConnection @constructor @param {String} clientName String representing name of the client federate @param {Number} port Websocket port number @param {Number} webLVCVersion WebLVC version number @param {String} serverLocation Hostname of websocket server **/ mak.WebLVCConnection = function (clientName, port, webLVCVersion, serverLocation, url) { var self = this; if (clientName == undefined) { throw new Error("clientName not specified"); } if (!(typeof clientName == "string" && clientName.length > 0)) { throw new Error("Invalid ClientName specified"); } if (port == undefined) { throw new Error("Port not specified"); } if (url == undefined) { url = "/ws"; } var websocket; if (serverLocation == undefined) { if (location.hostname) { websocket = new WebSocket("ws://" + location.hostname + ":" + port + url); } else { websocket = new WebSocket("ws://localhost:" + port + "/ws"); } } else { websocket = new WebSocket("ws://" + serverLocation + ":" + port + url); } /** Websocket connected to a WebLVC server. @property websocket @type WebSocket **/ this.websocket = websocket; /** DIS/RPR-style identifier, used to generate new unique IDs for entities simulated through this connection. Array of 3 numbers [site ID, host ID, entity number]. @property currentId @type Array **/ this.currentId = [1, 1, 0]; /** Manages registration and invoking of message callbacks. @property webLVCMessageCallbackManager @type WebLVCMessageCallbackManager **/ this.webLVCMessageCallbackManager = new mak.WebLVCMessageCallbackManager(); /** Simulation clock @property clock @type Clock **/ this.clock = new mak.Clock(); /** Indicates whether timestamping is relative or absolute (mak.TimeStampType.TimeStampRelative or mak.TimeStampType.TimeStampAbsolute). @property {Number} timeStampType **/ this.timeStampType = mak.TimeStampType.TimeStampRelative; /** List of incoming messages. When messages are received, they are placed in this queue. The drainInput() member function must be called regularly to remove and process messages in this queue. @property {Array} messageQueue **/ this.messageQueue = new Array(); /** Callback function invoked on receipt of a message. Calls webLVCMessageCallbackManager.processMessage(). @method processMessage @private **/ this.processMessage = this.webLVCMessageCallbackManager.processMessage.bind(this.webLVCMessageCallbackManager); /** Callback function invoked when websocket connection is opened. Sends the initial WebLVC connect message. @method onopen @private **/ this.websocket.onopen = function () { var connectMessage = { MessageKind: mak.MessageKindEnum.Connect, ClientName: clientName } if (webLVCVersion != undefined) { connectMessage.WebLVCVersion = webLVCVersion; } if (self.websocket.readyState == 1) { self.websocket.send(JSON.stringify(connectMessage)); } }; /** Callback function invoked when a WebLVC message is received. Parses the the JSON message data and passes the resulting object to processMessage. @method onmessage @event {Object} JSON message @private **/ this.websocket.onmessage = function (event) { //just in case if (event.data == "ping") return; var message = JSON.parse(event.data); if (message != null) { self.messageQueue.push(message); } else { console.warn("onmessage - null message received"); } }; /** Callback function invoked when the websocket is closed. @method onclose @private **/ this.websocket.onclose = function () { console.debug("In websocket.onclose"); }; /** Callback function invoked when an error in the websocket is detected. Sends warning to console. @method onerror @private **/ this.websocket.onerror = function () { console.log("websocket onerror"); }; this.isOk = function () { return this.websocket.readyState == 1; } }; mak.WebLVCConnection.prototype = { constructor: mak.WebLVCConnection, /** Set the DIS/RPR-style application ID. @method set applicationId @param {Array} applicationId Array of 2 integers [site ID, host ID]. **/ set applicationId(applicationId) { this.currentId[0] = applicationId[0]; this.currentId[1] = applicationId[1]; this.currentId[2] = 0; }, /** Returns next available DIS/RPR-style entity ID. @method nextId @return {Array} Array of 3 integers [site ID, host ID, entity number]. **/ get nextId() { this.currentId[2]++; return this.currentId; }, /** Register callback function for a given kind of message. @method addMessageCallback @param {Number} messageKind WebLVC MessageKind @param callback Function to be invoked **/ addMessageCallback: function (messageKind, callback) { this.webLVCMessageCallbackManager.addMessageCallback(messageKind, callback); }, /** De-register callback function for a given kind of message. @method removeMessageCallback @param messageKind WebLVC MessageKind @param callback Function to be invoked **/ removeMessageCallback: function (messageKind, callback) { this.webLVCMessageCallbackManager.removeMessageCallback(messageKind, callback); }, /** Send a WebLVC message to the server. @method send @param {Object} message **/ send: function (message) { try { if (this.websocket.readyState == 1) { this.websocket.send(JSON.stringify(message)); } } catch (exception) { console.log("Error sending on websocket - exception: " + exception); } }, /** Send a time-stamped WebLVC message to the server. @method sendStamped @param {Object} message **/ sendStamped: function (message) { // Timestamp is hex string var timeStamp = this.currentTimeForStamping().toString(16); //message.TimeStamp = ""; // timeStamp; this.send(message); }, /** Get the current simulation time for a time stamp. @method currentTimeForStamping @return {Number} Simulation time in seconds. **/ currentTimeForStamping: function () { if (this.timeStampType == mak.TimeStampType.TimeStampAbsolute) { return this.clock.simTime(); } else { return this.clock.absRealTime(); } }, /** Iterate through message queue, calling processMessage() and then removing each message. Should be called regularly from your application. @method drainInput **/ drainInput: function () { var message; while (this.messageQueue.length > 0) { message = this.messageQueue.shift(); this.processMessage(message); } }, /** Closes the websocket connection. Calls the destroy method on its WebLVCMessageCallbackManager data member. @method destroy **/ destroy: function () { console.debug("In WebLVCConnection.destroy"); this.webLVCMessageCallbackManager.destroy(); this.websocket.close(); } }; A: UMD modules, by definition, are CommonJS. The code above is just IIFE and relies on mak global. IIFE wrapper function can be replaced with default or named ES module export: const mak = {}; mak.MessageKindEnum = { ... }; ... export default mak; Or with CommonJS export: const mak = {}; mak.MessageKindEnum = { ... }; ... module.exports = mak; A: did you try: (function (mak) { ... }(module.exports)); // instead of // } (this.mak = this.mak || {}));
{ "language": "en", "url": "https://stackoverflow.com/questions/47998882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to disable the resizing button in a tkinter gui app? So, I want to build a tkinter app and I need to disable this button... how do I do that??? A: The following example disables the resizing of a tkinter GUI using the resizable method. import tkinter as tk class App(tk.Frame): def __init__(self,master=None,**kw): tk.Frame.__init__(self,master=master,**kw) tk.Canvas(self,width=100,height=100).grid() if __name__ == '__main__': root = tk.Tk() App(root).grid() root.resizable(width=False,height=False) root.mainloop() A: Even though you have an answer, here's a shortened code, without classes (if you want): from tkinter import Tk root = Tk() root.geometry("500x500") root.resizable(False, False) root.mainloop() A: try this. It should help. from tkinter import * tk = Tk() canvas = Canvas(tk, width='you can decide', height='you can decide') canvas.pack() canvas.mainloop()
{ "language": "en", "url": "https://stackoverflow.com/questions/69044950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to effectively refresh many to many relationship Lets say I have entity A, which have many to many relationship with another entities of type A. So on entity A, I have collection of A. And lets say I have to "update" this relationships according to some external service - from time to time I receive notification that relations for certain entity has changed, and array of IDs of current related entities - some relations can be new, some existing, some of existing no longer there... How can I effectively update my database with EF ? Some ideas: * *eager load entity with its related entities, do foreach on collection of IDs from external service, and remove/add as needed. But this is not very effective - need to load possibly hundreds of related entities *clear current relations and insert new. But how ? Maybe perform delete by stored procedure, and then insert by "fake" objects a.Related.Add(new A { Id = idFromArray }) but can this be done in transaction ? (call to stored procedure and then inserts done by SaveChanges) or is there any 3rd way ? Thanx. A: Well, "from time to time" does not sound like a situation to think much about performance improvement (unless you mean "from millisecond to millisecond") :) Anyway, the first approach is the correct idea to do this update without a stored procedure. And yes, you must load all old related entities because updating a many-to-many relationship goes only though EFs change detection. There is no exposed foreign key you could leverage to update the relations without having loaded the navigation properties. An example how this might look in detail is here (fresh question from yesterday): Selecting & Updating Many-To-Many in Entity Framework 4 (Only the last code snippet before the "Edit" section is relevant to your question and the Edit section itself.) For your second solution you can wrap the whole operation into a manually created transaction: using (var scope = new TransactionScope()) { using (var context = new MyContext()) { // ... Call Stored Procedure to delete relationships in link table // ... Insert fake objects for new relationships context.SaveChanges(); } scope.Complete(); } A: Ok, solution found. Of course, pure EF solution is the first one proposed in original question. But, if performance matters, there IS a third way, the best one, although it is SQL server specific (afaik) - one procedure with table-valued parameter. All new related IDs goes in, and the stored procedure performs delete and inserts in transaction. Look for the examples and performance comparison here (great article, i based my solution on it): http://www.sommarskog.se/arrays-in-sql-2008.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7784778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I setup an Azure Web Farm on multiple VM's using a shared IIS config I setup a VM running Windows Server 2012 R2 (VM1) and configured it to run IIS. I then created another VM in the same region off an image I made from the first (VM2). These two are in their own availability set located in the West US data center. Assuming I want to share my IIS configuration and website files between the two servers, I need to setup a location to store and access these files regardless of what server is making changes to them or is online at the time. Attached storage almost provides a solution, but this can only be tied to a single machine at a time. Files can be stored in a separate Blob storage, but I don't know how to get IIS to read and write to it. Once I do figure out how to share these files in a manner IIS will accept, I have a second problem where I would need a third VM (VM3) in Europe that would need access to this data as well. Thank you for any assistance anyone can provide! A: Have you thought about using something like Dropbox to keep the folders synchronized? A: You would use DFS (Distributed File System) to accomplish this. http://technet.microsoft.com/en-us/library/cc753479(v=ws.10).aspx http://blogs.iis.net/rickbarber/archive/2012/12/05/keeping-multiple-iis-7-servers-in-sync-with-shared-configuration.aspx Thanks. -matt
{ "language": "en", "url": "https://stackoverflow.com/questions/24770493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Twilio Call To Multiple Agents on Form Submit i am having a case where when client submit a form i want my system to call multiple agent if one agent pick call all the calls should be drop the code i am current using call is dropping all calls after execution of twiml $data = $req->input(); $action = $appUrl.'/wcc/gather-input?callId='.$data["callId"].'&visitorName='.$data["visitorName"].'&visitorMessage='.$data["visitorMessage"].'&visitorPhone='.$data["visitorPhone"]; $dial = $response->dial('', ['callerId' => '+123123123', 'timeout' => 30, 'action' => $action,"method"=>"GET"]); $dial->number('+123123213'); $dial->number('+12313123123'); header('Content-Type: text/xml'); echo $response; A: You won't be able to use SimRing (Dial Verb with Multiple Nested Number nouns) with that approach, as the first person to pick up the call results in all the other call legs being cancelled. You will need to use the /Calls resource to initiate the calls, and return TwiML that asked the dialed party to press any digit to be connected to the customer. You would then cancel (status=canceled) the other call legs. As you can see SimRing is not the best approach as it tends to tire out the dialed parties with incessant ringing and the voicemail issues you need to guard against as well as the default Calls Per Second (CPS) is 1 per second, so there will be a delay between each outbound call, unless you have Twilio Sales increase the outbound CPS. Once the agent presses a key, you can initiate a Dial Number to the customer. If you need to modify the call once it is established, you should connect the agent to a conference and the customer to the same conference, you anchors the call legs and allows easier manipulation of the call.
{ "language": "en", "url": "https://stackoverflow.com/questions/67021229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Way to set private variable of class having more than one member variable As we can set the private variable of class like this I was trying to set the private member variable int for below case. #include <iostream> #include <string> using namespace std; class Test { private: string s; int data; public: Test() : s("New") , data(0) { } int getData() { return data; } }; int main() { Test t; int* ptr = (int*)&t; *(ptr+sizeof(string)) = 10; cout << t.getData(); return 0; } But it is not able to print 10. I know there are other way to set this using setter function, but was checking to set using method shown here This is purely hack and not valid way though to learn. A: I reckon this'll solve it: char* ptr = (char*)&t; *(int*)(ptr+sizeof(string)) = 10; sizeof will return the size in bytes. Pointer increments will go for the size of the object its pointing at. char is a byte in size. If you want to read up on it: C pointer arithmetic article Just to reiterate what I think you've said: you're just hacking around as a point of learning, and you know there's no way you should ever do this in real life... !! A: Why it doesn't work Really just never write code like this. There is a way to set private data and that is via public members on the class. Otherwise, it's private for a reason. This being C++, there are actually non-UB ways of doing this but I'm not going to link them here because don't. Why it doesn't work, specifically Hint: What does ptr + sizeof(string) actually mean, for ptr being an int*? What is ptr pointing to after this line? A: The pointer arithmetic should be done with byte pointers, not integer pointers. #include <iostream> #include <string> using namespace std; class Test { private: string s; int data; public: Test() { s = "New", data = 0; } int getData() { return data; } }; int main() { Test t; char* ptr = (char*)&t; *(int*)(ptr+sizeof(string)) = 10; cout << t.getData(); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/41268827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Changing the Header of urllib2 to get different search results on google Can I change the header on a google query to get the results I would get for mobile? I'm trying to get different results on google according to different headers in the library urllib2 or requests. I use beautifulsoup to parse the results. For example I use this header to simulate the Desktop results: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ 58.0.3029.81 Safari/537.36 my mobile header would be this Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B137 Safari/601.1 The question is now: Is this possible or will google recognize, that I'm not using a phone to get the google results? I don't get different results. I use this code to just try: import requests headers_mobile = { 'User-Agent' : 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B137 Safari/601.1'} link = 'https://www.google.com/search?q=testseite&num=22&hl=de' B_response = requests.get(link, headers=headers_mobile) for i in B_response: print(i) A: It is possible. List of mobile user-agents. But instead of iterating over requests.get() result, you need to pass it to BeautifulSoup object, and then select a certain element (container with data) and iterate over it. # container with mobile layout data for mobile_result in soup.select('.xNRXGe'): title = mobile_result.select_one('.q8U8x').text link = mobile_result.select_one('a.C8nzq')['href'] snippet = mobile_result.select_one('.VwiC3b').text Code and example in the online IDE: from bs4 import BeautifulSoup import requests, lxml headers = { 'User-agent': 'Mozilla/5.0 (Linux; Android 7.0; LGMP260) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.93 Mobile Safari/537.36' } params = { 'q': 'how to create minecraft server', 'gl': 'us', # country to search from 'hl': 'en', # language } html = requests.get('https://www.google.com/search', headers=headers, params=params) soup = BeautifulSoup(html.text, 'lxml') for mobile_result in soup.select('.xNRXGe'): title = mobile_result.select_one('.q8U8x').text link = mobile_result.select_one('a.C8nzq')['href'] snippet = mobile_result.select_one('.VwiC3b').text print(title, link, snippet, sep='\n') ----------- ''' How to Setup a Minecraft: Java Edition Server – Home https://help.minecraft.net/hc/en-us/articles/360058525452-How-to-Setup-a-Minecraft-Java-Edition-Server How to Setup a Minecraft: Java Edition Server · Go to this website and download the minecraft_server. · After you have downloaded it, make a folder on your ... Minecraft Server Download https://www.minecraft.net/en-us/download/server Download the Minecraft: Java Edition server. Want to set up a multiplayer server? · Download minecraft_server.1.17.1.jar and run it with the following command:. # other results ''' Alternatively, you can achieve the same thing by using Google Organic Results API from SerpApi. It's a paid API with a free plan. Check out the playground. The difference in your case is that you don't have to figure out things (well, you have to, but it's a much more straightforward process), don't have to maintain the parser over time, and iterate over structured JSON instead. Code to integrate: import os from serpapi import GoogleSearch params = { "api_key": os.getenv("API_KEY"), "engine": "google", "q": "how to create minecraft server", "hl": "en", "gl": "us", "device": "mobile" # mobile results } search = GoogleSearch(params) results = search.get_dict() for result in results["organic_results"]: print(result['title']) print(result['link']) ----------- ''' How to Setup a Minecraft: Java Edition Server – Home https://help.minecraft.net/hc/en-us/articles/360058525452-How-to-Setup-a-Minecraft-Java-Edition-Server How to Setup a Minecraft: Java Edition Server · Go to this website and download the minecraft_server. · After you have downloaded it, make a folder on your ... Minecraft Server Download https://www.minecraft.net/en-us/download/server Download the Minecraft: Java Edition server. Want to set up a multiplayer server? · Download minecraft_server.1.17.1.jar and run it with the following command:. # other results ''' Disclaimer, I work for SerpApi.
{ "language": "en", "url": "https://stackoverflow.com/questions/65425739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where should rookie go for best SQL tutorial resources? I´m interested in both web resources and books. It´s a jungle out there, please give me a hand. My goal is to learn the SQL language so I can query Sql Server databases within a couple of weeks. I´ve got a programming background, and I know some basic stuff about relational databases, but almost nothing on how to use the SQL language. Thanks to you ALL for all good tips! I will save this page as a starting point in my mission to learn SQL. Sadly enough it´s not possible to set more than one answer as "accepted"... A: I don't normally go for the ' ... in 21 days' books but this online one seems reasonable: Teach Yourself SQL in 21 Days, Second Edition. See Where can I find training/tutorials for SQL and T-SQL? A: one of my favorite websites to get started with SQL is : SQLCourse Good luck for your starting A: This (w3schools) is always a nice place to start. A: Try SQL Exercises A: Perhaps You need to begin your own project, It is always recommended when learning something new that you fight with real problems. http://www.databasejournal.com/ is one of good recurses,
{ "language": "en", "url": "https://stackoverflow.com/questions/2895987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Sharing static classes data accross web garden/farm Scenario: * *ASP.NET web site *Global static classes containing TONS of configuration data *the static data is mostly read-only, but it can change every once in a while *data in static classes MUST BE real time, at all times now, this works really great in a single worker process, all the configuration data is in memory at all times (writing changes to disk only when modifications are made to the data), and since it is used a LOT, it speeds up the application by orders of magnitude (compared to having it stored on the DB and querying against it on every request) how would you go about converting this application so that it could be used in a web garden, or even web farm environment? what I'm looking for is a real time synchronization mechanism the issue, obviously, is that each worker would have it's own copy of the static classes data; I have some ideas on the approach that I would take, but would like to see what other ideas people have A: You could check the date on a shared file on the file system. Every time the configuration data changes, simply touch the file to change the modification date. Compare the date your program last loaded the data with the file's date. If the file has a newer date, reload the data, and update your LastLoaded date. It is light weight, and it allows you to easily trigger data reloads. So long as the file hasn't changed in a while, the OS should have most of the file metadata in ram anyway. While I haven't done performance comparisons, I've always found this way to be the a robust and easy to implement way to pass the "Reload your cache" message around to all clients. DateTime cacheDate = DateTime.Now.AddHours(-1); DateTime fileDate = System.IO.File.GetLastWriteTime(@"C:\cachefile.txt"); if(fileDate > cacheDate) { //Reload cache cacheDate = DateTime.Now; } //Get Cached Data You could also use the HttpContext cache. Context.Cache.Add(key, val, new System.Web.Caching.CacheDependency(@"C:\cachefile.txt"), System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null/* or your Callback for loading the cache.*/); I haven't used this before in this way, so I don't know much about how it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/1230320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dictionary with arrays of keys and values This question is in regards to javascript or jQuery, whichever will get the job done better. What I want to do is create an object similar to the following: var prodItems = [ { "product": "prod1", "item": ["prod1Item1", "prod1Item2"] }, { "product": "prod2", "item": ["prod2Item1", "prod2Item2", "prod2Item3", "prod2Item4"] } ]; with this I can access the members like this: prodItems[1]["product"] is "prod2" prodItems[1]["item"][0] is "prod2Item1" I would like to create this list dynamically and I am stumbling with the syntax, something like: var menuItems; menuItems.product[0] = "prod1"; menuItems.product[0].item[0] = "prod1Item1"; Can someone please give me some guidance on how I can do this? Edit, i want to create a function with something like returnDict("prod2", "prod2Item3") this will rearrange it like so: prodItems = [ { "product": "prod2", "item": ["prod2Item3", "prod2Item1", "prod2Item2", "prod2Item4"] }, { "product": "prod1", "item": ["prod1Item1", "prod2Item2"] } ]; A: My "guidance" on constructing the object would be to avoid this style of inserting each string separately: menuItems.product[0].product = "prod1"; menuItems.product[0].item[0] = "prod1Item1"; because this involves a lot of writing the same thing over and over, which is more error-prone and less readable/maintainable. I would prefer inserting more coarse-grained objects: menuItems.product[0] = { product: "prod1", item: ["prod1Item1"]; } Edit: Your edit is asking a completely different question, but it sounds like what you want to do is sort the elements of prodItems based on their "product" properties, then do the same thing for the "items" array inside the elements. I think the simplest way to do this would be to use Array.sort() with a custom comparison function that returns -1 on the element you want to see at the top. Something like this (hastily written and untested): function returnDict(product, item) { prodItems = prodItems.sort(function(a, b) { if(a.product === product) { return -1; } else if(b.product === product) { return 1; } else { return 0; } }); prodItems[0].items = prodItems[0].items.sort(function(a, b) { if(a === item) { return -1; } else if(b === item) { return 1; } else { return 0; } }); return prodItems; } A: var menuItems = []; menuItems.push({product:"prod1",item:[]}) menuItems[menuItems.length-1].item.push("product1Item1") menuItems[menuItems.length-1].item.push("product1Item2") menuItems.push({product:"prod2",item:[]}) menuItems[menuItems.length-1].item.push("product2Item1") menuItems[menuItems.length-1].item.push("product2Item2") menuItems[menuItems.length-1].item.push("product2Item3") menuItems[menuItems.length-1].item.push("product2Item4") A: var prodItems = [ { "product": "prod1", "item": ["prod1Item1", "prod2Item2"] }, { "product": "prod2", "item": ["prod2Item1", "prod2Item2", "prod2Item3", "prod2Item4"] } ]; alert(prodItems[0].product); for(var i = 0; i < prodItems.length; i++) { alert(prodItems[i].product); } A: I see your question has been answered, but I want to suggest a small improvement to keep your code more DRY (Do not Repeat Yourself). You can use a simple function that will save you some extra typing when adding new objects. var prodItems=[]; function addProduct(productName, items){ var product={ product: productName, items: items }; prodItems.push(product); }; //sample use addProduct("prod2",["prod2Item3", "prod2Item1", "prod2Item2", "prod2Item4"]) This will definitely also become more flexible if you need to change the object structure at some later point.
{ "language": "en", "url": "https://stackoverflow.com/questions/28003198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: bitwise operator in php Here is my code: (($order['financial_status']!='partially_refunded')?$order['fulfillments'][0]['updated_at']:null) Here, I want to check, refunded and partially_refunded by using or operator. Can anyone help me? Thanks. A: If I understand you correctly, it's not bitwise you need, but a simple if conditional statement: if ($order['financial_status'] !== 'partially_refunded' || $order['financial_status'] !== 'refunded') { // Do something with $order['fulfillments'][0]['updated_at'] }
{ "language": "en", "url": "https://stackoverflow.com/questions/23844305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: predict sequence of tuples using Transformer model I am fairly new to seq2seq models and transformers. Basically I am working on a sequence generation problem. I want to use the transformer. I am using python and pyTorch. I know how the transformer model works for a sequence generation like given [1,2,3] it can generate [1,2,3,4,5]. But the problem I am facing is that, in my dataset each point/element in the sequence has 2 attributes. So, the sequence looks like following: [(2,4), (1,8), (1,9)] and the generated sequence will be: [(2,4), (1,8), (1,9), (3,1), (2,9)] The first element of each tuple can be between 1-5 and the second element can be between 1-10. I want to follow the general approach of Transformers like creating embedding for each element, pass it through a decoder block of multihead attention and pointwise feed forward network and finally use softmax to sample out the output. My question is, as each data point contains 2 values, how do I change the transformer model to work with this kind of sequences? Any direction will be appreciated. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/65359224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: compound interest program problem in dev c++ using c I am trying to write a program to print simple interest and compound interest in dev c++ in c programming but it is not printing the correct compound interest can anybody tell why? here is my code: #include<stdio.h> #include<math.h> int main() { int p,r,t,si,ci; printf("enter the principle:"); scanf("%d",&p); printf("enter the rate:"); scanf("%d",&r); printf("enter the time:"); scanf("%d",&t); si=p*r*t/100; ci=p*pow((1+(r/100)),t); printf("simple interest:%d",si); printf("\ncompound interest:%d",ci); int a=getch(); return 0; } A: You have given int instead of float. #include<stdio.h> #include<math.h> int main(){ float p,r,t,si,ci; printf("enter the principle:"); scanf("%d",&p); printf("enter the rate:"); scanf("%d",&r); printf("enter the time:"); scanf("%d",&t); si=p*r*t/100; ci=p*pow((1+(r/100)),t); printf("simple interest:%d",si); printf("\ncompound interest:%d",ci); int a=getch(); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/70322098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom NSURLProtocol subclasses are not available to background sessions From NSURLSession.h... /* An optional array of Class objects which subclass NSURLProtocol. The Class will be sent +canInitWithRequest: when determining if an instance of the class can be used for a given URL scheme. You should not use +[NSURLProtocol registerClass:], as that method will register your class with the default session rather than with an instance of NSURLSession. Custom NSURLProtocol subclasses are not available to background sessions. */ @property (nullable, copy) NSArray<Class> *protocolClasses; Custom NSURLProtocol subclasses are not available to background sessions. What would be the advantage of restricting custom NSURLProtocol subclasses to only trigger in foreground sessions? A: From Apple documentation: Background sessions are similar to default sessions, except that a separate process handles all data transfers. Apple simply doesn't provide a way to inject your NSURLProtocol subclass into another process, managed by iOS itself. Same restriction applies to WKWebView.
{ "language": "en", "url": "https://stackoverflow.com/questions/34865414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Swing: Click on a button in a frame, show another frame with different components I am developing an application which needs to pop up new JFrame B with different components, when I click on a button on JFrame A. How do I achieve that? I don't want to use the tabs. A: Use a JDialog , problem solved! See this java tutorial for more help : How to Make Dialogs A: I'm not sure why no one has suggested CardLayout yet, but this is likely your best solution. The Swing tutorials have a good section on this: How to use CardLayout A: In a nutshell (a simple solution), you register a listener with the JButton and then have the listener perform the tasks you want it to perform: setVisible(true) for one frame. setVisible(false) for the other one. Regards! A: One way to approach this would be to create another jFrame and then add a listener onto your button like so: jFrameNew.setVisible(true); This way you have a whole new frame to work with. If you want to just have a pop-up message you can also try using the jDialog frames. Depending on which IDE you are using...for example Netbeans has a gui that makes designing interfaces slightly easier, so you can test out the different frames.
{ "language": "en", "url": "https://stackoverflow.com/questions/8185657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OpenTK mouse picking I have developed a small C# sample to pick the point by using OpenTK and winforms There is a method to draw the Squares and there is another method to pick the triangle. Somehow I am not getting any hits. Is there any problem with Readpixel methods? because I just converted Tao picking sample to OpenTK with correct methods? Could you please let me know what is wrong with my method? private static int[,] board = new int[3, 3]; //Definition private const int BUFSIZE = 512; private void glControl1_MouseDown(object sender, MouseEventArgs e) { int[] selectBuffer = new int[BUFSIZE]; //This has to be redifined int hits; int[] viewport = new int[4]; if (e.Button == MouseButtons.Left) { GL.GetInteger(GetPName.Viewport, viewport); GL.SelectBuffer(BUFSIZE, selectBuffer); GL.RenderMode(RenderingMode.Select); GL.InitNames(); GL.PushName(0); GL.MatrixMode(MatrixMode.Projection); GL.PushMatrix(); GL.LoadIdentity(); Byte4 Pixel = new Byte4(); GL.ReadPixels(e.X, viewport[3] - e.Y, 1, 1, PixelFormat.Rgba, PixelType.UnsignedByte, ref Pixel); uint SelectedTriangle=SelectedTriangle = Pixel.ToUInt32(); GL.Ortho(0, 3 ,0, 3, 1,-1); // Bottom-left corner pixel has coordinate (0, 0) DrawSquares(GL.RenderMode(RenderingMode.Select)); GL.MatrixMode(MatrixMode.Projection); GL.PopMatrix(); GL.Flush(); hits = GL.RenderMode(RenderingMode.Render); ProcessHits(hits, selectBuffer); glControl1.SwapBuffers(); } } private static void DrawSquares(int mode) { int i, j; for (i = 0; i < 3; i++) { if (mode == GL.RenderMode(RenderingMode.Select)) GL.LoadName(i); for (j = 0; j < 3; j++) { if (mode == GL.RenderMode(RenderingMode.Select)) GL.PushName(j); GL.Color3((float)i / 3.0f, (float)j / 3.0f, (float)board[i, j] / 3.0f); GL.Rect(i, j, (i + 1), (j + 1)); if (mode == GL.RenderMode(RenderingMode.Select)) GL.PopName(); } } } A: I made some problem in the code. It made the issue. Change the instances like this. then it will work :). A small mistake caused a big issue :-( //(mode == GL.RenderMode(RenderingMode.Select)) (mode == RenderingMode.Select) // Removed GL.RenderMode
{ "language": "en", "url": "https://stackoverflow.com/questions/16140124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: c# load txt file and split it to X files based on number of lines this is the code that i've written so far... it doesnt do the job except re-write every line on the same file over and over again... *RecordCntPerFile = 10K *FileNumberName = 1 (file number one) *Full File name should be something like this: 1_asci_split string FileFullPath = DestinationFolder + "\\" + FileNumberName + FileNamePart + FileExtension; using (System.IO.StreamReader sr = new System.IO.StreamReader(SourceFolder + "\\" + SourceFileName)) { for (int i = 0; i <= (RecordCntPerFile - 1); i++) { using (StreamWriter sw = new StreamWriter(FileFullPath)) { { sw.Write(sr.Read() + "\n"); } } } FileNumberName++; } Dts.TaskResult = (int)ScriptResults.Success; } A: If I understood correctly, you want to split a big file in smaller files with maximum of 10k lines. I see 2 problems on your code: * *You never change the FullFilePath variable. So you will always rewrite on the same file *You always read and write the whole source file to the target file. I rewrote your code to fit the behavior I said earlier. You just have to modify the strings. int maxRecordsPerFile = 10000; int currentFile = 1; using (StreamReader sr = new StreamReader("source.txt")) { int currentLineCount = 0; List<string> content = new List<string>(); while (!sr.EndOfStream) { content.Add(sr.ReadLine()); if (++currentLineCount == maxRecordsPerFile || sr.EndOfStream) { using (StreamWriter sw = new StreamWriter(string.Format("file{0}.txt", currentFile))) { foreach (var line in content) sw.WriteLine(line); } content = new List<string>(); currentFile++; currentLineCount = 0; } } } Of course you can do better than that, as you don't need to create that string and do that foreach loop. I just made this quick example to give you the idea. To improve the performance is up to you
{ "language": "en", "url": "https://stackoverflow.com/questions/46512542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display submitted values from Contact Form 7 form with var_dump() or printr() using plugin hooks I want to see what is inside "$name" variable, how can i do that? add_action("wpcf7_before_send_mail", "wpcf7_do_something_else"); function wpcf7_do_something_else( &$WPCF7_ContactForm ) { $name = $WPCF7_ContactForm->posted_data['your-name']; var_dump($name); } A: CF7 uses AJAX to submit forms and you can't see var_dump() in ordinary way. So through PHP you can use WordPress debug.log file. Iside "wp-config.php" instead of define('WP_DEBUG', false); write: // Enable WP_DEBUG mode define( 'WP_DEBUG', true ); // Enable Debug logging to the /wp-content/debug.log file define( 'WP_DEBUG_LOG', true ); // Disable display of errors and warnings define( 'WP_DEBUG_DISPLAY', false ); @ini_set( 'display_errors', 0 ); Then: add_action("wpcf7_before_send_mail", "wpcf7_do_something_else"); function wpcf7_do_something_else( &$WPCF7_ContactForm ) { $name = $WPCF7_ContactForm->posted_data['your-name']; ob_start(); // start buffer capture var_dump($name); $contents = ob_get_contents(); // put the buffer into a variable ob_end_clean(); // end capture error_log($contents); // write the log file } As option you can do that in front-end with JS thru the CF7 DOM events Example - when your form is submit: <script> document.addEventListener( 'wpcf7submit', function( event ) { var inputs = event.detail.inputs; for ( var i = 0; i < inputs.length; i++ ) { if ( 'your-name' == inputs[i].name ) { alert( inputs[i].value ); /* or in console: console.log( inputs[i].value ); */ break; } } }, false ); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/56468332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: getting HTML source or markdown text from the KDE clipboard with PySide I want to be able to highlight a section of a web page (which could be any web page I happen to be viewing) and copy it to the clipboard then save it to my local disk as markdown. I need an efficient way to do that. I'm on Kubuntu 12.04 and I want to use PySide. (I don't have any experience with Python, Qt or any related tools, but I googled around and found PySide highly recommended and I completed a Hello World tutorial so far.) My current cumbersome method is: * *highlight section and copy to clipboard *open Libre Office Writer *paste into Writer *save Writer doc as HTML *open terminal *cd to the directory where I saved the HTML *pandoc -s -r html /home/me/a/b/mydoc.html -o /home/me/a/b/mydoc.md Obviously, I need a better method! Here's my original question: https://unix.stackexchange.com/questions/78395/save-html-from-clipboard-as-markdown-text That pointed me to this possible answer: getting HTML source or rich text from the X clipboard The above is what motivated me to do this in Python. I need a KDE/PySide version of the answer above that also incorporates the pandoc conversion to markdown step. It seems simple enough except for replacing the gtk.Clipboard commands with their equivalent KDE Clipboard commands. I have no idea about that. A: This can be done via recent versions of xclip which support the -t text/html (target selection) and pandoc to convert html to markdown. See the details: Save HTML from clipboard as markdown text - Unix & Linux Stack Exchange Thanks to @mountainx for asking again on the Unix stackexchange, which provided this solution, as noted in a comment above.
{ "language": "en", "url": "https://stackoverflow.com/questions/16953581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can sqlite `order by` and `where` clause use the Index together Create a table CREATE TABLE Shares( shareId TEXT PRIMARY KEY NOT NULL, fromId INTEGER NOT NULL, toId INTEGER NOT NULL, time INTEGER NOT NULL); And create the index CREATE INDEX Shares_time_toId_fromId ON Shares(time, toId, fromId); Then insert some rows insert into Shares(shareId, fromId, toId, time) values(1,1,1,1); insert into Shares(shareId, fromId, toId, time) values(2,2,2,2); insert into Shares(shareId, fromId, toId, time) values(3,3,3,3); insert into Shares(shareId, fromId, toId, time) values(4,3,3,4); insert into Shares(shareId, fromId, toId, time) values(5,3,3,5); use explain to show explain select * from Shares where toId=3 and fromId=3 order by time desc; the result is 0|Init|0|20|0||00| 1|Noop|0|0|0||00| 2|OpenRead|0|2|0|4|00| 3|OpenRead|2|4|0|k(4,nil,nil,nil,nil)|00| 4|Last|2|17|1|0|00| 5|IdxRowid|2|1|0||00| 6|Seek|0|1|0||00| 7|Column|2|1|2||00| 8|Ne|3|16|2|(BINARY)|54| 9|Column|2|2|4||00| 10|Ne|3|16|4|(BINARY)|54| 11|Column|0|0|5||00| 12|Copy|4|6|0||00| 13|Copy|2|7|0||00| 14|Column|2|0|8||00| 15|ResultRow|5|4|0||00| 16|Prev|2|5|0||01| 17|Close|0|0|0||00| 18|Close|2|0|0||00| 19|Halt|0|0|0||00| 20|Transaction|0|0|2|0|01| 21|TableLock|0|2|0|Shares|00| 22|Integer|3|3|0||00| 23|Goto|0|1|0||00| It seems the query use the index to finish the job. But I don't know whether it uses all three index or just use time to do the index. I hope the indices could be all used to give the performance enhancement. A: To find out how the query is executed, don't use EXPLAIN but EXPLAIN QUERY PLAN: explain query plan select * from Shares where toId=3 and fromId=3 order by time desc; 0|0|0|SCAN TABLE Shares USING INDEX Shares_time_toId_fromId In this query, the toId and fromId values are read from the index, but this does not matter because the actual table has to be read anyway to get the shareId value. If the query did not try to read the shareId column, or if the shareId column had type INTEGER so that it would be an alias for the rowid and thus be part of the index, the separate table lookup step would not be needed. (Note: the latest version of the sqlite3 tool formats the EXPLAIN output better.)
{ "language": "en", "url": "https://stackoverflow.com/questions/38653204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: syntax error ternary operator in erb I have one link in view <%= @entry.user.present? ? link_to @entry.user.nickname , account_path(:user_id=>@entry.user,:key=>"check" ) ,:"data-ajax" => false : "user" %> I wrote the above but i am getting syntax error Please help me solve it. Thank you A: You should use parenthesis with link_to arguments. Ruby except a : but instead he find @entry.user.nickname. rewrite your ternary operator like that : boolean_output ? link_to(arguments,arguments) : "something else" A: Try this: <%= @entry.user.present? ? (link_to @entry.user.nickname, account_path(:user_id=>@entry.user,:key=>"check" ), :"data-ajax" => false) : "123ish" %>
{ "language": "en", "url": "https://stackoverflow.com/questions/38121027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Java: how to convert a List to a Map I want to construct a chapter directory. My data structure is as follow. private Map<String, ChapterPage> chapterPageRel; @Data @Builder @AllArgsConstructor @NoArgsConstructor public static class ChapterPage { @ApiModelProperty(value = "page list") private List<Integer> page; @ApiModelProperty(value = "page image list") private List<String> chapterImageId; } My database data is as follow. @Data @Builder @AllArgsConstructor @NoArgsConstructor @TableName(value = "tb_electronic_material_resource_rel") public class ElectronicMaterialResourceRelEntity { @TableId(value = "id", type = IdType.AUTO) private Long id; @TableField(value = "material_id") private Long materialId; @TableField(value = "chapter_image_id") private String chapterImageId; @TableField(value = "chapter_name") private String chapterName; @TableField(value = "page") private Integer page; } I want to get each chapterName of the corresponding page Numbers and pictures, in fact, I get a strange map, as shown below. List<ElectronicMaterialResourceRelEntity> materialResourceRelEntities = xxxx; Map<String, Map<Integer, String>> collect = materialResourceRelEntities .stream() .collect(Collectors.groupingBy(ElectronicMaterialResourceRelEntity::getChapterName, Collectors.toMap(ElectronicMaterialResourceRelEntity::getSort, ElectronicMaterialResourceRelEntity::chapterImageId))); But I want to ask, how to collect for a class like Map<String,ChapterPage>. A: A loop is probably better here, unless you need to collect to such ChapterPage objects in multiple places in your code or your input is already a stream and you want to avoid materializing it into a list first. Just to demonstrate how this could still be done, this is an example using a custom downstream Collector: Map<String, ChapterPage> res = input.stream() .collect(Collectors.groupingBy(ElectronicMaterialResourceRelEntity::chapterName, Collector.of( ChapterPage::new, (c, e) -> { c.getPage().add(e.page()); c.getChapterImage().add(e.chapterImageId()); }, (c1, c2) -> { c1.getPage().addAll(c2.getPage()); c2.getChapterImage().addAll(c2.getChapterImage()); return c1; } ))); Getters and constructors differ from your code, I used a record for ElectronicMaterialResourceRelEntity and a POJO without annotation magic for ChapterPage in my test. By "loop", I don't necessarily mean a traditional loop, but a somewhat less functional approach directly using a mutable HashMap: Map<String, ChapterPage> res = new HashMap<>(); input.forEach(e -> { ChapterPage c = res.computeIfAbsent(e.chapterName(), k -> new ChapterPage()); c.getPage().add(e.page()); c.getChapterImage().add(e.chapterImageId()); }); produces the same result in a less verbose way. A: You can convert List to Json, and then convert Json to Map
{ "language": "en", "url": "https://stackoverflow.com/questions/72308085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why are async state machines classes (and not structs) in Roslyn? Let’s consider this very simple async method: static async Task myMethodAsync() { await Task.Delay(500); } When I compile this with VS2013 (pre Roslyn compiler) the generated state-machine is a struct. private struct <myMethodAsync>d__0 : IAsyncStateMachine { ... void IAsyncStateMachine.MoveNext() { ... } } When I compile it with VS2015 (Roslyn) the generated code is this: private sealed class <myMethodAsync>d__1 : IAsyncStateMachine { ... void IAsyncStateMachine.MoveNext() { ... } } As you can see Roslyn generates a class (and not a struct). If I remember correctly the first implementations of the async/await support in the old compiler (CTP2012 i guess) also generated classes and then it was changed to struct from performance reasons. (in some cases you can completely avoid boxing and heap allocation…) (See this) Does anyone know why this was changed again in Roslyn? (I don’t have any problem regarding this, I know that this change is transparent and does not change the behavior of any code, I’m just curious) Edit: The answer from @Damien_The_Unbeliever (and the source code :) ) imho explains everything. The described behaviour of Roslyn only applies for debug build (and that's needed because of the CLR limitation mentioned in the comment). In Release it also generates a struct (with all the benefits of that..). So this seems to be a very clever solution to support both Edit and Continue and better performance in production. Interesting stuff, thanks for everyone who participated! A: It's hard to give a definitive answer for something like this (unless someone from the compiler team drops in :)), but there's a few points you can consider: The performance "bonus" of structs is always a tradeoff. Basically, you get the following: * *Value semantics *Possible stack (maybe even register?) allocation *Avoiding indirection What does this mean in the await case? Well, actually... nothing. There's only a very short time period during which the state machine is on the stack - remember, await effectively does a return, so the method stack dies; the state machine must be preserved somewhere, and that "somewhere" is definitely on the heap. Stack lifetime doesn't fit asynchronous code well :) Apart from this, the state machine violates some good guidelines for defining structs: * *structs should be at most 16-bytes large - the state machine contains two pointers, which on their own fill the 16-byte limit neatly on 64-bit. Apart from that, there's the state itself, so it goes over the "limit". This is not a big deal, since it's quite likely only ever passed by reference, but note how that doesn't quite fit the use case for structs - a struct that's basically a reference type. *structs should be immutable - well, this probably doesn't need much of a comment. It's a state machine. Again, this is not a big deal, since the struct is auto-generated code and private, but... *structs should logically represent a single value. Definitely not the case here, but that already kind of follows from having a mutable state in the first place. *It shouldn't be boxed frequently - not a problem here, since we're using generics everywhere. The state is ultimately somewhere on the heap, but at least it's not being boxed (automatically). Again, the fact that it's only used internally makes this pretty much void. And of course, all this is in a case where there's no closures. When you have locals (or fields) that traverse the awaits, the state is further inflated, limiting the usefulness of using a struct. Given all this, the class approach is definitely cleaner, and I wouldn't expect any noticeable performance increase from using a struct instead. All of the objects involved have similar lifetime, so the only way to improve memory performance would be to make all of them structs (store in some buffer, for example) - which is impossible in the general case, of course. And most cases where you'd use await in the first place (that is, some asynchronous I/O work) already involve other classes - for example, data buffers, strings... It's rather unlikely you would await something that simply returns 42 without doing any heap allocations. In the end, I'd say the only place where you'd really see a real performance difference would be benchmarks. And optimizing for benchmarks is a silly idea, to say the least... A: I didn't have any foreknowledge of this, but since Roslyn is open-source these days, we can go hunting through the code for an explanation. And here, on line 60 of the AsyncRewriter, we find: // The CLR doesn't support adding fields to structs, so in order to enable EnC in an async method we need to generate a class. var typeKind = compilationState.Compilation.Options.EnableEditAndContinue ? TypeKind.Class : TypeKind.Struct; So, whilst there's some appeal to using structs, the big win of allowing Edit and Continue to work within async methods was obviously chosen as the better option.
{ "language": "en", "url": "https://stackoverflow.com/questions/33871181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "89" }
Q: Combine multiple rows into one in SQL In sql server 2008, I have a table that has the columns [a],[b],[c],[sort] and it has 4 records: 1, NULL, NULL 0 NULL, 2, NULL 1 NULL, NULL, 3 2 10, NULL, NULL 3 I need to combine all the rows in a way that i get one row as a result, and for each column I get the first (ordered by sort column) non-null value. So my result should be: 1, 2, 3 Can anyone suggest how to do this? Thanks A: One way SELECT (SELECT TOP 1 [a] FROM @T WHERE [a] IS NOT NULL ORDER BY [sort]) AS [a], (SELECT TOP 1 [b] FROM @T WHERE [b] IS NOT NULL ORDER BY [sort]) AS [b], (SELECT TOP 1 [c] FROM @T WHERE [c] IS NOT NULL ORDER BY [sort]) AS [c] Or another ;WITH R AS (SELECT [a], [b], [c], [sort] FROM @T WHERE [sort] = 0 UNION ALL SELECT Isnull(R.[a], T.[a]), Isnull(R.[b], T.[b]), Isnull(R.[c], T.[c]), T.[sort] FROM @T T JOIN R ON T.sort = R.sort + 1 AND ( R.[a] IS NULL OR R.[b] IS NULL OR R.[c] IS NULL )) SELECT TOP 1 [a], [b], [c] FROM R ORDER BY [sort] DESC
{ "language": "en", "url": "https://stackoverflow.com/questions/12134305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Pygame Sprite unresponsive, mac First time building a game in python, let alone pygame. When I launch the code the window with the desired BG comes up, and my Sprite loads where I want. However, the Sprite doesn't move despite all efforts. I've scoured this site and other for resolutions but to no avail. Note: I am using an upgraded mid-2009 mac book with OS X 10.11.6 and I am launching the code via terminal (python boss_fight.py). Also, I downloaded[tag: pygame] via homebrew. Other things I've tried: * *elif then if vs. if then if statements *Adding print functions after if statements regarding key input to see if the input is registered, does not print. *List item adding print functions after if statements regarding key input to see if input is registered, does not print. *Updating pygame *Updating python *Launching with command pythonw boss_fight.py (this yields: ImportError: No module named pygame) which is weird because running the prompt python boss_fight.py runs the game. *I've tried a few other things but can't remember them all Here's the code: import pygame # load pygame keywords import sys # let python use your file system import os # help python identify your OS class Player(pygame.sprite.Sprite): # Spawn a player def __init__(self): pygame.sprite.Sprite.__init__(self) self.movex = 0 self.movey = 0 self.frame = 0 self.images = [] img = pygame.image.load(os.path.join('images','hero.png')) self.images.append(img) self.image = self.images[0] self.rect = self.image.get_rect() def control(self,x,y): # control player movement self.movex += x self.movey += y def update(self): # Update sprite position self.rect.x = self.rect.x + self.movex self.rect.y = self.rect.y + self.movey # moving left if self.movex < 0: self.frame += 1 if self.frame > 3 * ani: self.frame = 0 self.image = self.images[self.frame//ani] # moving right if self.movex > 0: self.frame += 1 if self.frame > 3 * ani: self.frame = 0 self.image = self.images[(self.frame//ani)+4] # Setup worldx = 960 worldy = 720 fps = 40 # frame rate ani = 4 # animation cycles clock = pygame.time.Clock() pygame.init() main = True BLUE = (25,25,200) BLACK = (23,23,23 ) WHITE = (254,254,254) ALPHA = (0,255,0) world = pygame.display.set_mode([worldx,worldy]) backdrop = pygame.image.load(os.path.join('images','stage.jpeg')).convert() backdropbox = world.get_rect() player = Player() # spawn player player.rect.x = 0 player.rect.y = 0 player_list = pygame.sprite.Group() player_list.add(player) steps = 10 # how fast to move # Main loop while main: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit(); sys.exit() main = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: player.control(-steps,0) print('left') elif event.key == pygame.K_RIGHT: player.control(steps,0) print('right') elif event.key == pygame.K_UP: print('up') elif event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: player.control(steps,0) elif event.key == pygame.K_RIGHT: player.control(-steps,0) elif event.key == pygame.K_q: pygame.quit() sys.exit() main = False world.blit(backdrop, backdropbox) player.update() player_list.draw(world) pygame.display.update() clock.tick(fps) A: The place where I think you've mistaken is where you're writing code for update The way I do it is def update(self): # Update sprite position self.rect.x = self.rect.x + self.movex self.rect.y = self.rect.y + self.movey # moving left if self.movex < 0: self.frame += 1 if self.frame > 3 * ani: self.frame = 0 self.image = self.images[self.frame//ani] # moving right elif self.movex > 0: self.frame += 1 if self.frame > 3 * ani: self.frame = 0 self.image = self.images[(self.frame//ani)+4] self.rect.topleft = self.rect.x, self.rect.y
{ "language": "en", "url": "https://stackoverflow.com/questions/62597494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to remove margin on html css mobile responsive form? I created the following code, but when I try to move to the mobile version there is a margin on the right side that doesn't let the page fit on the screen, and it doesn't look good. I don't know the exact reason why it is there, that is why I share most of my codes. The mobile view starts at 480px. My question is how could I remove that margin? Edit: The margin size is around 20px <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>My Name Necklace</title> </head> <style> :root{ --clr-accent: #FEC3B3; --clr-grey: rgb(207, 207, 207); } #confirmed{ background-color: var(--clr-accent); display: table; box-sizing: border-box; text-indent: initial; border-spacing: 2px; border-top: 3px solid white; } #hours{ background-color: black; color: white; text-align: center; border-color: black; padding-bottom: 0px; } #congrats{ text-align: center; } #button1{ text-align: center; } #btn1{ background-color: black; color: white; } @media screen and (max-width: 480px){ *{ max-width: 420px; } * table{ max-width: 410px; } element.style{ margin-right:0px; } html,body { margin-right:0px; padding: 0; } *img{ width: 80%; } .table01 { width: 460px; font-size: 12px; } #extra01{ width: 50%; font-size: 12px; } #track img{ max-width: 380px; } #o_details{ font-size: 14px; } #track2 img{ width: 75%; } #details01, #details02{ font-size: 12px; } #o_items{ font-size: 14px; } #o_info{ font-size: 14px; } h1{ font-size: 20px; } .orders1 img, .orders2 img{ width: 80%; } .orders1, .orders2{ font-size: 12px; } #method{ font-size: 12px; } .o_conf img{ width: 70%; } #pers_sel p{ font-size: 12px; } .sTotal td,.sCost td,.tCost{ display:none; } #eButton{ padding: 5px 5px 5px 5px; font-size: 12px; } } </style> <body> <header> <center> <table class="table01" align="center" style="width:650px;border-collapse: collapse; "> <tr> <a href="#"><img src="./images/bracelate_03.jpg" alt="bracelate_03" /> </a> </center> </tr> <tr id="extra01" style=" background-color: black; color: white; text-align: center; border-color: black; font-size: 12px; font-weight:100; "> <td id="oHours" style="padding-top: 5px; line-height: 0px;"> <p id="onlyh01" style="font-size: 16px; "> <b>48 HOURS ONLY</p></br> <p id="onlyh02" style="font-weight: 500; font-size: 16px;">EXTRA 15% OFF YOUR NEXT ORDER | CODE : B15CK </p> </td> </tr> <tr id="confirmed" style="width:650px"> <th rowspan="2" style="padding-left:50px ;"><img src="./images/bracelate_07.jpg" alt="bracelate_07" /></th> <td style="padding-left:10px ;"> <h1> YOUR ORDER IS CONFIRMED!</h1> </td> </tr> <tr id="congrats"> <td style=" padding-top: 20px; padding-bottom: 20px;">Congratulations %%firstname%%, you made a great choice </br> We're excited to start working on your personalized jewelry. </br> You will recieve a shipping notice as soon as it leaves our hand. </td> </tr> <tr id="button1"> <td> <button id="btn1" style="padding:5px 40px 5px 40px; font-weight: bold; ">GET 15% OFF</button> </td> </tr> <tr id="track1" style="text-align: center;"> <td style="padding-top: 15px; padding-bottom:25px; font-size: 14px;"> <b><u>TRACK YOUR ORDER ></u></b> </td> </tr> <tr id="track2"> <td> <center><img src="./images/bracelate_11.jpg" alt="bracelate_11" /> </center> </td> </tr> </table> <table class="oDetails" style="width:650px"> <tr id="o_details"> <td style="font-weight: bold; padding :5px; padding-left: 50px ; background-color: #f3f3f3;">Order Details </td> </tr> <tr id="details01"> <td style="padding-left:50px; padding-top:20px"> <u>Order Number:</u> 65224865 </td> <tr id="details02"> <td style="padding-left:50px; padding-bottom:20px"> <u>Order Date:</u> 02/09/2018</td> </tr> <tr id="o_items"> <td style="font-weight: bold; padding :5px; padding-left: 50px ; background-color: #f3f3f3;">Ordered Items </td> </tr> <tr id="items01"> <td></td> </tr> </table> <table class="orders1"> <tbody> <tr> <td rowspan="7" width="200"><b> <img src="./images/bracelate_22.jpg" alt="bracelate_22" style="margin-bottom:40px" /> </b></td> <td colspan="2" width="367" style="padding-top: 5px; padding-bottom: 15px;">Personalized Engraved Mum Birthstone Neklace</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">Material :</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">Sterling Silver</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">1st Inscription</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">Name#1</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">2nd Inscription</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">Name#2</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">Chain Length</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">45 cm chain - adult</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">Price</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;"></td> </tr> <tr> <td width="184" style="padding-top: 10px; padding-bottom: 10px; color:#ee9d86">Make Changes</td> <td width="183" style="padding-top: 10px; padding-bottom: 10px;"></td> </tr> </tbody> </table> <table> <tr id="divider2"> <td rowspan="2"><img src="./images/divider2.jpg" alt="divider2" /></td> </tr> </table> <table class="orders2"> <tbody> <tr> <td rowspan="7" width="200"><b> <img src="./images/Order_Confirmation_23.jpg" alt="Order_Confirmation_23" style="margin-bottom:40px"/> </b></td> <td colspan="2" width="367" style="padding-top: 5px; padding-bottom: 15px;">Personalized Engraved Mum Birthstone Neklace</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">Material :</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">Sterling Silver</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">1st Inscription</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">Name#1</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">2nd Inscription</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">Name#2</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">Chain Length</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">45 cm chain - adult</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">Price</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;"></td> </tr> <tr> <td width="184" style="padding-top: 10px; padding-bottom: 10px; color:#ee9d86">Make Changes</td> <td width="183" style="padding-top: 10px; padding-bottom: 10px;"></td> </tr> </tbody> </table> <table style="width:650px"> <tbody> <tr id="o_info"> <td style="font-weight: bold; padding :5px; padding-left: 50px ; background-color: #f3f3f3;"> Shipping Info</td> </tr> <tr> <td style=" padding-left: 50px ; padding-top: 10px; padding-bottom: 20px; text-align: center; "> <center> <button id="eButton" style="padding: 5px 20px 5px 20px; background-color: white; display: flex; align-items: center;"><img src="./images/bracelate_15.jpg" alt="bracelate_15" /> Estimated Delivery Date <b>Thursday November 7</b> </button></center> </td> </tr> <tr> <td style=" padding-left: 50px ; "><u>Shipping Method:</u> </br> </u>standard shipping – 10 business days – FREE &nbsp; </td> <tr> <td id="method" style=" padding-left: 50px ; "><a href="#">Change Shopping Method</a></td> </tr> </tr> <tr> <td style=" padding-left: 50px ; padding-top: 20px;"><u>Shipping Address </br> </u>Idania pérez </br> 3001 nw 15 st </br> Miami, florida 33125 </br> united states </br> <a href="#"> Change Shopping Method</a></td> </tr> </tbody> </table> <table> <tr id="divider"> <th rowspan="2"><img src="./images/divider.jpg" alt="divider" /></th> </tr> </table> <table class="sTotal" style="width:650px; margin-left: 100px "> <tr> <td id="stotal_1" style = "width:500px">Subtotal</td> <td id="stotal_2" >89.80</td> </tr> </table> <table class="sCost" style="width:650px; margin-left: 100px"> <tr> <td id="scost_1"style = "width:500px">Shipping cost</td> <td id="scost_2">Free of Charge</td> </tr> </table> <table> <tr id="divider2"> <td rowspan="2"><img src="./images/divider2.jpg" alt="divider2" /></td> </tr> </table> <table class="tCost" style="width:650px; margin-left: 100px"> <tr> <td id="tcost_1" style = "width:500px"><strong>Total Cost</strong></td> <td id="tcost_2"><strong>89.80</strong></td> </tr> </table> <table> <tr id="bracelate_18"> <th rowspan="2"><img src="./images/bracelate_18.jpg" alt="bracelate_18" /></th> <td> </table> <table > <tr id="selected"> <td id="pers_sel" style="width: 650px; text-align: center;padding: 10px 0px 10px 0px; font-size: 18px;"> <p>Personally Selected for %%firstname%%</p> </td> </tr> </table> <table class="o_conf"style="width: 650px;"> <tbody> <tr> <td width="190" style="text-align: center;"><img src="./images/Order_Confirmation_21.jpg" alt="Order_Confirmation_21" /> <p style="text-align: center; font-weight: bold; text-decoration: underline; "> SHOP NOW ></p></td> <td width="190"style="text-align: center;"><img src="./images/bracelate_22.jpg" alt="bracelate_22" /> <p style="text-align: center;font-weight: bold; text-decoration: underline; ">SHOP NOW ></p></td> <td width="190" style="text-align: center;"><img src="./images/Order_Confirmation_23.jpg" alt="Order_Confirmation_23" /><p style="text-align: center;font-weight: bold; text-decoration: underline; ">SHOP NOW ></p></td> </tr> </tbody> </table> <tr> <td id="btm_menu" width="650" style="padding-top: 30px;"> <table id="new_menue_2020" valign="middle" cellpadding="0" cellspacing="0" border="0" width="650" align="center" bgcolor="#ffffff" style="padding: 0px 0px 0px; vertical-align: middle;"> <tbody> <tr> <td id="btm_menu_men_icon" bgcolor="#f3f3f3" width="222" align="right" style="border-bottom: 3px solid #ffffff; padding: 0px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <img id="btm_menu_men_icon_img" width="38" src="./images/bracelate_27.jpg"></a> </td> <td id="btm_menu_men_text" bgcolor="#f3f3f3" width="372" align="left" style="border-bottom: 3px solid #ffffff; text-transform: uppercase; letter-spacing: 2px; font-family: Verdana, sans-serif; font-size: 18px; padding-left: 13px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> Jewelry for Him</a> </td> <td id="btm_menu_men_arrow" bgcolor="#f3f3f3" width="70" align="right" style="border-bottom: 3px solid #ffffff; padding: 0px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <img id="btm_menu_men_arrow_img" width="70" src="./images/bracelate_29.jpg"> </a> </td> </tr> <tr> <td id="btm_menu_mom_icon" width="222" bgcolor="#f3f3f3" align="right" style="border-bottom: 3px solid #ffffff; padding: 0px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <img id="btm_menu_mom_icon_img" width="38" src="./images/bracelate_36.jpg" ></a> </td> <td id="btm_menu_mom_text" width="372" bgcolor="#f3f3f3" align="left" style="border-bottom: 3px solid #ffffff; text-transform: uppercase; letter-spacing: 2px; font-family: Verdana, sans-serif; font-size: 18px; padding-left: 13px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> Jewelry for Her</a> </td> <td id="btm_menu_mom_arrow" width="70" bgcolor="#f3f3f3" align="right" style="border-bottom: 3px solid #ffffff; padding: 0px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <img id="btm_menu_mom_arrow_img" width="70" src="./images/bracelate_29.jpg"></a> </td> </tr> <tr> <td id="btm_menu_kid_icon" bgcolor="#f3f3f3" width="222" align="right" style="border-bottom: 3px solid #ffffff; padding: 0px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <img id="btm_menu_kid_icon_img" width="38" src="./images/bracelate_32.jpg"></a> </td> <td id="btm_menu_kid_text" bgcolor="#f3f3f3" width="358" style="border-bottom: 3px solid #ffffff; vertical-align: middle; text-transform: uppercase; letter-spacing: 2px; font-family: Verdana, sans-serif; font-size: 18px; padding-left: 13px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> Best Sellers </a> </td> <td id="btm_menu_kid_arrow" bgcolor="#f3f3f3" width="70" align="right" style="border-bottom: 3px solid #ffffff;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <img id="btm_menu_kid_arrow_img" width="70" src="./images/bracelate_29.jpg"></a> </td> </tr> </tbody> </table> </td> </tr> <table style="margin-top: 20px;"> </table> <table style="width:650px; margin: 30px, 0px, 30px, 0px; text-align: center; background-color:#f3f3f3; padding: 5px; line-height: 0px;"> <tbody> <tr> <tr> <td style="border: 1px solid rgb(189, 188, 188)"> <p style="font-size: 18px;"> <i> Got a Question ?</i></p> <p style="font-size: 14px;">Visit Our Help Center</p> </td> </tr> </tr> </tbody> </table> <table style="margin-top: 20px;"> </table> <table> <tr> <td style="text-align:center; line-height: 5px;"> <h1 style="padding-bottom: 5px;">SUBSCRIBERS SAVE THE MOST!</h1> <p> Sign up now for VIP access to exclusive offers, </p> <p>giveaways and new jewellery launches</p> </td> </tr> <tr id="button1"> <td> <button id="btn1" style="padding:5px 40px 5px 40px; font-weight: bold; ">SUBSCRIBE NOW</button> </td> </tr> </table> <table> <tr id="divider"> <th rowspan="2"><img src="./images/divider.jpg" alt="divider" /></th> <tr> </table> <table style="margin-top: 20px; line-height: 25px;"> <tr> <td>This e-mail was sent from an automated system that is unable to accept incoming e-mails. <br> Please do not reply to this e-mail. <p style="line-height: 0rem; color: gray;">Copyright <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <u>MyNameNecklace. </u> </a> All rights reserved.</p> </td> </tr> </table> </center> </header> </body> </html> A: It was because of the margin you have added to the table. <table class="sCost" style="width:650px; margin-left: 100px"> I removed margin-left from the tables which were causing the problem. </head> <style> :root{ --clr-accent: #FEC3B3; --clr-grey: rgb(207, 207, 207); } #confirmed{ background-color: var(--clr-accent); display: table; box-sizing: border-box; text-indent: initial; border-spacing: 2px; border-top: 3px solid white; } #hours{ background-color: black; color: white; text-align: center; border-color: black; padding-bottom: 0px; } #congrats{ text-align: center; } #button1{ text-align: center; } #btn1{ background-color: black; color: white; } @media screen and (max-width: 480px){ *{ max-width: 420px; } * table{ max-width: 410px; } element.style{ margin-right:0px; } html,body { margin-right:0px; padding: 0; } *img{ width: 80%; } .table01 { width: 460px; font-size: 12px; } #extra01{ width: 50%; font-size: 12px; } #track img{ max-width: 380px; } #o_details{ font-size: 14px; } #track2 img{ width: 75%; } #details01, #details02{ font-size: 12px; } #o_items{ font-size: 14px; } #o_info{ font-size: 14px; } h1{ font-size: 20px; } .orders1 img, .orders2 img{ width: 80%; } .orders1, .orders2{ font-size: 12px; } #method{ font-size: 12px; } .o_conf img{ width: 70%; } #pers_sel p{ font-size: 12px; } .sTotal td,.sCost td,.tCost{ display:none; } #eButton{ padding: 5px 5px 5px 5px; font-size: 12px; } } </style> <body> <header> <center> <table class="table01" align="center" style="width:650px;border-collapse: collapse; "> <tr> <a href="#"><img src="./images/bracelate_03.jpg" alt="bracelate_03" /> </a> </center> </tr> <tr id="extra01" style=" background-color: black; color: white; text-align: center; border-color: black; font-size: 12px; font-weight:100; "> <td id="oHours" style="padding-top: 5px; line-height: 0px;"> <p id="onlyh01" style="font-size: 16px; "> <b>48 HOURS ONLY</p></br> <p id="onlyh02" style="font-weight: 500; font-size: 16px;">EXTRA 15% OFF YOUR NEXT ORDER | CODE : B15CK </p> </td> </tr> <tr id="confirmed" style="width:650px"> <th rowspan="2" style="padding-left:50px ;"><img src="./images/bracelate_07.jpg" alt="bracelate_07" /></th> <td style="padding-left:10px ;"> <h1> YOUR ORDER IS CONFIRMED!</h1> </td> </tr> <tr id="congrats"> <td style=" padding-top: 20px; padding-bottom: 20px;">Congratulations %%firstname%%, you made a great choice </br> We're excited to start working on your personalized jewelry. </br> You will recieve a shipping notice as soon as it leaves our hand. </td> </tr> <tr id="button1"> <td> <button id="btn1" style="padding:5px 40px 5px 40px; font-weight: bold; ">GET 15% OFF</button> </td> </tr> <tr id="track1" style="text-align: center;"> <td style="padding-top: 15px; padding-bottom:25px; font-size: 14px;"> <b><u>TRACK YOUR ORDER ></u></b> </td> </tr> <tr id="track2"> <td> <center><img src="./images/bracelate_11.jpg" alt="bracelate_11" /> </center> </td> </tr> </table> <table class="oDetails" style="width:650px"> <tr id="o_details"> <td style="font-weight: bold; padding :5px; padding-left: 50px ; background-color: #f3f3f3;">Order Details </td> </tr> <tr id="details01"> <td style="padding-left:50px; padding-top:20px"> <u>Order Number:</u> 65224865 </td> <tr id="details02"> <td style="padding-left:50px; padding-bottom:20px"> <u>Order Date:</u> 02/09/2018</td> </tr> <tr id="o_items"> <td style="font-weight: bold; padding :5px; padding-left: 50px ; background-color: #f3f3f3;">Ordered Items </td> </tr> <tr id="items01"> <td></td> </tr> </table> <table class="orders1"> <tbody> <tr> <td rowspan="7" width="200"><b> <img src="./images/bracelate_22.jpg" alt="bracelate_22" style="margin-bottom:40px" /> </b></td> <td colspan="2" width="367" style="padding-top: 5px; padding-bottom: 15px;">Personalized Engraved Mum Birthstone Neklace</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">Material :</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">Sterling Silver</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">1st Inscription</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">Name#1</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">2nd Inscription</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">Name#2</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">Chain Length</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">45 cm chain - adult</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">Price</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;"></td> </tr> <tr> <td width="184" style="padding-top: 10px; padding-bottom: 10px; color:#ee9d86">Make Changes</td> <td width="183" style="padding-top: 10px; padding-bottom: 10px;"></td> </tr> </tbody> </table> <table> <tr id="divider2"> <td rowspan="2"><img src="./images/divider2.jpg" alt="divider2" /></td> </tr> </table> <table class="orders2"> <tbody> <tr> <td rowspan="7" width="200"><b> <img src="./images/Order_Confirmation_23.jpg" alt="Order_Confirmation_23" style="margin-bottom:40px"/> </b></td> <td colspan="2" width="367" style="padding-top: 5px; padding-bottom: 15px;">Personalized Engraved Mum Birthstone Neklace</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">Material :</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">Sterling Silver</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">1st Inscription</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">Name#1</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">2nd Inscription</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">Name#2</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">Chain Length</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;">45 cm chain - adult</td> </tr> <tr> <td width="184" style="padding-top: 5px; padding-bottom: 5px;">Price</td> <td width="183" style="padding-top: 5px; padding-bottom: 5px;"></td> </tr> <tr> <td width="184" style="padding-top: 10px; padding-bottom: 10px; color:#ee9d86">Make Changes</td> <td width="183" style="padding-top: 10px; padding-bottom: 10px;"></td> </tr> </tbody> </table> <table style="width:650px"> <tbody> <tr id="o_info"> <td style="font-weight: bold; padding :5px; padding-left: 50px ; background-color: #f3f3f3;"> Shipping Info</td> </tr> <tr> <td style=" padding-left: 50px ; padding-top: 10px; padding-bottom: 20px; text-align: center; "> <center> <button id="eButton" style="padding: 5px 20px 5px 20px; background-color: white; display: flex; align-items: center;"><img src="./images/bracelate_15.jpg" alt="bracelate_15" /> Estimated Delivery Date <b>Thursday November 7</b> </button></center> </td> </tr> <tr> <td style=" padding-left: 50px ; "><u>Shipping Method:</u> </br> </u>standard shipping – 10 business days – FREE &nbsp; </td> <tr> <td id="method" style=" padding-left: 50px ; "><a href="#">Change Shopping Method</a></td> </tr> </tr> <tr> <td style=" padding-left: 50px ; padding-top: 20px;"><u>Shipping Address </br> </u>Idania pérez </br> 3001 nw 15 st </br> Miami, florida 33125 </br> united states </br> <a href="#"> Change Shopping Method</a></td> </tr> </tbody> </table> <table> <tr id="divider"> <th rowspan="2"><img src="./images/divider.jpg" alt="divider" /></th> </tr> </table> <table class="sTotal" style="width:650px;"> <tr> <td id="stotal_1" style = "width:500px">Subtotal</td> <td id="stotal_2" >89.80</td> </tr> </table> <table class="sCost" style="width:650px;"> <tr> <td id="scost_1"style = "width:500px">Shipping cost</td> <td id="scost_2">Free of Charge</td> </tr> </table> <table> <tr id="divider2"> <td rowspan="2"><img src="./images/divider2.jpg" alt="divider2" /></td> </tr> </table> <table class="tCost" style="width:650px;"> <tr> <td id="tcost_1" style = "width:500px"><strong>Total Cost</strong></td> <td id="tcost_2"><strong>89.80</strong></td> </tr> </table> <table> <tr id="bracelate_18"> <th rowspan="2"><img src="./images/bracelate_18.jpg" alt="bracelate_18" /></th> <td> </table> <table > <tr id="selected"> <td id="pers_sel" style="width: 650px; text-align: center;padding: 10px 0px 10px 0px; font-size: 18px;"> <p>Personally Selected for %%firstname%%</p> </td> </tr> </table> <table class="o_conf"style="width: 650px;"> <tbody> <tr> <td width="190" style="text-align: center;"><img src="./images/Order_Confirmation_21.jpg" alt="Order_Confirmation_21" /> <p style="text-align: center; font-weight: bold; text-decoration: underline; "> SHOP NOW ></p></td> <td width="190"style="text-align: center;"><img src="./images/bracelate_22.jpg" alt="bracelate_22" /> <p style="text-align: center;font-weight: bold; text-decoration: underline; ">SHOP NOW ></p></td> <td width="190" style="text-align: center;"><img src="./images/Order_Confirmation_23.jpg" alt="Order_Confirmation_23" /><p style="text-align: center;font-weight: bold; text-decoration: underline; ">SHOP NOW ></p></td> </tr> </tbody> </table> <tr> <td id="btm_menu" width="650" style="padding-top: 30px;"> <table id="new_menue_2020" valign="middle" cellpadding="0" cellspacing="0" border="0" width="650" align="center" bgcolor="#ffffff" style="padding: 0px 0px 0px; vertical-align: middle;"> <tbody> <tr> <td id="btm_menu_men_icon" bgcolor="#f3f3f3" width="222" align="right" style="border-bottom: 3px solid #ffffff; padding: 0px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <img id="btm_menu_men_icon_img" width="38" src="./images/bracelate_27.jpg"></a> </td> <td id="btm_menu_men_text" bgcolor="#f3f3f3" width="372" align="left" style="border-bottom: 3px solid #ffffff; text-transform: uppercase; letter-spacing: 2px; font-family: Verdana, sans-serif; font-size: 18px; padding-left: 13px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> Jewelry for Him</a> </td> <td id="btm_menu_men_arrow" bgcolor="#f3f3f3" width="70" align="right" style="border-bottom: 3px solid #ffffff; padding: 0px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <img id="btm_menu_men_arrow_img" width="70" src="./images/bracelate_29.jpg"> </a> </td> </tr> <tr> <td id="btm_menu_mom_icon" width="222" bgcolor="#f3f3f3" align="right" style="border-bottom: 3px solid #ffffff; padding: 0px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <img id="btm_menu_mom_icon_img" width="38" src="./images/bracelate_36.jpg" ></a> </td> <td id="btm_menu_mom_text" width="372" bgcolor="#f3f3f3" align="left" style="border-bottom: 3px solid #ffffff; text-transform: uppercase; letter-spacing: 2px; font-family: Verdana, sans-serif; font-size: 18px; padding-left: 13px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> Jewelry for Her</a> </td> <td id="btm_menu_mom_arrow" width="70" bgcolor="#f3f3f3" align="right" style="border-bottom: 3px solid #ffffff; padding: 0px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <img id="btm_menu_mom_arrow_img" width="70" src="./images/bracelate_29.jpg"></a> </td> </tr> <tr> <td id="btm_menu_kid_icon" bgcolor="#f3f3f3" width="222" align="right" style="border-bottom: 3px solid #ffffff; padding: 0px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <img id="btm_menu_kid_icon_img" width="38" src="./images/bracelate_32.jpg"></a> </td> <td id="btm_menu_kid_text" bgcolor="#f3f3f3" width="358" style="border-bottom: 3px solid #ffffff; vertical-align: middle; text-transform: uppercase; letter-spacing: 2px; font-family: Verdana, sans-serif; font-size: 18px; padding-left: 13px;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> Best Sellers </a> </td> <td id="btm_menu_kid_arrow" bgcolor="#f3f3f3" width="70" align="right" style="border-bottom: 3px solid #ffffff;"> <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <img id="btm_menu_kid_arrow_img" width="70" src="./images/bracelate_29.jpg"></a> </td> </tr> </tbody> </table> </td> </tr> <table style="margin-top: 20px;"> </table> <table style="width:650px; margin: 30px, 0px, 30px, 0px; text-align: center; background-color:#f3f3f3; padding: 5px; line-height: 0px;"> <tbody> <tr> <tr> <td style="border: 1px solid rgb(189, 188, 188)"> <p style="font-size: 18px;"> <i> Got a Question ?</i></p> <p style="font-size: 14px;">Visit Our Help Center</p> </td> </tr> </tr> </tbody> </table> <table style="margin-top: 20px;"> </table> <table> <tr> <td style="text-align:center; line-height: 5px;"> <h1 style="padding-bottom: 5px;">SUBSCRIBERS SAVE THE MOST!</h1> <p> Sign up now for VIP access to exclusive offers, </p> <p>giveaways and new jewellery launches</p> </td> </tr> <tr id="button1"> <td> <button id="btn1" style="padding:5px 40px 5px 40px; font-weight: bold; ">SUBSCRIBE NOW</button> </td> </tr> </table> <table> <tr id="divider"> <th rowspan="2"><img src="./images/divider.jpg" alt="divider" /></th> <tr> </table> <table style="margin-top: 20px; line-height: 25px;"> <tr> <td>This e-mail was sent from an automated system that is unable to accept incoming e-mails. <br> Please do not reply to this e-mail. <p style="line-height: 0rem; color: gray;">Copyright <a href="https://www.mynamenecklace.com/" target="_blank" style="text-decoration: none; color: #3a4249;"> <u>MyNameNecklace. </u> </a> All rights reserved.</p> </td> </tr> </table> </center> </header> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/67291436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pagination on Pyrocms pages I am currently displaying a list of products on pyrocms page. Using plugin i get the products from db tables and display them as a list i want to use pagination but have no idea how to use it and where to start from. Does any one know any tutorial or have some suggstion? A: You won't need to load pagination library or initialize it. It is a little different from you do in regular codeigniter, also you can surely use the way you do it in codeigniter pagination class I usually do this for pagination. in your controller use this .... // Create pagination links $total_rows = $this->products_m->count_all_products(); $pagination = create_pagination('products/list', $total_rows); //notice that product/list is your controller/method you want to see pagination there // Using this data, get the relevant results $params = array( 'limit' => $pagination['limit'] ); $this_page_products = $this->product_m->get_all_products($params); .... //you got to pass $pagination to the view $this->template ->set('pagination', $pagination) ->set('products', $this_page_products) ->build('products/view'); obviously, you will have a model named products_m At your model this would be your get_all_products function, I am sure you can build the count_all_products() function too private function get_all_products($params){ //your query to get products here // use $this->db->limit(); // Limit the results based on 1 number or 2 (2nd is offset) if (isset($params['limit']) && is_array($params['limit'])) $this->db->limit($params['limit'][0], $params['limit'][1]); elseif (isset($params['limit'])) $this->db->limit($params['limit']); //rest of your query and return } Now at your view you have to foreach in your passed $products variable and to show pagination links use this line in your view <?php echo $pagination['links'];?> I use this in my works, hope it help. A: Pyrocms used codeigniter framework this code works perfectly in case of module but i have never tried this on a plugin but still you can try this. Load pagination library in Controller $this->load->library('pagination'); $config['base_url'] = 'http://example.com/index.php/test/page/'; $config['total_rows'] = 200; $config['per_page'] = 20; $this->pagination->initialize($config); Use this code in view to genrate the links echo $this->pagination->create_links();
{ "language": "en", "url": "https://stackoverflow.com/questions/12086615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what's the mean of the code about btrace In the following code: import static com.sun.btrace.BTraceUtils.*; import com.sun.btrace.annotations.*; import org.jboss.deployment.DeploymentInfo; @BTrace public class Trace{ @OnMethod( clazz="org.jboss.deployment.SARDeployer", method="parseDocument" ) public static void traceExecute(DeploymentInfo di){ printFields(di); } @OnMethod( clazz="java.net.URL", method="openConnection", location=@Location(Kind.RETURN) ) public static void resolveEntity(@Self Object instance){ String protocol = str(get(field("java.net.URL", "protocol"),instance)); String file = str(get(field("java.net.URL", "file"),instance)); if(startsWith(protocol,"http") && (endsWith(file,".xsd") || endsWith(file,".dtd"))){ String authority = str(get(field("java.net.URL", "authority"),instance)); String path = str(get(field("java.net.URL", "path"),instance)); println("====================================="); print(protocol); print("://"); print(authority); print(path); println(" not found!"); println("who call:"); jstack(); } } } What does this mean: get(field("java.net.URL", "authority"),instance) ? Please refer me to the documentation. A: field("java.net.URL", "authority") will safely retrieve the field named authority from the class java.net.URL get(field, instance) reflectively obtains the value of the given field in specified instance. The Javadoc for BTraceUtils is a good starting point.
{ "language": "en", "url": "https://stackoverflow.com/questions/19429895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Serilog ExpressionTemplate rename log level and apply formatting I'm trying to use serilog's ExpressionTemplate and write the log level in the following way: { "level": "INF", ... } I know how to alias @l to level - level: @l and I know how to format the level to three upper-case letters - @l:u3 but I'm unable to combine the two I have tried the following without success (fails when trying to format the template with an exception): level: @l:u3 {'level': @l:u3} A: At the time of writing this is a limitation in Serilog.Expressions, which will hopefully be addressed soon. Update: version 3.4.0-dev-* now on NuGet supports ToString(@l, 'u3'). You can work around it with conditionals: {'level': if @l = 'Information' then 'INF' else if @l = 'Warning' then 'WRN' else 'ERR'} With a few more branches for remaining levels. (Alternatively, you could write and plug in a user defined function along the lines of ToShortLevel(@l), and use that instead.)
{ "language": "en", "url": "https://stackoverflow.com/questions/72167523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set an object reference I am not sure how to set an object reference to frmD.Picture1.ClientRectangle?? I am using win7 and vb.net 2008 frmD.Picture1.ClientRectangle=new frmD.Picture1.ClientRectangle??? 'error object reference not set .... xpos = frmD.Picture1.ClientRectangle.Left ypos = frmD.Picture1.ClientRectangle.Top A: Object reference not set to an instance of an object means that you're trying to access some member of an uninstantiated object. What that means is that you forgot to create the object (via new). In your case, you're probably trying to use frmD or Picture1 before it has been created.
{ "language": "en", "url": "https://stackoverflow.com/questions/13328545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Slider - Moving Sliders at the same time I have three sliders as follows:- <div class="slider" data-min="3800" data-max="30000" data-value="3848" data-step="500" data-target=".calc-deposit"></div> <div class="slider" data-min="15400" data-max="120000" data-value="15393" data-step="2000" data-target=".calc-loan"></div> <div class="slider" data-min="57000" data-max="450000" data-value="57724" data-step="7500" data-target=".calc-mortgage"></div> $('.slider').each(function() { var $el = $(this); $el.slider({ range: "max", min: $el.data('min'), max: $el.data('max'), value: $el.data('value'), step: $el.data('step'), slide: function(event, ui) { $($el.data('target')).html('£' + ui.value); // place code here which will execute when *any* slider moves } }); }); What I want to do is regardless of which slider you use, they all increase at the same time. All three sliders have different increments so they need to update accordingly. Any help would be much appreciated. Example A: Here is one way using the stop and change event:- $('.slider').each(function() { var $el = $(this); $el.slider({ range: "max", min: $el.data('min'), max: $el.data('max'), value: $el.data('value'), step: $el.data('step'), stop: function(event, ui) { var percent = (100 / ($(this).data('max') - $(this).data('min'))) * $(this).slider('value'); $('.slider').not(this).each(function() { $(this).slider('value', (($(this).data('max') - $(this).data('min')) / 100) * percent); }); }, change: function(event, ui) { $($el.data('target')).html('£' + ui.value); } }); }); FIDDLE A: Based on BG101's answer, this is the final result:- jQuery('.slider').each(function() { var $el = jQuery(this); $el.slider({ range: "max", min: $el.data('min'), max: $el.data('max'), value: $el.data('value'), step: $el.data('step'), slide: function(event, ui) { var percent = (100 / (jQuery(this).data('max') - jQuery(this).data('min'))) * jQuery(this).slider('value'); jQuery('.slider').not(this).each(function() { jQuery(this).slider( 'value', ((jQuery(this).data('max') - jQuery(this).data('min')) / 100) * percent ); }); jQuery('.slider').each(function() { var thisTarget = jQuery(this).data('target'); var thisValue = jQuery(this).slider('option','value'); jQuery(thisTarget+' span').html(thisValue); }); }, }); }); JSFIDDLE (just thought I'd share)
{ "language": "en", "url": "https://stackoverflow.com/questions/34903438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Http Post to WebApi Angular 5 I have w big problem with request from angular 5 (localhost:4200) to my .NET Core WebApi (localhost:55007). I think I tried everything and all lost.. Situation looks: login.service.ts import { Injectable, Inject } from '@angular/core'; import {HttpModule, Http, URLSearchParams, Headers, RequestOptions} from '@angular/http'; @Injectable() export class LoginService { constructor( public http: Http) { } login(email:string, password:string){ this.http.post('http://localhost:55007/Login/Login', {email:"[email protected]",password:"loqweqko"}).subscribe( res => { console.log(res); }, (err) => { console.log(err); } ); } } webApi method: [Route("[controller]/[action]")] public class LoginController : Controller { [HttpPost] public object Login([FromBody] LoginDto model) { //something.. } } Where LoginDto is: public class LoginDto { [Required] public string Email { get; set; } [Required] public string Password { get; set; } } Please tell me what I'm doing wrong.. I have also tried use json.stringify as an object in request. Nothing happends.. I'm always getting 404.. (using postman all works correcty, also GET method works). ---------------------------EDIT--------------------------- Ok, I found solution - the problem was with CORS, I made the same as : How to enable CORS in ASP.net Core WebAPI and for me works. Thanks :) A: Simple enabling of Cors for allow any origin/method etc(Personal project): 1. nuget: Microsoft.AspNetCore.Cors *In configure method, add this before useMvc: app.UseCors(o =>o.AllowAnyOrigin().AllowAnyMethod().AllowAnyMethod().AllowCredentials()); *in ConfigureServices, before AddMvc, Add this: services.AddCors();
{ "language": "en", "url": "https://stackoverflow.com/questions/49592619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Php - Zend 2 lock cache file after read I am using zend 2 cache and I need modify a cache file and make sure no other process read the file while I am doing that.Is there a way to lock the cache file after read it then write and unlock ? I am more interested if Zend 2 cache already allow you to do that and if not what others way are in php to do something like that? A: With reference to zf2 docs - filesystem cache there is a boolean config param file_locking which does Lock files on writing.
{ "language": "en", "url": "https://stackoverflow.com/questions/31512126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular JS view not updating I am trying start with promises and angularJS. My backend is returning the correct values, but my html view doesn´t show my table with the data returning from backend. What is wrong here? Here is my HTML: <div ng-app="clinang" ng-controller="pacientesCtrl"> <a class='btn btnprimary' href='/getdadospac/?oper=S' >Button</a> <table ng-table="tableParams" class="table" show-filter="true"> <tr ng-repeat="paciente in $data"> <td title="'Pront'" filter="{ name: 'text'}" sortable="'pront'"> {{paciente.pront}}</td> <td title="'Nome'" filter="{ age: 'number'}" sortable="'nome'"> {{paciente.nome}}</td> </tr> </table> </div> Here is my JSON data returning from the backend: {"draw":1,"recordsTotal":5303,"recordsFiltered":5303, "data":[{"DT_RowId":"4367","pront":"4367","nome":"XXXXXXXXX","endereco":"RUA TEODORO DA SILVA,294\/314","bairro":"VILA ISABEL","cidade":"RIO DE JANEIRO","estado":"RJ","telefone":"2567*0440","cpf":"","email":""}, {"DT_RowId":"21","pront":"21","nome":"YYYYYYYYY","endereco":"R ARAGUAIA","bairro":"PARQUE CHUNO","cidade":"DUQUE DE CAXIAS","estado":"RJ","telefone":"35637685","cpf":"02570293709","email":"[email protected]"}, {"DT_RowId":"23","pront":"23","nome":"ZZZZZZZZZZ","endereco":"rua 18 de outubro 241 101","bairro":"tijuca","cidade":"RIO DE JANEIRO","estado":"RJ","telefone":"","cpf":"","email":""}, {"DT_RowId":"24","pront":"24","nome":"AAAAAAAAAAA","endereco":"RUA MARIZ E BARROS 470 APTO 610","bairro":"TIJUCA","cidade":"RIO DE JANEIRO","estado":"RJ","telefone":"22646701","cpf":"53551192715","email":""}, {"DT_RowId":"27","pront":"27","nome":"AAAAAAAA GON\u00C7ALVES","endereco":"rua an\u00E1polis 251","bairro":"nova igua\u00E7u","cidade":"RIO DE JANEIRO","estado":"RJ","telefone":"3101-9648","cpf":"","email":""}, {"DT_RowId":"28","pront":"28","nome":"ASKLJALDJSLKADJ","endereco":"lucio de mendon\u00E7a 24 apt 501","bairro":"maracana","cidade":"RIO DE JANEIRO","estado":"RJ","telefone":"2568-9519","cpf":"04301072772","email":""}, {"DT_RowId":"30","pront":"30","nome":"SADFSADFASDFSD","endereco":"RUA GRAVATAI N 61 APTO 302","bairro":"ROCHA MIRANDA","cidade":"RIO DE JANEIRO","estado":"RJ","telefone":"32787747","cpf":"","email":""}, {"DT_RowId":"29","pront":"29","nome":"ANASADFSA DOS SANTOS","endereco":"saboia lima 12 apt 04","bairro":"tijuca","cidade":"RIO DE JANEIRO","estado":"RJ","telefone":"2204-1498","cpf":"48080152268","email":""}, {"DT_RowId":"31","pront":"31","nome":"JOAO SDAFSA SOUZA","endereco":"av dom helder camara 312 bl 05 apt 102","bairro":"benfica","cidade":"RIO DE JANEIRO","estado":"RJ","telefone":"","cpf":"075422437-64","email":""}, {"DT_RowId":"33","pront":"33","nome":"SKDJFSDAJFLASD","endereco":"fabio da luz 275 bl 04 apt 504","bairro":"meier","cidade":"RIO DE JANEIRO","estado":"RJ","telefone":"3979-0859","cpf":"","email":""}]} JS CODE: var app = angular.module("clinang", ["ngTable", "ngResource"]); (function() { app.controller("pacientesCtrl", pacientesCtrl); pacientesCtrl.$inject = ["NgTableParams", "$resource"]; function pacientesCtrl(NgTableParams, $resource) { // tip: to debug, open chrome dev tools and uncomment the following line debugger; var Api = $resource("/getdadospac/?oper=S"); this.tableParams = new NgTableParams({}, { getData: function(params) { // ajax request to api return Api.get(params.url()) .$promise .then(function(rows) { params.total(rows.recordsTotal); // recal. page nav controls return rows.data; }); } }); this.tableParams.reload(); } })(); A: You have the controller, the call and everything but you need to bind the controller's variable to the view using scope function pacientesCtrl(NgTableParams, $resource) { vm = this; vm.rows = [] .. .then(function(rows) { vm.rows = rows.data; } then in your html: <tr ng-repeat="paciente in pacientesCtrl.rows"> You should read a book to learn angular, now that you played long enough. it will reinforce some concept and helped grow as dev. I did the same as you, get hands on angular and hit too many walls, then i read one book and everything changed I also recommend this simple and fun course: https://www.codeschool.com/courses/shaping-up-with-angular-js A: I believe you need to either use ControllerAs syntax or use $scope. ControllerAs: Since you're setting the tableParams on the controller instance, you'd need to use the ControllerAs syntax to assign an alias to the controller an access the property: ng-controller="pacientesCtrl as ctrl" and also ng-table="ctrl.tableParams" $scope If you instead would like to use $scope, then you'd need to inject $scope into your controller and set the tableParams property into the $scope, something like: var app = angular.module("clinang", ["ngTable", "ngResource"]); (function() { app.controller("pacientesCtrl", pacientesCtrl); pacientesCtrl.$inject = ["NgTableParams", "$resource", "$scope"]; function pacientesCtrl(NgTableParams, $resource, $scope) { // tip: to debug, open chrome dev tools and uncomment the following line debugger; var Api = $resource("/getdadospac/?oper=S"); $scope.tableParams = new NgTableParams({}, { getData: function(params) { // ajax request to api return Api.get(params.url()) .$promise .then(function(rows) { params.total(rows.recordsTotal); // recal. page nav controls return rows.data; }); } }); $scope.tableParams.reload(); } })(); Notice that we're setting the tableParams property on the $scope and not on the controller instance. Your HTML should remain the same. Personally I prefer the ControllerAs syntax, but both should work
{ "language": "en", "url": "https://stackoverflow.com/questions/42115623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Firing the select event on click for jQuery autocomplete After playing around with jQuery's autocomplete feature a bit, I couldn't get the select event to fire onclick. Which is strange because the onfocus event fires when the mouse is dragged over each element in the list. From what I've tried so far, it doesn't look like there's a built in way to have the select event fired onclick. Am I missing something? Or is there another way that people have dealt with this in the past? Thanks in advance, Brandon A: The selected event should fire automatically on click. Consider the following code block. Here I pass in a set of handlers to decide things like what url to use, what label to attach the auto complete behavior to etc. Ultimately making an ajax request to populate the auto complete list. ActivateInputFieldSearch: function (callBack, fieldID, urlHandler, labelHandler, valueHandler) { $("#" + fieldID).autocomplete({ source: function (request, response) { var requestUrl; if (_.isFunction(urlHandler)) { requestUrl = urlHandler(request); } else { requestUrl = urlHandler; } $.ajax({ url: requestUrl, dataType: "json", data: { maxRows: 10, searchParameter: request.term }, success: function (data) { response($.map(data, function (item) { var dataJson = $.parseJSON(item); return { label: labelHandler(dataJson), value: valueHandler(dataJson), data: dataJson }; })); } }); }, minLength: 0, select: function (event, ui) { if (callBack) { callBack(ui.item); } }, open: function () { $(this).removeClass("ui-corner-all").addClass("ui-corner-top"); }, close: function () { $(this).removeClass("ui-corner-top").addClass("ui-corner-all"); }, focus: function (event, ui) { $("#" + fieldID).val(ui.item.value); } }); } A: I had a similar problem. I was attempting to use an autocomplete on 3 text boxes. If the user started typing in any of the three text boxes, an ajax call would fire and would return all the distinct combinations of those boxes in the database based on what was typed in them. The important part of what I'm trying to say is that I had the "mouse click no autocompleting" problem. I had a function firing on select to set the values for all of the text boxes. It was something like this: function showAutocompleteDropDown( a_options ){ console.log('options: ' + a_options); if ( a_options == "" ){ // nothing to do return; }// if // find out which text box the user is typing in and put the drop down of choices underneath it try{ // run jquery autocomplete with results from ajax call $(document.activeElement).autocomplete({ source: eval(a_options), select: function(event, ui){ console.log( 'event: ' + event.type ); console.log( ' running select ' ); // set the value of the currently focused text box to the correct value if (event.type == "autocompleteselect"){ console.log( "logged correctly: " + ui.item.value ); ui.item.value = fillRequestedByInformation( ); } else{ console.log( "INCORRECT" ); } }// select }); } catch(e){ alert( e ); }// try / catch }// showAutocompleteDropDown() function fillRequestedByInformation( ){ // split the values apart in the name attribute of the selected option and put the values in the appropriate areas var requestedByValues = $(document.activeElement).val().split(" || "); var retVal = $(document.activeElement).val(); $(document.activeElement).val(""); var currentlyFocusedID = $(document.activeElement).attr("id"); console.log( 'requestedByValues: ' + requestedByValues ); console.log( 'requestedByValues.length: ' + requestedByValues.length ); for (index = 0; index < requestedByValues.length; index++ ){ console.log( "requestedByValues[" + index + "]: " + requestedByValues[index] ); switch ( index ){ case 0: if ( currentlyFocusedID == "RequestedBy" ){ retVal = requestedByValues[index]; } $('#RequestedBy').val(requestedByValues[index]); break; case 1: if ( currentlyFocusedID == "RequestedByEmail" ){ retVal = requestedByValues[index]; } $('#RequestedByEmail').val(requestedByValues[index]); break; case 2: if ( currentlyFocusedID == "RequestedByPhone" ){ retVal = requestedByValues[index]; } $('#RequestedByPhone').val(requestedByValues[index]); break; default: break; } } }// fillRequestedByInformation() and then I changed it to the following: function showAutocompleteDropDown( a_options ){ console.log('options: ' + a_options); if ( a_options == "" ){ // nothing to do return; }// if // find out which text box the user is typing in and put the drop down of choices underneath it try{ // run jQuery autocomplete with results from ajax call $(document.activeElement).autocomplete({ source: eval(a_options), select: function(event, ui){ console.log( 'event: ' + event.type ); console.log( ' running select ' ); // set the value of the currently focused text box to the correct value if (event.type == "autocompleteselect"){ console.log( "logged correctly: " + ui.item.value ); ui.item.value = fillRequestedByInformation( ui.item.value ); } else{ console.log( "INCORRECT" ); } }// select }); } catch(e){ alert( e ); }// try / catch }// showAutocompleteDropDown() function fillRequestedByInformation( a_requestedByValues ){ // split the values apart in the name attribute of the selected option and put the values in the appropriate areas var requestedByValues = a_requestedByValues.split(" || "); var retVal = $(document.activeElement).val(); $(document.activeElement).val(""); var currentlyFocusedID = $(document.activeElement).attr("id"); console.log( 'requestedByValues: ' + requestedByValues ); console.log( 'requestedByValues.length: ' + requestedByValues.length ); for (index = 0; index < requestedByValues.length; index++ ){ console.log( "requestedByValues[" + index + "]: " + requestedByValues[index] ); switch ( index ){ case 0: if ( currentlyFocusedID == "RequestedBy" ){ retVal = requestedByValues[index]; } $('#RequestedBy').val(requestedByValues[index]); break; case 1: if ( currentlyFocusedID == "RequestedByEmail" ){ retVal = requestedByValues[index]; } $('#RequestedByEmail').val(requestedByValues[index]); break; case 2: if ( currentlyFocusedID == "RequestedByPhone" ){ retVal = requestedByValues[index]; } $('#RequestedByPhone').val(requestedByValues[index]); break; default: break; } } }// fillRequestedByInformation() The debugging is still in there for now, but the change was in the select event in the autocomplete by adding a parameter to the function fillRequestedByInformation() and the first line of said function. It returns to and overwrites ui.item.value to get the correct value for that box instead of the selected value. Example of a selected autocomplete value: "John Doe || [email protected] || 1-222-123-1234" Also, used eval( a_options ) so that the autocomplete could utilize a_options. before I used eval, it would not even recognize I had values in the source. a_options is the result. A: i think you need the select event $( ".selector" ).autocomplete({ select: function(event, ui) { ... } }); http://jqueryui.com/demos/autocomplete/#event-select
{ "language": "en", "url": "https://stackoverflow.com/questions/8158246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Importing Spark avro packages into a dockerized python project to import avro file in S3 I am trying to read some avro files stored in S3 bucket with the following code. spark version is 2.4.7 from pyspark.sql import SparkSession spark = SparkSession.builder.appName('Statistics').getOrCreate() sc = spark.sparkContext df = spark.read.format("com.databricks.spark.avro").load("s3://test/sqoopData/part-m-00000.avro") df.show() With this im getting the below error py4j.protocol.Py4JJavaError: An error occurred while calling o28.load. : java.lang.ClassNotFoundException: Failed to find data source: org.apache.spark.sql.avro.AvroFileFormat. Please find packages at http://spark.apache.org/third-party-projects.html at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:678) at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:213) at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:197) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:282) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:238) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.ClassNotFoundException: org.apache.spark.sql.avro.AvroFileFormat.DefaultSource at java.net.URLClassLoader.findClass(URLClassLoader.java:382) at java.lang.ClassLoader.loadClass(ClassLoader.java:418) at java.lang.ClassLoader.loadClass(ClassLoader.java:351) at org.apache.spark.sql.execution.datasources.DataSource$.$anonfun$lookupDataSource$5(DataSource.scala:652) at scala.util.Try$.apply(Try.scala:213) at org.apache.spark.sql.execution.datasources.DataSource$.$anonfun$lookupDataSource$4(DataSource.scala:652) at scala.util.Failure.orElse(Try.scala:224) at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:652) I know this is due to not having spark avro packages within my project. But Im not sure how to import those into my project. Please note that all spark, hadoop and python are setup using a docker file. therefore some solutions given in the internet couldn't be applied. eg importing required jar files using spark shell. A: Take a look at this setup https://github.com/kurtzace/python-spark-avro-query (dockerfile within it) * *This solution loads avro jar into spark jars *sets up spark home *also exposes the avro file as an API (main.py)
{ "language": "en", "url": "https://stackoverflow.com/questions/68320603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to update Dataset Parent & Child tables with Autogenerated Identity Key? I am using ADO.NET Datasets in my VB Applications. I have a typed dataset with one Parent table and many child tables. I want to generate Identity Key when I insert data into Parent Table and then update the data in all child tables with the Same key (As Foregin key). At last, I want to update the dataset in Database(SQL Server08). Well, the above thing can be possible by first inserting Parent Table in Database directly, get the Identity column and than use to for Child tables. But I want to this as an automatic operation (Like LINQ to SQL which takes care of Primary & Foreign key in datacontext.) I such thing possible in Dataset which takes care of Autogenerated column for Parent and child tables? Thanks, ABB A: I think this should be more obvious and should work without any tweaking. But still, it's pretty easy. The solution has two parts: * *Create DataRelation between child and parent tables and set it to cascade on updates. That way whenever parent Id changes, all children will be updated. Dim rel = ds.Relations.Add(parentTab.Columns("Id"), childTab.Columns("ParentId")) rel.ChildKeyConstraint.UpdateRule = Rule.Cascade *Dataset insert and update commands are two-way: If there are any output parameters bound or any data rows returned, they will be used to update dataset row that caused the update. This is most useful for this particular problem: getting autogenerated columns back to application. Apart from identity this might be for example a timestamp column. But identity is most useful. All we need to do is set insert command to return identity. There are several ways to do it, for example: a) Using stored procedure with output parameter. This is the most portable way among "real" databases. b) Using multiple SQL statements, with last one returning inserted row. This is AFAIK specific to SQL Server, but the simplest: insert into Parent (Col1, Col2, ...) values (@Col1, @Col2, ...); select * from Parent where Id = SCOPE_IDENTITY(); After setting this up, all you need to do is create parent rows with Ids that are unique (within single dataset) but impossible in the database. Negative numbers are usually a good choice. Then, when you save dataset changes to database, all new parent rows will get real Ids from database. Note: If you happen to work with database without multiple statements supports and without stored procedures (e.g. Access), you will need to setup event handler on RowUpdated event in parent table adapter. In the hanler you need to get identity with select @@IDENTITY command. Some links: * *MSDN: Retrieving Identity or Autonumber Values (ADO.NET) *MSDN: Managing an @@IDENTITY Crisis *Retrieving Identity or Autonumber Values into Datasets *C# Learnings: Updating identity columns in a Dataset A: Couple of things to point out. * *Yes, you definitely need relations assigned for both tables. You can check from xsd editor (double click your xsd file). By default the relation is set as 'relation only' which doesn't has any 'update rule'. Edit this relation by going into 'edit relation' and select 'Foreign Key Constraint Only' or 'Both~~~' one. And need to set 'Update Rule' as Cascade! 'Delete Rule' is up to you. *Now when you use a new parent table row's ID (AutoIncrement) for new child table rows as a foreign key, You have to add the parent row into the table first before you use the new parent row's ID around. *As soon as you call Update for the parent table using tableadapter, the associated child table's new rows will have correct parentID AUTOMATICALLY. My simple code snippets: '--- Make Parent Row Dim drOrder as TOrderRow = myDS.TOder.NewTOrderRow drOrder.SomeValue = "SomeValue" myDS.TOrder.AddTOrderRow(drOrder) '===> THIS SHOULD BE DONE BEFORE CHILD ROWS '--- Now Add Child Rows!!! there are multiple ways to add a row into tables.... myDS.TOrderDetail.AddTOrderDetailRow(drOrder, "detailValue1") myDS.TOrderDetail.AddTOrderDetailRow(drOrder, "detailvalue2") '.... '.... '--- Update Parent table first myTableAdapterTOrder.Update(myDS.TOrder) '--- As soon as you run this Update above for parent, the new parent row's AutoID(-1) '--- will become real number given by SQL server. And also new rows in child table will '--- have the updated parentID '--- Now update child table myTableAdapterTOrderDetail.Update(myDS.TOrderDetail) I hope it helps! A: And if you don't want to use datasets and yet get the ids assigned to childs and getting the ids so that you can update your model: https://danielwertheim.wordpress.com/2010/10/24/c-batch-identity-inserts/
{ "language": "en", "url": "https://stackoverflow.com/questions/931630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to write data from an AJAX request to DATA in VUE JS? Tell me please, how in DATA to write data from the AJAX response? Example: var example = new Vue({ el: '#example', data:{ myArr: [] }, created: function () { $.getJSON('data.json', function(data) { this.myArr = data; }); } }); The problem is that in myArr, the response data is not written. How to solve this? Thank you. A: Can you try this ? Basically this inside the ajax is not exactly the one you would expect. var example = new Vue({ el: '#example', data:{ myArr: [] }, created: function () { var vm = this; $.getJSON('data.json', function(data) { vm.myArr = data; }); } }); You can also use reactivity setting method $set instead of directly assigning to the vm.myArr : https://v2.vuejs.org/v2/guide/reactivity.html
{ "language": "en", "url": "https://stackoverflow.com/questions/43768333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use webchimera.js/node.js for rtsp streaming In my web application i am using VLC player to play RTSP streaming, but now chrome has completely stopped NPAPI. After this my customer couldn't stream their camera in the browser. My manager suggested me to use webchimera.js and node.js to test streaming in browser, but i am new to this could any one please suggest how can i use these technology in my java project A: WebChimera.js could not be used with regular browser. It could be used only with NW.js or Electron or any other Node.js based frameworks.
{ "language": "en", "url": "https://stackoverflow.com/questions/32605370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ember's volatile and templates I have a property mood which is part of the interface for a component. Behind the scenes I have a computed property called _mood: const { computed, typeOf } = Ember; _mood: computed('mood','A','B','C' function() { let mood = this.get('mood'); if (typeOf(mood) === 'function') { mood = mood(this); } return !mood || mood === 'default' ? '' : `mood-${mood}`; }).volatile(), I have a situation where with the volatile() that hangs of of Ember's computed object resolves all non DOM unit tests successfully but for some reason it is not triggering the template to update the DOM under any circumstance. It should, at the very least, update if any of properties being watched change (in this case ['mood','A', 'B', 'C']) change. Because it is volatile (aka, doesn't cache results) the new results would show up in a template if the template knew to re-render the component but for some reason it doesn't. If I remove the volatile() tag it works fine for static/scalar values but if mood is a function then the result is cached and therefore it only works once (not a working solution for this problem). How do I get the best of both worlds? A: I'm still not sure why the volatile() method is turning off updates to templates. This might be a real bug but in terms of solving my problem the important thing to recognise was that the volatile approach was never the best approach. Instead the important thing to ensure is that when mood comes in as a function that the function's dependencies are included in the CP's dependencies. So, for instance, if mood is passed the following function: mood: function(context) { return context.title === 'Monkeys' ? 'happy' : 'sad'; } For this function to evaluate effectively -- and more importantly to trigger a re-evaluation at the right time -- the title property must be part of the computed property. Hopefully that's straight forward as to why but here's how I thought I might accommodated this: _moodDependencies: ['title','subHeading','style'], _mood: computed('mood','size','_moodDependencies', function() { let mood = this.get('mood'); console.log('mood is: %o', mood); if (typeOf(mood) === 'function') { run( ()=> { mood = mood(this); }); } return !mood || mood === 'default' ? '' : `mood-${mood}`; }), That's better, as it allows at build time for a static set of properties to be defined per component (the _mood CP for me is part of a mixin used by a few components). Unfortunately this doesn't yet work completely as the it apparently doesn't unpack/destructure the _moodDependencies. I'll get this sorted and update this unless someone else beats me to the punch.
{ "language": "en", "url": "https://stackoverflow.com/questions/30189542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EXCEL VBA Filter user input MY inputbox allow user to input a value into a cell. Therefore I wish to filter some input like =SUM(A:A) and ' which will show nothing, and other formula or possibly entry that will affect the actual value. Thanks in advance. Private Sub testInputBox_Click() Dim x As String Dim y As String Dim yDefault As String Dim found As Range x = InputBox("Enter Parts No.", "Edit Description") If (x <> "") Then If (WorksheetFunction.CountIf(Worksheets("Sheet1").Range("E2:E27"), x) > 0) Then Set found = Worksheets("Sheet1").Range("E2:E27").Find(x, LookIn:=xlValues) yDefault = found.Offset(0, 1).Text y = InputBox("Amend Description", "Edit Description", yDefault) Else MsgBox ("Not found!") End If If (y <> "") Then 'Filter should be done here If MsgBox("Proceed to edit?", vbYesNo, "Confirmation") = vbNo Then Else found.Offset(0, 1).Value = CStr(y) End If End If End If End Sub A: You could use different attempts to filter some or all required values. Keep in mind that you y variable is string type. Therefore here are some of ideas with some comments: 'tests for starting characters If y <> "'" And y <> "=" Then 'test for formulas If UCase(Left(y, 4)) <> "=SUM" Then 'test for any string within other string If InStr(1, y, "sum", vbTextCompare) = 0 Then '...here your code End If End If End If you could combine them all into one if...then statement using and or or operators.
{ "language": "en", "url": "https://stackoverflow.com/questions/16161939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django- CMS: Plugin position in a placeholder I was looking for a way to check the plugin's position within a placeholder in Django-CMS. I found this question Detect last plugin in a placeholder Is "plugin" a django cms keyword? I can't find documentation about it. My question is: How can I obtain information about the plugins rendered within a Placeholder? Thanks A: if you don't override your plugins render method (2.4 and up), you'll have your plugin as instance in your context. using the following, you'll get the 1 based position of your plugin: {{ instance.get_position_in_placeholder }} also interesting: is_first_in_placeholder and is_last_in_placeholder. in fact, @paulo already showed you the direction in his comment ;) this is the code, with new line number: https://github.com/divio/django-cms/blob/develop/cms/models/pluginmodel.py#L382
{ "language": "en", "url": "https://stackoverflow.com/questions/12977863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can I run a program from visual studio without elevated permissions? Okay, so originally I was going to ask about dragging and dropping in Windows 7. I found the answer I was looking for here: C# Drag drop does not work on windows 7. Basically it says that since I'm running Visual Studio (and subsequently, my program) with elevated permissions, some sort of isolation layer prevents me from dragging and dropping files from explorer into my program. The reason I run visual studio with elevated permissions is because admin privileges are needed to run a site locally on IIS and the web app is in my solution. Is there a way I can tell visual studio to run and debug my other apps as a normal user? A: Why don't you just create another short-cut on the desktop that starts devenv.exe without elevation? A: MSDN states: Launching an Un-Elevated Application from an Elevated Process A frequently asked question is how to launch an un-elevated application from an elevated process, or more fundamentally, how to I launch a process using my un-elevated token once I’m running elevated. Since there is no direct way to do this, the situation can usually be avoided by launching the original application as standard user and only elevating those portions of the application that require administrative rights. This way there is always a non-elevated process that can be used to launch additional applications as the currently logged on desktop user. Sometimes, however, an elevated process needs to get another application running un-elevated. This can be accomplished by using the task scheduler within Windows Vista®. The elevated process can register a task to run as the currently logged on desktop user. You could use that and implement a simple launcher app (possibly a VS macro) that you start instead of your application. The launcher app would: * *Create a scheduled task that would run immediately or that is triggered by an event *Start the debuggee *Connect the VS debugger to the started process A: The VS debugger is tied to the browser instance that VS is launched, but you can still use with another browser instance to browse the site under test. Actions on the server side will still operate through the debugger (but you'll not get client side debugging—IE8 developer tools and FireBug are still available of course). A: From your application, call ChangeWindowMessageFilter with the following values to allow dragging and dropping to/from your elevated application and non-elevated applications like Explorer: ChangeWindowMessageFilter (WM_DROPFILES, MSGFLT_ADD); ChangeWindowMessageFilter (WM_COPYDATA, MSGFLT_ADD); ChangeWindowMessageFilter (0x0049, MSGFLT_ADD); Credit: http://blog.helgeklein.com/2010/03/how-to-enable-drag-and-drop-for.html A: I use old-school command line for this purpose: runas /trustlevel:0x20000 "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe" And then just press F5 in Studio. A: You can use the elevated Visual Studio to do your programming, you just can't have Visual Studio launch the executable. I like 0xA3's answer, but if you don't want to go to the trouble of creating a VS macro and a scheduled task to launch your program, you can just create a shortcut on the desktop to the executable (either the debug or release version) and use that to launch your program. If you launch the debug version, you can use "Attach to Process" in the Visual Studio Debug menu to attach and do some debugging.
{ "language": "en", "url": "https://stackoverflow.com/questions/3677854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Delete file with BIM360 API Issue My aim is to Upload files into a specific subfolder of the "Plans" folder. The first problem I got was that I can only upload a file with version 1, when I use the API. So I decided to copy all files from the specific folder into an archive folder. Now I can delete all files from the specific folder, that I can upload the new files to the specific folder. I am using the forge-api-dotnet-client. I know there are two different ways of deleting files. (https://forge.autodesk.com/blog/way-delete-file-version-through-forge-dm-api) I tried both of them but they did not work. let project = { Id = "projectId" ProjectFilesFolder = "specificFolderId" UploadFolder = "destinationFolderId" } let itemName = "itemName" let itemId = "urn:adsk.wipprod:dm.lineage:QCtjhnZ5TWWCASh-mQ5nmA" let createVersionBody fileName itemId = sprintf """{ "jsonapi":{ "version":"1.0" }, "data":{ "type":"versions", "attributes":{ "name":"%s", "extension":{ "type":"versions:autodesk.bim360:Deleted", "version":"1.0" } }, "relationships":{ "item":{ "data":{ "type":"items", "id":"%s" } } } } }""" fileName itemId |> JsonConvert.DeserializeObject<CreateVersion> let versionApi = VersionsApi() let result = versionApi.PostVersion(project.Id, (createVersionBody itemName itemId)) result |> ignore It gives me this BAD_INPUT Exception and I found that I get a different id from the api than from the webpage. ItemId from Api: "urn:adsk.wipprod:dm.lineage:QCtjhnZ5TWWCASh-mQ5nmA" ItemId from Webpage: "urn:adsk.wipprod:dm.lineage:EdJjPVzFQR6tlbUJ5WK-zg" The second way I found was to do it with "DeleteObject". let project = { Id = "projectId" ProjectFilesFolder = "specificFolderId" UploadFolder = "destinationFolderId" } let getStorage = ifcs project ObjectsApi().DeleteObject(getStorage.BucketKey, getStorage.ObjectName) I get this exception . I am using a TwoLegged Authentication and my scope is also fine. Is there an error in my code or is there another way of doing it?
{ "language": "en", "url": "https://stackoverflow.com/questions/59036025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML page is appearing different in Mozilla Firefox and Internet Explorer Hey guys, i have recently created a HTML page but it is appearing differently in Mozilla Firefox and Internet Explorer. I have uploaded the page on ripway. Here is the URL http://h1.ripway.com/gurusmith/My%20site/Index/index.html Please watch the page in both Internet Explorer and Mozilla Firefox and after watching you will find that the page is appearing fine in Internet Explorer but not in Mozilla Firefox. Can anyone tell where i have made the problems. If anyone can edit the source code and post the correct source code here which works fine in both the browsers then i will be really thankful to you. Sorry, i can't post the source code and the outputs due to restrictions but i have given the link above for the page. So please do visit it and help me. A: Your page is not even remotely valid HTML. For one thing, you have two body elements. Check out W3C Validation of your page for more problems. If a browser gets invalid HTML it makes its best guess at what the DOM should be (as opposed to a deterministic interpretation). Since browsers are designed by independent teams, these interpretations will differ. Then, when it comes to applying CSS, variations are bond to occur. Get your HTML in order and then see what happens. A: Older versions of IE are known to display pages slightly differently than most "modern" browsers. A quick Google search turned up the following lists of common differences: http://www.wipeout44.com/brain_food/css_ie_bug_fixes.asp http://css-tricks.com/ie-css-bugs-thatll-get-you-every-time/
{ "language": "en", "url": "https://stackoverflow.com/questions/5444457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: chrome filesystem - rename a directory In the new chrome filesystem api, how do I rename a directory? moveTo() on the directory itself doesn't seem to work, and I don't want to iterate over all the files in the directory. Is there a simple way to just rename it? thanks! A: This worked for me, can you give some more information about what sort of error you are encountering? We get the parent directly from the entry and simply place the folder with a new name under the same parent. Take note that this will fail, with an invalidmodification error if the new name is the same as the old, even if you change the caps in the name. var test = function( entry, new_name ){ entry.getParent( function( parent ){ entry.moveTo( parent , new_name, function( new_node ){ console.log( new_node ) console.log( "Succes creating the new node" ) //We were able to rename the node }, function( error ){ console.error( error ) console.error( "Something wrong when finding the parent" ) }) }, function( error ){ console.error( error ) console.error( "Something wrong when finding the parent" ) }) } test( entry, "For the watch" )
{ "language": "en", "url": "https://stackoverflow.com/questions/32615032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Node.js server on raspberry Pi 3B unreachable from React Native app after few succesful iterations I'm currently working on a simple React Native which sends to a Node.js server hosted on a Raspberry Pi3B an order to switch on or off a led. React Native code : import React from 'react'; import {StyleSheet, Text, View, Button} from 'react-native'; export default class App extends React.Component { constructor(props){ super(props);}; led(couleur){ fetch('http://XXX.XXX.XXX.XXX:XXX/switchOnOff', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', },body: JSON.stringify({'couleur': couleur}), }).catch((error) => { console.error(error); }); } render() { return ( <View> <View style={styles.bleu}> <Button title="Bleu" color='blue' onPress={() => this.led('bleu')}/> </View> </View> ); } } On the Raspberry, I have the following for my Node.js server : var express = require('express'); var fs = require("fs"); var bodyParser = require('body-parser'); var Gpio = require('onoff').Gpio, led14 = new Gpio(14, 'out'); var app = express(); app.use(bodyParser.json()); var allumer = false; app.post('/switchOnOff', function (req, res) { coul = req.body['couleur']; console.log('working!'); var val = !allumer ? 1 : 0; if (coul == 'bleu'){ led14.writeSync(val);} led14.watch((err, mess) => { if (err){throw err }}) allumer = !allumer; } }); var server = app.listen(8000, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) strangely, this is working 5 times in a row (I get in the server console "working!" printed five times, and the led is toggled on/off). But then I get the following error : From then, I'm not able to send data to the server using the React Native app... Has anyone any idea ? Thanks A: Actually I got it : the error was coming from the server side: I was missing one line of code res.end() which ends each request Modified server side code : app.post('/switchOnOff', function (req, res) { coul = req.body['couleur']; console.log('working!'); var val = !allumer ? 1 : 0; if (coul == 'bleu'){ led14.writeSync(val);} led14.watch((err, mess) => { if (err){throw err }}) allumer = !allumer; } //#########solving line########## res.end });
{ "language": "en", "url": "https://stackoverflow.com/questions/53932582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Play mkv file with included srt using python-vlc When I want to start to play an mp4 file from python using python-vlc, I will do import vlc from time import sleep movie = "/path/to/movie.mp4" subs = "/path/to/subs.srt" i = vlc.Instance() media_player = i.media_player_new() media = i.media_new(movie) media.slaves_add(vlc.MediaSlaveType.subtitle, 1, "file://{}".format(subs)) media_player.set_media(media) media_player.play() sleep(10) However, I now have an mkv file which includes an srt file. How would I start playing this file using python-vlc with the included srt file? A: One way to do it is to give options when you create the Instance. E.g.: i = vlc.Instance((' --sub-file <your srt file> ')) I have gotten this to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/60855805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove special characters from excel(xlsx) file using python3? How to extract all the rows from excel file using python3 and remove special characters? Table.xlsx Tablle.xlsx import xlrd loc = ("Table.xlsx") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) print(sheet.row_values(1)) Expected Output: Expected Output A: This worked for me in a word document. It may do the same for you... Function I used: import re def removeSpecialCharacters(cellValue): text=re.sub(r"[\r\n\t\x07\x0b]", "", cellValue) return text Afterwards, I used this for the values: character = table.Cell(Row = 1, Column = 1).Range.Text character = removeSpecialCharacters(character) You may also use a for loop for your solution as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/55494593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Violin plot of a list of arrays I have some data in the format: [array([[0, 1, 2]], dtype=int64), array([[1, 2, 3]], dtype=int64)] My data can be generated using: di_DFs = {} groups = [1,2] for grp in groups: di_DFs[grp] = pd.DataFrame({'A' : [grp-1], 'B' : [grp], 'C' : [grp+1]}) data = [] for k in di_DFs: data.append(di_DFs[k].iloc[[0]].values) I can plot it: for v in data: plt.scatter(range(len(v[0])),v[0]) I would like to get a violin plot with 3 vertical violins where my pairs of points are in the scatter plot please, to compare the distributions within my arrays. I tried: for v in data: plt.violinplot(v) But I got: A: I believe you need something like this: for v in data: plt.violinplot(v) Plots this: Since the example dataset has only a few points, you will not see much of distribution but more like flat dashes/points. But try with more data points and it will do the needed. A: I needed to re-format my data: df_Vi = pd.DataFrame({'Z' : data[0][0], 'Y' : data[1][0]}, index=range(len(data[0][0]))) plt.violinplot(df_Vi) Or, a version that works with more data: di_DFs = {} groups = [1,2,0,7] for grp in groups: di_DFs[grp] = pd.DataFrame({'A' : [grp-1], 'B' : [grp], 'C' : [grp+1]}) data = [] for k in di_DFs: data.append(di_DFs[k].iloc[[0]].values) Indexes = range(len(groups)) df_Vi = pd.DataFrame() for inD in Indexes: df_Po = pd.DataFrame({inD : data[inD][0]}, index=range(len(data[0][0]))) df_Vi = pd.concat([df_Vi, df_Po], axis=1) plt.violinplot(df_Vi)
{ "language": "en", "url": "https://stackoverflow.com/questions/63884251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Disable scrolling with panel animation In my navigation, the contact link slides down a panel which overlays on top of the site like so: When the panel slides down I do not want the user to be able to scroll down below the panel. Basically, I want to disable scrolling on the page. If there is more content than available space within the panel, it will scroll within the panel. This is done simply by adding overflow:scroll to the panel's css like so: #contactPanel{width:100%; height:100%; overflow:scroll;position: absolute; top:-100%; left:0; z-index: 6; background: #000000; color:white;} So, scrolling is fine within the panel, but I do not want any scrolling within the body / document. If not possible with pure CSS,javascript is an option. A: So long as your "contactPanel" is not larger than the body (or viewport) then the body won't scroll. But you can set overflow:hidden just to make sure of it. I'm guessing you actually only want to scroll the contactPanel vertically as well, and not on both axis? Use overflow-y:scroll; I'd also recommend moving text styling rules onto to the text objects themselves... but that's just me. body { overflow:hidden; } #contactPanel { overflow-y:scroll; width:100%; height:100%; position: absolute; top:-100%; left:0; z-index: 6; background: #000000; } #contactPanel p { color:#fff; }
{ "language": "en", "url": "https://stackoverflow.com/questions/17352352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: best practice for header.php with div? I have a page including a header, which is a div containing two sub-divs. I am wondering whether it is better to require header.php inside the header div, and have header.php create the two subdivs, or whether I should require header.php at the start of the script and have it create the header div with two sub-divs. A: "require header.php at the start of the script and have it create the header div with two sub-divs" this way, it will be easier for you to change anything including that parent div. And its usually a good practice to include a header file before starting any html output. You can do several things with it in future... like writing some statement that require sending of headers (http headers) like start session etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/13372548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Login PHP Session gets cleared when chrome closes, persistent in Firefox My login script: if (login_user($user_login, $password)){//Login check is verified ini_set('session.cookie_lifetime', 60 * 60 * 24 * 365); ini_set('session.gc_maxlifetime', 60 * 60 * 24 * 365); session_start(); $user = get_user($user_login); $_SESSION['username'] = $user['username']; When I login for testing, the session is active between different pages on both Firefox and Chrome. No problems there. Though, when I restart the browser, the Login session is lost in Chrome, whilist I'm still logged in in Firefox. I've tried to google the issue but the main pointed out issue is a missing favicon which I have in my root folder. EDIT * *I don't know if it helps, but I've found a cookie in Chrome called PHPSESSID (related to my website) and it basically says "Expires when browser closes". *The same cookie, PHPSESSID, expires on Friday, May 3, 2019, 2:12:28 AM A: In this case you should use session cookie for exactly checking when Browser session is opened - it is the idea behind the function. What you are looking for is something called Persistent Login Cookie that is something similar to "Remember me" functionality mostly used in login forms. Basically you set encrypted login cookie on user's browser and then can use it for automatic authentication of user. This answer on Stack Overflow may be helpful: Improved Persistent Login Cookie Best Practice
{ "language": "en", "url": "https://stackoverflow.com/questions/50172401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pyspark 2.6 How increase a value column I'm training in Pyspark using the cloudera virtual machine that is coming with Python 2.6. I read already the file in a RDD. I need to increase the number in one of the file columns. structure file: student,grade Owen,4 Andres,3.9 Leidy,4 Flor,5 Jhon,4 Paola,3.8 My code to read the file is already working and showing up the data as below: code: from pyspark import SparkConf, SparkContext #Context-definition conf = SparkConf().setAppName('local') sc = SparkContext(conf=conf) sc.setLogLevel("WARN") grades_report = sc.textFile("file:///home/cloudera/input/family_grades.txt") grades = grades_report.map(lambda x: x.split(',')) print(grades.collect()) It's printing: Now I need to increase the column grade in 2, then I added the code: header = grades_report.first() grades = grades_report.map(lambda x: x.split(',')) grades_incr = grades.filter(lambda x: x != header).map(lambda x : int(x[1]) + 2) print(grades_incr.take(2)) This approach doesn't work because it's not mapping the columns as I expect and the error I'm getting is: File "/home/cloudera/scripts/spark0123.py", line 25, in <lambda> grades_incr = grades.filter(lambda x: x != header).map(lambda x : int(x[1]) + 2) ValueError: invalid literal for int() with base 10: 'grade' Please someone has an idea? I think my filter is not working right. thanks so much. A: You could do something like this: DataFrame Approach grades = spark.read.option('header', 'true').csv('file.txt') print(grades.collect()) grades_incr = grades.select(grades['student'], grades['grade'] + 2) print(grades_incr.take(2)) RDD Approach grades_report = sc.textFile('file.txt') grades = grades_report.map(lambda x: x.split(',')) header = grades.first() grades_incr = grades.filter(lambda x: x != header).map(lambda (_, grade): float(grade) + 2) A: The problem is that you extract the header before you split on ,. You could change it to: grades = grades_report.map(lambda x: x.split(',')) header = grades .first() grades_incr = grades.filter(lambda x: x != header).map(lambda x : float(x[1]) + 2) And I belive the int cast should be a float since you have doubles.
{ "language": "en", "url": "https://stackoverflow.com/questions/48414420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to optimize this array loop I have array which contains info about many flights. I want only the five lowest prices. First I make a loop to sort array by price. Second I print first five array But it takes more time..How can I reduce this time? foreach ($flights_result->json_data['response']['itineraries'] as $key => $value) { $mid[$key] = $value['price']['totalAmount']; } //Sort the data with mid descending //Add $data as the last parameter, to sort by the common key array_multisort($mid, SORT_ASC, $flights_result->json_data['response']['itineraries']); // print 5 arrays foreach ($flights_result->json_data['response']['itineraries'] as $value) { echo 'departureTime:' . $value['inboundInfo']['departureTime'] . '</br>'; echo 'layoverInMin:' . $value['inboundInfo']['layoverInMin'] . '</br>'; // // loop echo foreach ($value['inboundInfo']['flightNumbers'] as $flightNumbers) { echo 'flightNumbers :' . $flightNumbers . '</br>'; } echo 'durationInMin:' . $value['inboundInfo']['durationInMin'] . '</br>'; echo 'localDepartureTimeStr:' . $value['inboundInfo']['localDepartureTimeStr'] . '</br>'; echo ' arrivalTime:' . $value['inboundInfo']['arrivalTime'] . '</br>'; echo ' numStops:' . $value['inboundInfo']['numStops'] . '</br>'; //// loop foreach ($value[' inboundInfo']['flightClasses'] as $flightClasses) { echo 'flightClasses name :' . $flightClasses['name'] . '</br>'; echo 'flightClasses fareClass :' . $flightClasses['fareClass'] . '</br>'; } echo 'localArrivalTimeStr:' . $value['inboundInfo']['localArrivalTimeStr'] . '</br>'; // loop echo foreach ($value[' carrier'] as $carrier) { echo 'carrier name :' . $carrier['name'] . '</br>'; echo 'carrier code :' . $carrier['code'] . '</br>'; } echo 'amount:' . $value['price']['amount'] . '</br>'; echo ' totalAmount :' . $value['price']['totalAmount'] . '</br>'; echo 'pricePerPassenger:' . $value['price']['pricePerPassenger'] . '</br>'; echo 'currencyCode: ' . $value['price']['currencyCode'] . '</br>'; echo 'totalPricePerPassenger: ' . $value['price']['totalPricePerPassenger'] . '</br>'; echo 'includesTax: ' . $value['price ']['includesTax'] . '</br>'; echo 'destinationCountryCode:' . $value[' destinationCountryCode'] . ' </br> -------- </br>'; $count++; if ($count > 2) { break; } } array example Array ( [0] => Array ( [ecpcRank] => 0 [inboundInfo] => Array ( [aircraftTypes] => Array ( ) [departureTime] => 1381448400000 [layoverInMin] => 1359 [flightNumbers] => Array ( [0] => DL3672 [1] => EK204 [2] => EK923 ) [durationInMin] => 2360 [airportsExpanded] => Array ( [0] => PHL [1] => JFK [2] => JFK [3] => DXB [4] => DXB [5] => CAI ) [localDepartureTimeStr] => 2013/10/10 18:40 -0500 [airports] => Array ( [0] => PHL [1] => JFK [2] => DXB [3] => CAI ) [arrivalTime] => 1381590000000 [numStops] => 2 [flightClasses] => Array ( [0] => Array ( [name] => Economy [fareClass] => 1 ) [1] => Array ( [name] => Economy [fareClass] => 1 ) [2] => Array ( [name] => Economy [fareClass] => 1 ) ) [localArrivalTimeStr] => 2013/10/12 17:00 +0200 ) [location] => Array ( [0] => Array ( [code] => CAI [name] => Cairo ) [1] => Array ( [code] => DXB [name] => Dubai ) [2] => Array ( [code] => PHL [name] => Philadelphia ) [3] => Array ( [code] => JFK [name] => New York J F Kennedy ) [4] => Array ( [code] => MXP [name] => Milan Malpensa ) ) [carrier] => Array ( [0] => Array ( [name] => Delta Air Lines [code] => DL ) [1] => Array ( [name] => US Airways [code] => US ) [2] => Array ( [name] => Emirates [code] => EK ) [3] => Array ( [name] => Egyptair [code] => MS ) ) [bookingType] => WEBSITE [price] => Array ( [name] => [nameOTA] => [description] => [amount] => 26280 [totalAmount] => 26280 [pricePerPassenger] => 26280 [currencyCode] => EGP [totalPricePerPassenger] => 26280 [includesTax] => 1 ) [generatedDate] => 1380212804686 [providerId] => emirates.com [id] => MS703[CAI-MXP],EK205[MXP-JFK],US3407[JFK-PHL]|DL3672[PHL-JFK],EK204[JFK-DXB],EK923[DXB-CAI] [originCountryCode] => EG [bookingCode] => 13600077136293253 [destinationCountryCode] => US [outboundInfo] => Array ( [aircraftTypes] => Array ( ) [departureTime] => 1380958800000 [layoverInMin] => 1050 [flightNumbers] => Array ( [0] => MS703 [1] => EK205 [2] => US3407 ) [durationInMin] => 1940 [airportsExpanded] => Array ( [0] => CAI [1] => MXP [2] => MXP [3] => JFK [4] => JFK [5] => PHL ) [localDepartureTimeStr] => 2013/10/05 09:40 +0200 [airports] => Array ( [0] => CAI [1] => MXP [2] => JFK [3] => PHL ) [arrivalTime] => 1381075200000 [numStops] => 2 [flightClasses] => Array ( [0] => Array ( [name] => Economy [fareClass] => 1 ) [1] => Array ( [name] => Economy [fareClass] => 1 ) [2] => Array ( [name] => Economy [fareClass] => 1 ) ) [localArrivalTimeStr] => 2013/10/06 11:00 -0500 ) ) [1] => Array ( [ecpcRank] => 0 [inboundInfo] => Array ( [aircraftTypes] => Array ( ) [departureTime] => 1381448400000 [layoverInMin] => 1359 [flightNumbers] => Array ( [0] => DL3672 [1] => EK204 [2] => EK923 ) [durationInMin] => 2360 [airportsExpanded] => Array ( [0] => PHL [1] => JFK [2] => JFK [3] => DXB [4] => DXB [5] => CAI ) [localDepartureTimeStr] => 2013/10/10 18:40 -0500 [airports] => Array ( [0] => PHL [1] => JFK [2] => DXB [3] => CAI ) [arrivalTime] => 1381590000000 [numStops] => 2 [flightClasses] => Array ( [0] => Array ( [name] => Economy [fareClass] => 1 ) [1] => Array ( [name] => Economy [fareClass] => 1 ) [2] => Array ( [name] => Economy [fareClass] => 1 ) ) [localArrivalTimeStr] => 2013/10/12 17:00 +0200 ) [location] => Array ( [0] => Array ( [code] => CAI [name] => Cairo ) [1] => Array ( [code] => PHL [name] => Philadelphia ) [2] => Array ( [code] => DXB [name] => Dubai ) [3] => Array ( [code] => JFK [name] => New York J F Kennedy ) ) [carrier] => Array ( [0] => Array ( [name] => Delta Air Lines [code] => DL ) [1] => Array ( [name] => Emirates [code] => EK ) ) [bookingType] => WEBSITE [price] => Array ( [name] => [nameOTA] => [description] => [amount] => 28183 [totalAmount] => 28183 [pricePerPassenger] => 28183 [currencyCode] => EGP [totalPricePerPassenger] => 28183 [includesTax] => 1 ) [generatedDate] => 1380212804689 [providerId] => emirates.com [id] => EK928[CAI-DXB],EK203[DXB-JFK],DL6122[JFK-PHL]|DL3672[PHL-JFK],EK204[JFK-DXB],EK923[DXB-CAI] [originCountryCode] => EG [bookingCode] => 13600077139546083 [destinationCountryCode] => US [outboundInfo] => Array ( [aircraftTypes] => Array ( ) [departureTime] => 1380966900000 [layoverInMin] => 947 [flightNumbers] => Array ( [0] => EK928 [1] => EK203 [2] => DL6122 ) [durationInMin] => 2118 [airportsExpanded] => Array ( [0] => CAI [1] => DXB [2] => DXB [3] => JFK [4] => JFK [5] => PHL ) [localDepartureTimeStr] => 2013/10/05 11:55 +0200 [airports] => Array ( [0] => CAI [1] => DXB [2] => JFK [3] => PHL ) [arrivalTime] => 1381093980000 [numStops] => 2 [flightClasses] => Array ( [0] => Array ( [name] => Economy [fareClass] => 1 ) [1] => Array ( [name] => Economy [fareClass] => 1 ) [2] => Array ( [name] => Economy [fareClass] => 1 ) ) [localArrivalTimeStr] => 2013/10/06 16:13 -0500 ) ) ) A: To answer your questions: but it take more time..how to reduce this big time? Before you can reduce that you need to find out exactly where that more comes from. As you wrote in a comment, you are using a remote request to obtain the data. Sorting for array the data you've provided works extremely fast, so I would assume you don't need to optimize the array sorting but just the way when and how you get the data from remote. One way to do so is to cache that or to prefetch it or to do parallel processing. But the details so far are not important at all, unless you've found out where that more comes from so that it is clear what is responsible for big time so then it can be looked into reducing it. Hope this is helpful so far, and feel free to add the missing information to your question. You can see the array-only code in action here, it's really fast: * *https://eval.in/51770 You can find the execution stats just below the output, exemplary from there: OK (0.008 sec real, 0.006 sec wall, 14 MB, 99 syscalls) A: You should really install a profiler (XHProf) and check what exactly takes so much time. I assume it is the sorting, because foreach through the final array of 5 elements should be lighning fast. Why do you sort it then? If the sole purpose of sorting is to find 5 "lowest" items, then the fastest way would be to just find 5 lowest items: $min5 = array(); foreach ($flights_result->json_data['response']['itineraries'] as $key => $value) { $amount = $value['price']['totalAmount']; // Just put first 5 elements in our result array if(count($min5) < 5) { $min5[$key] = $amount; continue; } // Find largest element of those 5 we check $maxMinK = null; foreach($min5 as $minK=>$minV) { if($maxMinK === null) { $maxMinK = $minK; continue; } if($minV > $min5[$maxMinK]) { $maxMinK = $minK; } } // If our current amount is less than largest one found so far, // we should remove the largest one and store the current amount instead if($amount < $min5[$maxMinK]) { unset($min5[$maxMinK]); $min5[$key] = $amount; } } asort($min5); // now we can happily sort just those 5 lowest elements It will find 5 items with about O(6n) which in your case should better than potential O(n²) with sorting; Then you may just use it like: foreach($min5 as $key=>$minValue) { $intinerary = $flights_result->json_data['response']['itineraries'][$key] ... } This should be a lot faster, provided it was the sorting! so get that XHprof and check :) A: Here's what I would have done: <?php // Initialize html Array $html = array(); // Iterate Over Values, Using Key as Label. foreach( $value['inboundInfo'] as $inboundLabel => &$inboundValue ) { // Check for Special Cases While Adding to html Array if( $inboundLabel == 'flightNumbers' ) { $html[] = $inboundLabel . ': ' . implode( ', ', $inboundValue ); } elseif( $inboundLabel == 'flightClasses' ) { foreach( $inboundValue as $fcName => &$fcValue ) { $html[] = 'flightClasses ' . $fcName . ': ' . $fcValue; } } else { $html[] = $inboundLabel . ': ' . $inboundValue; } } // Don't Need Foreach to Complicate Things Here $html[] = 'carrier name: ' . $value[' carrier']['name']; $html[] = 'carrier code: ' . $value[' carrier']['code']; // Add Price Info to Array foreach( $value['price'] as $priceLabel => &$price ) { $html[] = $priceLabel . ': ' . $price; } $html[] = ' -------- </br>'; // And Finally: echo implode( "<br/>\r\n", $html ); It's either that or write a recursive function to go through all the data. Also note, this only works if your data is in the order you want. A: I would do the following things: // This is optional, it just makes the example more readable (IMO) $itineraries = $flights_result->json_data['response']['itineraries']; // Then this should sort in the smallest way possible foreach ($flights_result->json_data['response']['itineraries'] as $key => $value) { $mid[$key] = $value['price']['totalAmount']; } // Sort only one array keeping the key relationships. asort($mid); // Using the keys in mid, since they are the same as the keys in the itineraries // we can get directly to the data we need. foreach($mid AS $key => $value) { $value = $itineraries[$key]; // Then continue as above, I think your performance issue is the sort ... } A: Buffer echo/print (ie, do not echo/print from inside loop): $buffer = ""; for ($i = 0; $i < 1000; $i++) { $buffer .= "hello world\n"; } print($buffer); This is probably negligable in your case, but worth doing for larger iteration counts. You don't need to sort the entire array if you're only interested in the 5 lowest prices. Loop through the array while maintaining a list of the keys with the 5 lowest prices. I'm too rusty in PHP to effectively provide a sample. A: I see two potential areas slowing down the code: * *Sorting the array *Echoing + string concatenating all those strings I would first find out which area is causing the lag. If profiling is difficult, you can insert debugging print statements into your code with each statement print the current time. This will give you a rough idea, which area of code is taking bulk of the time. Something like: echo "Time at this point is " . date(); Once we have those results we can optimize further. A: Try this... $arr_fli = array(0 => array('f_name'=> 'Flight1', 'price' => 2000), 1 => array('f_name'=> 'Flight1', 'price' => 5000), 3 => array('f_name'=> 'Flight1', 'price' => 7000), 4 => array('f_name'=> 'Flight1', 'price' => 4000), 5 => array('f_name'=> 'Flight1', 'price' => 6000), 6 => array('f_name'=> 'Flight1', 'price' => 800), 7 => array('f_name'=> 'Flight1', 'price' => 1000), 8 => array('f_name'=> 'Flight1', 'price' => 500) ); foreach($arr_fli as $key=>$flights) { $fl_price[$flights['price']] = $flights; } sort($fl_price); $i = 0; foreach($fl_price as $final) { $i++; print_r($final); echo '<br />'; if($i==5) { break; } } A: The first thing to understand is which part of you code takes long to execute. A quick and dirty but simple way is to use your logger. Which I assume you are using already to log all your other information you want to keep as your code runs, such as memory usage, disc usage, user requests, purchases made etc. Your logger can be a highly sofisticated tool (just google for "loggin framework" or the likes) or as simple as message writer to your file. To get a quick start, you can using something like that: class Logger { private $_fileName; private $_lastTime; public function __construct ($fileName) { $this->_fileName = $fileName; $this->_lastTime = microtime(true); } public function logToFile ($message) { // open file for writing by appending your message to the end of the file $file = fopen($this->_fileName, 'a'); fwrite($file, $message . "\n"); fclose($file); } // optional for testing - see your logs quickly without bothering with files public function logToConsole($message) { echo $message; } // optional $message to add, e.g. about what happened in your code public function logTimePassed ($message = '') { $timePassed = microtime(true) - $this->_lastTime; //$this->logToConsole("Milliseconds Passed since last log: " . $timePassed . ", " . $message . "\n"); $this->logToFile("Milliseconds Passed since last log: " . $timePassed . ", " . $message . "\n"); // reset time $this->_lastTime = microtime(true); } } // before your code starts $myLogFileName = 'my-logs'; // or whatever the name of the file to write in $myLogger = new Logger($myLogFileName); // ... your code goes ... // after something interesting $myLogger->logTimePassed(); // log time since last logging // ... your code continues ... // after something else, adding a message for your record $myLogger->logTimePassed("after sorting my flight array"); Now you can go over your code and place your loggers at all crucial points after anything that may potentially take too long. Add your messages to know what happened. There can potentially be many places for delays. Usually array manipulations done in-memory are blazing fast. But more attention needs to be paid for more time consuming operations such as: * *File reading/ writing, directory access *Database access *HTTP requests For instance, http requests - are your echos being sent immediately to browser over a network? Are they being sent every time in the loop? If yes, you probably want to avoid it. Either save them into array as indicated by other answers, or use Output Buffering. Further to minimize http requests to your server, you can try to put more functions on the client side and use ajax to only retrieve what is really needed from the server. Also don't forget about things that are hidden. For instance, I see object property access: $flights_result->json_data How is this object implemented? Is it in-memory only? Does it call to outside services? If yes, that may be your culprit. Then you have to work on optimizing that. Reducing the number of queries by caching them, optimizing your data so you only need to query the changes, etc. All this depends on the structure of you application and may have nothing to do with the rest of your code. If you want any help on that, you obviously need to put this information in your question. Basically anything that is not done entirely in memory can cause delays. As for the in-memory operations, unless your data are huge or your operations are intense, their effect will likely be negligible. Still if you have any doubt, simply place your loggers at all "suspicious" places. Now to your specific code, it mixes all sort of things, such that outside object access, array value access, array sorting, echo outputs, maybe other things that are hidden. This makes it hard even to know where to place your time loggers. What would make it much easier, is to use object oriented approach and follow, among others, the Principle of Separating Concerns (google on that). That way your objects and their methods will have single responsibilities and you will easily see who does what and where to place your loggers. I can't highly enough recommend the legendary book by "Uncle Bob" to learn more about it. I presume your code comes from inside a function. According to Uncle Bob: The first rule of functions is that they should be small. The second rule is that they should be smaller than that. and Functions should do one thing. They should do it well. They should do it only. When splitting your code into more functions, you are forced to give those functions meaningful names that can greatly improve readability of your code. Needless to say, all functions not intended for use outside the class, should be private, so you can easily re-use your classes via inheritance. There is a lot that can be done, but just to get you started, here are some ideas: * *Encapsulate your data array into an object with methods only doing there what you need. Something like that: class Itineraries { private $_itineraryArray; public function __construct(array $itineraryArray) { $this->_itineraryArray = $itineraryArray; } public function getNCheapest ($number) { $this->_sortByPrice(); $result = array(); for ($i=0; $i< $number; $i++) { $result[] = $this->_itineraryArray[$i]; } return $result; } private function _sortByPrice() { $prices = $this->_getPriceArray(); array_multisort($prices, SORT_ASC, $this->_itineraryArray); } private function _getPriceArray () { foreach ($this->_itineraryArray as $entry) { $this->_getPrice($entry); } } private function _getPrice($entry) { return $entry['price']['totalAmount']; // or whatever it is } } //Then you instantiate your object: $myItineraries = new Itineraries($flights_result->json_data['response']['itineraries']); // or whatever Notice that should your array structure completely change, you'll only need to adjust the method _getPrice and the single line to instantiate your object! The rest of your code will remain intact! This is a part of your Model Layer in the Model-View-Controller paradigm. You can google on that to find lots of information. The model knows how to handle its data but knows nothing about the source of them, no browser output, no http requests etc. * *Then everything responsible for generating user output goes into your View Layer or into so-called Presenter Layer, where you have other objects dealing with it. All your 'echo's will go here. Something like that: class Presenter { public function outputNCheapest ($myItineraries, $number) { $outputData = $myItineraries->getNCheapest ($number); echo $this->generateOutput($outputData); } private function _generateOutput($outputData) { $html = ''; // your html string is generated return $html; } } However, I am personally against generating HTML on the server. It is just a waste of bandwidth and the time of your users waiting for response. Every time I am waiting for my browser to reload the whole page, I want the developer to read this. You can output JSON instead of HTML and request it with ajax or via other ways on the client side. Furthermore, your user's browser can cache some of the data instead of requesting them again, and decide what to ask for. That will further minimize the delay for your users, which at the end of the day is precisely what you are concerned with.
{ "language": "en", "url": "https://stackoverflow.com/questions/19033833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Prevent datepicker from triggering parent mouseleave I display an absolute div with a jQuery $.animate({height: 'toggle', opacity: 'toggle'}) on a jQuery $.hover(). I have a jQuery UI datepicker attached to a div within the aforementioned absolute div with changeMonth: true and changeYear: true. When a month or year are changed or a date is selected the animation fires. How can I prevent the month/year change & date selection from triggering the $.hover()? http://jsfiddle.net/e3zP2/ html <div id="hoverAnchor">hover me</div> <div id="hoverMe" style="display:none"> arbitrary text <div id="dateSelector"></div> </div> js $(document).ready(function () { $("#dateSelector").datepicker({ changeMonth: true, changeYear: true }); $("#hoverAnchor").add($("#hoverMe")).hover(function(){ $("#hoverMe").stop(true,false).animate({ height: 'toggle', opacity: 'toggle' }, 200); }); }); A: You need to do a couple things in order for this to work properly. First, you need to wrap the HTML in a div to act as the container: HTML: <div id="container"> <div id="hoverAnchor">hover me</div> <div id="hoverMe" style="display:none">arbitrary text <div id="dateSelector"></div> </div> </div> Next, rather than using .hover() (which can sometimes be unreliable), I recommend using .mouseenter() along with .mouseleave(). Also use a var to hold boolean of whether datepicker open/closed. The reason for this boolean is due to the input. On click, a second .mouseenter() event will be called, so without it, #hoverme would toggle a second time. $(document).ready(function () { $("#dateSelector").datepicker({ changeMonth: true, changeYear: true }); var _enter = false; $("#container").add( $("#container")).mouseenter(function () { if (!_enter) { $("#hoverMe").stop(true, false).animate({ height: 'toggle', opacity: 'toggle' }, 200); } _enter = true; }).mouseleave(function () { _enter = false; $("#hoverMe").stop(true, false).animate({ height: 'toggle', opacity: 'toggle' }, 200); }); }); DEMO: http://jsfiddle.net/dirtyd77/e3zP2/18/ Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/16195454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Accessing React Function in Meteor I have : addW () { code code } render () { return ( html code html code <button onClick={this.addW}>Add</button> ) } For some reason, I get an error : this.addW is not a function. Why is it not finding the function above? TY! A: Maybe you are missing a "" return "<button onClick={this.addW}>Add</button>" A: I've determined that I need to '.bind(this)' <button onClick={this.addW.bind(this)}>Add</button> It would help for someone to help explain this.
{ "language": "en", "url": "https://stackoverflow.com/questions/36586792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I use out from Jquery as variable for php Query I have this code below which display the item that has been clicked using Jquery <html> <head> <?php include('config/js.php');?> </head> <body> <div id="target"> <h4>Hydraulics</h4> <ul> <li><a href="#">Bikes</a></li> <li><a href="#">Utes</a></li> <li><a href="#">cars</a></li> <li><a href="#">Trucks</a></li> </ul> </div> <body> <script> $('#target li').click(function() { var text = $(this).text(); alert('Text is ' + text); }); </script> </html> Is there a way I can use this output as a variable for php query something like below so that I can use '$var' instead of 'Trucks'; <?php $q = "SELECT subgroup FROM jqm_categories WHERE name = 'Trucks' "; $r = mysqli_query($dbc, $q); While($list = mysqli_fetch_assoc($r)) {?> <a href="#" class="catag"><?php echo $list['subgroup'].'<br/>';?></a> <?php } ?> A: In the javascript put $.get("http://example.com/foo.php?name=" + text); instead of the alert and in the php use: mysql_real_escape_string($_GET['name']) instead of Trucks.
{ "language": "en", "url": "https://stackoverflow.com/questions/34748634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Putting a CGImageRef on the clipboard I'm trying to copy a CGImageRef to the clipboard pasteboard. I found a function that claims it should do this by creating a destination from (zero sized), adding the image to the destination, finalizing, then PasteboardPutItemFlavor the ref into the clipboard. However it doesn't work, so two questions: * *Is this the correct way to go about this? (ie, is there just a small bug, or am I doing it wrong?) *What type should I make the destination? The source had it as TIFF, but word doesn't seem to know how to deal with that, I changed it to PICT, which at least gave me the "paste" option, but then said it was too big... Code: void copyCGImageRefToPasteboard(CGImageRef ref) { OSStatus err = noErr; PasteboardRef theClipboard; err = PasteboardCreate( kPasteboardClipboard, &theClipboard ); err = PasteboardClear( theClipboard );// 1 CFMutableDataRef url = CFDataCreateMutable(kCFAllocatorDefault, 0); CFStringRef type = kUTTypePICT; size_t count = 1; CFDictionaryRef options = NULL; CGImageDestinationRef dest = CGImageDestinationCreateWithData(url, type, count, options); CGImageDestinationAddImage(dest, ref, NULL); CGImageDestinationFinalize(dest); err = PasteboardPutItemFlavor( theClipboard, (PasteboardItemID)1, type, url, 0 ); } A: Enter "The Cupertino Tongue Twister" by James Dempsey Peter put a PICT upon the pasteboard. Deprecated PICT's a poor pasteboard type to pick. For reference see: http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/PasteboardGuide106/Articles/pbUpdating105.html In short: it's deprecated to put PICT on the pasteboard. A: Ok, I'm answering my own question here, but here's what I've found: Apple wants you to use PDF for pasteboards. So if you swap out Pict with PDF, it pretty muc just works. However, MS Word (what I was testing with) only started to allow pasting of PDF in the newest version (Which I don't have). So, that's the solution, use PDF, and require Word 2008.
{ "language": "en", "url": "https://stackoverflow.com/questions/462982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I assign the result of iPython profiler %%prun -r to a variable? In the docs of the iPython magic functions it says: Usage, in cell mode: %%prun [options] [statement] code... code... In cell mode, the additional code lines are appended to the (possibly empty) statement in the first line. Cell mode allows you to easily profile multiline blocks without having to put them in a separate function. Options: -r return the pstats.Stats object generated by the profiling. This object has all the information about the profile in it, and you can later use it for further analysis or in other functions. But it doesn't give any examples of how to use the -r option. How do I associate the pstats.Stats object to a variable? using the cell profiler? edit: This is not a duplicate because I specifically ask about cell mode, the other questions are about line magic functions. Thomas K answers my question by saying it is not possible. That should be allowed as an answer to my question here which is not an answer to the other questions. A: Unfortunately there is not a way to capture a returned value from a cell magic. With a line magic you can do: a = %prun -r ... But cell magics have to start at the beginning of the cell, with nothing before them.
{ "language": "en", "url": "https://stackoverflow.com/questions/36773106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating a new MailAddress produces "The specified string is not in the form required for an e-mail address", although it is in the correct format I am trying to create a new MailAddress, the email is coming from Request Parameters, that is: Request.Params("fromEmail"). It is actually being sent from an android device through an http request. When I try to create a new MailAddress from this email, I get the error "The specified string is not in the form required for an e-mail address". When trying to create it directly, that it ma=new MailAddress("[email protected]") using the same coming string, it works, but creating it using ma=new MailAddress(Convert.ToString(Request.Params("fromEmail")) produces the error. I suspect there are some special caharacters being sent and making the email format unrecognizable, how can this be fixed Thanks A: Either you have an encoding problem, or a non-printing character in the parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7670787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Simple str_replace() making things wrong - WordPress I need some special filtering to certain text all over my website, like below: function special_text( $content ) { $search_for = 'specialtext'; $replace_with = '<span class="special-text"><strong>special</strong>text</span>'; return str_replace( $search_for, $replace_with, $content ); } add_filter('the_content', 'special_text', 99); It's doing thing in an excellent way, BUT... in content if there's any link like: <a title="specialtext" href="http://specialtext.com">specialtext</a> then the title and href texts also changed and the link becomes broken. How can I make exception there? Is there a way I can put some exceptions in an array and str_replace() simply skip 'em? A: You should use regular expression and use function preg_replace() to replace matched string. Here is the full implementation of your special_text() function. function special_text( $content ) { $search_for = 'specialtext'; $replace_with = '<span class="special-text"><strong>special</strong>text</span>'; return preg_replace( '/<a.*?>(*SKIP)(*F)|'.$search_for.'/m', $replace_with, $content ); } In the following regular expression first, using <a.*?> - everything between <a...> is matched and using (*SKIP)(*F)| it is skipped and then from anything else $search_for is matched (in your case it's specialtext). A: Jezzabeanz quite got it except you can simplify it still with: return preg_replace("/^def/", $replace_with, $content); A: If you just want to change the text between the the a tags then a regular expression works wonders. Here is something I used when I was pulling data from emails sent to me: (?<=">)(.*?\w)(?=<\/a) returns "specialtext" It also returns "specialtext test" if there is whitespace. Regular expressions are definitely the way to go. $subject = "abcdef"; $pattern = '/^def/'; preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3); print_r($matches); ?> Source And then do a replace on the returned matches.
{ "language": "en", "url": "https://stackoverflow.com/questions/24942355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: loading styles from remote json file - React Native I am trying to use styles / colors from a JSON file that exist on a server, so I am using useEffect function to load the style variable and pass them to stylesheet. But issue is fetching data from remote file takes some time and stylesheet doesn't load styles. var themeStyle2 = []; const themeStyleOnline = "https://someremote.server/theme.json"; export default function HomeScreen({ navigation }) { useEffect(() => { fetch(themeStyleOnline) .then((response) => response.json()) .then((json) => themeStyle2 = json) .catch((error) => alert(error)).finally(() => { console.log("THEME STYLE >>>>>>>>>> " + themeStyle2.cardbg); }); }) } const styles = StyleSheet.create({ container: { backgroundColor: themeStyle2.background, //style won't load }, }) Above code doesn't load style because remotely loading style variables takes some time. Then I tried following method. const themeStyleOnline = "https://someremote.server/theme.json"; export default function HomeScreen({ navigation }) { const [themeStyle2, setThemeStyle] = useState([]); useEffect(() => { fetch(themeStyleOnline) .then((response) => response.json()) .then((json) => setThemeStyle(json)) .catch((error) => alert(error)).finally(() => { console.log("THEME STYLE >>>>>>>>>> " + themeStyle2.cardbg); }); }) } const styles = StyleSheet.create({ container: { backgroundColor: themeStyle2.background, //This Gives error themeStyle2 not found }, }) What is correct way to achieve this? Following is JSON I am trying to load. { "statusbar":"#7209b7", "header":"#560bad", "headertext":"#fffffc", "background":"#001219", "cardbg":"#ffba08", "titlebg":"#3f37c9", "titletext":"#fffffc" } A: You can’t access the theme state variable from the global scope where you are using it. I.e. the Stylesheet.create method call. You can just use the themeState in the components instead of calling in the StyleSheet.create call.
{ "language": "en", "url": "https://stackoverflow.com/questions/69448632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: leanModel ajax call Hi how i can render a different form using leanModel dialog box? Currently this is how the lean model works: <a id="go" rel="privateMsg" name="signup" href="#signup">With Close Button</a> <div id="signup" style="display: none; position: relative; opacity: 1; z-index: 11000; left: 50%; margin-left: -202px; top: 200px;"> <div id="signup-ct"> <div id="signup-header"> <h2>Create a new account</h2> <p>It's simple, and free.</p> <a class="modal_close" href="#"></a> </div> <form action=""> <div class="txt-fld"> <label for="">Username</label> <input id="" class="" name="" type="text"> </div> <div class="txt-fld"> <label for="">Email address</label> <input id="" name="" type="text"> </div> <div class="txt-fld"> <label for="">Password</label> <input id="" name="" type="text"> </div> <div class="btn-fld"> <a href="#" class="close">Cancel</a> <button type="submit">Sign Up</button> </div> </form> </div> </div> $(function() { $('a[rel*=privateMsg]').leanModal({ top : 100, closeButton: ".modal_close,.close" }); }); The leanModel js is as follows : (function($){ $.fn.extend({ leanModal:function(options){ var defaults={top:100,overlay:0.5,closeButton:null}; var overlay=$("<div id='lean_overlay'></div>"); $("body").append(overlay); options=$.extend(defaults,options); return this.each(function(){ var o=options; $(this).click(function(e){ var modal_id=$(this).attr("href"); $("#lean_overlay").click(function(){ close_modal(modal_id) }); $(o.closeButton).click(function(){ close_modal(modal_id); }); var modal_height=$(modal_id).outerHeight(); var modal_width=$(modal_id).outerWidth(); $("#lean_overlay").css({"display":"block",opacity:0}); $("#lean_overlay").fadeTo(200,o.overlay); $(modal_id).css({"display":"block","position":"fixed","opacity":0,"z-index":11000,"left":50+"%","margin-left":-(modal_width/2)+"px","top":"100px"}); $(modal_id).fadeTo(200,1);e.preventDefault() }); }); function close_modal(modal_id){ $("#lean_overlay").fadeOut(200);$(modal_id).css({"display":"none"}) } } }); })(jQuery); How i can improve this code so that i can open a dialog box just for any form? Also if i would like to load signup div from ajax how can i do so? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/14189219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Q Network Access manager in pyQt Python (Segmentation Fault Core Dumped) i have developed an application using pyQt in python and using a web browser and a table to show the headers coming with the browser request. here is my code:- import sys from PyQt4.QtGui import QApplication, QTableWidget, QTableWidgetItem from PyQt4.QtCore import QUrl from PyQt4.QtWebKit import QWebView, QWebPage from PyQt4.QtGui import QGridLayout, QLineEdit, QWidget, QHeaderView from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest class RequestsTable(QTableWidget): header = ["url", "status", "content-type","cookies","user_agent"] def __init__(self): super(RequestsTable, self).__init__() self.setColumnCount(5) self.setHorizontalHeaderLabels(self.header) header = self.horizontalHeader() header.setStretchLastSection(True) def update(self, data): last_row = self.rowCount() next_row = last_row + 1 self.setRowCount(next_row) for col, dat in enumerate(data, 0): if not dat: continue self.setItem(last_row, col, QTableWidgetItem(dat)) class Manager(QNetworkAccessManager): def __init__(self, table): QNetworkAccessManager.__init__(self) self.finished.connect(self._finished) self.table = table def _finished(self, reply): user_agent = str(reply.request().rawHeader("User-Agent")) headers = reply.rawHeaderPairs() headers = {str(k):str(v) for k,v in headers} content_type = headers.get("Content-Type") url = reply.url().toString() status = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) status, ok = status.toInt() cookies = headers.get("Set-Cookie") self.table.update([url, str(status), content_type,cookies,user_agent]) if __name__ == "__main__": app = QApplication(sys.argv) grid = QGridLayout() browser = QWebView() browser.load(QUrl("http://www.indiatimes.com/")) def on_html_available(): page = QWebPage() page.setNetworkAccessManager(manager) # problem is here browser.setPage(page) # if i dont use above line then it don't show any error but the headers don't get append in the table but if i use the above line it shows me the error segmentation fault browser.loadFinished.connect(on_html_available) requests_table = RequestsTable() manager = Manager(requests_table) grid.addWidget(browser, 3, 0) grid.addWidget(requests_table, 4, 0) main_frame = QWidget() main_frame.setLayout(grid) main_frame.show() sys.exit(app.exec_()) but the above code is showing me the error "core dumped segmentation fault"? what may be the problem ? please help me in resolving this issue. A: Its showing this error because you are again setting the browser's page on html finished, which is wrong, to access network access manager you should first take the manager then set the manager with page and then set the browser page. let me know if you don't get this.
{ "language": "en", "url": "https://stackoverflow.com/questions/37018084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use getJSON sending data from prompt var to PHP? I Created a button that when onclick he delivering a prompt message in order The user will enter a free text. Now I need to use this free text and pass it as var input with GET method to external PHP in my system. I have tried using the getJSON method to do the following : '<button onclick="SendFreeMSG()">Test MSG </button> <p id="testMSG"></p> <script> function SendFreeMSG() { var InputMessage= prompt("Please enter your Message", "Write down your message Here"); if (InputMessage!= null) { document.getElementById("testMSG").innerHTML = "Your message is: " + InputMessage + " " ; $.getJSON("sending_msg_to_user.php?userinput=" . $InputMessage ["userinput"] . } } </script>' ; The scrpit is working fine without the getJSON row, but when I tried it with that row nothing happen. ----- Addition ---- Here is another part of my code with click button and $getJSON In this part it is working well: '<button onclick="' . "if (confirm('sending message ?')) { var activeValue = $(this).siblings('.all_users_active_value');" . "var activeCaption = $(this).siblings('.all_users_active_caption');" . "$.getJSON('sending_general_msg.php?General=" . $rowData['General'] . "&active=' + (activeValue.html() == '1' ? '0' : '1'), " . "function(data) { " . "activeValue.html(data.active);" . "activeCaption.html(data.active == 1 ? 'Active' : 'Inactive')" . "}) } else { alert('sending message cancelled') };" . "return false;". '"> Sending new message </button>'; I will appreciate any help with that matter Abraham A: You need to use ajax to send sometime from java to a php file. below is a tutorial on how to use ajax. http://www.w3schools.com/ajax/ A: If you need to pass the input value to another php, you must to use Ajax in jQuery, I hope this example will help you $.ajax({ type:"get", url:"sending_msg_to_user.php", data:"InputMessage="+InputMessage, beforeSend: function(){ $('#some_div').html('<img src="img/Loading.gif"/> Sending Data'); }, success:function(data){ alert(data); $('#some_div').html(''); } }); If you have an echo in sending_msg_to_user.php you could see in an alert message tha value of inpu in prompt A: Your $.getJSON request is poorly formed. If you paste that function directly into your favorite JavaScript console and hit 'enter', you would see the error: Uncaught SyntaxError: Unexpected token } at Object.InjectedScript._evaluateOn (<anonymous>:905:140) at Object.InjectedScript._evaluateAndWrap (<anonymous>:838:34) at Object.InjectedScript.evaluate (<anonymous>:694:21) Try something like: $.getJSON('sending_msg_to_user.php?userinput=' + InputMessage);
{ "language": "en", "url": "https://stackoverflow.com/questions/31947897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why do I need getPointResolution when creating circle polygons in Openlayers? So I saw an example of creating a polygon circle to scale. That is the actual distance from the point of interest to the how far the radius is. map.on('postrender', function (event) { const { projection, resolution, center, } = event.frameState.viewState; pointResolution = getPointResolution(projection.getCode(), resolution, center); }); Is it necessary to do this var newradius = radius / pointResolution because this does not give me the right distance in meters. It actually divides it. I don't know if this makes sense. function addCirclePolygon(coordinates) { if (vectorSource && vectorSource.getFeatures().length > 0) { vectorSource.clear(); } var radius = $scope.options.radius; if (createPolygon) { **var radius = radius / pointResolution;** <---problem circle = new Feature(new Circle(coordinates, radius)); circle.setStyle(new Style({ stroke: new Stroke({ color: $scope.options.lcolor, width: $scope.options.lwidth }), fill: new Fill({ color: $scope.options.fcolor ? $scope.options.fcolor : 'rgba(255, 255, 255, 0.0)' }) })); var geom = circle.get('geometry'); if (circle instanceof Circle) { // We don't like circles, at all. So here we convert // drawn circles to their equivalent polygons. circle.set('geometry', fromCircle(geom)); } vectorSource.addFeature(circle); /** * Adds a line to show the radius in Units(meters as default) * Leaving this here for prosterity */ if (circle) { let line = addRadius(circle); vectorSource.addFeature(line); } } } A: tldr; You don't need getPointResolution to create circle polygons. You can use geom.Polygon.circular to create the blue circle which has the correct radius. new ol.geom.Polygon.circular([lng, lat], radius); You will need to divide the radius by the resolution if you plan to create a circle (green) or create a polygon.fromCircle (red). https://codepen.io/dbauszus-glx/pen/LYmjZvP
{ "language": "en", "url": "https://stackoverflow.com/questions/65887948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google genomics bigQuery difference tables data description I would like read all the calls in a specific region of the genome. regardless of the genotype (equal to the reference genome or alternate, coding or non coding region). Assuming that all genome was sequenced. Which of the following tables should I look at? I am using Google BigQuery genomics data and need explanation on the differences between the following files extensions: *.genome_calls *.variants *.multisample_variants *.single_sample_genome_calls Many thanks, Eila A: genome_calls - all genomic calls - not only variants. might have calls with low quality multisample_variants - variants by samples - where each variant will have all the samples that harbor this mutation in one variant row single_sample_genome_calls - variants by samples matrix. Variants that exists in multiple samples will have a row per sample
{ "language": "en", "url": "https://stackoverflow.com/questions/47678942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 301 redirect to a php redirect - bad for SEO? So my company has a huge website with over 7000 static pages. I have been tasked with creating a new website and attempting to account for all of the content. One way in which I've been able to do that, is by using a hash in the url to direct an AJAX call to pull content in dynamically. While this has effectively been able to eliminate many of the pages, I've been concerned with losing the site's SEO rankings, hence: redirects. Since the new URL's have the potential to become complex (not to mention they all have a hash symbol in them), I came across one user's answer on here on how one might implement a 301 to point to a "redirector.php" and then create a php formula to point the user to the final destination. (https://stackoverflow.com/a/1279955/2005787) This method has been working beautifully, however, my main concern is that by redirecting someone to a "redirector.php" file, you are losing all of your SEO rankings, since the final location is two steps removed from the original address. So first, can I implement the "redirector.php" method without destroying my SEO rankings? Second, if the "redirector.php" method does, in fact, hurt my rankings, then is there an alternative way to generate complicated redirects? Thank you! A: Ideally you would just have one redirect. Though Google will follow more than one and suggests 2. Maximum 3. So you could be okay with your plan. https://youtu.be/r1lVPrYoBkA
{ "language": "en", "url": "https://stackoverflow.com/questions/31035904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: cuda nppiResize() for RGB images nVidia Cuda nppiResize_32f_C1R works OK on grayscale 1 x 32f, but nppiResize_32f_C3R returns garbage. Clearly, a work around would be to call this routine 3 times by first de-interleaving the data as planar R, G, B, but I was expecting to be able to run it through in a single pass. nVidia has a lot of example code for single plane image processing, but a scant amount for interleaved color planes, so I'm turning to stackoverflow for help. I don't know how the stride is computed, but I understand that the stride is the image width times the number of bytes per column index. So in my case - with no padded lines - it should be width 32f x 3 for RGB. Tried different strides/pitches in cudaMemcpy2D(). Can't get a workable solution for the color RGB code. Compiles & runs OK, no errors. The first section is for Grayscale (works OK). The second section is RGB (garbage). // nppiResize using 2D aligned allocations #include <Exceptions.h> #include <cuda_runtime.h> #include <npp.h> #include <nppi.h> #include <nppdefs.h> #define CUDA_CALL(call) do { cudaError_t cuda_error = call; if(cuda_error != cudaSuccess) { std::cerr << "CUDA Error: " << cudaGetErrorString(cuda_error) << ", " << __FILE__ << ", line " << __LINE__ << std::endl; return(NULL);} } while(0) float* decimate_cuda(float* readbuff, uint32_t nSrcH, uint32_t nSrcW, uint32_t nDstH, uint32_t nDstW, uint8_t byteperpixel) { if (byteperpixel == 1){ // source : Grayscale, 1 x 32f size_t srcStep; size_t dstStep; NppiSize oSrcSize = {nSrcW, nSrcH}; NppiRect oSrcROI = {0, 0, nSrcW, nSrcH}; float *devSrc; CUDA_CALL(cudaMallocPitch((void**)&devSrc, &srcStep, nSrcW * sizeof(float), nSrcH)); CUDA_CALL(cudaMemcpy2D((void**)devSrc, srcStep,(void**)readbuff, nSrcW * sizeof(Npp32f), nSrcW * sizeof(Npp32f), nSrcH, cudaMemcpyHostToDevice)); NppiSize oDstSize = {nDstW, nDstH}; NppiRect oDstROI = {0, 0, nDstW, nDstH}; float *devDst; CUDA_CALL(cudaMallocPitch((void**)&devDst, &dstStep, nDstW * sizeof(float), nDstH)); NppStatus result = nppiResize_32f_C1R(devSrc,srcStep,oSrcSize,oSrcROI,devDst,dstStep,oDstSize,oDstROI,NPPI_INTER_SUPER); if (result != NPP_SUCCESS) { std::cerr << "Unable to run decimate_cuda, error " << result << std::endl; } Npp64s writesize; Npp32f *hostDst; writesize = (Npp64s) nDstW * nDstH; // Y if(NULL == (hostDst = (Npp32f *)malloc(writesize * sizeof(Npp32f)))){ printf("Error : Unable to alloctae hostDst in decimate_cuda, exiting...\n"); exit(1); } CUDA_CALL(cudaMemcpy2D(hostDst, nDstW * sizeof(Npp32f),(void**)devDst, dstStep, nDstW * sizeof(Npp32f),nDstH, cudaMemcpyDeviceToHost)); CUDA_CALL(cudaFree(devSrc)); CUDA_CALL(cudaFree(devDst)); return(hostDst); } // source : Grayscale 1 x 32f, YYYY... else if (byteperpixel == 3){ // source : 3 x 32f interleaved RGBRGBRGB... size_t srcStep; size_t dstStep; // rows = height; columns = width NppiSize oSrcSize = {nSrcW, nSrcH}; NppiRect oSrcROI = {0, 0, nSrcW, nSrcH}; float *devSrc; CUDA_CALL(cudaMallocPitch((void**)&devSrc, &srcStep, 3 * nSrcW * sizeof(float), nSrcH)); CUDA_CALL(cudaMemcpy2D((void**)devSrc, srcStep, (void**)readbuff, 3 * nSrcW * sizeof(Npp32f), nSrcW * sizeof(Npp32f), nSrcH, cudaMemcpyHostToDevice)); NppiSize oDstSize = {nDstW, nDstH}; NppiRect oDstROI = {0, 0, nDstW, nDstH}; float *devDst; CUDA_CALL(cudaMallocPitch((void**)&devDst, &dstStep, 3 * nDstW * sizeof(float), nDstH)); NppStatus result = nppiResize_32f_C3R((devSrc,srcStep,oSrcSize,oSrcROI,devDst,dstStep,oDstSize,oDstROI,NPPI_INTER_SUPER); if (result != NPP_SUCCESS) { std::cerr << "Unable to run decimate_cuda, error " << result << std::endl; } Npp64s writesize; Npp32f *hostDst; writesize = (Npp64s) nDstW * nDstH * 3; // RGB if(NULL == (hostDst = (Npp32f *)malloc(writesize * sizeof(Npp32f)))){ printf("Error : Unable to alloctae hostDst in decimate_cuda, exiting...\n"); exit(1); } CUDA_CALL(cudaMemcpy2D((void**)hostDst, nDstW * sizeof(Npp32f), (void**)devDst, dstStep, nDstW * sizeof(Npp32f),nDstH, cudaMemcpyDeviceToHost)); CUDA_CALL(cudaFree(devSrc)); CUDA_CALL(cudaFree(devDst)); return(hostDst); } // source - 3 x 32f, interleaved RGBRGBRGB... return(0); } A: You had various errors in your calls to cudaMemcpy2D (both of them, in the 3 channel code). This code seems to work for me: $ cat t1521.cu #include <cuda_runtime.h> #include <npp.h> #include <nppi.h> #include <nppdefs.h> #include <iostream> #include <stdint.h> #include <stdio.h> #define CUDA_CALL(call) do { cudaError_t cuda_error = call; if(cuda_error != cudaSuccess) { std::cerr << "CUDA Error: " << cudaGetErrorString(cuda_error) << ", " << __FILE__ << ", line " << __LINE__ << std::endl; return(NULL);} } while(0) using namespace std; float* decimate_cuda(float* readbuff, uint32_t nSrcH, uint32_t nSrcW, uint32_t nDstH, uint32_t nDstW, uint8_t byteperpixel) { if (byteperpixel == 1){ // source : Grayscale, 1 x 32f size_t srcStep; size_t dstStep; NppiSize oSrcSize = {nSrcW, nSrcH}; NppiRect oSrcROI = {0, 0, nSrcW, nSrcH}; float *devSrc; CUDA_CALL(cudaMallocPitch((void**)&devSrc, &srcStep, nSrcW * sizeof(float), nSrcH)); CUDA_CALL(cudaMemcpy2D(devSrc, srcStep,readbuff, nSrcW * sizeof(Npp32f), nSrcW * sizeof(Npp32f), nSrcH, cudaMemcpyHostToDevice)); NppiSize oDstSize = {nDstW, nDstH}; NppiRect oDstROI = {0, 0, nDstW, nDstH}; float *devDst; CUDA_CALL(cudaMallocPitch((void**)&devDst, &dstStep, nDstW * sizeof(float), nDstH)); NppStatus result = nppiResize_32f_C1R(devSrc,srcStep,oSrcSize,oSrcROI,devDst,dstStep,oDstSize,oDstROI,NPPI_INTER_SUPER); if (result != NPP_SUCCESS) { std::cerr << "Unable to run decimate_cuda, error " << result << std::endl; } Npp64s writesize; Npp32f *hostDst; writesize = (Npp64s) nDstW * nDstH; // Y if(NULL == (hostDst = (Npp32f *)malloc(writesize * sizeof(Npp32f)))){ printf("Error : Unable to alloctae hostDst in decimate_cuda, exiting...\n"); exit(1); } CUDA_CALL(cudaMemcpy2D(hostDst, nDstW * sizeof(Npp32f),devDst, dstStep, nDstW * sizeof(Npp32f),nDstH, cudaMemcpyDeviceToHost)); CUDA_CALL(cudaFree(devSrc)); CUDA_CALL(cudaFree(devDst)); return(hostDst); } // source : Grayscale 1 x 32f, YYYY... else if (byteperpixel == 3){ // source : 3 x 32f interleaved RGBRGBRGB... size_t srcStep; size_t dstStep; // rows = height; columns = width NppiSize oSrcSize = {nSrcW, nSrcH}; NppiRect oSrcROI = {0, 0, nSrcW, nSrcH}; float *devSrc; CUDA_CALL(cudaMallocPitch((void**)&devSrc, &srcStep, 3 * nSrcW * sizeof(float), nSrcH)); CUDA_CALL(cudaMemcpy2D(devSrc, srcStep,readbuff, 3 * nSrcW * sizeof(Npp32f), 3*nSrcW * sizeof(Npp32f), nSrcH, cudaMemcpyHostToDevice)); NppiSize oDstSize = {nDstW, nDstH}; NppiRect oDstROI = {0, 0, nDstW, nDstH}; float *devDst; CUDA_CALL(cudaMallocPitch((void**)&devDst, &dstStep, 3 * nDstW * sizeof(float), nDstH)); NppStatus result = nppiResize_32f_C3R(devSrc,srcStep,oSrcSize,oSrcROI,devDst,dstStep,oDstSize,oDstROI,NPPI_INTER_SUPER); if (result != NPP_SUCCESS) { std::cerr << "Unable to run decimate_cuda, error " << result << std::endl; } Npp64s writesize; Npp32f *hostDst; writesize = (Npp64s) nDstW * nDstH * 3; // RGB if(NULL == (hostDst = (Npp32f *)malloc(writesize * sizeof(Npp32f)))){ printf("Error : Unable to alloctae hostDst in decimate_cuda, exiting...\n"); exit(1); } CUDA_CALL(cudaMemcpy2D(hostDst, nDstW*3 * sizeof(Npp32f), devDst, dstStep, nDstW*3 * sizeof(Npp32f),nDstH, cudaMemcpyDeviceToHost)); CUDA_CALL(cudaFree(devSrc)); CUDA_CALL(cudaFree(devDst)); return(hostDst); } // source - 3 x 32f, interleaved RGBRGBRGB... return(0); } int main(){ uint32_t nSrcH = 480; uint32_t nSrcW = 640; uint8_t byteperpixel = 3; float *readbuff = (float *)malloc(nSrcW*nSrcH*byteperpixel*sizeof(float)); for (int i = 0; i < nSrcH*nSrcW; i++){ readbuff [i*3+0] = 1.0f; readbuff [i*3+1] = 2.0f; readbuff [i*3+2] = 3.0f;} uint32_t nDstW = nSrcW/2; uint32_t nDstH = nSrcH/2; float *res = decimate_cuda(readbuff, nSrcH, nSrcW, nDstH, nDstW, byteperpixel); for (int i = 0; i < nDstH*nDstW*byteperpixel; i++) if (res[i] != ((i%3)+1.0f)) {std::cout << "error at: " << i << std::endl; return 0;} return 0; } $ nvcc -o t1521 t1521.cu -lnppig $ cuda-memcheck ./t1521 ========= CUDA-MEMCHECK ========= ERROR SUMMARY: 0 errors $ In the future, its convenient if you provide a complete code, just as I have done in my answer. In fact SO requires this, see item 1 here. By the way, the use of pitched allocations on the device, here, which introduce complexity that you were not able to work your way through, should really be unnecessary both for correctness and performance, using any modern GPU and CUDA version. Ordinary linear/flat allocations, where pitch==width, should be just fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/58159930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python Start & stop a continous function with Gtk Switch I have a issue where I want a Gtk.Switch to start and stop a function. This function should work as long as the switch is active. For example it could just print "Function is on" as long as switch is active. But unless I thread this function it will freeze GUI and it won't be possible to stop it. ### Gtk Gui ### self.sw = Gtk.Switch() self.sw.connect("notify::active", self.on_sw_activated) ### Gtk Gui ### ### Function ### def on_sw_activated(self, switch, gparam): if switch.get_active(): state = "on" else: state = "off" ### This needs to be "threaded" as to not freeze GUI while state == "on": print("Function is on") time.sleep(2) else: print("Function is off") ### Function ### As far as I know there is no good way to stop a thread in python, my question is if there is another way of implementing this without using python threads. A: Try this code: #!/usr/bin/env python import gi gi.require_version ('Gtk', '3.0') from gi.repository import Gtk, GdkPixbuf, Gdk, GLib import os, sys, time class GUI: def __init__(self): window = Gtk.Window() self.switch = Gtk.Switch() window.add(self.switch) window.show_all() self.switch.connect('state-set', self.switch_activate) window.connect('destroy', self.on_window_destroy ) def on_window_destroy(self, window): Gtk.main_quit() def switch_activate (self, switch, boolean): if switch.get_active() == True: GLib.timeout_add(200, self.switch_loop) def switch_loop(self): print time.time() return self.switch.get_active() #return True to loop; False to stop def main(): app = GUI() Gtk.main() if __name__ == "__main__": sys.exit(main())
{ "language": "en", "url": "https://stackoverflow.com/questions/45899107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WCF Authentication with ClientCredentials error I am trying to connect to a WCF service but when I do I get this error: The HTTP Request is unauthorized with client authetication scheme 'Anonymous'. The authentication header received from the server was 'Basic realm="ServiceGateway"'. I know I do authentication as I set the client credentials on my WCF client: new wcfClient(enpointconfigurationName, url) { ClientCredentials = { UserName = { UserName = "yyy", Password = "zzz" } } } Edit I have this WCF configuration in the web.config: <client> <endpoint address="xxx" binding="basicHttpBinding" bindingconfiguration="myBinding" contract="yyy" name="myName" /> </client> <basichttpbinding> <binding name="myBinding" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:01:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basichttpbinding> A: Config needs to be modified to use this in the binding: <security mode="TransportCredentialOnly"> <transport clientCredentialType="Basic" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> EDIT The reason it works is because that eventhough the UserName property is set in code the WCF service still needs to be configured to send the credentials. This is done in the B of the WCF ABC (http://msdn.microsoft.com/en-us/library/aa480190.aspx): "A" stands for Address: Where is the service? "B" stands for Binding: How do I talk to the service? "C" stands for Contract: What can the service do for me? The whole idea of WCF is that it should be configurable so that there is no need to redeploy the code if the service changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/23624835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change name of the folders when copying multiple folders in PowerShell? This is my code right now: [int]$NumberOfProfiles = Read-Host "Enter the number of Portable Firefox profiles You need" $WhereToWrite = Read-Host "Enter the full path where You'd like to install the profiles" $Source = Get-Location $FolderName = "JonDoFoxPortable" $SourceDirectory = "$Source\$Foldername" $Copy = Copy-Item $SourceDirectory $WhereToWrite -Recurse -Container while ($NumberOfProfiles -ge 0) {$Copy; $NumberOfProfiles--} As You can see right now it just overwrites the folders, but I'd need it to copy certain amount of folders that is declared in $NumberOfProfiles (e.g. $NumberOfProfiles = 10) and it makes JonDoFoxPortable1, JonDoFoxPortable2 ... JonDoFoxPortable10. A: Something like this should work: while ($NumberOfProfiles -ge 0) { $DestinationDirectory = Join-Path $WhereToWrite "$Foldername$NumberOfProfiles" Copy-Item $SourceDirectory $DestinationDirectory -Recurse -Container $NumberOfProfiles-- } Or, probably even simpler, something like this: 0..$NumberOfProfiles | % { $DestinationDirectory = Join-Path $WhereToWrite "$Foldername$_" Copy-Item $SourceDirectory $DestinationDirectory -Recurse -Container } A: This should do it for you: replace: while ($NumberOfProfiles -ge 0) {$Copy; $NumberOfProfiles--} with: (0..$NumberOfProfiles) | % { Copy-Item $SourceDirectory "$WhereToWrite$_" -Recurse -Container } This will loop around from 0 to $NumberOfProfiles and copy to a location named $WhereToWrite with the iteration number attached $_
{ "language": "en", "url": "https://stackoverflow.com/questions/24282993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }