id
stringlengths
40
40
text
stringlengths
29
2.03k
original_text
stringlengths
3
154k
subdomain
stringclasses
20 values
metadata
dict
bbb65565ac11dbb25266413787944bf3b71c2f61
Stackoverflow Stackexchange Q: Java: Is it possible to record audio from the sound card output (speakers)? What I'm trying now (don't mind about the syntax - it's Kotlin): audioFormat = AudioFormat(8000f, 8, 2, true, false) mixerInfo = AudioSystem.getMixerInfo() mixer = AudioSystem.getMixer(mixerInfo[0]) // have tried all dataLineInfo = DataLine.Info(TargetDataLine::class.java, audioFormat) dataLine = mixer.getLine(dataLineInfo) as TargetDataLine // IllegalArgumentException dataLine.open() dataLine.start() AudioSystem.write(AudioInputStream(dataLine), AudioFileFormat.Type.WAVE, File("1.wav")) Unfortunatelly a IllegalArgumentException is being thrown at mixer.getLine: java.lang.IllegalArgumentException: Line unsupported: interface TargetDataLine supporting format PCM_SIGNED 8000.0 Hz, 8 bit, stereo, 2 bytes/frame, little-endian I've tried all the available mixers and audio formats. Still no luck. The only working mixer is the microphone mixer. All the output-mixers cause the exception. I've also tried to detect supported audio formats using AudioSystem.isLineSupported, but I coudn't detect any single format that would be supported by output-mixers. AudioSystem.isLineSupported always returns false for all the possible formats I've checked. So, is it possible to record the sound I hear from speakers? PS: There is some capture soft that can perform such record. For example, SnagIt 12 can record audio from my sound card. And there are lot of similar apps.
Q: Java: Is it possible to record audio from the sound card output (speakers)? What I'm trying now (don't mind about the syntax - it's Kotlin): audioFormat = AudioFormat(8000f, 8, 2, true, false) mixerInfo = AudioSystem.getMixerInfo() mixer = AudioSystem.getMixer(mixerInfo[0]) // have tried all dataLineInfo = DataLine.Info(TargetDataLine::class.java, audioFormat) dataLine = mixer.getLine(dataLineInfo) as TargetDataLine // IllegalArgumentException dataLine.open() dataLine.start() AudioSystem.write(AudioInputStream(dataLine), AudioFileFormat.Type.WAVE, File("1.wav")) Unfortunatelly a IllegalArgumentException is being thrown at mixer.getLine: java.lang.IllegalArgumentException: Line unsupported: interface TargetDataLine supporting format PCM_SIGNED 8000.0 Hz, 8 bit, stereo, 2 bytes/frame, little-endian I've tried all the available mixers and audio formats. Still no luck. The only working mixer is the microphone mixer. All the output-mixers cause the exception. I've also tried to detect supported audio formats using AudioSystem.isLineSupported, but I coudn't detect any single format that would be supported by output-mixers. AudioSystem.isLineSupported always returns false for all the possible formats I've checked. So, is it possible to record the sound I hear from speakers? PS: There is some capture soft that can perform such record. For example, SnagIt 12 can record audio from my sound card. And there are lot of similar apps.
stackoverflow
{ "language": "en", "length": 184, "provenance": "stackexchange_0000F.jsonl.gz:885016", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604880" }
ee27a391e47554761a3817c2f55bbbdfaa01927c
Stackoverflow Stackexchange Q: ASP.Net Core API routing without attributes I want to set up API routing inside Startup.Configure method using the same approach that is used for MVC actions by default, without Route attributes. I try the following: // API routes.MapRoute( name: "api", template: "api/{controller}/{id?}"); // default routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); The controller looks like this public class CategoriesController : Controller { [HttpGet] public async Task<Category[]> Get(int currentPageNo = 1, int pageSize = 20) { // return data here } } But it doesn't match this url: /api/categories. The next rule is applied instead. If I use attribute routing like this [Route("api/[controller]")] public class CategoriesController : Controller { [HttpGet] public async Task<Category[]> Get(int currentPageNo = 1, int pageSize = 20) { // return data here } } it works fine. But I want to avoid putting the same routing attribute on every API controller. What is the right way to configure routing in this case?
Q: ASP.Net Core API routing without attributes I want to set up API routing inside Startup.Configure method using the same approach that is used for MVC actions by default, without Route attributes. I try the following: // API routes.MapRoute( name: "api", template: "api/{controller}/{id?}"); // default routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); The controller looks like this public class CategoriesController : Controller { [HttpGet] public async Task<Category[]> Get(int currentPageNo = 1, int pageSize = 20) { // return data here } } But it doesn't match this url: /api/categories. The next rule is applied instead. If I use attribute routing like this [Route("api/[controller]")] public class CategoriesController : Controller { [HttpGet] public async Task<Category[]> Get(int currentPageNo = 1, int pageSize = 20) { // return data here } } it works fine. But I want to avoid putting the same routing attribute on every API controller. What is the right way to configure routing in this case?
stackoverflow
{ "language": "en", "length": 162, "provenance": "stackexchange_0000F.jsonl.gz:885023", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604902" }
30ab2f801f32c38e4272985f17b638250a816b34
Stackoverflow Stackexchange Q: Laravel echo server killed on exit console i'm using laravel-echo-server and all works fine, if i launch server with this command: laravel-echo-server start i see: L A R A V E L E C H O S E R V E R version 1.2.8 Starting server... ✔ Running at localhost on port 3001 ✔ Channels are ready. ✔ Listening for http events... ✔ Listening for redis events... Server ready! But if i close with ctrl+c the server has been killed! the same things if i use this command: laravel-echo-server start & if i disconnect my ssh connection, the server stop work! How can i launch in background mode? thanks! A: I recommend to use the pm2 tool to manage the larval-echo-server service. After install pm2 you must create a json file inside the Laravel project with a content like this: echo-pm2.json { "name": "echo", "script": "laravel-echo-server", "args": "start" } Then run the next command to start the service in background: pm2 start echo-pm2.json Yo can use pm2 monit command for real time monitoring or pm2 logs to get the service logs as well.
Q: Laravel echo server killed on exit console i'm using laravel-echo-server and all works fine, if i launch server with this command: laravel-echo-server start i see: L A R A V E L E C H O S E R V E R version 1.2.8 Starting server... ✔ Running at localhost on port 3001 ✔ Channels are ready. ✔ Listening for http events... ✔ Listening for redis events... Server ready! But if i close with ctrl+c the server has been killed! the same things if i use this command: laravel-echo-server start & if i disconnect my ssh connection, the server stop work! How can i launch in background mode? thanks! A: I recommend to use the pm2 tool to manage the larval-echo-server service. After install pm2 you must create a json file inside the Laravel project with a content like this: echo-pm2.json { "name": "echo", "script": "laravel-echo-server", "args": "start" } Then run the next command to start the service in background: pm2 start echo-pm2.json Yo can use pm2 monit command for real time monitoring or pm2 logs to get the service logs as well. A: Install Supervisor on linux. Here is a manual: https://laravel.com/docs/5.4/queues#supervisor-configuration Here is my supervisor config file: [program:websocket-server] process_name=%(program_name)s directory=/var/www/example.de/public_html/ command=/usr/lib/node_modules/laravel-echo-server/bin/server.js start autostart=true autorestart=true user=www-data numprocs=1 redirect_stderr=true stdout_logfile=/var/www/example.de/logs/websocket-server.log Now you can start the server in the background with supervisorctl start websocket-server:*
stackoverflow
{ "language": "en", "length": 224, "provenance": "stackexchange_0000F.jsonl.gz:885032", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604932" }
02fc6e515968b45fb21f6aaa48241e4ec865f54f
Stackoverflow Stackexchange Q: How to filter TableQuery with the list of IDs? I'm really new to Slick and Scala and I'm strugling with filtering the query with the list of ids. productsNeededIds // = "1,2,3,4,5" - list of Ids of products Question: How can I use .filter to get a query with all the ids from the splitted list? def productsWithIds(productsNeededIds: String)(implicit ec: ExecutionContext): Future[List[ProductsREST]] = { var splitedArray :Array[String] = productsNeededIds.split(",") val query = Products.filter(_.prodId === splitedArray)// what should be here instead of ===splitedArray? } A: You should use the inSet method: def productsWithIds(productsNeededIds: String)(implicit ec: ExecutionContext): Future[List[ProductsREST]] = { val splitedSet: Set[String] = productsNeededIds.split(",").toSet val query = Products.filter(_.prodId.inSet(splitedSet)) } That's assuming your product IDs are strings. If they're Ints instead, you should map your splittedSet to Ints first, of course.
Q: How to filter TableQuery with the list of IDs? I'm really new to Slick and Scala and I'm strugling with filtering the query with the list of ids. productsNeededIds // = "1,2,3,4,5" - list of Ids of products Question: How can I use .filter to get a query with all the ids from the splitted list? def productsWithIds(productsNeededIds: String)(implicit ec: ExecutionContext): Future[List[ProductsREST]] = { var splitedArray :Array[String] = productsNeededIds.split(",") val query = Products.filter(_.prodId === splitedArray)// what should be here instead of ===splitedArray? } A: You should use the inSet method: def productsWithIds(productsNeededIds: String)(implicit ec: ExecutionContext): Future[List[ProductsREST]] = { val splitedSet: Set[String] = productsNeededIds.split(",").toSet val query = Products.filter(_.prodId.inSet(splitedSet)) } That's assuming your product IDs are strings. If they're Ints instead, you should map your splittedSet to Ints first, of course.
stackoverflow
{ "language": "en", "length": 130, "provenance": "stackexchange_0000F.jsonl.gz:885036", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604941" }
b1152f16f3de20ed6d21d22e0ffd7738d20d1a64
Stackoverflow Stackexchange Q: How to click an image and make a rotation I have below reactjs code. It renders an image dom. I want to implement a feather that when a user click on that image, the image is rotated 180 degrees. And at the end of the rotate animation, replace it with a new image. How can I implement it in reactjs? <div> <img className="icon-arrow" src={icon} role="button" onClick={()=> { // create an animation to rotate the image }} /> </div> A: Here's a crossbrowser way to do with Javascript, it will rotate each time you click, you can apply the same idea for react. var rotated = false; document.getElementById('image').onclick = function() { var div = document.getElementById('image'), angle = rotated ? 0 : 180; div.style.webkitTransform = 'rotate('+ angle +'deg)'; div.style.mozTransform = 'rotate('+ angle +'deg)'; div.style.msTransform = 'rotate('+ angle +'deg)'; div.style.oTransform = 'rotate('+ angle +'deg)'; div.style.transform = 'rotate('+ angle +'deg)'; rotated = !rotated; } #image { -webkit-transition: all 0.5s ease-in-out; -moz-transition: all 0.5s ease-in-out; -o-transition: all 0.5s ease-in-out; transition: all 0.5s ease-in-out; } <p>click on the image.</p> <img id="image" src="http://lorempixel.com/400/200/" width="300" height="auto" id="image" />
Q: How to click an image and make a rotation I have below reactjs code. It renders an image dom. I want to implement a feather that when a user click on that image, the image is rotated 180 degrees. And at the end of the rotate animation, replace it with a new image. How can I implement it in reactjs? <div> <img className="icon-arrow" src={icon} role="button" onClick={()=> { // create an animation to rotate the image }} /> </div> A: Here's a crossbrowser way to do with Javascript, it will rotate each time you click, you can apply the same idea for react. var rotated = false; document.getElementById('image').onclick = function() { var div = document.getElementById('image'), angle = rotated ? 0 : 180; div.style.webkitTransform = 'rotate('+ angle +'deg)'; div.style.mozTransform = 'rotate('+ angle +'deg)'; div.style.msTransform = 'rotate('+ angle +'deg)'; div.style.oTransform = 'rotate('+ angle +'deg)'; div.style.transform = 'rotate('+ angle +'deg)'; rotated = !rotated; } #image { -webkit-transition: all 0.5s ease-in-out; -moz-transition: all 0.5s ease-in-out; -o-transition: all 0.5s ease-in-out; transition: all 0.5s ease-in-out; } <p>click on the image.</p> <img id="image" src="http://lorempixel.com/400/200/" width="300" height="auto" id="image" /> A: This is the react way to do it. class Image extends React.Component { constructor(props) { super(props); this.state = { rotate: false, toggle: false }; this.rotatingDone = this.rotatingDone.bind(this); } componentDidMount() { const elm = this.image; elm.addEventListener("animationend", this.rotatingDone); } componentWillUnmount() { const elm = this.image; elm.removeEventListener("animationend", this.rotatingDone); } rotatingDone() { this.setState(function(state) { return { toggle: !state.toggle, rotate: false }; }); } render() { const { rotate, toggle } = this.state; return ( <img src={ toggle ? "https://video-react.js.org/assets/logo.png" : "https://www.shareicon.net/data/128x128/2016/08/01/640324_logo_512x512.png" } ref={elm => { this.image = elm; }} onClick={() => this.setState({ rotate: true })} className={rotate ? "rotate" : ""} /> ); } } ReactDOM.render(<Image />, document.getElementById("container")); .rotate { animation: rotate-keyframes 1s; } @keyframes rotate-keyframes { from { transform: rotate(0deg); } to { transform: rotate(180deg); } } <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="container"> </div>
stackoverflow
{ "language": "en", "length": 312, "provenance": "stackexchange_0000F.jsonl.gz:885047", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44604966" }
a64d39ee0011c826f0cd053cc325f3724ac34cf6
Stackoverflow Stackexchange Q: How to pass Leaf tag to another Leaf tag? Is there a way to passing Leaf tag to another Leaf tag? For example, in my custom Leaf tag I return some html code: public func run( tagTemplate: TagTemplate, arguments: ArgumentList) throws -> Node? { return .bytes("<span>#(foo)</span>".bytes) } but in my template #(foo) shows as plain text, not render as a Leaf tag, whereas html tags <span></span> works properly.
Q: How to pass Leaf tag to another Leaf tag? Is there a way to passing Leaf tag to another Leaf tag? For example, in my custom Leaf tag I return some html code: public func run( tagTemplate: TagTemplate, arguments: ArgumentList) throws -> Node? { return .bytes("<span>#(foo)</span>".bytes) } but in my template #(foo) shows as plain text, not render as a Leaf tag, whereas html tags <span></span> works properly.
stackoverflow
{ "language": "en", "length": 69, "provenance": "stackexchange_0000F.jsonl.gz:885079", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44605077" }
18f0a1b1e89d44d84df799b8c333058ad655d384
Stackoverflow Stackexchange Q: MAMP PRO doesn't allow me to change PHP version over hosts I don't know why but for some reason my MAMP PRO doesn't allow me to change PHP version over host. I'm using MAMP PRO 4. If you take a look you will notice the option for that is disabled, I left here a screenshot, MAMP PRO configuration Any idea?, Regards! A: To run a different PHP version on each host, go Languages > PHP > Individual PHP version for every host (CGI mode). Return to Settings > Hosts and under the host a dropdown should be available to choose your PHP version.
Q: MAMP PRO doesn't allow me to change PHP version over hosts I don't know why but for some reason my MAMP PRO doesn't allow me to change PHP version over host. I'm using MAMP PRO 4. If you take a look you will notice the option for that is disabled, I left here a screenshot, MAMP PRO configuration Any idea?, Regards! A: To run a different PHP version on each host, go Languages > PHP > Individual PHP version for every host (CGI mode). Return to Settings > Hosts and under the host a dropdown should be available to choose your PHP version. A: I just resolved. The error was running PHP as module mode, if you want to have multiples version for each vhost you must run as CGI A: Possibility 1: your server is running (you cannot change php version when the serving is running) Possibility 2: you only have 1 version of php installed on your computer
stackoverflow
{ "language": "en", "length": 161, "provenance": "stackexchange_0000F.jsonl.gz:885097", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44605144" }
b678dae52672d4043fd942fed2b1256c718fc3a3
Stackoverflow Stackexchange Q: FirebaseUI convert anonymous account to permanent account I am using Firebase UI for Android app. I want users to be able to log in Anonymously and use basic features. Then when they want additional features I want to convert their account to a permanent email/password or google provider account. Firebase has documentation on a way to do this here: https://firebase.google.com/docs/auth/android/anonymous-auth by using linkWithCredential However, I want to do this using Firebase UI auth. Is it possible to use this linkWithCredential with FirebaseUI? If so a simple example would be great.
Q: FirebaseUI convert anonymous account to permanent account I am using Firebase UI for Android app. I want users to be able to log in Anonymously and use basic features. Then when they want additional features I want to convert their account to a permanent email/password or google provider account. Firebase has documentation on a way to do this here: https://firebase.google.com/docs/auth/android/anonymous-auth by using linkWithCredential However, I want to do this using Firebase UI auth. Is it possible to use this linkWithCredential with FirebaseUI? If so a simple example would be great.
stackoverflow
{ "language": "en", "length": 91, "provenance": "stackexchange_0000F.jsonl.gz:885116", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44605204" }
e1d4b953007800a65d719ce53ca92a1fbcb7949b
Stackoverflow Stackexchange Q: What is the purpose of *.ngsummary.json I've just learning about AOT, ngc etc. After running ngc I see plenty of *.ngsummary.json (in src folder, next to *.ts files). What are they for? A: This is apparently the new name of NgFactory files used by the AOT compiler. Search for NgFactory on this page Ahead-of-Time Compilation Extract : After ngc completes, look for a collection of NgFactory files in the aot folder. The aot folder is the directory specified as genDir in tsconfig-aot.json. These factory files are essential to the compiled application. Each component factory creates an instance of the component at runtime by combining the original class file and a JavaScript representation of the component's template. Note that the original component class is still referenced internally by the generated factory.
Q: What is the purpose of *.ngsummary.json I've just learning about AOT, ngc etc. After running ngc I see plenty of *.ngsummary.json (in src folder, next to *.ts files). What are they for? A: This is apparently the new name of NgFactory files used by the AOT compiler. Search for NgFactory on this page Ahead-of-Time Compilation Extract : After ngc completes, look for a collection of NgFactory files in the aot folder. The aot folder is the directory specified as genDir in tsconfig-aot.json. These factory files are essential to the compiled application. Each component factory creates an instance of the component at runtime by combining the original class file and a JavaScript representation of the component's template. Note that the original component class is still referenced internally by the generated factory.
stackoverflow
{ "language": "en", "length": 131, "provenance": "stackexchange_0000F.jsonl.gz:885144", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44605313" }
23000389486a541580dab5b5e727c051302cda4c
Stackoverflow Stackexchange Q: Parsing Last Name from Name in Python Trying to determine a single last name. names = ["John Smith", "D.J. Richies III","AJ Hardie Jr.", "Shelia Jackson-Lee", "Bob O'Donnell"] Desired Output last_names = ['Smith', 'Richies','Hardie','Lee', 'ODonnell' ] I'm hoping there is an existing library or set of code that can easily handle some of these more rare/odd cases. Thanks for your help! A: Dealing with Names is Hard Naive string-manipulation solutions will eventually fail. You start to realize this with suffixes (III, Jr.), but what about compound last names like de la Paz? You want: The Python Human Name Parser >>> from nameparser import HumanName >>> name = HumanName("Dr. Juan Q. Xavier de la Vega III") >>> name.title 'Dr.' >>> name["title"] 'Dr.' >>> name.first 'Juan' >>> name.middle 'Q. Xavier' >>> name.last 'de la Vega' >>> name.suffix 'III'
Q: Parsing Last Name from Name in Python Trying to determine a single last name. names = ["John Smith", "D.J. Richies III","AJ Hardie Jr.", "Shelia Jackson-Lee", "Bob O'Donnell"] Desired Output last_names = ['Smith', 'Richies','Hardie','Lee', 'ODonnell' ] I'm hoping there is an existing library or set of code that can easily handle some of these more rare/odd cases. Thanks for your help! A: Dealing with Names is Hard Naive string-manipulation solutions will eventually fail. You start to realize this with suffixes (III, Jr.), but what about compound last names like de la Paz? You want: The Python Human Name Parser >>> from nameparser import HumanName >>> name = HumanName("Dr. Juan Q. Xavier de la Vega III") >>> name.title 'Dr.' >>> name["title"] 'Dr.' >>> name.first 'Juan' >>> name.middle 'Q. Xavier' >>> name.last 'de la Vega' >>> name.suffix 'III' A: You can try this: names = ["John Smith", "D.J. Richies III","AJ Hardie Jr.", "Shelia Jackson-Lee", "Bob O'Donnell"] suffixes = ["II", "Jr.", "III", "Sr."] last_names = [] for i in names: new_name = i.split() if len(new_name) == 2 and "-" in new_name[1]: last_names.append(new_name[1].split("-")[1]) elif len(new_name) == 2: last_names.append(new_name[1]) else: if new_name[-1] in suffixes: last_names.append(new_name[1]) print(last_names) Output will contain the last names: ['Smith', 'Richies', 'Hardie', 'Lee', "O'Donnell"] A: You can use the nameparser package. For more examples you can have a look at the link: from nameparser import HumanName import pandas as pd df = pd.DataFrame({'Name': ["John Smith", "D.J. Richies III","AJ Hardie Jr.", "Shelia Jackson-Lee", "Bob O'Donnell"]}) df["title"] = df["Name"].apply(lambda x: HumanName(x).title) df["first"] = df["Name"].apply(lambda x: HumanName(x).first) df["middle"] = df["Name"].apply(lambda x: HumanName(x).middle) df["last"] = df["Name"].apply(lambda x: HumanName(x).last) df["suffix"] = df["Name"].apply(lambda x: HumanName(x).suffix) df["nickname"] = df["Name"].apply(lambda x: HumanName(x).nickname) df And the output is: Name title first middle last suffix nickname 0 John Smith John Smith 1 D.J. Richies III D.J. Richies III 2 AJ Hardie Jr. AJ Hardie Jr. 3 Shelia Jackson-Lee Shelia Jackson-Lee 4 Bob O'Donnell Bob O'Donnell So if you want only the surnames: df['last'] And you get: 0 Smith 1 Richies 2 Hardie 3 Jackson-Lee 4 O'Donnell Name: last, dtype: object
stackoverflow
{ "language": "en", "length": 338, "provenance": "stackexchange_0000F.jsonl.gz:885148", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44605333" }
635597796bb46d48bf2900c3aa8a88c2bc757f55
Stackoverflow Stackexchange Q: Get DateTime of the next nth day of the month If given a date and a variable n, how can I calculate the DateTime for which the day of the month will be the nth Date? For example, Today is the 17th of June. I would like a function that when provided 15 would return the DateTime for July 15. A few more examples: * *Today is Feb. 26: Function would return March 30 when provided 30. *Today is Dec. 28. Function would return Jan 4 when provided 4. *Today is Feb. 28. Function would return March 29 when provided 29, unless it was a leap year, in which case it would return Feb 29. A: Why not just do? private DateTime GetNextDate(DateTime dt, int DesiredDay) { if (DesiredDay >= 1 && DesiredDay <= 31) { do { dt = dt.AddDays(1); } while (dt.Day != DesiredDay); return dt.Date; } else { throw new ArgumentOutOfRangeException(); } }
Q: Get DateTime of the next nth day of the month If given a date and a variable n, how can I calculate the DateTime for which the day of the month will be the nth Date? For example, Today is the 17th of June. I would like a function that when provided 15 would return the DateTime for July 15. A few more examples: * *Today is Feb. 26: Function would return March 30 when provided 30. *Today is Dec. 28. Function would return Jan 4 when provided 4. *Today is Feb. 28. Function would return March 29 when provided 29, unless it was a leap year, in which case it would return Feb 29. A: Why not just do? private DateTime GetNextDate(DateTime dt, int DesiredDay) { if (DesiredDay >= 1 && DesiredDay <= 31) { do { dt = dt.AddDays(1); } while (dt.Day != DesiredDay); return dt.Date; } else { throw new ArgumentOutOfRangeException(); } } A: After many, many edits, corrections and re-writes, here is my final answer: The method that follows returns a a DateTime representing the next time the day of number day comes up in the calendar. It does so using an iterative approach, and is written in the form of an extension method for DateTime objects, and thus isn't bound to today's date but will work with any date. The code executes the following steps to get the desired result: * *Ensure that the day number provided is valid (greater than zero and smaller than 32). *Enter into a while loop that keeps going forever (until we break). *Check if cDate's month works (the day must not have passed, and the month must have enough days in it). * *If so, return. *If not, increase the month by one, set the day to one, set includeToday to true so that the first day of the new month is included, and execute the loop again. The code: static DateTime GetNextDate3(this DateTime cDate, int day, bool includeToday = false) { // Make sure provided day is valid if (day > 0 && day <= 31) { while (true) { // See if day has passed in current month or is not contained in it at all if ((includeToday && day > cDate.Day || (includeToday && day >= cDate.Day)) && day <= DateTime.DaysInMonth(cDate.Year, cDate.Month)) { // If so, break and return break; } // Advance month by one and set day to one // FIXED BUG HERE (note the order of the two calls) cDate = cDate.AddDays(1 - cDate.Day).AddMonths(1); // Set includeToday to true so that the first of every month is taken into account includeToday = true; } // Return if the cDate's month contains day and it hasn't passed return new DateTime(cDate.Year, cDate.Month, day); } // Day provided wasn't a valid one throw new ArgumentOutOfRangeException("day", "Day isn't valid"); } A: The spec is a little bit unclear about to do when today is the dayOfMonth. I assumed it was it to return the same. Otherwise it would just be to change to <= today.Day public DateTime FindNextDate(int dayOfMonth, DateTime today) { var nextMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1); if(dayOfMonth < today.Day){ nextMonth = nextMonth.AddMonths(1); } while(nextMonth.AddDays(-1).Day < dayOfMonth){ nextMonth = nextMonth.AddMonths(1); } var month = nextMonth.AddMonths(-1); return new DateTime(month.Year, month.Month, dayOfMonth); } A: Stumbled upon this thread today while trying to figure out this same problem. From my testing, the following seems to work well and the loop only needs two goes (I think? Maybe 3 max(?)) to get to the answer: public static DateTime GetNearestSpecificDay(DateTime start, int dayNum) { if (dayNum >= 1 && dayNum <= 31) { DateTime result = start; while (result.Day != dayNum) result = dayNum > result.Day ? result.AddDays(dayNum - result.Day) : new DateTime(result.Month == 12 ? result.Year + 1 : result.Year, (result.Month % 12) + 1, 1); return result; } else return DateTime.Today; } Edit: As requested, here's a less compact version that walks through the logic step by step. I've also updated the original code to account for a required year change when we reach December. public static DateTime GetNearestSpecificDay(DateTime start, int dayNum) { // Check if target day is valid in the Gregorian calendar if (dayNum >= 1 && dayNum <= 31) { // Declare a variable which will hold our result & temporary results DateTime result = start; // While the current result's day is not the desired day while (result.Day != dayNum) { // If the desired day is greater than the current day if (dayNum > result.Day) { // Add the difference to try and skip to the target day (if we can, if the current month does not have enough days, we will be pushed into the next month and repeat) result = result.AddDays(dayNum - result.Day); } // Else, get the first day of the next month, then try the first step again (which should get us where we want to be) else { // If the desired day is less than the current result day, it means our result day must be in the next month (it obviously can't be in the current) // Get the next month by adding 1 to the current month mod 12 (so when we hit december, we go to january instead of trying to use a not real 13th month) // If result.Month is November, 11%12 = 11; 11 + 1 = 12, which rolls us into December // If result.Month is December, 12%12 = 0; 0 + 1 = 1, which rolls us into January var month = (result.Month % 12) + 1; // Get current/next year. // Since we are adding 1 to the current month, we can assume if the previous month was 12 that we must be entering into January of next year // Another way to do this would be to check if the new month is 1. It accomplishes the same thing but I chose 12 since it doesn't require an extra variable in the original code. // Below can be translated as "If last result month is 12, use current year + 1, else, use current year" var year = result.Month == 12 ? result.Year + 1 : result.Year; // Set result to the start of the next month in the current/next year result = new DateTime(year, month, 1); } } // Return result return result; } else // If our desired day is invalid, just return Today. This can be an exception or something as well, just using Today fit my use case better. return DateTime.Today; } A: Fun little puzzle. I generated 100 DateTimes which represent the starting day of each month, then checked each month to see if it had the date we want. It's lazy so we stop when we find a good one. public DateTime FindNextDate(int dayOfMonth, DateTime today) { DateTime yesterday = today.AddDays(-1); DateTime currentMonthStart = new DateTime(today.Year, today.Month, 1); var query = Enumerable.Range(0, 100) .Select(i => currentMonthStart.AddMonths(i)) .Select(monthStart => MakeDateOrDefault( monthStart.Year, monthStart.Month, dayOfMonth, yesterday) .Where(date => today <= date) .Take(1); List<DateTime> results = query.ToList(); if (!results.Any()) { throw new ArgumentOutOfRangeException(nameof(dayOfMonth)) } return results.Single(); } public DateTime MakeDateOrDefault( int year, int month, int dayOfMonth, DateTime defaultDate) { try { return new DateTime(year, month, dayOfMonth); } catch { return defaultDate; } }
stackoverflow
{ "language": "en", "length": 1208, "provenance": "stackexchange_0000F.jsonl.gz:885217", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44605557" }
8356217f3b90b91a787ed8d4db8ccc4a6420c235
Stackoverflow Stackexchange Q: How to force UI Display to update in swift? I'm trying to get the View Controller to update while I'm in a loop that calls a function that does tons of Label updates. But the update to the screen doesn't happen until I've finished the loop. Is there a way to force a UI update before continuing? Something like forcing data to be written to a disk. code for the button to start the loop is something like this: while (match.currentInnings == currentInnings) { playSingleBall() if (gameover == true) { return } } After playSingleBall, I'd like to force a UI update before continuing. Thanks. A: Call it in Dispatch Queue: Swift 3.x DispatchQueue.main.async { updateYourUI() } Swift 2.x dispatch_async(dispatch_get_main_queue()) { updateYourUI() }
Q: How to force UI Display to update in swift? I'm trying to get the View Controller to update while I'm in a loop that calls a function that does tons of Label updates. But the update to the screen doesn't happen until I've finished the loop. Is there a way to force a UI update before continuing? Something like forcing data to be written to a disk. code for the button to start the loop is something like this: while (match.currentInnings == currentInnings) { playSingleBall() if (gameover == true) { return } } After playSingleBall, I'd like to force a UI update before continuing. Thanks. A: Call it in Dispatch Queue: Swift 3.x DispatchQueue.main.async { updateYourUI() } Swift 2.x dispatch_async(dispatch_get_main_queue()) { updateYourUI() }
stackoverflow
{ "language": "en", "length": 124, "provenance": "stackexchange_0000F.jsonl.gz:885256", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44605673" }
5f2c3afdf7c9a8b6ef277e876183a8353f7aa906
Stackoverflow Stackexchange Q: Inspect element without right clicking in Chrome When I inspect html/css on a website, I usually open the chrome developers panel ctrl+shift+I → right click context menu "inspect" so I can highlight that class however, sometimes I'm trying to inspect an element that is sensitive to "right clicks" events , e.g. if I right click an item on the website functionality changes Example: so I can't inspect an element Normally I inspect elements like this (e.g. stackoverflow) How do you inspect an element without using the right click button? Normally I would have to just dig through the chrome developer's panel elements and just go one by one to find said element, which takes a really long time I must be missing something important here about chrome's inspect element tools. Could someone enlighten me here a better workflow / maybe chrome extension tools? A: Try pressing ctrl+shift+c. This will open the dev tools in element selection mode, allowing you to left-click on elements to jump straight to them in the elements view.
Q: Inspect element without right clicking in Chrome When I inspect html/css on a website, I usually open the chrome developers panel ctrl+shift+I → right click context menu "inspect" so I can highlight that class however, sometimes I'm trying to inspect an element that is sensitive to "right clicks" events , e.g. if I right click an item on the website functionality changes Example: so I can't inspect an element Normally I inspect elements like this (e.g. stackoverflow) How do you inspect an element without using the right click button? Normally I would have to just dig through the chrome developer's panel elements and just go one by one to find said element, which takes a really long time I must be missing something important here about chrome's inspect element tools. Could someone enlighten me here a better workflow / maybe chrome extension tools? A: Try pressing ctrl+shift+c. This will open the dev tools in element selection mode, allowing you to left-click on elements to jump straight to them in the elements view. A: You can press Ctrl+Shift+C to enter a mode where you can mouse over elements and it will inspect it. With your mouse over the element you want to inspect, just press Ctrl+Shift+C again and your element will be selected in the developer panel. A: You can open the dev tools on a different windows and refresh your page or use firebug. or use Firefox
stackoverflow
{ "language": "en", "length": 238, "provenance": "stackexchange_0000F.jsonl.gz:885271", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44605729" }
653dcd60f7f970e918dcf58dc7c4c28e74707620
Stackoverflow Stackexchange Q: What is the type of a jQuery object in TypeScript? What type I should use for jQuery elements? Without jQuery I go on like this: export class Modal { constructor(protected element:HTMLElement) { } } But, lets say element will be a jQuery selector like $('.myDiv') for example. What type should element then have? A: After installing the types needed (npm install --save-dev @types/jquery), you can type it as just JQuery: constructor(protected element: JQuery) { }
Q: What is the type of a jQuery object in TypeScript? What type I should use for jQuery elements? Without jQuery I go on like this: export class Modal { constructor(protected element:HTMLElement) { } } But, lets say element will be a jQuery selector like $('.myDiv') for example. What type should element then have? A: After installing the types needed (npm install --save-dev @types/jquery), you can type it as just JQuery: constructor(protected element: JQuery) { }
stackoverflow
{ "language": "en", "length": 76, "provenance": "stackexchange_0000F.jsonl.gz:885305", "question_score": "21", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44605824" }
d625634129a24ac8bde796410cfb3840e394469d
Stackoverflow Stackexchange Q: How to sync ngrx/store with the Angular 4 router At the moment I have no routing but I do have a default state and a working set of reducers. A simplified version looks like this: const defaultMapState: MapState = { baseLayer: 'roadmap', overlays: [] }; Then I have some actions that manipulate that state, e.g.: * *MAP_SET_BASELAYER *MAP_ADD_OVERLAY *MAP_REMOVE_OVERLAY I'm trying to support the following scenarios: * *Have 2 URL parameters, baselayer and overlays. On initialisation of the app use those values to set the state. If a value is missing, grab the value for that variable form the defaultState. *After each action, execute some sort of middleware to sync the route with the current state. *If the URL changes (without being triggered by an action) update the state. I'm lost here. I have found '@ngrx/router-store' but I'm not sure how that works and if it's even intended to solve these problems.
Q: How to sync ngrx/store with the Angular 4 router At the moment I have no routing but I do have a default state and a working set of reducers. A simplified version looks like this: const defaultMapState: MapState = { baseLayer: 'roadmap', overlays: [] }; Then I have some actions that manipulate that state, e.g.: * *MAP_SET_BASELAYER *MAP_ADD_OVERLAY *MAP_REMOVE_OVERLAY I'm trying to support the following scenarios: * *Have 2 URL parameters, baselayer and overlays. On initialisation of the app use those values to set the state. If a value is missing, grab the value for that variable form the defaultState. *After each action, execute some sort of middleware to sync the route with the current state. *If the URL changes (without being triggered by an action) update the state. I'm lost here. I have found '@ngrx/router-store' but I'm not sure how that works and if it's even intended to solve these problems.
stackoverflow
{ "language": "en", "length": 153, "provenance": "stackexchange_0000F.jsonl.gz:885316", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44605856" }
f2c6e22138c0343697f57f5e6559360c416d71db
Stackoverflow Stackexchange Q: React, warning 'css' is defined but never used no-unused-vars I'm working to import CSS files in my React App. I have css being imported successfully like so: Original source app: https://github.com/timscott/react-devise-sample MainLayout.jsx import css from '../styles/base.css' base.css body { opacity: .1; } When I load my app in a browser I see the styles taking effect. The problem is, in the console I'm getting a JS warning: webpackHotDevClient.js:198 ./src/layouts/MainLayout.jsx .../client/src/layouts/MainLayout.jsx 12:8 warning 'css' is defined but never used no-unused-vars ✖ 1 problem (0 errors, 1 warning) What am I doing wrong in React to cause the CSS to render but still get a warning in the console? A: Name this "component" only if you need call them in some part of the code. e.g. Using CSS-Modules. This is only a regular css so load in this manner : import '../styles/base.css' But if you still want to keep this unused var you can edit your es-lint, and delete this rule. (Not Recommended)
Q: React, warning 'css' is defined but never used no-unused-vars I'm working to import CSS files in my React App. I have css being imported successfully like so: Original source app: https://github.com/timscott/react-devise-sample MainLayout.jsx import css from '../styles/base.css' base.css body { opacity: .1; } When I load my app in a browser I see the styles taking effect. The problem is, in the console I'm getting a JS warning: webpackHotDevClient.js:198 ./src/layouts/MainLayout.jsx .../client/src/layouts/MainLayout.jsx 12:8 warning 'css' is defined but never used no-unused-vars ✖ 1 problem (0 errors, 1 warning) What am I doing wrong in React to cause the CSS to render but still get a warning in the console? A: Name this "component" only if you need call them in some part of the code. e.g. Using CSS-Modules. This is only a regular css so load in this manner : import '../styles/base.css' But if you still want to keep this unused var you can edit your es-lint, and delete this rule. (Not Recommended) A: You do not need "css from" since the css file is already connected to the jsx file. You only do that when using other jsx components, for example: import SomeComponent from '../SomeComponent.jsx'
stackoverflow
{ "language": "en", "length": 195, "provenance": "stackexchange_0000F.jsonl.gz:885325", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44605873" }
68dc41252aadae255c9b682e423484cf185a34d3
Stackoverflow Stackexchange Q: Convert nanoseconds (since midnight) to printable time? I have a uint64_t representing the number of nanoseconds since midnight. Would std::chrono allow me to convert this into a meaningful "time", relatively simply? Also, how would I do it if I have the time since epoch? For example in such a format: 14:03:27.812374923 And same situation, but when given nanoseconds since epoch? (in case the answer is significantly different) A: You could use Howard Hinnant's, free, open-source, header-only library to do this: #include "date.h" #include <cstdint> #include <iostream> int main() { using namespace std; using namespace std::chrono; using namespace date; uint64_t since_midnight = 50607812374923; cout << make_time(nanoseconds{since_midnight}) << '\n'; uint64_t since_epoch = 1499522607812374923; cout << sys_time<nanoseconds>{nanoseconds{since_epoch}} << '\n'; } This outputs: 14:03:27.812374923 2017-07-08 14:03:27.812374923 Or did you need to take leap seconds into account for since_epoch? cout << utc_time<nanoseconds>{nanoseconds{since_epoch}} << '\n'; 2017-07-08 14:03:00.812374923 For this latter computation, you'll need "tz.h" documented here, and this library is not header only.
Q: Convert nanoseconds (since midnight) to printable time? I have a uint64_t representing the number of nanoseconds since midnight. Would std::chrono allow me to convert this into a meaningful "time", relatively simply? Also, how would I do it if I have the time since epoch? For example in such a format: 14:03:27.812374923 And same situation, but when given nanoseconds since epoch? (in case the answer is significantly different) A: You could use Howard Hinnant's, free, open-source, header-only library to do this: #include "date.h" #include <cstdint> #include <iostream> int main() { using namespace std; using namespace std::chrono; using namespace date; uint64_t since_midnight = 50607812374923; cout << make_time(nanoseconds{since_midnight}) << '\n'; uint64_t since_epoch = 1499522607812374923; cout << sys_time<nanoseconds>{nanoseconds{since_epoch}} << '\n'; } This outputs: 14:03:27.812374923 2017-07-08 14:03:27.812374923 Or did you need to take leap seconds into account for since_epoch? cout << utc_time<nanoseconds>{nanoseconds{since_epoch}} << '\n'; 2017-07-08 14:03:00.812374923 For this latter computation, you'll need "tz.h" documented here, and this library is not header only.
stackoverflow
{ "language": "en", "length": 158, "provenance": "stackexchange_0000F.jsonl.gz:885332", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44605898" }
f2a53a17992a5dd42ee7f6fe42b7dae3f171d817
Stackoverflow Stackexchange Q: Block (or strip out) FlowFile Content I need to perform an HTTP Post from NiFi, but I don't want/need the request to carry all of the FlowFile's content. Is there some way to pass attributes of a FlowFile but not the full content? A: If the request body of your Http Post is JSON, you can use the AttributesToJSON Processor which allows you to pick which attributes you want to include in the resulting JSON. You can then configure the processor so the resulting JSON overwrites the existing flowfile content. Keep in mind that the resulting JSON will be flat so you may need to transform it to the expected format. For that, you can use the JoltTransformJSON Processor. Below is an example of what your dataflow might look like. I hope this helps!
Q: Block (or strip out) FlowFile Content I need to perform an HTTP Post from NiFi, but I don't want/need the request to carry all of the FlowFile's content. Is there some way to pass attributes of a FlowFile but not the full content? A: If the request body of your Http Post is JSON, you can use the AttributesToJSON Processor which allows you to pick which attributes you want to include in the resulting JSON. You can then configure the processor so the resulting JSON overwrites the existing flowfile content. Keep in mind that the resulting JSON will be flat so you may need to transform it to the expected format. For that, you can use the JoltTransformJSON Processor. Below is an example of what your dataflow might look like. I hope this helps!
stackoverflow
{ "language": "en", "length": 135, "provenance": "stackexchange_0000F.jsonl.gz:885356", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606003" }
19c159b5a99a7996d58a45a751f442b939a88acb
Stackoverflow Stackexchange Q: Manually compute the length of a string I have a homework assignment asking for string length calculation without using built-in functions. What I had in mind is to use a counter: s = 0 while name[s] != "": s += 1 but I'm stuck with how to solve the string index out of range error...or is there actually another way? A: you have two simple options : Either add a try/except clause: s = 0 try: while(name[s]): s += 1 except IndexError: pass print(s) Or use an iterator: s = 0 for _ in name: s += 1 print(s)
Q: Manually compute the length of a string I have a homework assignment asking for string length calculation without using built-in functions. What I had in mind is to use a counter: s = 0 while name[s] != "": s += 1 but I'm stuck with how to solve the string index out of range error...or is there actually another way? A: you have two simple options : Either add a try/except clause: s = 0 try: while(name[s]): s += 1 except IndexError: pass print(s) Or use an iterator: s = 0 for _ in name: s += 1 print(s) A: Try this, counter = 0 st = 'ABCDEF' for i in st: counter += 1 print('Length of String is : ', str(counter)) A: So, a string is basically a sequence of characters. For example: 'hello' = ['h', 'e', 'l', 'l', 'o'] So if you just loop through this array and add 1 to your length variable every loop, you will get the length: string = "hello" length = 0 for character in string: length = length + 1 print(length) This way, you won't even need to worry about handling exceptions :) Try it online https://repl.it/IptA/0 Further Reading Strings Lists A: There is an alternative to the "stupid" counting by adding one for each character: * *An exponential search finds a range for the string length. *A binary search pins down the string length starting with the range, found in the previous step. The code with test section: def is_valid_index(s, i): '''Returns True, if i is a valid index of string s, and False otherwise.''' try: s[i] return True except IndexError: return False def string_length(s): '''Returns the length of string s without built-ins.''' # Test for empty string (needed for the invariant # of the following exponential search.) if not is_valid_index(s, 0): return 0 # Exponential search with low as inclusive lower bound # and high as exclusive upper bound. # Invariant for the loop: low is a valid index. low = 0 high = 1 while True: if is_valid_index(s, high): low = high high *= 2 continue break # Binary search inside the found range while True: if low + 1 == high: return high middle = (low + high) // 2 if is_valid_index(s, middle): low = middle else: high = middle # Test section print(string_length('hello')) # Test the first thousand string lengths for i in range(1000): s = 'x' * i if len(s) != string_length(s): print('Error for {}: {}'.format(i, string_length(s))) # Test quite a large string s = 'x' * 1234567890 print(string_length(s)) Result: 5 1234567890 A: A string has an attribute __len__, a function that returns the length of the string. Thus, the following solution does not use built-ins, but the calculation is trivial (without calculating operations, thus, it might be not the intention of the homework): def get_string_length(s): return s.__len__() Test: print(get_string_length('hello')) Result: 5
stackoverflow
{ "language": "en", "length": 477, "provenance": "stackexchange_0000F.jsonl.gz:885375", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606051" }
df90dbd2bdff6acda3c1236672480f047f2e21c2
Stackoverflow Stackexchange Q: Get Size of ImageView in RemoteViews I am writing an Android AppWidget. The layout for the widget contains a LinearLayout and, inside that, a number of ImageViews. In the AppWidgetProvider OnUpdate method, I first create a RemoteViews for the layout ... var rv = new RemoteViews(context.PackageName, Resource.Layout.WidgetLayout); ... and, using that, I can set the bitmaps for each of the child ImageViews. However, what I really want to do is to get the actual size of the ImageViews once layout is complete so that I can draw exactly sized images (probably via Bitmaps) into them. I see no way to get the ImageView sizes via RemoteViews, nor any way to get to the underlying ImageView of a RemoteViews item. Can I even do this? Is it done in OnUpdate()? If so, how? If not, where should I be doing it? Thanks in advance. A: Can I even do this? No. The rendering of the UI defined by the RemoteViews is handled by a separate app (home screen) in a separate process. You have no means of getting at Java objects from other processes, Views in particular.
Q: Get Size of ImageView in RemoteViews I am writing an Android AppWidget. The layout for the widget contains a LinearLayout and, inside that, a number of ImageViews. In the AppWidgetProvider OnUpdate method, I first create a RemoteViews for the layout ... var rv = new RemoteViews(context.PackageName, Resource.Layout.WidgetLayout); ... and, using that, I can set the bitmaps for each of the child ImageViews. However, what I really want to do is to get the actual size of the ImageViews once layout is complete so that I can draw exactly sized images (probably via Bitmaps) into them. I see no way to get the ImageView sizes via RemoteViews, nor any way to get to the underlying ImageView of a RemoteViews item. Can I even do this? Is it done in OnUpdate()? If so, how? If not, where should I be doing it? Thanks in advance. A: Can I even do this? No. The rendering of the UI defined by the RemoteViews is handled by a separate app (home screen) in a separate process. You have no means of getting at Java objects from other processes, Views in particular. A: You can get size of widget - approximate size of widget. In layout, you can use "weights" - and if you know sizes of widget, and weights of images - you can approximately calculate sizes of images. I am using such approach to make proper bitmaps. One of problems - is different devices lie differently. One of my bitmaps has next weights - 0.6 of width, and 0.15 of height. SetTitleButton( context, views, (int) (w*0.6), (int)(h*0.15*coefficient)); where coefficient is attempt to compensate different "lie" and user can modify it to fit... w and h - are size of widget. Bundle awo = appWidgetManager.getAppWidgetOptions( appWidgetId); int h=awo.getInt("appWidgetMaxHeight"); int w=awo.getInt("appWidgetMaxWidth");
stackoverflow
{ "language": "en", "length": 296, "provenance": "stackexchange_0000F.jsonl.gz:885380", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606058" }
c8831de5c01306d17ec758f59f88e8b49d2c5fe0
Stackoverflow Stackexchange Q: How to set charset="utf-8" in the javascript file itself I am trying to set charset="utf-8" inside the javascript file itself, not in the script tag, I know that I can do this: <script type="text/javascript" charset="UTF-8" src="xyz.js"></script> But unfortunately, this solution needs me to do the same step with hundreds of websites which are using the same script. so I am trying to set the charset in the javascript file itself. Is this possible? thanks A: I found another way, so instead of declaring charset="UTF-8" for the script tag like this: <script type="text/javascript" charset="UTF-8" src="xyz.js"></script> I can declare the charset for the web page itself using meta tag, so I can append <meta charset="UTF-8"> to the DOM dynamically, and end up with something like: <head> ... <meta charset="UTF-8"> ... </head>
Q: How to set charset="utf-8" in the javascript file itself I am trying to set charset="utf-8" inside the javascript file itself, not in the script tag, I know that I can do this: <script type="text/javascript" charset="UTF-8" src="xyz.js"></script> But unfortunately, this solution needs me to do the same step with hundreds of websites which are using the same script. so I am trying to set the charset in the javascript file itself. Is this possible? thanks A: I found another way, so instead of declaring charset="UTF-8" for the script tag like this: <script type="text/javascript" charset="UTF-8" src="xyz.js"></script> I can declare the charset for the web page itself using meta tag, so I can append <meta charset="UTF-8"> to the DOM dynamically, and end up with something like: <head> ... <meta charset="UTF-8"> ... </head> A: I think you can't set this in the Javascript file itself. The browser need the charset to read the file. So without the charset the browser is not able to understand your file and therefore would not be able to read the charset definition
stackoverflow
{ "language": "en", "length": 175, "provenance": "stackexchange_0000F.jsonl.gz:885407", "question_score": "25", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606147" }
43f7dff70631c8e12697fda0a0453b56094a80ea
Stackoverflow Stackexchange Q: Qt without Xcode Is it possible to use Qt and Qt Creator on MacOS with Command Line Tools only, i.e. without installing the whole Xcode? I'm asking because I'm getting "Project ERROR: Could not resolve SDK Path for 'macosx'" and all the solutions I read ask for full Xcode. A: I had the same question when I wanted to install Qt on an old MacBook Air that can't run the version of macOS that XCode now requires. I found this document detailing how to install Qt without XCode. It does complain about XCode not being present, but as the document notes you can ignore that and proceed anyway. (Note: solution didn't solve my problem for a couple obscure reasons, but I'm leaving the answer because it is an additional option not yet mentioned.)
Q: Qt without Xcode Is it possible to use Qt and Qt Creator on MacOS with Command Line Tools only, i.e. without installing the whole Xcode? I'm asking because I'm getting "Project ERROR: Could not resolve SDK Path for 'macosx'" and all the solutions I read ask for full Xcode. A: I had the same question when I wanted to install Qt on an old MacBook Air that can't run the version of macOS that XCode now requires. I found this document detailing how to install Qt without XCode. It does complain about XCode not being present, but as the document notes you can ignore that and proceed anyway. (Note: solution didn't solve my problem for a couple obscure reasons, but I'm leaving the answer because it is an additional option not yet mentioned.)
stackoverflow
{ "language": "en", "length": 134, "provenance": "stackexchange_0000F.jsonl.gz:885423", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606219" }
4534b4c8cfa02d747036c331106e5bf0cb4c42bf
Stackoverflow Stackexchange Q: What's the difference between Program Fixpoint and Function in Coq? They seem to serve similar purposes. The one difference I've noticed so far is that while Program Fixpoint will accept a compound measure like {measure (length l1 + length l2) }, Function seems to reject this and will only allow {measure length l1}. Is Program Fixpoint strictly more powerful than Function, or are they better suited for different use cases? A: This may not be a complete list, but it is what I have found so far: * *As you already mentioned, Program Fixpoint allows the measure to look at more than one argument. *Function creates a foo_equation lemma that can be used to rewrite calls to foo with its RHS. Very useful to avoid problems like Coq simpl for Program Fixpoint. *In some (simple?) cases, Function can define a foo_ind lemma to perform induction along the structure of recursive calls of foo. Again, very useful to prove things about foo without effectively repeating the termination argument in the proof. *Program Fixpoint can be tricked into supporting nested recursion, see https://stackoverflow.com/a/46859452/946226. This is also why Program Fixpoint can define the Ackermann function when Function cannot.
Q: What's the difference between Program Fixpoint and Function in Coq? They seem to serve similar purposes. The one difference I've noticed so far is that while Program Fixpoint will accept a compound measure like {measure (length l1 + length l2) }, Function seems to reject this and will only allow {measure length l1}. Is Program Fixpoint strictly more powerful than Function, or are they better suited for different use cases? A: This may not be a complete list, but it is what I have found so far: * *As you already mentioned, Program Fixpoint allows the measure to look at more than one argument. *Function creates a foo_equation lemma that can be used to rewrite calls to foo with its RHS. Very useful to avoid problems like Coq simpl for Program Fixpoint. *In some (simple?) cases, Function can define a foo_ind lemma to perform induction along the structure of recursive calls of foo. Again, very useful to prove things about foo without effectively repeating the termination argument in the proof. *Program Fixpoint can be tricked into supporting nested recursion, see https://stackoverflow.com/a/46859452/946226. This is also why Program Fixpoint can define the Ackermann function when Function cannot.
stackoverflow
{ "language": "en", "length": 196, "provenance": "stackexchange_0000F.jsonl.gz:885432", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606245" }
edaa2c3a2aa7135df685c44576ca448fbd5e6dd1
Stackoverflow Stackexchange Q: JavaScript outerHTML encodes URL-string I'm trying to set the src attribute of an image to a URL that I also generate in JS. The URL contains several parameters chained with a "&", but when getting the element's outer HTML as string value, all the "&" are replaced by "&amp ;, making the URL useless. Why is this happening? Do I have to replace all the occurencies to fix it? var img = $("<img>"); img.attr("src","/test?param1=1&param2=2"); console.log(img[0].outerHTML); //printing <img src="/test?param1=1&amp;param2=2"> getting the src attribute from that object shows the original string so I believe the value is encoded when accessing outerHTML. A: This is just the result of logging the img using outerHTML, because that function serialises strings before they are output. In the example below I am just logging the element and you will see the image source is correct. Also if you output the image on the page it also has the correct source. So there is nothing wrong with your code other than the way you are logging the output. var img = $("<img>"); img.attr("src","http://www.placecage.com/gif/284/196?param1=1&param2=2"); console.log(img[0]); $("div").append(img); <div></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Q: JavaScript outerHTML encodes URL-string I'm trying to set the src attribute of an image to a URL that I also generate in JS. The URL contains several parameters chained with a "&", but when getting the element's outer HTML as string value, all the "&" are replaced by "&amp ;, making the URL useless. Why is this happening? Do I have to replace all the occurencies to fix it? var img = $("<img>"); img.attr("src","/test?param1=1&param2=2"); console.log(img[0].outerHTML); //printing <img src="/test?param1=1&amp;param2=2"> getting the src attribute from that object shows the original string so I believe the value is encoded when accessing outerHTML. A: This is just the result of logging the img using outerHTML, because that function serialises strings before they are output. In the example below I am just logging the element and you will see the image source is correct. Also if you output the image on the page it also has the correct source. So there is nothing wrong with your code other than the way you are logging the output. var img = $("<img>"); img.attr("src","http://www.placecage.com/gif/284/196?param1=1&param2=2"); console.log(img[0]); $("div").append(img); <div></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
stackoverflow
{ "language": "en", "length": 182, "provenance": "stackexchange_0000F.jsonl.gz:885433", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606250" }
aab969e8accff8981b5aa3918801a26cebc99482
Stackoverflow Stackexchange Q: imwrite 16 bit png depth image I have the following code. I am trying to save a 16 bit depth image which I retrieve from Kinect v1 as a png file. I wrote the following code sample: def display_depth(dev, data, timestamp): global keep_runningp cv2.imshow('Depth', frame_convert2.pretty_depth_cv(data)) depthf.write(repr(timestamp)+" Depth/"+repr(timestamp)+".png\n") namef="Sample_dataset/Depth/"+repr(timestamp)+".png" cv2.imwrite(namef,frame_convert2.pretty_depth(data)) if cv2.waitKey(10) == 27: keep_running = False It works when I add the following code, which converts data from a 16 bit unsigned to an 8 bit unsigned NumPy array: depth = depth.astype(np.uint8) Without this line, I am just getting the whole blank/white png image. But I need to have a 16 bit png file. How I can save it as a 16 bit png file? A: Though type of my data was like this <type 'numpy.uint16'> Solution , to my problem was adding this line to my code depth.astype(np.uint16)
Q: imwrite 16 bit png depth image I have the following code. I am trying to save a 16 bit depth image which I retrieve from Kinect v1 as a png file. I wrote the following code sample: def display_depth(dev, data, timestamp): global keep_runningp cv2.imshow('Depth', frame_convert2.pretty_depth_cv(data)) depthf.write(repr(timestamp)+" Depth/"+repr(timestamp)+".png\n") namef="Sample_dataset/Depth/"+repr(timestamp)+".png" cv2.imwrite(namef,frame_convert2.pretty_depth(data)) if cv2.waitKey(10) == 27: keep_running = False It works when I add the following code, which converts data from a 16 bit unsigned to an 8 bit unsigned NumPy array: depth = depth.astype(np.uint8) Without this line, I am just getting the whole blank/white png image. But I need to have a 16 bit png file. How I can save it as a 16 bit png file? A: Though type of my data was like this <type 'numpy.uint16'> Solution , to my problem was adding this line to my code depth.astype(np.uint16)
stackoverflow
{ "language": "en", "length": 140, "provenance": "stackexchange_0000F.jsonl.gz:885435", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606257" }
646b3eabdfa8fd26e964292a031be1f62dcfb608
Stackoverflow Stackexchange Q: How to add two DataFrame I have DataFrame number 1 Price Things 0 1 pen 1 2 pencil 2 6 apple I have DataFrame number 2: Price Things 0 5 pen 1 6 pencil 2 10 cup I want to join two DataFrames and I'd like to see this DataFrame: DataFrame number 1 + DatFRame number 2 Price Things 0 6 pen 1 8 pencil 2 6 apple 3 10 cup How can I do this? This code: import pandas as pd df = pd.DataFrame({'Things': ['pen', 'pencil'], 'Price': [1, 2]}) series = pd.Series([1,2], index=[0,1]) df["Price"] = series df.loc[2] = [6, "apple"] print("DataFrame number 1") print(df) df2 = pd.DataFrame({'Things': ['pen', 'pencil'], 'Price': [1, 2]}) series = pd.Series([5,6], index=[0,1]) df2["Price"] = series df2.loc[2] = [10, "cup"] print("DataFrame number 2") print(df2) A: You can also use concatenate function to combine two dataframes along axis = 0, then group by column and sum them. df3 = pd.concat([df, df2], axis=0).groupby('Things').sum().reset_index() df3 Output: Things Price 0 apple 6 1 cup 10 2 pen 6 3 pencil 8
Q: How to add two DataFrame I have DataFrame number 1 Price Things 0 1 pen 1 2 pencil 2 6 apple I have DataFrame number 2: Price Things 0 5 pen 1 6 pencil 2 10 cup I want to join two DataFrames and I'd like to see this DataFrame: DataFrame number 1 + DatFRame number 2 Price Things 0 6 pen 1 8 pencil 2 6 apple 3 10 cup How can I do this? This code: import pandas as pd df = pd.DataFrame({'Things': ['pen', 'pencil'], 'Price': [1, 2]}) series = pd.Series([1,2], index=[0,1]) df["Price"] = series df.loc[2] = [6, "apple"] print("DataFrame number 1") print(df) df2 = pd.DataFrame({'Things': ['pen', 'pencil'], 'Price': [1, 2]}) series = pd.Series([5,6], index=[0,1]) df2["Price"] = series df2.loc[2] = [10, "cup"] print("DataFrame number 2") print(df2) A: You can also use concatenate function to combine two dataframes along axis = 0, then group by column and sum them. df3 = pd.concat([df, df2], axis=0).groupby('Things').sum().reset_index() df3 Output: Things Price 0 apple 6 1 cup 10 2 pen 6 3 pencil 8 A: You can merge, add, then drop the interim columns: common = pd.merge( df, df2, on='Things', how='outer').fillna(0) common['Price'] = common.Price_x + common.Price_y common.drop(['Price_x', 'Price_y'], axis=1, inplace=True) >>> common Things Price 0 pen 6.0 1 pencil 8.0 2 apple 6.0 3 cup 10.0 A: You can also set Things as index on both data frames and then use add(..., fill_value=0): df.set_index('Things').add(df2.set_index('Things'), fill_value=0).reset_index() # Things Price #0 apple 6.0 #1 cup 10.0 #2 pen 6.0 #3 pencil 8.0
stackoverflow
{ "language": "en", "length": 248, "provenance": "stackexchange_0000F.jsonl.gz:885457", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606317" }
1627e3565240e6e6f524d6faff32cea6903bfdb1
Stackoverflow Stackexchange Q: In what cases are go binaries dynamically linked? One important feature of the Go programming language is that it produces statically linked binaries. However, when I ran ldd * in my $GOPATH/bin, I found several dynamic executables. Is there a clear set of rules to understand under what circumstances does the go compiler produce dynamically linked binaries? A: When using cgo, which is how Go links to C programs, which can of course use dynamically-linked libraries.
Q: In what cases are go binaries dynamically linked? One important feature of the Go programming language is that it produces statically linked binaries. However, when I ran ldd * in my $GOPATH/bin, I found several dynamic executables. Is there a clear set of rules to understand under what circumstances does the go compiler produce dynamically linked binaries? A: When using cgo, which is how Go links to C programs, which can of course use dynamically-linked libraries. A: Go 1.8 has introduced something called Go Plugin which seems to be using dynamic linking. https://golang.org/pkg/plugin/
stackoverflow
{ "language": "en", "length": 94, "provenance": "stackexchange_0000F.jsonl.gz:885477", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606374" }
4bb2862f173fcb6df211aaae3074ad62d3649727
Stackoverflow Stackexchange Q: TypeScript - How to access the class instance from event handler method In the code snippet below, I have a TypeScript class and the instance method buz is the listener for canvas' click event. this keyword in buz method refers to the event's target object(canvas). How to get access to the foo instance from the buz method? class Foo { constructor(private _canvas: HTMLCanvasElement, private _message: string) { } public bar(): void { this._canvas.addEventListener(`click`, this.buz); } private buz(e: MouseEvent): void { console.info(`After click event, 'this' refers to canvas and not to the instance of Foo:`); console.info(this); console.warn(`Message is: "${this._message}"`); // error } } window.addEventListener('load', () => { let canvas = <HTMLCanvasElement> document.getElementById('canvas'); let foo = new Foo(canvas, "Hello World"); foo.bar(); }); My tsconfig.json has these settings: "compilerOptions": { "module": "commonjs", "target": "es5", "sourceMap": true }, A: Your context is lost in the buz method when you pass it as a parameter. You can use arrow functions to achieve that. Arrow functions will save the context. public bar(): void { this._canvas.addEventListener(`click`, (evt) => this.buz(evt)); }
Q: TypeScript - How to access the class instance from event handler method In the code snippet below, I have a TypeScript class and the instance method buz is the listener for canvas' click event. this keyword in buz method refers to the event's target object(canvas). How to get access to the foo instance from the buz method? class Foo { constructor(private _canvas: HTMLCanvasElement, private _message: string) { } public bar(): void { this._canvas.addEventListener(`click`, this.buz); } private buz(e: MouseEvent): void { console.info(`After click event, 'this' refers to canvas and not to the instance of Foo:`); console.info(this); console.warn(`Message is: "${this._message}"`); // error } } window.addEventListener('load', () => { let canvas = <HTMLCanvasElement> document.getElementById('canvas'); let foo = new Foo(canvas, "Hello World"); foo.bar(); }); My tsconfig.json has these settings: "compilerOptions": { "module": "commonjs", "target": "es5", "sourceMap": true }, A: Your context is lost in the buz method when you pass it as a parameter. You can use arrow functions to achieve that. Arrow functions will save the context. public bar(): void { this._canvas.addEventListener(`click`, (evt) => this.buz(evt)); }
stackoverflow
{ "language": "en", "length": 174, "provenance": "stackexchange_0000F.jsonl.gz:885486", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606399" }
05361e5a433f67918f7ff5cadd9b122bbe3e0729
Stackoverflow Stackexchange Q: Grouping columns by unique values in Python I have a data set with two columns and I need to change it from this format: 10 1 10 5 10 3 11 5 11 4 12 6 12 2 to this 10 1 5 3 11 5 4 12 6 2 I need every unique value in the first column to be on its own row. I am a beginner with Python and beyond reading in my text file, I'm at a loss for how to proceed. A: You can use Pandas dataframes. import pandas as pd df = pd.DataFrame({'A':[10,10,10,11,11,12,12],'B':[1,5,3,5,4,6,2]}) print(df) Output: A B 0 10 1 1 10 5 2 10 3 3 11 5 4 11 4 5 12 6 6 12 2 Let's use groupby and join: df.groupby('A')['B'].apply(lambda x:' '.join(x.astype(str))) Output: A 10 1 5 3 11 5 4 12 6 2 Name: B, dtype: object
Q: Grouping columns by unique values in Python I have a data set with two columns and I need to change it from this format: 10 1 10 5 10 3 11 5 11 4 12 6 12 2 to this 10 1 5 3 11 5 4 12 6 2 I need every unique value in the first column to be on its own row. I am a beginner with Python and beyond reading in my text file, I'm at a loss for how to proceed. A: You can use Pandas dataframes. import pandas as pd df = pd.DataFrame({'A':[10,10,10,11,11,12,12],'B':[1,5,3,5,4,6,2]}) print(df) Output: A B 0 10 1 1 10 5 2 10 3 3 11 5 4 11 4 5 12 6 6 12 2 Let's use groupby and join: df.groupby('A')['B'].apply(lambda x:' '.join(x.astype(str))) Output: A 10 1 5 3 11 5 4 12 6 2 Name: B, dtype: object A: an example using itertools.groupby only; this is all in the python standard library (although the pandas version is way more concise!). assuming the keys you want to group are adjacent this could all be done lazily (no need to have all your data in-memory at any time): from io import StringIO from itertools import groupby text = '''10 1 10 5 10 3 11 5 11 4 12 6 12 2''' # read and group data: with StringIO(text) as file: keys = [] res = {} data = (line.strip().split() for line in file) for k, g in groupby(data, key=lambda x: x[0]): keys.append(k) res[k] = [item[1] for item in g] print(keys) # ['10', '11', '12'] print(res) # {'12': ['6', '2'], '10': ['1', '5', '3'], '11': ['5', '4']} # write grouped data: with StringIO() as out_file: for key in keys: out_file.write('{:3s}'.format(key)) out_file.write(' '.join(['{:3s}'.format(item) for item in res[key]])) out_file.write('\n') print(out_file.getvalue()) # 10 1 5 3 # 11 5 4 # 12 6 2 you can then replace the with StringIO(text) as file: with something like with open('infile.txt', 'r') as file for the program to read your actual file (and similar for the output file with open('outfile.txt', 'w')). again: of course you could directly write to the output file every time a key is found; this way you would not need to have all the data in-memory at any time: with StringIO(text) as file, StringIO() as out_file: data = (line.strip().split() for line in file) for k, g in groupby(data, key=lambda x: x[0]): out_file.write('{:3s}'.format(k)) out_file.write(' '.join(['{:3s}'.format(item[1]) for item in g])) out_file.write('\n') print(out_file.getvalue()) A: Using collections.defaultdict subclass: import collections with open('yourfile.txt', 'r') as f: d = collections.defaultdict(list) for k,v in (l.split() for l in f.read().splitlines()): # processing each line d[k].append(v) # accumulating values for the same 1st column for k,v in sorted(d.items()): # outputting grouped sequences print('%s %s' % (k,' '.join(v))) The output: 10 1 5 3 11 5 4 12 6 2 A: Using pandas may be easier. You can use read_csv function to read txt file where data is separated by space or spaces. import pandas as pd df = pd.read_csv("input.txt", header=None, delimiter="\s+") # setting column names df.columns = ['col1', 'col2'] df This is will give output of dataframe as: col1 col2 0 10 1 1 10 5 2 10 3 3 11 5 4 11 4 5 12 6 6 12 2 After reading txt file to dataframe, similar to apply in previous other answer, you can also use aggregate and join: df_combine = df.groupby('col1')['col2'].agg(lambda col: ' '.join(col.astype('str'))).reset_index() df_combine Output: col1 col2 0 10 1 5 3 1 11 5 4 2 12 6 2 A: I found this solution using dictonaries: with open("data.txt", encoding='utf-8') as data: file = data.readlines() dic = {} for line in file: list1 = line.split() try: dic[list1[0]] += list1[1] + ' ' except KeyError: dic[list1[0]] = list1[1] + ' ' for k,v in dic.items(): print(k,v) OUTPUT 10 1 5 3 11 5 4 12 6 2 Something more functional def getdata(datafile): with open(datafile, encoding='utf-8') as data: file = data.readlines() dic = {} for line in file: list1 = line.split() try: dic[list1[0]] += list1[1] + ' ' except KeyError: dic[list1[0]] = list1[1] + ' ' for k,v in dic.items(): v = v.split() print(k, ':',v) getdata("data.txt") OUTPUT 11 : ['5', '4'] 12 : ['6', '2'] 10 : ['1', '5', '3']
stackoverflow
{ "language": "en", "length": 700, "provenance": "stackexchange_0000F.jsonl.gz:885489", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606413" }
036331842a68f980a88e04b33778a143186aa8a3
Stackoverflow Stackexchange Q: Controlling the position of angular material 2 autocomplete options panel I am trying to control the position of angular material 2 autocomplete options panel and place this panel in a separate div from the div of the actual input. Here is what I have tried: <div fxLayout="row"> <div fxFlex="50"> <form [formGroup]="formStatus.form"> <div> <md-input-container> <input mdInput formControlName="title" placeholder="Titre"> </md-input-container> </div> <div> <md-input-container> <input mdInput placeholder="Address" [mdAutocomplete]="auto" formControlName="address"> </md-input-container> </div> </form> </div> <div fxFlex="50" style="background-color: palegreen"> <!-- options panel should appear here in the palegreen div --> <md-autocomplete #auto="mdAutocomplete" [displayWith]="addressFormatter"> <md-option *ngFor="let address of addresses | async" [value]="address"> {{ address.description }} </md-option> </md-autocomplete> </div> </div> However, the options panel still appears right below the input and its position seems to be bound to that of the input... A: You can control the position of angular material 2 autocomplete options panel with the following code ::ng-deep .mat-autocomplete-panel{ position: fixed !important; top:30% !important; left: 40%; right: 30%; border: 3px solid #73AD21; background-color: palegreen !important; }
Q: Controlling the position of angular material 2 autocomplete options panel I am trying to control the position of angular material 2 autocomplete options panel and place this panel in a separate div from the div of the actual input. Here is what I have tried: <div fxLayout="row"> <div fxFlex="50"> <form [formGroup]="formStatus.form"> <div> <md-input-container> <input mdInput formControlName="title" placeholder="Titre"> </md-input-container> </div> <div> <md-input-container> <input mdInput placeholder="Address" [mdAutocomplete]="auto" formControlName="address"> </md-input-container> </div> </form> </div> <div fxFlex="50" style="background-color: palegreen"> <!-- options panel should appear here in the palegreen div --> <md-autocomplete #auto="mdAutocomplete" [displayWith]="addressFormatter"> <md-option *ngFor="let address of addresses | async" [value]="address"> {{ address.description }} </md-option> </md-autocomplete> </div> </div> However, the options panel still appears right below the input and its position seems to be bound to that of the input... A: You can control the position of angular material 2 autocomplete options panel with the following code ::ng-deep .mat-autocomplete-panel{ position: fixed !important; top:30% !important; left: 40%; right: 30%; border: 3px solid #73AD21; background-color: palegreen !important; } A: I am not sure if this exactly meets your requirements but you can control the position of mat-calendar and mat-autocomplete-panel by manipulating their parent classes. These overwritten classes need to sit level above the targeted component to take effect. Example: .mat-autocomplete-panel { position: fixed !important; top:30% !important; left: 40%; right: 30%; border: 3px solid #73AD21; background-color: palegreen !important; } Datepicker demo Autocomplete demo A: Just adding to current solutions provided by @ferralucho and @Nehal ::ng-deep as @ferralucho suggested was required for me to affect the parent component class. I wanted to show my autocomplete options panel further down from my because I had a wrapper div around the input box. The following worked: ::ng-deep .mat-autocomplete-panel { position: relative; top: 30px; }
stackoverflow
{ "language": "en", "length": 284, "provenance": "stackexchange_0000F.jsonl.gz:885513", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606476" }
f45fd9637b428edd0e61804af0980b8c336f4b19
Stackoverflow Stackexchange Q: Delete Row from Pandas DataFrame based on cell value How can i delete a row in a Pandas Dataframe, based on a cell value without giving a specific column name? For example: I have this DataFrame and i want to delete all rows where a cell contains the value 'd'. A B C D 1 1 2 d 5 2 1 3 4 0 3 d 2 1 2 4 3 2 1 7 So I end up with the DataFrame A B C D 2 1 3 4 0 4 3 2 1 7 Is there a way to achive this? My google skills only found solutions where a specific column name is required. A: you can do it this way: df = df[~df.select_dtypes(['object']).eq('d').any(1)] Result: In [23]: df Out[23]: A B C D 2 1 3 4 0 4 3 2 1 7
Q: Delete Row from Pandas DataFrame based on cell value How can i delete a row in a Pandas Dataframe, based on a cell value without giving a specific column name? For example: I have this DataFrame and i want to delete all rows where a cell contains the value 'd'. A B C D 1 1 2 d 5 2 1 3 4 0 3 d 2 1 2 4 3 2 1 7 So I end up with the DataFrame A B C D 2 1 3 4 0 4 3 2 1 7 Is there a way to achive this? My google skills only found solutions where a specific column name is required. A: you can do it this way: df = df[~df.select_dtypes(['object']).eq('d').any(1)] Result: In [23]: df Out[23]: A B C D 2 1 3 4 0 4 3 2 1 7 A: Another way you could do it to use astype, ne and all: df[df.astype(str).ne('d').all(axis=1)] Output: A B C D 2 1 3 4 0 4 3 2 1 7 Another way: df.where(df.values != 'd').dropna() Output: A B C D 2 1 3 4 0 4 3 2 1 7
stackoverflow
{ "language": "en", "length": 194, "provenance": "stackexchange_0000F.jsonl.gz:885520", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606508" }
e1ea22ef291cba4321d8b6a45b3e2f8367cc717d
Stackoverflow Stackexchange Q: Ansible 2.3.1.0: Enable repo on CENTOS 7 In order to install php7 seven I need to enable remi-php71 repo using following command: yum-config-manager --enable remi-php71 How can I do it in an ansible task? A: I had the same need (but for 5.6). Following the advice in the discussion here I used the following: - name: enable remi-php56 ini_file: dest: /etc/yum.repos.d/remi.repo section: remi-php56 option: enabled value: 1 The advantage over using yum_repository is I don't have to maintain the definition - I install the remi repos from the RPM he provides. The advantage over the shell variant (which should probably be command anyway) is I don't need to run commands and I don't need the yum utils installed just for this
Q: Ansible 2.3.1.0: Enable repo on CENTOS 7 In order to install php7 seven I need to enable remi-php71 repo using following command: yum-config-manager --enable remi-php71 How can I do it in an ansible task? A: I had the same need (but for 5.6). Following the advice in the discussion here I used the following: - name: enable remi-php56 ini_file: dest: /etc/yum.repos.d/remi.repo section: remi-php56 option: enabled value: 1 The advantage over using yum_repository is I don't have to maintain the definition - I install the remi repos from the RPM he provides. The advantage over the shell variant (which should probably be command anyway) is I don't need to run commands and I don't need the yum utils installed just for this A: You can do this to issue that specific shell command: - name: enable remi-php71 shell: yum-config-manager --enable remi-php71 Although it is probably better to declare the yum repo itself via something like: - name: Add remi-php71 yum_repository: name: remi-php71 description: Remi's PHP 7.1 RPM repository for Enterprise Linux $releasever - $basearch mirrorlist: http://rpms.remirepo.net/enterprise/$releasever/php71/mirror enabled: yes gpgcheck: 1 gpgkey: http://rpms.remirepo.net/RPM-GPG-KEY-remi Docs here and here. A: You can also enable the repository only during the installation process: - name: Install PHP packages yum: name: - php - php-cli - php-common - php-devel - php-fpm - php-gd - php-ldap - etc... state: latest enablerepo: "remi,remi-php71"
stackoverflow
{ "language": "en", "length": 225, "provenance": "stackexchange_0000F.jsonl.gz:885523", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606514" }
cc9d309ef77336c438d7101a5aeffc0e5084f463
Stackoverflow Stackexchange Q: RMysql encoding utf8 issue I am trying to make use of RMysql package to connect with mysql database and fetch data from it. While importing into R it is changing the encoding format from utf8 thus a records which is "Córdoba" in UTF-8 is returned as "Córdoba". I have tried many things from few post from Stackflow but with no success. I have tried to set the names as utf 8 using the command and few other thing as dbGetQuery(mydb,'set character set "utf8"') It looks that i am missing at something. Really looking for someone who can guide me to the resolution as it has become a show stopper for me. Kindly help please. A: For anyone who is looking for the resolution to it, i would like to mention it. After exporting the data from SQL into R either using dbGetQuery or dbSendQuery, function "iconv" can be executed on the table's vectors to convert it into utf8 format. Bekow is the code example of extracting the data and converting it into utf8 format. rs = dbSendQuery(mydb, "select * from dim_survey_response_alignment") alignfile = fetch(rs, n=-1) alignfile <- subset(alignfile, select = c("attribute","response","aligned")) alignfile$response <- iconv(alignfile$response,from = "UTF-8") Enjoy Learning
Q: RMysql encoding utf8 issue I am trying to make use of RMysql package to connect with mysql database and fetch data from it. While importing into R it is changing the encoding format from utf8 thus a records which is "Córdoba" in UTF-8 is returned as "Córdoba". I have tried many things from few post from Stackflow but with no success. I have tried to set the names as utf 8 using the command and few other thing as dbGetQuery(mydb,'set character set "utf8"') It looks that i am missing at something. Really looking for someone who can guide me to the resolution as it has become a show stopper for me. Kindly help please. A: For anyone who is looking for the resolution to it, i would like to mention it. After exporting the data from SQL into R either using dbGetQuery or dbSendQuery, function "iconv" can be executed on the table's vectors to convert it into utf8 format. Bekow is the code example of extracting the data and converting it into utf8 format. rs = dbSendQuery(mydb, "select * from dim_survey_response_alignment") alignfile = fetch(rs, n=-1) alignfile <- subset(alignfile, select = c("attribute","response","aligned")) alignfile$response <- iconv(alignfile$response,from = "UTF-8") Enjoy Learning A: I could solve the same problem with: dbSendQuery(conn, 'set character set "utf8"') data <- dbReadTable( conn, "name")
stackoverflow
{ "language": "en", "length": 217, "provenance": "stackexchange_0000F.jsonl.gz:885550", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606597" }
e1a096ec8b2335c43cf3c26b6101dde8c11116c1
Stackoverflow Stackexchange Q: Firebase Database not working and no response I'm trying to insert a new user record in to my Firebase database: databaseReference .child("users") .child(firebaseUser.getUid()) .setValue(User.fromFirebaseUser(application.firebaseUser)) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { startActivity(MainActivity.createIntent(SplashActivity.this)); finish(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { showSnackbar(R.string.error_user_registration_failed); } }) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Log.d(TAG, "complete"); } }); But nothing happens. There is no messages from logcat and none of the listeners get hit. My permissions are the default (must be authenticated) and I've made sure I am. A call to firebaseUser.getUid() just before the database call returns the current userId as expected. I've triple checked all my dependencies and made sure my google-services.json file is up to date. I've tried to enable debugging via firebaseDatabase.setLogLevel() but for some reason Logger.Level doesn't contain the enums (they're obfuscated?) Am I missing something? A: After enabling debugging (thanks Bob Snyder) it gave me an error. Essentially you need to enable the "Token Service API" in your Google Developer console. I'm not sure why and how this relates to FirebaseDatabase, and I couldn't find any references to it throughout Google's docs, but it worked.
Q: Firebase Database not working and no response I'm trying to insert a new user record in to my Firebase database: databaseReference .child("users") .child(firebaseUser.getUid()) .setValue(User.fromFirebaseUser(application.firebaseUser)) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { startActivity(MainActivity.createIntent(SplashActivity.this)); finish(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { showSnackbar(R.string.error_user_registration_failed); } }) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Log.d(TAG, "complete"); } }); But nothing happens. There is no messages from logcat and none of the listeners get hit. My permissions are the default (must be authenticated) and I've made sure I am. A call to firebaseUser.getUid() just before the database call returns the current userId as expected. I've triple checked all my dependencies and made sure my google-services.json file is up to date. I've tried to enable debugging via firebaseDatabase.setLogLevel() but for some reason Logger.Level doesn't contain the enums (they're obfuscated?) Am I missing something? A: After enabling debugging (thanks Bob Snyder) it gave me an error. Essentially you need to enable the "Token Service API" in your Google Developer console. I'm not sure why and how this relates to FirebaseDatabase, and I couldn't find any references to it throughout Google's docs, but it worked. A: I had the same issue with reading the users data.. I changed the database rules to: { "rules": { ".read": true, ".write": true } } And it worked, but make sure you kill the app first after changing and publishing the new rules. Note: these rules are only for testing and should never be saved for the published app A: Make sure you have "firebase_url": in google-services.json file in project_info": block. Some how in my case the URL option was not created. Note: In the url option you have to give your firebase database link
stackoverflow
{ "language": "en", "length": 294, "provenance": "stackexchange_0000F.jsonl.gz:885555", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606621" }
0f0eb657a371355af874380fcb5771baeceb1ead
Stackoverflow Stackexchange Q: How to clean NaN and Inf in list type data in Python from math import * raw_data = [3.1, float('NaN'), 3.14, 3.141, 3.1415, float('Nan'), 3.14159, float('Inf'), float('-Inf'), 3.1415926] filtered_data = [] for v in raw_data: if not ((v is float('NaN')) | (v is float('Inf')) | (v is float('-Inf'))): filtered_data.append(v) print(filtered_data) print(raw_data[1]) print(raw_data[1] is float('NaN')) I'm trying to remove the NaN, Inf and -Inf values in the list data. The if condition seems to take no effect. raw_data[1] is a NaN. Why then is print(raw_data[1] is float('NaN')) False? A: Use math.isnan and math.isinf and list comprehensions: import math raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8, float('Inf'), float('-Inf')] filtered_data = [v for v in raw_data if not (math.isinf(v) or math.isnan(v))] print(raw_data) print(filtered_data) Output: [56.2, nan, 51.7, 55.3, 52.5, nan, 47.8, inf, -inf] [56.2, 51.7, 55.3, 52.5, 47.8] | It is a bitwise operator, you should use the boolean operator or. Boolean operators are short-circuiting but bitwise operators are not short-circuiting.
Q: How to clean NaN and Inf in list type data in Python from math import * raw_data = [3.1, float('NaN'), 3.14, 3.141, 3.1415, float('Nan'), 3.14159, float('Inf'), float('-Inf'), 3.1415926] filtered_data = [] for v in raw_data: if not ((v is float('NaN')) | (v is float('Inf')) | (v is float('-Inf'))): filtered_data.append(v) print(filtered_data) print(raw_data[1]) print(raw_data[1] is float('NaN')) I'm trying to remove the NaN, Inf and -Inf values in the list data. The if condition seems to take no effect. raw_data[1] is a NaN. Why then is print(raw_data[1] is float('NaN')) False? A: Use math.isnan and math.isinf and list comprehensions: import math raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8, float('Inf'), float('-Inf')] filtered_data = [v for v in raw_data if not (math.isinf(v) or math.isnan(v))] print(raw_data) print(filtered_data) Output: [56.2, nan, 51.7, 55.3, 52.5, nan, 47.8, inf, -inf] [56.2, 51.7, 55.3, 52.5, 47.8] | It is a bitwise operator, you should use the boolean operator or. Boolean operators are short-circuiting but bitwise operators are not short-circuiting. A: If you step through your code you can begin to see what is happening >>> import math >>> raw_data = [56.2, float('NaN'), 51.7, ... 55.3, 52.5, float('Nan'), 47.8, float('Inf'), float('-Inf')] >>> >>> print(raw_data) [56.2, nan, 51.7, 55.3, 52.5, nan, 47.8, inf, -inf] >>> filtered_data = [] >>> for v in raw_data: ... if not ((v is float('NaN')) | (v is float('Inf')) | (v is float('-Inf'))): filtered_data.append(v) ... >>> filtered_data [56.2, nan, 51.7, 55.3, 52.5, nan, 47.8, inf, -inf] so clearly your attempt to remove the 'NaN's, etc. ain't working. So let's begin at the beginning and determine what went wrong! >>> raw_data [56.2, nan, 51.7, 55.3, 52.5, nan, 47.8, inf, -inf] >>> raw_data[0] 56.2 >>> raw_data[1] nan >>> raw_data[1] is float('Nan') False >>> raw_data[1] == float('Nan') False aha! The test for whether x is a NaN isn't what we expected. Looking for methods in math is a start. >>> math. math.acos( math.cosh( math.fmod( math.isnan( math.pow( math.acosh( math.degrees( math.frexp( math.ldexp( math.radians( math.asin( math.e math.fsum( math.lgamma( math.sin( math.asinh( math.erf( math.gamma( math.log( math.sinh( math.atan( math.erfc( math.gcd( math.log10( math.sqrt( math.atan2( math.exp( math.hypot( math.log1p( math.tan( math.atanh( math.expm1( math.inf math.log2( math.tanh( math.ceil( math.fabs( math.isclose( math.modf( math.tau math.copysign( math.factorial( math.isfinite( math.nan math.trunc( math.cos( math.floor( math.isinf( math.pi where we see isnan() as well as isinf(). Let's try it: >>> math.isnan(raw_data[1]) True Good. so now we can accurately test. Let's turn to that loop. >>> filtered_data = [v for v in raw_data if not isnan(v)] >>> filtered_data [3.1, 3.14, 3.141, 3.1415, 3.14159, inf, -inf, 3.1415926] That created a List and assigned it to filtered_data in one step, using a list comprehension, which is more pythonic and more performant for that matter. The for loop is in the [] and assigns each v that passes the filter at the end of the statement, if not isnan(v). It can take compound conditionals as well: >>> filtered_data = [v for v in raw_data if not isnan(v) and not isinf(v)] >>> filtered_data [3.1, 3.14, 3.141, 3.1415, 3.14159, 3.1415926] Notice that isinf() took care of positive and negative infinities. A: You have a couple of issues. Firstly, as Carcigenicate says, you have used is when you should use ==, and you've used | when you should have used or. The other issue, is that you cannot check NaNs for equality directly. You can use the isnan() function from the math library. The following will work: from math import * raw_data = [3.1, float('NaN'), 3.14, 3.141, 3.1415, float('Nan'), 3.14159, float('Inf'), float('-Inf'), 3.1415926] filtered_data = [] for v in raw_data: if not ((isnan(v)) or (v == float('Inf')) or (v == float('-Inf'))): filtered_data.append(v)
stackoverflow
{ "language": "en", "length": 588, "provenance": "stackexchange_0000F.jsonl.gz:885608", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606799" }
8f963c5173e1a2ae42d99b2ed7a6a8ff40889ea0
Stackoverflow Stackexchange Q: Google Charts: Maps - requesting API Key I have some doubts about Google Charts library when we talk about maps and GeoCharts. I was having this issue that maps stopped working when simply changed the name of the file and this error popped up in my browser console: Google Maps API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys I searched over the web and found some questions here declaring that the maps service VIA GoogleCharts (visualization) didn't have limitations nor charges. BUT, I was able to resolve the problem above using a free JS Map API key as oriented here: https://github.com/google/google-visualization-issues/issues/2292 It's a standard free key, so no charges, but there are limitations, right? What about geocoding?? So, wrapping up all, considering Google Charts scope: 1) Is there a limitation or charge for Google Charts Maps & Geochart view? 2) Is there a limitation or change for geocoding data? Thanks you for the clarification!
Q: Google Charts: Maps - requesting API Key I have some doubts about Google Charts library when we talk about maps and GeoCharts. I was having this issue that maps stopped working when simply changed the name of the file and this error popped up in my browser console: Google Maps API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys I searched over the web and found some questions here declaring that the maps service VIA GoogleCharts (visualization) didn't have limitations nor charges. BUT, I was able to resolve the problem above using a free JS Map API key as oriented here: https://github.com/google/google-visualization-issues/issues/2292 It's a standard free key, so no charges, but there are limitations, right? What about geocoding?? So, wrapping up all, considering Google Charts scope: 1) Is there a limitation or charge for Google Charts Maps & Geochart view? 2) Is there a limitation or change for geocoding data? Thanks you for the clarification!
stackoverflow
{ "language": "en", "length": 151, "provenance": "stackexchange_0000F.jsonl.gz:885615", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606828" }
5965c767480c55cc97b7b9097bc07a23f7907e10
Stackoverflow Stackexchange Q: Difference between let and var inside setTimeout? I know the difference between let and var. let is block scope and var is functional scope. for(var i=0; i< 3; i++){ setTimeout(function(){ console.log(i); }, 10); } output : 3 3 3 I know how above code snippet is working(console.log(i) is executing at that time when value of i is 3, because scope of i is global). But for(let i=0; i< 3; i++){ setTimeout(function(){ console.log(i); }, 10); } output : 1 2 3 the above code snippet confusing me. according to me it should throw Reference Error(because the time when console.log(i) execute, will look the value of i in global scope not in local scope, and i is not declare/defined in global. so it should give reference error.) Anyone who can explain how 2nd for loop working on Runtime ? A: When you use let in this context, a new binding/scope is created at each iteration. If you want to achieve a similar behavior in ES5 with var, you have to use an IIFE: for (var i = 0; i < 3; i++) { (function (i) { setTimeout(function () { console.log(i); }, 10); })(i); }
Q: Difference between let and var inside setTimeout? I know the difference between let and var. let is block scope and var is functional scope. for(var i=0; i< 3; i++){ setTimeout(function(){ console.log(i); }, 10); } output : 3 3 3 I know how above code snippet is working(console.log(i) is executing at that time when value of i is 3, because scope of i is global). But for(let i=0; i< 3; i++){ setTimeout(function(){ console.log(i); }, 10); } output : 1 2 3 the above code snippet confusing me. according to me it should throw Reference Error(because the time when console.log(i) execute, will look the value of i in global scope not in local scope, and i is not declare/defined in global. so it should give reference error.) Anyone who can explain how 2nd for loop working on Runtime ? A: When you use let in this context, a new binding/scope is created at each iteration. If you want to achieve a similar behavior in ES5 with var, you have to use an IIFE: for (var i = 0; i < 3; i++) { (function (i) { setTimeout(function () { console.log(i); }, 10); })(i); } A: The second example (using let) works because a function will close over all variables that are in scope when it is declared. Each iteration of the for loop a new variable is being created with let, the function in the timeout closes over the variable and keeps a referance. When the function is dereferenced after the timeout, so are its closure variables. See How do JavaScript closures work for more information on function closure. A: This is the magic of closure. In side your loop for(let i=0; i< 3; i++){ setTimeout(function(){ console.log(i); }, 10); } you are declaring a function function(){ console.log(i); } Additionally, the loop itself declares a block for(let i=0; i< 3; i++){ // this is a block scope because it is contained in // braces } Variables defined with let are block scoped. Because of closure, the function you declare inside the loop has access to all the variables declared in its scope and its parents scopes until it is garbage collected. A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time that the closure was created. The variable i is in-scope when the functions used by setTimeout are created. The i referred to is a different instance of i for each iteration of the loop. The function exists until the interval you declared passes. That is why each of the 3 functions declared in your loop print the value of i; it was declared in the containing scope and remains available to the function.
stackoverflow
{ "language": "en", "length": 463, "provenance": "stackexchange_0000F.jsonl.gz:885629", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606868" }
1e90d38b47f1a873c818d1297609c81632b2fdd8
Stackoverflow Stackexchange Q: how to export sql data to csv using bcp I use simple code declare @sql varchar(8000) select @sql = 'bcp ExcelAnalysis.dbo.ClearDB out c:\csv\comm.txt -c -t, -T -S '+ @@servername exec master..xp_cmdshell @sql but this code export all my table, but i need only some fields and conditions like: declare @sql varchar(8000) select @sql = 'bcp SELECT ,[vl] ,[data] ,[URL] ,[parse] ,[Strata] ,[Id] FROM [ExcelAnalysis].[dbo].[ClearDB] where [data]> "01.05.2017" and NOT [vl] ="mag"and NOT [vl] ="Maxximo" out c:\csv\status.txt -c -t, -T -S '+ @@servername exec master..xp_cmdshell @sql but if i use any fields, the bcd returns message with his syntax. How do correct? A: Bcp queryout option should be used. Syntax would be: SET @sql = 'bcp "SELECT [vl] ,[data] ,[URL] ,[parse] ,[Strata] ,[Id] FROM [dbo].[ClearDB] WHERE [data] > ''01.05.2017'' AND NOT [vl] =''mag'' AND NOT [vl] =''Maxximo''" queryout c:\csv\comm.txt -c -t, -T -S '+ @@servername + '\' + @@servicename
Q: how to export sql data to csv using bcp I use simple code declare @sql varchar(8000) select @sql = 'bcp ExcelAnalysis.dbo.ClearDB out c:\csv\comm.txt -c -t, -T -S '+ @@servername exec master..xp_cmdshell @sql but this code export all my table, but i need only some fields and conditions like: declare @sql varchar(8000) select @sql = 'bcp SELECT ,[vl] ,[data] ,[URL] ,[parse] ,[Strata] ,[Id] FROM [ExcelAnalysis].[dbo].[ClearDB] where [data]> "01.05.2017" and NOT [vl] ="mag"and NOT [vl] ="Maxximo" out c:\csv\status.txt -c -t, -T -S '+ @@servername exec master..xp_cmdshell @sql but if i use any fields, the bcd returns message with his syntax. How do correct? A: Bcp queryout option should be used. Syntax would be: SET @sql = 'bcp "SELECT [vl] ,[data] ,[URL] ,[parse] ,[Strata] ,[Id] FROM [dbo].[ClearDB] WHERE [data] > ''01.05.2017'' AND NOT [vl] =''mag'' AND NOT [vl] =''Maxximo''" queryout c:\csv\comm.txt -c -t, -T -S '+ @@servername + '\' + @@servicename A: First Part : Create a view in database and second part to execute statement to get results into CSV.Let me know if you need more help use [ExcelAnalysis]. go ; create view [dbo].[vw_ClearDB] as SELECT [vl] ,[data] ,[URL] ,[parse] ,[Strata] ,[Id] FROM [dbo].[ClearDB] where [data]> "01.05.2017" and NOT [vl] ='magand' NOT [vl] ='Maxximo' GO ; declare @sql varchar(8000) select @sql = 'bcp ExcelAnalysis.dbo.vw_ClearDB out c:\csv\comm.txt -c -t, -T -S '+ @@servername exec master..xp_cmdshell @sql
stackoverflow
{ "language": "en", "length": 224, "provenance": "stackexchange_0000F.jsonl.gz:885637", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606889" }
17ad15e850b712c9f72fe39be00956872a122936
Stackoverflow Stackexchange Q: Embedded tomcat giving failed to scan jars from classloader hierarchy I am newly trying out Embedded tomcat version 8.0.15. Downloaded the maven dependency into my project. Create the necessary context and instances. Tomcat server is coming up fine. But I am getting the below warnings Jun 17, 2017 9:50:44 PM org.apache.tomcat.util.scan.StandardJarScanner scan WARNING: Failed to scan [file:/C:/Users/raghavender.n/.m2/repository/xalan/xalan/2.7.2/xercesImpl.jar] from classloader hierarchy java.io.FileNotFoundException:C:\Users\raghavender.n\.m2\repository\xalan\xalan\2.7.2\xercesImpl.jar (The system cannot find the file specified) WARNING: Failed to scan [file:/C:/Users/raghavender.n/.m2/repository/xalan/xalan/2.7.2/xml-apis.jar] from classloader hierarchy java.io.FileNotFoundException: C:\Users\raghavender.n\.m2\repository\xalan\xalan\2.7.2\xml-apis.jar (The system cannot find the file specified) <!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-core --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <version>8.5.15</version> </dependency> How can i disable/avoid the warnings from embedded tomcat jar? A: Do not think xml-apis.jar is a dependency needed by tomcat-embed-core as shown with dependency hierachy. For your error, make sure scope of xml-apis.jar is not "provided", delete all files under C:/Users/raghavender.n/.m2/repository/xalan/xalan/ and do "mvn clean install" then check if xml-apis.jar is there. For Spring Web Application with Embeded Tomcat without Spring Boot , you may refer to this post.
Q: Embedded tomcat giving failed to scan jars from classloader hierarchy I am newly trying out Embedded tomcat version 8.0.15. Downloaded the maven dependency into my project. Create the necessary context and instances. Tomcat server is coming up fine. But I am getting the below warnings Jun 17, 2017 9:50:44 PM org.apache.tomcat.util.scan.StandardJarScanner scan WARNING: Failed to scan [file:/C:/Users/raghavender.n/.m2/repository/xalan/xalan/2.7.2/xercesImpl.jar] from classloader hierarchy java.io.FileNotFoundException:C:\Users\raghavender.n\.m2\repository\xalan\xalan\2.7.2\xercesImpl.jar (The system cannot find the file specified) WARNING: Failed to scan [file:/C:/Users/raghavender.n/.m2/repository/xalan/xalan/2.7.2/xml-apis.jar] from classloader hierarchy java.io.FileNotFoundException: C:\Users\raghavender.n\.m2\repository\xalan\xalan\2.7.2\xml-apis.jar (The system cannot find the file specified) <!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-core --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <version>8.5.15</version> </dependency> How can i disable/avoid the warnings from embedded tomcat jar? A: Do not think xml-apis.jar is a dependency needed by tomcat-embed-core as shown with dependency hierachy. For your error, make sure scope of xml-apis.jar is not "provided", delete all files under C:/Users/raghavender.n/.m2/repository/xalan/xalan/ and do "mvn clean install" then check if xml-apis.jar is there. For Spring Web Application with Embeded Tomcat without Spring Boot , you may refer to this post. A: you can add server.tomcat.additional-tld-skip-patterns=*.jar in application.propertiesfile or server: tomcat: additional-tld-skip-patterns: '*.jar' in application.ymlfile. Refer : The Jar Scanner Component、The official reply. A: For workaround, in catalina.properties file put the following line: tomcat.util.scan.StandardJarScanFilter.jarsToSkip=*.jar
stackoverflow
{ "language": "en", "length": 197, "provenance": "stackexchange_0000F.jsonl.gz:885647", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606914" }
117b7812acf10bb8d464e3a223e2540ee7c9798f
Stackoverflow Stackexchange Q: How to unsubscribe from redux store when component will unmount? How to decorate redux connect? I am passing the following props (storeName) to my component: <MyComponent reducerName="city" /> and I want to connect to store with a dynamic name (this.props.reducerName) for example export default connect(state => ({ some: state[this.props.reducerName] }), { })(MyComponent); How to decorate redux connect, or what i must to do? I tried to skip redux connect and used store.subscribe componentDidMount() { store.subscribe(() => { this.setState({some: store.getState([this.props.reducerName]}); }); } But when I move to another page, I see the following error: Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. How to unsubscribe from redux store when component will unmount? A: To unsubscribe you can simple execute the function return by store.subscribe: componentDidMount() { this.unsubscribe = store.subscribe(() => { // ... }); } componentWillUnmount() { this.unsubscribe(); }
Q: How to unsubscribe from redux store when component will unmount? How to decorate redux connect? I am passing the following props (storeName) to my component: <MyComponent reducerName="city" /> and I want to connect to store with a dynamic name (this.props.reducerName) for example export default connect(state => ({ some: state[this.props.reducerName] }), { })(MyComponent); How to decorate redux connect, or what i must to do? I tried to skip redux connect and used store.subscribe componentDidMount() { store.subscribe(() => { this.setState({some: store.getState([this.props.reducerName]}); }); } But when I move to another page, I see the following error: Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. How to unsubscribe from redux store when component will unmount? A: To unsubscribe you can simple execute the function return by store.subscribe: componentDidMount() { this.unsubscribe = store.subscribe(() => { // ... }); } componentWillUnmount() { this.unsubscribe(); } A: connect has a second parameter of ownProps, which is an object containing all passed-in props. You would do something like this: const mapStateToProps = (state, { reducerName = 'defaultReducer' }) => ({ some: state[reducerName], }); export default connect(mapStateToProps)(MyComponent);
stackoverflow
{ "language": "en", "length": 194, "provenance": "stackexchange_0000F.jsonl.gz:885661", "question_score": "17", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44606955" }
5a17f83ba8ec28c9debe90e72bf2b3a6e9ab1f60
Stackoverflow Stackexchange Q: Behaviour of std::array vs. std::vector Does the std::array<bool> implement the same bit packing memory optimisation that std::vector<bool> does? Thanks! A: No, std::array has no specialization for bool type. You can find more details here, but, basically, std::array is just a: an aggregate type with the same semantics as a struct holding a C-style array T[N] and in case of bool you might consider it as a C-style array of bools, not any kind of bitset.
Q: Behaviour of std::array vs. std::vector Does the std::array<bool> implement the same bit packing memory optimisation that std::vector<bool> does? Thanks! A: No, std::array has no specialization for bool type. You can find more details here, but, basically, std::array is just a: an aggregate type with the same semantics as a struct holding a C-style array T[N] and in case of bool you might consider it as a C-style array of bools, not any kind of bitset.
stackoverflow
{ "language": "en", "length": 76, "provenance": "stackexchange_0000F.jsonl.gz:885801", "question_score": "21", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44607389" }
dff7ed074791e168202d808418b63889ed4a0051
Stackoverflow Stackexchange Q: Cannot kill Postgres process I keep trying to kill a PostgreSQL process that is running on port 5432 to no avail. Whenever I type sudo lsof -i :5432, I see something like the below: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME postgres 587 postgres 4u IPv6 0x218f97e9af5d0303 0t0 TCP *:postgresql (LISTEN) postgres 587 postgres 5u IPv4 0x218f97e9ae0f6c63 0t0 TCP *:postgresql (LISTEN) I then try to kill the process 587 in this example with sudo kill -9 587, but then another process automatically restarts on the same port! I have tried killing it on activity monitor as well to no avail. Please help? Thanks, Laura A: list your postgres pid: pg_ctl status -D /usr/local/var/postgres pg_ctl: server is running (PID: 715) force kill it.. kill -9 715
Q: Cannot kill Postgres process I keep trying to kill a PostgreSQL process that is running on port 5432 to no avail. Whenever I type sudo lsof -i :5432, I see something like the below: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME postgres 587 postgres 4u IPv6 0x218f97e9af5d0303 0t0 TCP *:postgresql (LISTEN) postgres 587 postgres 5u IPv4 0x218f97e9ae0f6c63 0t0 TCP *:postgresql (LISTEN) I then try to kill the process 587 in this example with sudo kill -9 587, but then another process automatically restarts on the same port! I have tried killing it on activity monitor as well to no avail. Please help? Thanks, Laura A: list your postgres pid: pg_ctl status -D /usr/local/var/postgres pg_ctl: server is running (PID: 715) force kill it.. kill -9 715 A: Try to run this command: sudo pkill -u postgres A: If you installed postgres using brew, this command might be what you are looking for : brew services stop postgres A: The process is restarting likely because it's spawned from a launchd daemon. You can try finding it and killing it through the launchctl command: $ launchctl list To kill a process you would: $ launchctl kill A: I have 9.5 and 9.6 installed, so sudo su - postgres /Library/PostgreSQL/9.6/bin/pg_ctl -D /Library/PostgreSQL/9.6/data stop 9.5 started ... /Library/PostgreSQL/9.5/bin/pg_ctl -D /Library/PostgreSQL/9.5/data stop A: I had this issue and what I did to resolve it was first run brew services to see a list of the services that home brew is running. In my case the service was called 'postgresql@12' so I had to run brew services stop postgres@12 A: I had this issue trying to stop postgres. I was unable to use pg_ctl stop. I installed postgress using brew. I eventually stumbled upon this post which solved the issue for me. A: For those who's still struggling. You can give it a try with the steps below brew install pstree // enables you to see structuralized tree process pstree | grep postgre Remember the path of the parent task Example) /opt/homebrew/var/postgres Then you remove the .pid file located at the directory of the parent task rm -rf <path of the parent task>/postmaster.pid kill <PID of the parent task> I hope it works for you too :)
stackoverflow
{ "language": "en", "length": 373, "provenance": "stackexchange_0000F.jsonl.gz:885811", "question_score": "35", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44607421" }
8aedb3800104fed1c14367c3a51e62a31dbdc5a5
Stackoverflow Stackexchange Q: How to resolve error 400 in excel-vba I am writing an excel-vba to find and delete entire row if having blanks cell in a particular column. My macro is working fine if there is at least one blank cell but showing error 400 if there is no blank cell. My code is Sub GPF_Sign() Dim i As Integer, n as integer Dim LROW As Long LROW = Sheets("GPF").Range("B200").End(xlUp).Row n = Range("D9:D" & LROW).SpecialCells(xlCellTypeBlanks).Cells.Count If n > 0 Then Range("D9:D" & LROW).SpecialCells(xlCellTypeBlanks).EntireRow.Delete End If End Sub A: You can use On Error Resume Next, but this is not a usually recommended approach because it may mask other errors. Instead, try computing n in an error free way: n = Application.CountIf(Sheets("GPF").Range("D9:D" & LROW), "") yet another, still better way is to use AutoFilter: Sub GPF_Sign() With Sheets("GPF").Range("D8:D200") .AutoFilter 1, "" .Offset(1).EntireRow.Delete .AutoFilter End With End Sub
Q: How to resolve error 400 in excel-vba I am writing an excel-vba to find and delete entire row if having blanks cell in a particular column. My macro is working fine if there is at least one blank cell but showing error 400 if there is no blank cell. My code is Sub GPF_Sign() Dim i As Integer, n as integer Dim LROW As Long LROW = Sheets("GPF").Range("B200").End(xlUp).Row n = Range("D9:D" & LROW).SpecialCells(xlCellTypeBlanks).Cells.Count If n > 0 Then Range("D9:D" & LROW).SpecialCells(xlCellTypeBlanks).EntireRow.Delete End If End Sub A: You can use On Error Resume Next, but this is not a usually recommended approach because it may mask other errors. Instead, try computing n in an error free way: n = Application.CountIf(Sheets("GPF").Range("D9:D" & LROW), "") yet another, still better way is to use AutoFilter: Sub GPF_Sign() With Sheets("GPF").Range("D8:D200") .AutoFilter 1, "" .Offset(1).EntireRow.Delete .AutoFilter End With End Sub A: Take your pick Way 1: Using OERN (On Error Resume Next) Sub WAY_ONE() Dim ws As Worksheet, LROW As Long Dim rng As Range Set ws = Sheets("GPF") With ws LROW = .Range("B" & .Rows.Count).End(xlUp).Row On Error Resume Next Set rng = .Range("D9:D" & LROW).SpecialCells(xlCellTypeBlanks) On Error GoTo 0 If Not rng Is Nothing Then rng.EntireRow.Delete End With End Sub Way 2: Using Autofilter Sub WAY_TWO() Dim ws As Worksheet, LROW As Long Dim rng As Range Set ws = Sheets("GPF") With ws .AutoFilterMode = False LROW = .Range("B" & .Rows.Count).End(xlUp).Row Set rng = .Range("D9:D" & LROW) With rng 'Filter, offset(to exclude headers) and delete visible rows .AutoFilter Field:=1, Criteria1:="" .Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With .AutoFilterMode = False End With End Sub A: The method you are using ".SpecialCells(xlCellTypeBlanks)" is attempting to return a range. If there are no blank cells, the next part ".cells.count" is attempting to count Nothing. That's why it gives you an error. Since you are already checking if n>0, you could just add On Error Resume Next right above the "n= " line. If there is more code after this, you probably want to put a On Error GoTo 0 after this part so it doesn't ignore later errors.
stackoverflow
{ "language": "en", "length": 348, "provenance": "stackexchange_0000F.jsonl.gz:885812", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44607423" }
ef3aa3ad91dec9d0797cc0a1988995ca69657b06
Stackoverflow Stackexchange Q: How do I test that I'm calling pickle.dump() correctly? I want to test this method: class Data(object): def save(self, filename=''): if filename: self.filename = filename if not self.filename: raise ValueError('Please provide a path to save to') with open(self.filename, 'w') as f: pickle.dump(self, f) I can set up the test to make sure pickle.dump gets called, and that the first argument is the object: @patch('pickle.dump') def test_pickle_called(self, dump): self.data.save('foo.pkl') self.assertTrue(dump.called) self.assertEquals(self.data, dump.call_args[0][0]) I'm not sure what to do for the second argument, though. If I open a new file for the test, it's not going to be the same as what gets called for the execution. I'd at least like to be sure I'm opening the right file. Would I just mock open and make sure that gets called with the right name at some point? A: Patch open() and return an instance of writeable StringIO from it. Load pickled data from that StringIO and test its structure and values (test that it's equivalent to self.data). Something like this: import builtins # or __builtin__ for Python 2 builtins.open = open = Mock() open.return_value = sio = StringIO() self.data.save('foo.pkl') new_data = pickle.load(sio.getvalue()) self.assertEqual(self.data, new_data)
Q: How do I test that I'm calling pickle.dump() correctly? I want to test this method: class Data(object): def save(self, filename=''): if filename: self.filename = filename if not self.filename: raise ValueError('Please provide a path to save to') with open(self.filename, 'w') as f: pickle.dump(self, f) I can set up the test to make sure pickle.dump gets called, and that the first argument is the object: @patch('pickle.dump') def test_pickle_called(self, dump): self.data.save('foo.pkl') self.assertTrue(dump.called) self.assertEquals(self.data, dump.call_args[0][0]) I'm not sure what to do for the second argument, though. If I open a new file for the test, it's not going to be the same as what gets called for the execution. I'd at least like to be sure I'm opening the right file. Would I just mock open and make sure that gets called with the right name at some point? A: Patch open() and return an instance of writeable StringIO from it. Load pickled data from that StringIO and test its structure and values (test that it's equivalent to self.data). Something like this: import builtins # or __builtin__ for Python 2 builtins.open = open = Mock() open.return_value = sio = StringIO() self.data.save('foo.pkl') new_data = pickle.load(sio.getvalue()) self.assertEqual(self.data, new_data)
stackoverflow
{ "language": "en", "length": 193, "provenance": "stackexchange_0000F.jsonl.gz:885827", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44607468" }
23da132bb2a2863e2a2c1dc9798eea0238826d2d
Stackoverflow Stackexchange Q: Python Interactive Is there a way to execute a method automatically from a python file after each command input while in python interactive? For example: If I have a method that prints information about file, but I do not want to call that method constantly, how can I make it output after each command in python interactive? A: sys.displayhook is the function called to display values in the interactive interpreter. You can provide your own that performs other actions: >>> 2+2 4 >>> original_display_hook = sys.displayhook >>> def my_display_hook(value): ... original_display_hook(value) ... print("Hello there from the hook!") ... >>> sys.displayhook = my_display_hook >>> 2+2 4 Hello there from the hook! >>>
Q: Python Interactive Is there a way to execute a method automatically from a python file after each command input while in python interactive? For example: If I have a method that prints information about file, but I do not want to call that method constantly, how can I make it output after each command in python interactive? A: sys.displayhook is the function called to display values in the interactive interpreter. You can provide your own that performs other actions: >>> 2+2 4 >>> original_display_hook = sys.displayhook >>> def my_display_hook(value): ... original_display_hook(value) ... print("Hello there from the hook!") ... >>> sys.displayhook = my_display_hook >>> 2+2 4 Hello there from the hook! >>>
stackoverflow
{ "language": "en", "length": 112, "provenance": "stackexchange_0000F.jsonl.gz:885836", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44607513" }
7ec312ea3482ce9300cf5863f40b92ac37b52b47
Stackoverflow Stackexchange Q: How to do intermediate process in list comprehension I have a list of string that look like that : ['1 2 3 4 5', '1 2 3 4 5',...] And I want for example only the third and fifth element of each string : [(3,5), (3,5),...] how can I do something like this : [(ans[2],ans[4]); ans.split() for ans in answers] ? A: Use operator.itemgetter to get multiple items from different indices: from operator import itemgetter lst = ['1 2 3 4 5', '1 2 3 4 5'] f = itemgetter(2, 4) # get third and fifth items r = [f(x.split()) for x in lst] print(r) # [('3', '5'), ('3', '5')] Cool thing is, it also works with slice objects: f = itemgetter(2, 4, slice(3, 0, -1)) r = [f(x.split()) for x in lst] print(r) # [('3', '5', ['4', '3', '2']), ('3', '5', ['4', '3', '2'])]
Q: How to do intermediate process in list comprehension I have a list of string that look like that : ['1 2 3 4 5', '1 2 3 4 5',...] And I want for example only the third and fifth element of each string : [(3,5), (3,5),...] how can I do something like this : [(ans[2],ans[4]); ans.split() for ans in answers] ? A: Use operator.itemgetter to get multiple items from different indices: from operator import itemgetter lst = ['1 2 3 4 5', '1 2 3 4 5'] f = itemgetter(2, 4) # get third and fifth items r = [f(x.split()) for x in lst] print(r) # [('3', '5'), ('3', '5')] Cool thing is, it also works with slice objects: f = itemgetter(2, 4, slice(3, 0, -1)) r = [f(x.split()) for x in lst] print(r) # [('3', '5', ['4', '3', '2']), ('3', '5', ['4', '3', '2'])] A: You first perform a mapping, for instance using a genrator: (ans.split() for ans in answers) and then you iterate over the generator, and process the intermediate result further, like: [(imm[2],imm[4]) for imm in (ans.split() for ans in answers)] generating: >>> [(imm[2],imm[4]) for imm in (ans.split() for ans in answers)] [('3', '5'), ('3', '5')]
stackoverflow
{ "language": "en", "length": 200, "provenance": "stackexchange_0000F.jsonl.gz:885852", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44607571" }
639c0d4db2f8be4bfeba9c444540f21c8ae2399c
Stackoverflow Stackexchange Q: What is a difference between "foo is null" and "foo == null" Is there any difference between: foo is null and foo == null? A: From the MSDN Docs: Is operator Checks if an object is compatible with a given type, or (starting with C# 7) tests an expression against a pattern. The is keyword evaluates type compatibility at runtime. It determines whether an object instance or the result of an expression can be converted to a specified type. == is For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings. Summary: No, there isn't in this example. is is normally use if you wanna check the type. In this case it is null. == if you wanna check the value. In this case also null, so both would evaluate to true.
Q: What is a difference between "foo is null" and "foo == null" Is there any difference between: foo is null and foo == null? A: From the MSDN Docs: Is operator Checks if an object is compatible with a given type, or (starting with C# 7) tests an expression against a pattern. The is keyword evaluates type compatibility at runtime. It determines whether an object instance or the result of an expression can be converted to a specified type. == is For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings. Summary: No, there isn't in this example. is is normally use if you wanna check the type. In this case it is null. == if you wanna check the value. In this case also null, so both would evaluate to true. A: Short version: For well-behaved types, there is no difference between foo is null and foo == null. Long version: When you write foo == null and an appropriate overload of operator == exists, then that's what is called. Otherwise, reference equality is used for reference types and value equality is used for value types. When you write foo is null for a reference type, this is compiled as if you wrote object.Equals(null, foo) (notice the switched order, it makes a difference). In effect, this performs reference equality comparison between foo and null. For a value type, foo is null does not compile. This means that if you write a class with operator == that says that some instance of foo is equal to null, then foo == null will give different result than foo is null. An example showing this: using System; public class Foo { public static void Main() { var foo = new Foo(); Console.WriteLine(foo == null); Console.WriteLine(foo is null); } public static bool operator ==(Foo foo1, Foo foo2) => true; // operator != has to exist to appease the compiler public static bool operator !=(Foo foo1, Foo foo2) => false; } This code outputs: True False When you overload operator ==, you should make it behave in a reasonable way, which, among other things, means you should not say that foo == null is true for non-null foo. As a side effect of this, under normal circumstances, foo == null and foo is null will have the same value.
stackoverflow
{ "language": "en", "length": 425, "provenance": "stackexchange_0000F.jsonl.gz:885857", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44607581" }
21aeee7e0ff9bb3d92bce715b3f3e73b32629152
Stackoverflow Stackexchange Q: Why does the closure compiler create void 0 instead of shorter alternatives? Comparing these strings: {}[0] [][0] void 0 Why does Closure Compiler generate void 0 when it could generate [][0] or {}[0] or even [].a as torazaburo mentioned which are 1 character shorter? A: Minimum code size isn't the only goal of the Closure compiler. Another goal (I assume) is to generate code that is as fast as the original. void 0 is likely to be faster across various JavaScript runtimes. It doesn't have to construct an object or array and dereference a nonexistent property. A JavaScript runtime engine could possibly optimize away the {}[0] or [][0], but why would the Closure compiler want to depend on that? If those don't get optimized away, they would be significantly slower than void 0. Keep in mind that JavaScript code is usually downloaded in compressed form, and if void 0 appears in multiple places they are likely to get compressed out. Also see Blaise's answer for another good reason not to use {}[0] or [][0].
Q: Why does the closure compiler create void 0 instead of shorter alternatives? Comparing these strings: {}[0] [][0] void 0 Why does Closure Compiler generate void 0 when it could generate [][0] or {}[0] or even [].a as torazaburo mentioned which are 1 character shorter? A: Minimum code size isn't the only goal of the Closure compiler. Another goal (I assume) is to generate code that is as fast as the original. void 0 is likely to be faster across various JavaScript runtimes. It doesn't have to construct an object or array and dereference a nonexistent property. A JavaScript runtime engine could possibly optimize away the {}[0] or [][0], but why would the Closure compiler want to depend on that? If those don't get optimized away, they would be significantly slower than void 0. Keep in mind that JavaScript code is usually downloaded in compressed form, and if void 0 appears in multiple places they are likely to get compressed out. Also see Blaise's answer for another good reason not to use {}[0] or [][0]. A: {}[0] doesn't (always? see comments) return undefined, and [][0] could in theory return something other than undefined since you can override Array constructors/getters.
stackoverflow
{ "language": "en", "length": 199, "provenance": "stackexchange_0000F.jsonl.gz:885887", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44607683" }
d9e264748b792a5092732292d2de83612152cf49
Stackoverflow Stackexchange Q: python error "quote_from_bytes() expected bytes" So I have this code snippet that returns an error whenever I try to execute it. Below is the code, it's supposed to make a google image search based on flexible amount of string arguments. @bot.command() async def randomimage(*args): """Displays a random image of said thing""" q = '' for arg in enumerate(args): q += urllib.parse.quote(arg) + '+' f = urllib2.urlopen('http://ajax.googleapis.com/ajax/services/search/images?q=' + q + '&v=1.0&rsz=large&start=1') data = json.load(f) f.close() I get this error when I try to execute it however: Traceback (most recent call last): File "Python36\lib\site-packages\discord\ext\commands\core.py", line 50, in wrapped ret = yield from coro(*args, **kwargs) File "bot.py", line 39, in randomimage q += urllib.parse.quote(arg) + '+' File "parse.py", line 775, in quote return quote_from_bytes(string, safe) File "parse.py", line 800, in quote_from_bytes raise TypeError("quote_from_bytes() expected bytes") TypeError: quote_from_bytes() expected bytes Any help would be appreciated A: Is args a list of strings? If so, you should convert them to bytes for urllib.parse.quote to work properly. Change q += urllib.parse.quote(arg) + '+' to q += urllib.parse.quote(arg.encode('utf-8')) + '+' or q += urllib.parse.quote(bytes(arg)) + '+'
Q: python error "quote_from_bytes() expected bytes" So I have this code snippet that returns an error whenever I try to execute it. Below is the code, it's supposed to make a google image search based on flexible amount of string arguments. @bot.command() async def randomimage(*args): """Displays a random image of said thing""" q = '' for arg in enumerate(args): q += urllib.parse.quote(arg) + '+' f = urllib2.urlopen('http://ajax.googleapis.com/ajax/services/search/images?q=' + q + '&v=1.0&rsz=large&start=1') data = json.load(f) f.close() I get this error when I try to execute it however: Traceback (most recent call last): File "Python36\lib\site-packages\discord\ext\commands\core.py", line 50, in wrapped ret = yield from coro(*args, **kwargs) File "bot.py", line 39, in randomimage q += urllib.parse.quote(arg) + '+' File "parse.py", line 775, in quote return quote_from_bytes(string, safe) File "parse.py", line 800, in quote_from_bytes raise TypeError("quote_from_bytes() expected bytes") TypeError: quote_from_bytes() expected bytes Any help would be appreciated A: Is args a list of strings? If so, you should convert them to bytes for urllib.parse.quote to work properly. Change q += urllib.parse.quote(arg) + '+' to q += urllib.parse.quote(arg.encode('utf-8')) + '+' or q += urllib.parse.quote(bytes(arg)) + '+'
stackoverflow
{ "language": "en", "length": 180, "provenance": "stackexchange_0000F.jsonl.gz:885909", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44607755" }
bb61b3b54ceff909be9ba53d2920ddac092ba276
Stackoverflow Stackexchange Q: Invoke-RestMethod Powershell V3 Content-Type I am able to use the JIRA rest API from powershell v5. However the same code throws the below error in powershell v3. WARNING: Remote Server Response: The 'Content-Type' header must be modified using the appropriate property or method. Source Code $basicAuth = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Username):$Password")) $headers = @{ "Authorization" = $basicAuth "Content-Type"="application/json" } $response = Invoke-RestMethod -Uri $requestUri -Method POST -Headers $headers -Body $body A: Invoke-Restmethod has a -ContentType parameter, so the error seems to be indicating you should use that to specify Content Type instead of passing it via the headers parameter: $basicAuth = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Username):$Password")) $headers = @{ "Authorization" = $basicAuth } $response = Invoke-RestMethod -Uri $requestUri -Method POST -Headers $headers -Body $body -ContentType 'application/json'
Q: Invoke-RestMethod Powershell V3 Content-Type I am able to use the JIRA rest API from powershell v5. However the same code throws the below error in powershell v3. WARNING: Remote Server Response: The 'Content-Type' header must be modified using the appropriate property or method. Source Code $basicAuth = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Username):$Password")) $headers = @{ "Authorization" = $basicAuth "Content-Type"="application/json" } $response = Invoke-RestMethod -Uri $requestUri -Method POST -Headers $headers -Body $body A: Invoke-Restmethod has a -ContentType parameter, so the error seems to be indicating you should use that to specify Content Type instead of passing it via the headers parameter: $basicAuth = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Username):$Password")) $headers = @{ "Authorization" = $basicAuth } $response = Invoke-RestMethod -Uri $requestUri -Method POST -Headers $headers -Body $body -ContentType 'application/json'
stackoverflow
{ "language": "en", "length": 126, "provenance": "stackexchange_0000F.jsonl.gz:885925", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44607806" }
108e645057f4624672838767346418ca2144cbb8
Stackoverflow Stackexchange Q: GitHub pages: 404 on / but /index.html works fine my situation is the following: * *I have deployed a jekyll site to github using the docs folder on the master branch *It has a markdown index file *username.github.io/repo/index.html works *username.github.io/repo/ returns a 404 The site works well locally using jekyll serve (no 404). I'd expect GitHub to return the content of index.html when receiving a request for a directory. Could it be a problem with markdown?
Q: GitHub pages: 404 on / but /index.html works fine my situation is the following: * *I have deployed a jekyll site to github using the docs folder on the master branch *It has a markdown index file *username.github.io/repo/index.html works *username.github.io/repo/ returns a 404 The site works well locally using jekyll serve (no 404). I'd expect GitHub to return the content of index.html when receiving a request for a directory. Could it be a problem with markdown?
stackoverflow
{ "language": "en", "length": 77, "provenance": "stackexchange_0000F.jsonl.gz:885944", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44607868" }
7b7bf665947e6a6cd0d683e0f3d762a57fd3efd5
Stackoverflow Stackexchange Q: iOS How can I use pushviewcontroller with NavigationController(Objective - c) I want to change view by clicking button with NavigationController So I added a button to Main.storyboard and write some codes like @property (weak, nonatomic) IBOutlet UIButton *button; in my ViewController.m (Created automatically when I made my project) And I added method - (IBAction)buttonClicked:(id)sender { SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil]; [self.navigationController pushViewController:secondViewController animated:YES]; } (I made SecondViewController.m, SecondViewController.h, SecondViewController.xib) After this, I started the application and clicked the button but the screen didn't change. Actually, when I added log like NSLog(@"%@", self.navigationController); null was printed. I think I need to add some code about NavigationController to AppDelegate.m but I don't know what to do. Please help me. A: Try This, in Appdelegate.m `- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; UINavigationController *navigation = [[UINavigationController alloc]initWithRootViewController:self.viewController]; self.window.rootViewController = navigation; [self.window makeKeyAndVisible]; return YES; }` You need to embed Navigation Controller through code or Storyboard.
Q: iOS How can I use pushviewcontroller with NavigationController(Objective - c) I want to change view by clicking button with NavigationController So I added a button to Main.storyboard and write some codes like @property (weak, nonatomic) IBOutlet UIButton *button; in my ViewController.m (Created automatically when I made my project) And I added method - (IBAction)buttonClicked:(id)sender { SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil]; [self.navigationController pushViewController:secondViewController animated:YES]; } (I made SecondViewController.m, SecondViewController.h, SecondViewController.xib) After this, I started the application and clicked the button but the screen didn't change. Actually, when I added log like NSLog(@"%@", self.navigationController); null was printed. I think I need to add some code about NavigationController to AppDelegate.m but I don't know what to do. Please help me. A: Try This, in Appdelegate.m `- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; UINavigationController *navigation = [[UINavigationController alloc]initWithRootViewController:self.viewController]; self.window.rootViewController = navigation; [self.window makeKeyAndVisible]; return YES; }` You need to embed Navigation Controller through code or Storyboard. A: First select your initial viewcontroller in storyboard and embed it in NavigationController. Then give a storyboard identifier to the second viewcontroller. Then lastly instantiate Second ViewController from storyboard and push it. - (IBAction)buttonClicked:(id)sender { SecondViewController *secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"]; [self.navigationController pushViewController:entryController animated:YES]; }
stackoverflow
{ "language": "en", "length": 219, "provenance": "stackexchange_0000F.jsonl.gz:885945", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44607871" }
ea5b426a3037d67000aba8c69334387f3d617591
Stackoverflow Stackexchange Q: Matplotlib plot window is black I recently started studying python and matplotlib. The problem I face is that I always get a black window as a plot output. See simple code below. import numpy as np import matplotlib.pyplot as plt import pylab x = np.arange(0, 5, 0.1) y = np.sin(x) #plot the x and y and you are supposed to see a sine curve plt.plot(x, y) pylab.show() I get the same result executing code samples from matplotlib pages. Does anyone have any idea where this comes from and how to overcome this? I'm using the Operating system Linux Mint. A: I executed code in python shell and it works, the problem comes executing code in python editors. I worked with two different editors. Best regards Robert
Q: Matplotlib plot window is black I recently started studying python and matplotlib. The problem I face is that I always get a black window as a plot output. See simple code below. import numpy as np import matplotlib.pyplot as plt import pylab x = np.arange(0, 5, 0.1) y = np.sin(x) #plot the x and y and you are supposed to see a sine curve plt.plot(x, y) pylab.show() I get the same result executing code samples from matplotlib pages. Does anyone have any idea where this comes from and how to overcome this? I'm using the Operating system Linux Mint. A: I executed code in python shell and it works, the problem comes executing code in python editors. I worked with two different editors. Best regards Robert
stackoverflow
{ "language": "en", "length": 127, "provenance": "stackexchange_0000F.jsonl.gz:885958", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44607918" }
1fa52870268ef50919fbde7981c8745618e49438
Stackoverflow Stackexchange Q: How to give access permissions to broker in OpenMQ JMS I am getting this error when I am creating producer on server to give response back to client using getJMSReplyTo() com.sun.messaging.jms.MQRuntimeException: [C4076]: Client does not have permission to create producer on destination: temporary_destination://queue/10.59.12.160/57006/1 user=guest, broker=localhost:7676(61127) as it is clearly the error of authentication I changed few lines in access.properties file too but still getting this error. Does anyone know is there any other permission file in OpenMQ or how to configure the broker so that producer can be created anywhere.
Q: How to give access permissions to broker in OpenMQ JMS I am getting this error when I am creating producer on server to give response back to client using getJMSReplyTo() com.sun.messaging.jms.MQRuntimeException: [C4076]: Client does not have permission to create producer on destination: temporary_destination://queue/10.59.12.160/57006/1 user=guest, broker=localhost:7676(61127) as it is clearly the error of authentication I changed few lines in access.properties file too but still getting this error. Does anyone know is there any other permission file in OpenMQ or how to configure the broker so that producer can be created anywhere.
stackoverflow
{ "language": "en", "length": 91, "provenance": "stackexchange_0000F.jsonl.gz:885990", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44608016" }
36b5996a8d2eb7d37a63078bec3372843bbc6e93
Stackoverflow Stackexchange Q: How does Python share memory among multiple processes? I read that processes operate on seperate memory spaces (link). However the multiprocessing package of python offers shared memory (multiprocessing.Value, multiprocessing.Array). * *Where (in which process) is this data stored? *Is the data accessed by reference by the child processes? A: The data is allocated in a shared, anonymous memory map created through the mmap module. You can see the code here and here.
Q: How does Python share memory among multiple processes? I read that processes operate on seperate memory spaces (link). However the multiprocessing package of python offers shared memory (multiprocessing.Value, multiprocessing.Array). * *Where (in which process) is this data stored? *Is the data accessed by reference by the child processes? A: The data is allocated in a shared, anonymous memory map created through the mmap module. You can see the code here and here.
stackoverflow
{ "language": "en", "length": 73, "provenance": "stackexchange_0000F.jsonl.gz:886001", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44608043" }
d6bc84c922fa8ad42a6fed17526d3cfb582f8256
Stackoverflow Stackexchange Q: Refreshing an SSL certificate in Express I'm using a letsencrypt certificate on an Express server to enable https. The certificate is automatically renewed by a cron job running certbot-auto periodically. Express reads the certificate file at startup. Do I need to do something to let Express know when the certificate is renewed, or will it pick up the changes automatically? If I need to manually refresh it, how would I do so without restarting the whole app?
Q: Refreshing an SSL certificate in Express I'm using a letsencrypt certificate on an Express server to enable https. The certificate is automatically renewed by a cron job running certbot-auto periodically. Express reads the certificate file at startup. Do I need to do something to let Express know when the certificate is renewed, or will it pick up the changes automatically? If I need to manually refresh it, how would I do so without restarting the whole app?
stackoverflow
{ "language": "en", "length": 78, "provenance": "stackexchange_0000F.jsonl.gz:886045", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44608193" }
154c6794d47d75fbc6599782e4a3ec85f77e5632
Stackoverflow Stackexchange Q: Anchor smooth scrolling not working on a Wordpress site I have this smooth anchor scroll code inserted on my Wordpress site http://www.ilovestvincent.com jQuery(function(){ jQuery('a[href^="#"]').on('click',function (e) { var target = this.hash; var $target = jQuery(target); jQuery('html, body').stop().animate({ 'scrollTop': $(target).offset().top }, 900, 'swing', function () { window.location.hash = target; }); }); }); This should trigger a smooth scroll when clicking the top menu links but it's not working. This code is working fine on my other sites but I'm stumped as to why it wouldn't be working on ilovestvincent.com. Any tips would be highly appreciated, cheers. A: Here is the snippet which should work: jQuery(document).ready(function(){ jQuery('a[href^="#"]').click(function() { var target = jQuery(this).attr('href'); jQuery('html, body').stop().animate({ 'scrollTop': target.offset().top }, 900, 'swing', function () { window.location.hash = target; }); }); });
Q: Anchor smooth scrolling not working on a Wordpress site I have this smooth anchor scroll code inserted on my Wordpress site http://www.ilovestvincent.com jQuery(function(){ jQuery('a[href^="#"]').on('click',function (e) { var target = this.hash; var $target = jQuery(target); jQuery('html, body').stop().animate({ 'scrollTop': $(target).offset().top }, 900, 'swing', function () { window.location.hash = target; }); }); }); This should trigger a smooth scroll when clicking the top menu links but it's not working. This code is working fine on my other sites but I'm stumped as to why it wouldn't be working on ilovestvincent.com. Any tips would be highly appreciated, cheers. A: Here is the snippet which should work: jQuery(document).ready(function(){ jQuery('a[href^="#"]').click(function() { var target = jQuery(this).attr('href'); jQuery('html, body').stop().animate({ 'scrollTop': target.offset().top }, 900, 'swing', function () { window.location.hash = target; }); }); });
stackoverflow
{ "language": "en", "length": 126, "provenance": "stackexchange_0000F.jsonl.gz:886101", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44608355" }
01c5135b36e953b402b1f17cf3bf8523e723f7f7
Stackoverflow Stackexchange Q: Pandas replace column values with a list I have a dataframe df where some of the columns are strings and some are numeric. I am trying to convert all of them to numeric. So what I would like to do is something like this: col = df.ix[:,i] le = preprocessing.LabelEncoder() le.fit(col) newCol = le.transform(col) df.ix[:,i] = newCol but this does not work. Basically my question is how do I delete a column from a data frame then create a new column with the same name as the column I deleted when I do not know the column name, only the column index? A: This should do it for you: # Find the name of the column by index n = df.columns[1] # Drop that column df.drop(n, axis = 1, inplace = True) # Put whatever series you want in its place df[n] = newCol ...where [1] can be whatever the index is, axis = 1 should not change. This answers your question very literally where you asked to drop a column and then add one back in. But the reality is that there is no need to drop the column if you just replace it with newCol.
Q: Pandas replace column values with a list I have a dataframe df where some of the columns are strings and some are numeric. I am trying to convert all of them to numeric. So what I would like to do is something like this: col = df.ix[:,i] le = preprocessing.LabelEncoder() le.fit(col) newCol = le.transform(col) df.ix[:,i] = newCol but this does not work. Basically my question is how do I delete a column from a data frame then create a new column with the same name as the column I deleted when I do not know the column name, only the column index? A: This should do it for you: # Find the name of the column by index n = df.columns[1] # Drop that column df.drop(n, axis = 1, inplace = True) # Put whatever series you want in its place df[n] = newCol ...where [1] can be whatever the index is, axis = 1 should not change. This answers your question very literally where you asked to drop a column and then add one back in. But the reality is that there is no need to drop the column if you just replace it with newCol. A: newcol = [..,..,.....] df['colname'] = newcol This will keep the colname intact while replacing its contents with newcol.
stackoverflow
{ "language": "en", "length": 217, "provenance": "stackexchange_0000F.jsonl.gz:886159", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44608524" }
66266ecc826dbdf94aa7d0dcb2a242390b5341e3
Stackoverflow Stackexchange Q: Coding convention for empty functions that need to be overridden in Kotlin Accourding to the very short Coding Conventions there is no answer for the opimal way of writing down empty functions in Kotlin. Example: ani.setAnimationListener(object: Animation.AnimationListener { override fun onAnimationRepeat(animation: Animation?) = Unit override fun onAnimationStart(animation: Animation?) {} override fun onAnimationEnd(animation: Animation?) = activity.runOnUiThread { loadLists() } }) Here only one of the 3 necessary Methods of AnimationListener (Android) is used. Which type of empty Method should be used? Single Expression (fun name() = Unit) or the traditional way used in Java (fun name() {})? I personally like the = Unit-Way more because that seems to be meant the way of shorting functions down to one line. But {} is shorter yet older and probably more ugly. And is there any better/shorter way for doing this code? A: You've added link to Coding Conventions where seems like actually there is an answer to your question Unit If a function returns Unit, the return type should be omitted: fun foo() { // ": Unit" is omitted here } So I believe fun foo() {} or fun foo() { } should be the answer
Q: Coding convention for empty functions that need to be overridden in Kotlin Accourding to the very short Coding Conventions there is no answer for the opimal way of writing down empty functions in Kotlin. Example: ani.setAnimationListener(object: Animation.AnimationListener { override fun onAnimationRepeat(animation: Animation?) = Unit override fun onAnimationStart(animation: Animation?) {} override fun onAnimationEnd(animation: Animation?) = activity.runOnUiThread { loadLists() } }) Here only one of the 3 necessary Methods of AnimationListener (Android) is used. Which type of empty Method should be used? Single Expression (fun name() = Unit) or the traditional way used in Java (fun name() {})? I personally like the = Unit-Way more because that seems to be meant the way of shorting functions down to one line. But {} is shorter yet older and probably more ugly. And is there any better/shorter way for doing this code? A: You've added link to Coding Conventions where seems like actually there is an answer to your question Unit If a function returns Unit, the return type should be omitted: fun foo() { // ": Unit" is omitted here } So I believe fun foo() {} or fun foo() { } should be the answer
stackoverflow
{ "language": "en", "length": 194, "provenance": "stackexchange_0000F.jsonl.gz:886180", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44608595" }
9465e36ab69455d874a07da86b736c0b609f6939
Stackoverflow Stackexchange Q: Using Chrome DevTools Protocol Input.dispatchKeyEvent or Input.dispatchMouseEvent to send an event I'm writing a DSL that will interact with a page via Google Chrome's Remote Debugging API. The INPUT domain (link here: https://chromedevtools.github.io/devtools-protocol/1-2/Input/) lists two functions that can be used for sending events: Input.dispatchKeyEvent and Input.dispatchMouseEvent. I can't seem to figure out how to specify the target element as there is no link between the two functions and DOM.NodeId, or an intermediate API that accepts a DOM.NodeId which then returns an X,Y co-ordinate. I know that it's possible to use Selenium, but I'm interested in doing directly using WebSockets. Any help is appreciated. A: this protocol is probably not the best if you are wanting to click on specific elements rather than clicking on spots on the screen... It's important to keep in mind that this area of the devtools protocol is intended to emulate the raw input. If you want to try and figure out the position of the elements using the protocol or by running some javascript in the page you could do that, however it might be better to use something like target.dispatchEvent() with MouseEvent and inject the javascript into the page instead.
Q: Using Chrome DevTools Protocol Input.dispatchKeyEvent or Input.dispatchMouseEvent to send an event I'm writing a DSL that will interact with a page via Google Chrome's Remote Debugging API. The INPUT domain (link here: https://chromedevtools.github.io/devtools-protocol/1-2/Input/) lists two functions that can be used for sending events: Input.dispatchKeyEvent and Input.dispatchMouseEvent. I can't seem to figure out how to specify the target element as there is no link between the two functions and DOM.NodeId, or an intermediate API that accepts a DOM.NodeId which then returns an X,Y co-ordinate. I know that it's possible to use Selenium, but I'm interested in doing directly using WebSockets. Any help is appreciated. A: this protocol is probably not the best if you are wanting to click on specific elements rather than clicking on spots on the screen... It's important to keep in mind that this area of the devtools protocol is intended to emulate the raw input. If you want to try and figure out the position of the elements using the protocol or by running some javascript in the page you could do that, however it might be better to use something like target.dispatchEvent() with MouseEvent and inject the javascript into the page instead. A: Brief Intro I'm currently working on a NodeJS interaction library to work with Chrome Headless via the Remote Debugging Protocol. The idea is to integrate it into my colleague's testing framework to eventually replace the usage of PhantomJS, which is no longer being supported. Evaluating JavaScript I'm just experimenting with things currently, but I have a way of evaluating JavaScript on the page, for example, to click on element via a selector reference. It should in theory work for anything assuming my implementation isn't flawed. let evaluateOnPage: function (fn) { let args = [...arguments].slice(1).map(a => { return JSON.stringify(a); }); let evaluationStr = ` (function() { let fn = ${String(fn)}; return fn.apply(null, [${args}]); })()`; return Runtime.evaluate({expression: evaluationStr}); } } The code above will accept a function and any number of arguments. It will turn the arguments into strings, so they are serializable. It then evaluates an IIFE on the page, which calls the function passed in with the arguments. Example Usage let selector = '.mySelector'; let result = evaluateOnPage(selector => { return document.querySelector(selector).click(); }, selector); The result of Runtime.evaluate is a promise, which when is fulfilled, you can check the result object for a type to determine success or failure. For example, subtype may be node or error. I hope this may be of some use to you.
stackoverflow
{ "language": "en", "length": 415, "provenance": "stackexchange_0000F.jsonl.gz:886214", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44608734" }
19df89e7a3970480a063c66ee8d5c51d220b92a8
Stackoverflow Stackexchange Q: Click listener in flatlist How can I add click listener in Flatlist? My code: renderItem({item, index}){ return <View style = {{ flex:1, margin: 5, minWidth: 170, maxWidth: 223, height: 304, maxHeight: 304, backgroundColor: '#ccc', }}/> } render(){ return(<FlatList contentContainerStyle={styles.list} data={[{key: 'a'}, {key: 'b'},{key:'c'}]} renderItem={this.renderItem} />); } } Update 1: I used button but it is not working in Flatlist. However using only button instead of Flatlist, it works. Why is it not working in Flatlist renderItem? _listener = () => { alert("clicked"); } renderItem({item, index}){ return<View> <Button title = "Button" color = "#ccc" onPress={this._listener} /> </View> } A: If you are facing flatlist row first click issue please add below property to flatlist. disableScrollViewPanResponder = {true}
Q: Click listener in flatlist How can I add click listener in Flatlist? My code: renderItem({item, index}){ return <View style = {{ flex:1, margin: 5, minWidth: 170, maxWidth: 223, height: 304, maxHeight: 304, backgroundColor: '#ccc', }}/> } render(){ return(<FlatList contentContainerStyle={styles.list} data={[{key: 'a'}, {key: 'b'},{key:'c'}]} renderItem={this.renderItem} />); } } Update 1: I used button but it is not working in Flatlist. However using only button instead of Flatlist, it works. Why is it not working in Flatlist renderItem? _listener = () => { alert("clicked"); } renderItem({item, index}){ return<View> <Button title = "Button" color = "#ccc" onPress={this._listener} /> </View> } A: If you are facing flatlist row first click issue please add below property to flatlist. disableScrollViewPanResponder = {true} A: The Pressable component is now preferred over TouchableWithoutFeedback (and TouchableOpacity). According to the React Native docs for TouchableWithoutFeedback: If you're looking for a more extensive and future-proof way to handle touch-based input, check out the Pressable API. Example implementation: import { Pressable } from "react-native"; render() { return( <FlatList contentContainerStyle={styles.list} data={[{key: 'a'}, {key: 'b'}, {key:'c'}]} renderItem={({item}) => ( <Pressable onPress={this._listener}> // BUILD VIEW HERE, e.g. this.renderItem(item) </Pressable> )} /> ); } References * *TouchableWithoutFeedback (React Native): https://reactnative.dev/docs/touchablewithoutfeedback *Pressable (React Native): https://reactnative.dev/docs/pressable A: I used TouchableWithoutFeedback. For that, you need to add all the renderItem elements (i.e your row) into the TouchableWithoutFeedback. Then add the onPress event and pass the FaltList item to the onPress event. import {View, FlatList, Text, TouchableWithoutFeedback} from 'react-native'; render() { return ( <FlatList style={styles.list} data={this.state.data} renderItem={({item}) => ( <TouchableWithoutFeedback onPress={ () => this.actionOnRow(item)}> <View> <Text>ID: {item.id}</Text> <Text>Title: {item.title}</Text> </View> </TouchableWithoutFeedback> )} /> ); } actionOnRow(item) { console.log('Selected Item :',item); } A: You need to wrap your row element (inside your renderItem method) inside <TouchableWithoutFeedback> tag. TouchableWithoutFeedback takes onPress as it's prop where you can provide onPress event. For TouchableWithoutFeedback refer this link A: I used TouchableOpacity. and it's working great.This will give you click feedback. which will not be provided by TouchableWithoutFeedback. I did the following: import { View, Text, TouchableOpacity } from "react-native"; . . . _onPress = () => { // your code on item press }; render() { <TouchableOpacity onPress={this._onPress}> <View> <Text>List item text</Text> </View> </TouchableOpacity> } A: you dont need to add Touchable related component into your Flatlist renderItem. Just pass onTouchStart prop to your Flatlist. in example: <FlatList style={themedStyles.flatListContainer} data={translations} renderItem={renderItem} keyExtractor={(item, index) => `${item.originalText}____${index}`} showsHorizontalScrollIndicator={false} showsVerticalScrollIndicator={false} ListEmptyComponent={renderEmptyListComponent} onTouchStart={onBackgroundPressed} />
stackoverflow
{ "language": "en", "length": 397, "provenance": "stackexchange_0000F.jsonl.gz:886242", "question_score": "26", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44608824" }
8282d54048584f5ed3c7753ee16cc147ef4e1162
Stackoverflow Stackexchange Q: Plots.jl - Turn off axis and grid lines I am trying to make a surface plot without the axis and grid lines. I found that I can turn off the grid with grid = false but I can't find a way to remove the axis lines. surface(x2d, y2d, z2d, fill_z = color_mat, fc = :haline, grid=false) Thanks! A: You can almost but not quite get rid of them with ticks = false.
Q: Plots.jl - Turn off axis and grid lines I am trying to make a surface plot without the axis and grid lines. I found that I can turn off the grid with grid = false but I can't find a way to remove the axis lines. surface(x2d, y2d, z2d, fill_z = color_mat, fc = :haline, grid=false) Thanks! A: You can almost but not quite get rid of them with ticks = false. A: axis=([], false) should do the trick A: Try showaxis = false, as described in the axis attributes documentation. Here's an example that works for me (in the Plotly backend). surface(-10:10, -10:10, (x, y) -> x^2 - y^2, showaxis = false)
stackoverflow
{ "language": "en", "length": 114, "provenance": "stackexchange_0000F.jsonl.gz:886262", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44608878" }
238a986417c762f99b088040f2b1c90e969d3934
Stackoverflow Stackexchange Q: How to let script to use setAttribute 'style' without breaking CSP Im am trying to keep my CSP policy as strict as possible. I need to include 3d party component in my bundle. But it uses element.setAttribute('style'...) method which breaks CSP. Is there a way to allow this particular script to inline styles in that manner? A: Yes, there is a way. There is much discussion about this here: https://github.com/w3c/webappsec-csp/issues/212 Which is succinctly summarised towards the end: CSP is checked at parsing and blocks parsing the style attribute. Any direct operations go through. Using setAttribute invokes the HTML parser and CSP is triggered. So, instead of: .setAttribute("style","background:red"); // needs HTML parsing You would need: .style.background = "red"; // direct manipulation It may sound odd that one method works and the other does not, I think the understanding here is that there is a subtle difference between HTML attributes and DOM properties. https://joji.me/en-us/blog/html-attribute-vs-dom-property/
Q: How to let script to use setAttribute 'style' without breaking CSP Im am trying to keep my CSP policy as strict as possible. I need to include 3d party component in my bundle. But it uses element.setAttribute('style'...) method which breaks CSP. Is there a way to allow this particular script to inline styles in that manner? A: Yes, there is a way. There is much discussion about this here: https://github.com/w3c/webappsec-csp/issues/212 Which is succinctly summarised towards the end: CSP is checked at parsing and blocks parsing the style attribute. Any direct operations go through. Using setAttribute invokes the HTML parser and CSP is triggered. So, instead of: .setAttribute("style","background:red"); // needs HTML parsing You would need: .style.background = "red"; // direct manipulation It may sound odd that one method works and the other does not, I think the understanding here is that there is a subtle difference between HTML attributes and DOM properties. https://joji.me/en-us/blog/html-attribute-vs-dom-property/ A: 2018-10-06 update The original answer here is still correct for now — because with CSP as currently implemented in browsers at least, there’s still no way to have dynamically injected styles at all without specifying unsafe-inline, and specifying unsafe-inline basically negates the whole purpose of CSP. However, CSP3 adds a new unsafe-hashes expression for enabling you to allow particular inline scripts/styles. See https://w3c.github.io/webappsec-csp/#unsafe-hashes-usage, and see Explainer: ‘unsafe-hashes’, ‘unsafe-inline-attributes’ and CSP directive versioning. It hasn’t shipped in any browsers yet, though. So for the time being, the answer below still fully applies. The only way to allow style attributes is to use unsafe-inline. It doesn’t matter whether the style attributes are coming from a different origin or from self—they’re still going to be considered a CSP violation unless you have unsafe-inline. Specifically, one solution that won’t work for style attributes is to use a nonce or hash—because in CSP, nonce and hash usage are only defined for style and script elements; the spec has a Hash usage for style elements section that explicitly omits defining hash use for style attributes. So even if in your policy you specify the correct hash for the contents of a style attribute, your browser will still handle it as a violation. The bottom line is that since unsafe-inline is the only way to allow style attributes—but using unsafe-inline pretty much completely defeats the purpose of having any CSP policy to begin with—the only safe solution from a CSP perspective is just to never use style attributes—neither directly from your own markup/code nor by way of any third-party code. A: For anyone looking for a jQuery patch to change setting the style attrib into setting the proper css values, here is one I use (sourced from this Github but with an important bug fix to make it work correctly): var native = jQuery.attr; jQuery.attr = function (element, attr, value) { if (attr === 'style') { resetStyles(element); return applyStyles(element, value); } else { //native.apply(jQuery, arguments); return native(element, attr, value); } }; function applyStyles(element, styleString) { if (styleString) { var styles = styleString.split(';'); styles.forEach(function (styleBit) { var parts = styleBit.split(':'); var property, value; if (parts.length === 2) { property = parts[0].trim(); value = parts[1].trim(); element.style[property] = value; } }); return styleString; } } function resetStyles(element) { var styleList = [].slice.call(element); styleList.forEach(function (propertyName) { element.style.removeProperty(propertyName); }); } A: It is strange why the '3 years old' question appeared in the new ones, and why the topicstarter's issue still unsolved. The issue of using element.setAttribute('style', ...) without causing a CSP violation is easily solved with a little hack that globally replaces the problematic element.setAttribute('style') with the safe element.style.ptop = '...'. After that you can use setAttribute('style') without breaking CSP, this will fix jQuery and other libs too. Solutions using only the CSP itself will be ineffective because: * *the 'unsafe-hashes' token is still not supported in all browsers. *in the case of third-party JavaScript libraries that actively use dynamic styles through 'setAttribute('style')', it is technically impossible to maintain a list of dozens of hashes. In addition, CSP headers are limited in size. cakeboeing727 started on the right track, but unfortunately the idea of the new contributor was not heard by society. It's a pity.
stackoverflow
{ "language": "en", "length": 688, "provenance": "stackexchange_0000F.jsonl.gz:886283", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44608927" }
917269fd638d4fcad6c5e83b7a5f7b5e9b784e8f
Stackoverflow Stackexchange Q: Javascript Nested Array Return Even Numbers I am trying to write a function that prints only the even numbers from a nested array. Here is my attempt and it keeps returning "undefined". function printEvents(){ var nestedArr = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]]; for (var i = 0; i<nestedArr.length; i++) { for (var j = 0; j<nestedArr[i]; j++) { var evenNumbers = nestedArr[i][j] } } if (evenNumbers % 2 == 0) { console.log(evenNumbers) } } printEvents(); A: You could use a recursive approach, if the item is an array. You need to move the test for evenness inside of the for loop. function printEvents(array) { var i; for (i = 0; i < array.length; i++) { if (Array.isArray(array[i])) { printEvents(array[i]); continue; } if (array[i] % 2 == 0) { console.log(array[i]); } } } printEvents([[1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 11, 12], [[[13, [14]]]]]); Solution with a callback function getEven(a) { if (Array.isArray(a)) { a.forEach(getEven); return; } if (a % 2 == 0) { console.log(a); } } getEven([[1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 11, 12], [[[13, [14]]]]]);
Q: Javascript Nested Array Return Even Numbers I am trying to write a function that prints only the even numbers from a nested array. Here is my attempt and it keeps returning "undefined". function printEvents(){ var nestedArr = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]]; for (var i = 0; i<nestedArr.length; i++) { for (var j = 0; j<nestedArr[i]; j++) { var evenNumbers = nestedArr[i][j] } } if (evenNumbers % 2 == 0) { console.log(evenNumbers) } } printEvents(); A: You could use a recursive approach, if the item is an array. You need to move the test for evenness inside of the for loop. function printEvents(array) { var i; for (i = 0; i < array.length; i++) { if (Array.isArray(array[i])) { printEvents(array[i]); continue; } if (array[i] % 2 == 0) { console.log(array[i]); } } } printEvents([[1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 11, 12], [[[13, [14]]]]]); Solution with a callback function getEven(a) { if (Array.isArray(a)) { a.forEach(getEven); return; } if (a % 2 == 0) { console.log(a); } } getEven([[1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 11, 12], [[[13, [14]]]]]); A: You just have a couple issues. You need to check the length of your nested arrays and you need to move your code that checks whether a number is even or not inside the array. var nestedArr = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]]; for (var i = 0; i<nestedArr.length; i++) { for (var j = 0; j<nestedArr[i].length; j++) { var evenNumbers = nestedArr[i][j] if (evenNumbers % 2 == 0) { console.log(evenNumbers) } } } A: You can do this more easy using filter method which accepts a callback method. var nestedArr = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]]; var mergedArray=[].concat.apply([], nestedArr); console.log(mergedArray.filter(a => a%2 == 0)); A: You can use reduce with every for something quick. var nestedArr = [ [1, 2, 3],[4, 5, 6],[7, 8],[9, 10, 11, 12]]; var sift = nestedArr.reduce(function(r,o) { o.every(i => i % 2 === 0 ? r.push(i) : true) return r; }, []); console.log(sift); If you want a one-liner you can use ReduceRight with Filter var nestedArr = [[1, 2, 3],[4, 5, 6],[7, 8],[9, 10, 11, 12]]; var sift = nestedArr.reduceRight((p, b) => p.concat(b).filter(x => x % 2 === 0), []); console.log(sift)
stackoverflow
{ "language": "en", "length": 360, "provenance": "stackexchange_0000F.jsonl.gz:886321", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44609035" }
8864d874233bf536497b61ae41822be2d8ca6faf
Stackoverflow Stackexchange Q: Ctrl+Shift+Tab in Visual Studio 2017 I'm using Visual Studio 2017 and have followed the instructions in this answer to change the behaviour of Ctrl+Tab and Ctrl+Shift+Tab to switch to next and previous tab, respectively. Problem is, while Ctrl+Tab works fine, Ctrl+Shift+Tab only switches to the previous tab when the current document is not a Web Form or similar (e.g. master page). On those pages, the combo switches between Source, Design and Split view instead. How can I disable this behaviour? I've looked through the keyboard shortcuts in Visual Studio settings and haven't found any others that are mapped to that combination. I've even disabled Web Forms designer (so only Source view is available), but it doesn't help, Ctrl+Shift+Tab simply doesn't do anything then. A: Set the shortcut keys for the Window.PreviousTabAndAddToSelection command in the HTML Editor Source View (instead of Global) to Ctrl+Shift+Tab. This has the minor side effect of selecting the previous tab when navigating away from a web form tab, but successfully avoids the unexpected behavior of taking you to the split or design sub tabs.
Q: Ctrl+Shift+Tab in Visual Studio 2017 I'm using Visual Studio 2017 and have followed the instructions in this answer to change the behaviour of Ctrl+Tab and Ctrl+Shift+Tab to switch to next and previous tab, respectively. Problem is, while Ctrl+Tab works fine, Ctrl+Shift+Tab only switches to the previous tab when the current document is not a Web Form or similar (e.g. master page). On those pages, the combo switches between Source, Design and Split view instead. How can I disable this behaviour? I've looked through the keyboard shortcuts in Visual Studio settings and haven't found any others that are mapped to that combination. I've even disabled Web Forms designer (so only Source view is available), but it doesn't help, Ctrl+Shift+Tab simply doesn't do anything then. A: Set the shortcut keys for the Window.PreviousTabAndAddToSelection command in the HTML Editor Source View (instead of Global) to Ctrl+Shift+Tab. This has the minor side effect of selecting the previous tab when navigating away from a web form tab, but successfully avoids the unexpected behavior of taking you to the split or design sub tabs.
stackoverflow
{ "language": "en", "length": 179, "provenance": "stackexchange_0000F.jsonl.gz:886348", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44609141" }
abffaf1e4212730cc05a9ab3ae43dadc168087f4
Stackoverflow Stackexchange Q: How do I override applicationIdSuffix for a particular build variant? I have the following in my app.gradle: flavorDimensions 'app', 'type' productFlavors { AppA { dimension 'app' applicationIdSuffix '.appa' } AppB { dimension 'app' applicationIdSuffix '.appb' } TypeA { dimension 'type' applicationIdSuffix '.typea' } TypeB { dimension 'type' applicationIdSuffix '.typeb' } } android.applicationVariants.all { variant -> println("Flavor name: " + variant.flavorName.toLowerCase()) if (variant.flavorName.toLowerCase() == "appatypea") { println("Detected legacy app.") //variant.productFlavors[0].applicationIdSuffix = "" variant.mergedFlavor.setApplicationId("com.example.special") } } If I try to build an app with flavors AppA and TypeA though, it still attaches the applicationIdPrefixes. So I get applicationId com.example.special.appa.typea. How do I get Gradle to disregard the applicationIdSuffix in this one case?
Q: How do I override applicationIdSuffix for a particular build variant? I have the following in my app.gradle: flavorDimensions 'app', 'type' productFlavors { AppA { dimension 'app' applicationIdSuffix '.appa' } AppB { dimension 'app' applicationIdSuffix '.appb' } TypeA { dimension 'type' applicationIdSuffix '.typea' } TypeB { dimension 'type' applicationIdSuffix '.typeb' } } android.applicationVariants.all { variant -> println("Flavor name: " + variant.flavorName.toLowerCase()) if (variant.flavorName.toLowerCase() == "appatypea") { println("Detected legacy app.") //variant.productFlavors[0].applicationIdSuffix = "" variant.mergedFlavor.setApplicationId("com.example.special") } } If I try to build an app with flavors AppA and TypeA though, it still attaches the applicationIdPrefixes. So I get applicationId com.example.special.appa.typea. How do I get Gradle to disregard the applicationIdSuffix in this one case?
stackoverflow
{ "language": "en", "length": 111, "provenance": "stackexchange_0000F.jsonl.gz:886357", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44609170" }
2f240ec2624fbabeb75dda0c0baae42454fc8089
Stackoverflow Stackexchange Q: Ionic 3 Lazy loading plugins So with Ionic 3 lazy loading of pages and components was introduced into the framework. I have app optimized to lazy load all the pages now but it still has a slow startup time. I do however use a lot of native plugins which I think might be the reason for this slow start up. Now in Ionic the native plugins are wrapped in Angular, so would it be possible to also lazy load the plugins so that the plugins, which might only come into play at certain moments of app usage, won't get loaded until necessary hence improving boot performance? A: I guess you could remove the native plugins from your main app.module.ts and add it to the component's module that's actually using the plugin. That way the plugin will only be called when the module it's loaded.
Q: Ionic 3 Lazy loading plugins So with Ionic 3 lazy loading of pages and components was introduced into the framework. I have app optimized to lazy load all the pages now but it still has a slow startup time. I do however use a lot of native plugins which I think might be the reason for this slow start up. Now in Ionic the native plugins are wrapped in Angular, so would it be possible to also lazy load the plugins so that the plugins, which might only come into play at certain moments of app usage, won't get loaded until necessary hence improving boot performance? A: I guess you could remove the native plugins from your main app.module.ts and add it to the component's module that's actually using the plugin. That way the plugin will only be called when the module it's loaded. A: You don't need to add any plugin for lazy loading. Go to your app.componer.ts file just change rootPage:any = HomePage; to rootPage:string = "HomePage";. You don't need import your file.
stackoverflow
{ "language": "en", "length": 176, "provenance": "stackexchange_0000F.jsonl.gz:886394", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44609278" }
c766c0d18fded7b9fe28e1bed778507e30d9d4c2
Stackoverflow Stackexchange Q: "moment is not defined" using moment.js I am working with moment.js, but as I am testing the moment.js library I continue to receive an error. var back30Days=moment().subtract(30, 'days').format("dddd, MMMM Do YYYY, h:mm:ss p"); it returns "moment not defined." referring to .format("dddd, MMMM Do YYYY, h:mm:ss p"); I've read the documentation, and everything looks fine, but when I reload my page, the js I'm working with won't load. any tips would be greatly appreciated! A: With latest momentjs: <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> var back30Days=moment().subtract(30, 'days').format("dddd, MMMM Do YYYY, h:mm:ss p"); console.log('back30Days --> ' + back30Days); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Q: "moment is not defined" using moment.js I am working with moment.js, but as I am testing the moment.js library I continue to receive an error. var back30Days=moment().subtract(30, 'days').format("dddd, MMMM Do YYYY, h:mm:ss p"); it returns "moment not defined." referring to .format("dddd, MMMM Do YYYY, h:mm:ss p"); I've read the documentation, and everything looks fine, but when I reload my page, the js I'm working with won't load. any tips would be greatly appreciated! A: With latest momentjs: <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> var back30Days=moment().subtract(30, 'days').format("dddd, MMMM Do YYYY, h:mm:ss p"); console.log('back30Days --> ' + back30Days); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
stackoverflow
{ "language": "en", "length": 95, "provenance": "stackexchange_0000F.jsonl.gz:886403", "question_score": "25", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44609306" }
a8bcce34c8d6d1a48fec932699ef596ac2c7bfa4
Stackoverflow Stackexchange Q: How to fix libpng in android I have submitted my release apk to the Google Play console, however it was rejected due to a libpng security vulnerability. I have a couple of libraries I use in my app. How do I know which of these uses libpng ? i try to fix it by changed files but keep same problem when i publish it in google play he told me that my apk has a libpng pleas how i can fix it http://freecode-source.blogspot.com/2017/01/super-max-super-mario-free-code-source.html A: Just check Which one of your libraries uses Libpng manipulates your png images in your app? you can find mainly in their documentations Libpng versions should be v1.0.66, v.1.2.56, v.1.4.19, v1.5.26 or Higher https://support.google.com/faqs/answer/7011127?hl=en
Q: How to fix libpng in android I have submitted my release apk to the Google Play console, however it was rejected due to a libpng security vulnerability. I have a couple of libraries I use in my app. How do I know which of these uses libpng ? i try to fix it by changed files but keep same problem when i publish it in google play he told me that my apk has a libpng pleas how i can fix it http://freecode-source.blogspot.com/2017/01/super-max-super-mario-free-code-source.html A: Just check Which one of your libraries uses Libpng manipulates your png images in your app? you can find mainly in their documentations Libpng versions should be v1.0.66, v.1.2.56, v.1.4.19, v1.5.26 or Higher https://support.google.com/faqs/answer/7011127?hl=en
stackoverflow
{ "language": "en", "length": 119, "provenance": "stackexchange_0000F.jsonl.gz:886409", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44609334" }
bb3e9fc6b81ac89a0f8e1b76fb257ac10342ec1e
Stackoverflow Stackexchange Q: How can i specify the dns servers when terrafrorm uses aws_route53_zone When terraform runs the following, it apparently picks random NS servers: resource "aws_route53_zone" "example.com" { name = "example.com" } The problem with this is that the registered domain that I have in AWS already has specified NS servers. Is there a way to specify the NS servers this resource uses - or maybe change the hosted domain's NS servers to what is picked when the zone is created? A: When you create a new zone, AWS generates the Name server list for you. Using this example from Terraform. resource "aws_route53_zone" "dev" { name = "dev.example.com" tags { Environment = "dev" } } resource "aws_route53_record" "dev-ns" { zone_id = "${aws_route53_zone.main.zone_id}" name = "dev.example.com" type = "NS" ttl = "30" records = [ "${aws_route53_zone.dev.name_servers.0}", "${aws_route53_zone.dev.name_servers.1}", "${aws_route53_zone.dev.name_servers.2}", "${aws_route53_zone.dev.name_servers.3}", ] } https://www.terraform.io/docs/providers/aws/r/route53_zone.html API returns a Delegation Set after the call to Create Zone. http://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateHostedZone.html#API_CreateHostedZone_ResponseSyntax
Q: How can i specify the dns servers when terrafrorm uses aws_route53_zone When terraform runs the following, it apparently picks random NS servers: resource "aws_route53_zone" "example.com" { name = "example.com" } The problem with this is that the registered domain that I have in AWS already has specified NS servers. Is there a way to specify the NS servers this resource uses - or maybe change the hosted domain's NS servers to what is picked when the zone is created? A: When you create a new zone, AWS generates the Name server list for you. Using this example from Terraform. resource "aws_route53_zone" "dev" { name = "dev.example.com" tags { Environment = "dev" } } resource "aws_route53_record" "dev-ns" { zone_id = "${aws_route53_zone.main.zone_id}" name = "dev.example.com" type = "NS" ttl = "30" records = [ "${aws_route53_zone.dev.name_servers.0}", "${aws_route53_zone.dev.name_servers.1}", "${aws_route53_zone.dev.name_servers.2}", "${aws_route53_zone.dev.name_servers.3}", ] } https://www.terraform.io/docs/providers/aws/r/route53_zone.html API returns a Delegation Set after the call to Create Zone. http://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateHostedZone.html#API_CreateHostedZone_ResponseSyntax A: I have been able to specify DNS servers but I would imagine that AWS is allocating servers based on availability, load etc... so you may want to think hard about baking these configs in. resource "aws_route53_record" "primary-ns" { zone_id = "${aws_route53_zone.primary.zone_id}" name = "www.bacon.rocks" type = "NS" ttl = "172800" records = ["ns-869.awsdns-44.net","ns-1237.awsdns-26.org","ns-1846.awsdns-38.co.uk","ns-325.awsdns-40.com"] } or something along those lines
stackoverflow
{ "language": "en", "length": 212, "provenance": "stackexchange_0000F.jsonl.gz:886415", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44609348" }
bd9b19b3e0209f77777fbf7e372a2dfde11a8294
Stackoverflow Stackexchange Q: Should identity primary keys be always non-clustered? Assuming a table with an auto-increment identity such as: CREATE TABLE [dbo].[Category] ( [CategoryId] INT IDENTITY(1,1) NOT NULL PRIMARY KEY, [Title] NVARCHAR(50) NOT NULL, [Description] NVARCHAR(128) NULL ) Since the auto-increment PK makes the table inherently sorted, does it mean that I should make the CategoryId Non Clustered and then create a clustered index on the other two columns CREATE CLUSTERED INDEX [IX_Category_Column] ON [dbo].[JobCategory] ([Title], [Description])? A: PRIMARY KEY by default creates a clustered index on that PK column and it's that index which stores the physical sorting order and not the IDENTITY column by itself I believe. Thus, you should create a Non-clustered index on the rest column if needed. Indexes on other column would definitely help increase query performance if you intend to use those cols in filter condition or join condition etc. In which case, it will perform a index scan instead of table scan. To experience the same, run a query which involve the other columns in such condition with and without having index on them. Get the actual query execution plan and see for yourself.
Q: Should identity primary keys be always non-clustered? Assuming a table with an auto-increment identity such as: CREATE TABLE [dbo].[Category] ( [CategoryId] INT IDENTITY(1,1) NOT NULL PRIMARY KEY, [Title] NVARCHAR(50) NOT NULL, [Description] NVARCHAR(128) NULL ) Since the auto-increment PK makes the table inherently sorted, does it mean that I should make the CategoryId Non Clustered and then create a clustered index on the other two columns CREATE CLUSTERED INDEX [IX_Category_Column] ON [dbo].[JobCategory] ([Title], [Description])? A: PRIMARY KEY by default creates a clustered index on that PK column and it's that index which stores the physical sorting order and not the IDENTITY column by itself I believe. Thus, you should create a Non-clustered index on the rest column if needed. Indexes on other column would definitely help increase query performance if you intend to use those cols in filter condition or join condition etc. In which case, it will perform a index scan instead of table scan. To experience the same, run a query which involve the other columns in such condition with and without having index on them. Get the actual query execution plan and see for yourself. A: Clustered Index means that all data in the table are sorted according such index. When you created PrimaryKey, you created that Clustered Index. In each table can be only one Clustered Index. So you create nonclustered index on other two columns as you need based on queries you will run against the table. Also note that Clustered Index should be as narrow as possilbe. Reason for it is that it is included in all other indexes. So when you create index on Title column, it will also contain CategoryId column even if you don't specify it. When creating index you should also consider another aspect. Columns can be part of the index or just "included". It means that it is included in the index but data are not sorted using this column. It can come handy, when you want column in your index, that you will not use in where clause or in join but will be output of your query. Especially when data in this column change frequently. Let's take your table and add some data to it insert into Category (Title, Description) values ('Title2', 'Description2_B') insert into Category (Title, Description) values ('Title2', 'Description2_A') insert into Category (Title, Description) values ('Title1', 'Description1_B') insert into Category (Title, Description) values ('Title1', 'Description1_A') Now create index on both Title and Description columns create nonclustered index idx_category_title on Category (title, Description) Running select on this table will give you select Title, Description from category where title Like 'Title%' Results: | Title | Description | |--------|----------------| | Title1 | Description1_A | | Title1 | Description1_B | | Title2 | Description2_A | | Title2 | Description2_B | As you can see result is sorted by Title first, then by Description. With this index every time you modify Description your index will have to be updated to have data sorted. Now Let's try same table and same data but with index, where column Description is "included" create nonclustered index idx_category_title on Category (title) include (Description) Running same select on this setup will give you select Title, Description from category where title Like 'Title%' Results: | Title | Description | |--------|----------------| | Title1 | Description1_B | | Title1 | Description1_A | | Title2 | Description2_B | | Title2 | Description2_A | As you can see data are sorted by Title, but not by Description. The real performance gain here is when you modify Description. As the index is not sorted using this column, changing it will not change position of the records in the index. A: Since the auto-increment PK makes the table inherently sorted That is not true. The clustering key is what determines how rows are sorted when stored. In general, the clustering key should be narrow (e.g. int or bigint) and ever-increasing (like identity()). You should also consider giving your constraints and indexes more sensible names rather than accepting whatever name would be automatically generated by sql server. create table dbo.Category ( CategoryId int identity(1,1) not null , Title nvarchar(50) not null , Description nvarchar(128) null , constraint pk_Category_CategoryId primary key clustered (CategoryId) ); To support queries like: select CategoryId, Title, Description from dbo.Category where Title = 'MyTitle'; You would create an additional nonclustered index like the following: create nonclustered index ix_Category_Title on dbo.Category (Title) include (Description); Reference: * *SQL Server training for developers: primary keys & indexes - Brent Ozar *Ever-increasing clustering key – the Clustered Index Debate……….again! - Kimberly Tripp *The Clustered Index Debate Continues… - Kimberly Tripp *More considerations for the clustering key – the clustered index debate continues! - Kimberly Tripp *How much does that key cost? (plus sp_helpindex9) - Kimberly Tripp *Disk space is cheap - that is not the point! - Kimberly Tripp *101 Things I Wish You Knew About Sql Server - Thomas LaRock *SQL Server: Natural Key Verses Surrogate Key - Database Journal - Gregory A. Larsen *Ten Common Database Design Mistakes - Simple Talk - Louis Davidson
stackoverflow
{ "language": "en", "length": 842, "provenance": "stackexchange_0000F.jsonl.gz:886500", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44609622" }
81b54a1bcff50cff7c07f821b5ba4c9b75650e65
Stackoverflow Stackexchange Q: How to map the alt-keys on the command line I'm using Cygwin and followed the post at In bash, how do I bind a function key to a command? I used Ctrl-v to determine the mapping of some keys (e.g. alt-h is ^[h). As a result, I put "^[h":backward-word in my .inputrc but it doesn't work. Other mappings for control-keys work, but not for alt-keys. A: Use vi to edit your .inputrc file, and then enter the ^[ character with Ctrl-v[ while in insert mode.
Q: How to map the alt-keys on the command line I'm using Cygwin and followed the post at In bash, how do I bind a function key to a command? I used Ctrl-v to determine the mapping of some keys (e.g. alt-h is ^[h). As a result, I put "^[h":backward-word in my .inputrc but it doesn't work. Other mappings for control-keys work, but not for alt-keys. A: Use vi to edit your .inputrc file, and then enter the ^[ character with Ctrl-v[ while in insert mode. A: You may also write "\eh": backward-word (in .inputrc), which bind the key Alt-h.
stackoverflow
{ "language": "en", "length": 100, "provenance": "stackexchange_0000F.jsonl.gz:886542", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44609749" }
f60696279a35bf1ee786c025c11c9d4f442d250e
Stackoverflow Stackexchange Q: Android studio freezes on debugging with message "SIGNAL = SIGABRT (signal SIGABRT)" My app runs perfectly with no problems. But when I try to debug it, android studio freezes. So I get the message "Waiting for debugger" and then that message goes away and next I get only a black screen in the emulator. I also get the message SIGNAL = SIGABRT (signal SIGABRT) in the debug window under variables tab. How do I fix this? A: I had been facing same problem for some time. I got to know that the fix is very simple. Disable instant run. Go to "File -> Settings -> Build, Execution, Deployment -> Instant Run" and disable the instant run. Please try out this.
Q: Android studio freezes on debugging with message "SIGNAL = SIGABRT (signal SIGABRT)" My app runs perfectly with no problems. But when I try to debug it, android studio freezes. So I get the message "Waiting for debugger" and then that message goes away and next I get only a black screen in the emulator. I also get the message SIGNAL = SIGABRT (signal SIGABRT) in the debug window under variables tab. How do I fix this? A: I had been facing same problem for some time. I got to know that the fix is very simple. Disable instant run. Go to "File -> Settings -> Build, Execution, Deployment -> Instant Run" and disable the instant run. Please try out this.
stackoverflow
{ "language": "en", "length": 121, "provenance": "stackexchange_0000F.jsonl.gz:886583", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44609891" }
a33d947933516389e4e237caec4327fd79a684b8
Stackoverflow Stackexchange Q: Reshape rows to columns in pandas dataframe In pandas how to go from a: a = pd.DataFrame({'foo': ['m', 'm', 'm', 's', 's', 's'], 'bar': [1, 2, 3, 4, 5, 6]}) >>> a bar foo 0 1 m 1 2 m 2 3 m 3 4 s 4 5 s 5 6 s to b: b = pd.DataFrame({'m': [1, 2, 3], 's': [4, 5, 6]}) >>> b m s 0 1 4 1 2 5 2 3 6 I tried solutions in other answers, e.g. here and here but none seemed to do what I want. Basically, I want to swap rows with columns and drop the index, but how to do it? A: a.set_index( [a.groupby('foo').cumcount(), 'foo'] ).bar.unstack()
Q: Reshape rows to columns in pandas dataframe In pandas how to go from a: a = pd.DataFrame({'foo': ['m', 'm', 'm', 's', 's', 's'], 'bar': [1, 2, 3, 4, 5, 6]}) >>> a bar foo 0 1 m 1 2 m 2 3 m 3 4 s 4 5 s 5 6 s to b: b = pd.DataFrame({'m': [1, 2, 3], 's': [4, 5, 6]}) >>> b m s 0 1 4 1 2 5 2 3 6 I tried solutions in other answers, e.g. here and here but none seemed to do what I want. Basically, I want to swap rows with columns and drop the index, but how to do it? A: a.set_index( [a.groupby('foo').cumcount(), 'foo'] ).bar.unstack() A: This is my solution a = pd.DataFrame({'foo': ['m', 'm', 'm', 's', 's', 's'], 'bar': [1, 2, 3, 4, 5, 6]}) a.pivot(columns='foo', values='bar').apply(lambda x: pd.Series(x.dropna().values)) foo m s 0 1.0 4.0 1 2.0 5.0 2 3.0 6.0
stackoverflow
{ "language": "en", "length": 155, "provenance": "stackexchange_0000F.jsonl.gz:886603", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44609952" }
e065ba1c32dbb59247043b077980ba5c18c97468
Stackoverflow Stackexchange Q: How to MSDeploy an ASP.NET Core app from command line? (csproj not project.json) Can ASP.NET Core apps be deployed via msdeploy.exe and a .pubxml definition similar to what was possible for pre-.NET Core? This is the command that I've used previously: msbuild myproj.csproj /p:DeployOnBuild=true /p:PublishProfile=<profile-name>. If not, what is the preferred way to deploy an ASP.NET Core app from the command line? A: You can find documentation on the commandline usage here : https://github.com/aspnet/websdk/blob/dev/README.md#microsoftnetsdkpublish You can use any of the below commands to publish using MSDeploy from commandline msbuild WebApplication.csproj /p:DeployOnBuild=true /p:PublishProfile=<MsDeployProfileName> /p:Password=<DeploymentPassword> or dotnet publish WebApplication.csproj /p:PublishProfile=<MsDeployProfileName> /p:Password=<DeploymentPassword> You can find samples of various profiles here - https://github.com/vijayrkn/PublishProfiles/tree/master/samples To fix the errors. make sure you run restore first before running the publish command: dotnet restore
Q: How to MSDeploy an ASP.NET Core app from command line? (csproj not project.json) Can ASP.NET Core apps be deployed via msdeploy.exe and a .pubxml definition similar to what was possible for pre-.NET Core? This is the command that I've used previously: msbuild myproj.csproj /p:DeployOnBuild=true /p:PublishProfile=<profile-name>. If not, what is the preferred way to deploy an ASP.NET Core app from the command line? A: You can find documentation on the commandline usage here : https://github.com/aspnet/websdk/blob/dev/README.md#microsoftnetsdkpublish You can use any of the below commands to publish using MSDeploy from commandline msbuild WebApplication.csproj /p:DeployOnBuild=true /p:PublishProfile=<MsDeployProfileName> /p:Password=<DeploymentPassword> or dotnet publish WebApplication.csproj /p:PublishProfile=<MsDeployProfileName> /p:Password=<DeploymentPassword> You can find samples of various profiles here - https://github.com/vijayrkn/PublishProfiles/tree/master/samples To fix the errors. make sure you run restore first before running the publish command: dotnet restore A: To deploy your asp.net core app to Azure web App simply do the following steps: 1. dotnet publishsomeproject.csproj -c release -o someDirectory 2. msdeploy.exe -verb:sync -source:contentPath="someDirectory" -dest:contentPath="webAppName",ComputerName="https://WebAppName.scm.azurewebsites.net/msdeploy.axd",UserName="username",Password="password",IncludeAcls="False",AuthType="Basic" -enablerule:AppOffline -enableRule:DoNotDeleteRule -retryAttempts:20 -verbose Username and Password can be retrieved or set on the deployment preview section in the web app in Azure portal. I have set an env path for my msdeploy.exe which can be found usually here C:\Program Files\IIS\Microsoft Web Deploy V3. A: One approach using the dotnet cli tool is the dotnet publish command. dotnet restore dotnet publish -c Release -o output This will restore all NuGet dependencies and then create a release build in a folder named output. You can then "xcopy deploy" it, add to a Dockerfile or do whatever else you need to do. Note that this works with csproj based projects using newer versions of the dotnet cli tool (which no longer support project.json files).
stackoverflow
{ "language": "en", "length": 277, "provenance": "stackexchange_0000F.jsonl.gz:886612", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44609989" }
65801fd72253256bfa1a7fa224d1abe7833b8eac
Stackoverflow Stackexchange Q: Imbalanced dataset using MLP classifier in python I am dealing with imbalanced dataset and I try to make a predictive model using MLP classifier. Unfortunately the algorithm classifies all the observations from test set to class "1" and hence the f1 score and recall values in classification report are 0. Does anyone know how to deal with it? model= MLPClassifier(solver='lbfgs', activation='tanh') model.fit(X_train, y_train) score=accuracy_score(y_test, model.predict(X_test), ) fpr, tpr, thresholds = roc_curve(y_test, model.predict_proba(X_test)[:,1]) roc=roc_auc_score(y_test, model.predict_proba(X_test)[:,1]) cr=classification_report(y_test, model.predict(X_test)) A: There are few techniques to handle the imbalanced dataset. A fully dedicated python library "imbalanced-learn" is available here. But one should be cautious about which technique should be used in a specific case. Few interesting examples are also available at https://svds.com/learning-imbalanced-classes/
Q: Imbalanced dataset using MLP classifier in python I am dealing with imbalanced dataset and I try to make a predictive model using MLP classifier. Unfortunately the algorithm classifies all the observations from test set to class "1" and hence the f1 score and recall values in classification report are 0. Does anyone know how to deal with it? model= MLPClassifier(solver='lbfgs', activation='tanh') model.fit(X_train, y_train) score=accuracy_score(y_test, model.predict(X_test), ) fpr, tpr, thresholds = roc_curve(y_test, model.predict_proba(X_test)[:,1]) roc=roc_auc_score(y_test, model.predict_proba(X_test)[:,1]) cr=classification_report(y_test, model.predict(X_test)) A: There are few techniques to handle the imbalanced dataset. A fully dedicated python library "imbalanced-learn" is available here. But one should be cautious about which technique should be used in a specific case. Few interesting examples are also available at https://svds.com/learning-imbalanced-classes/
stackoverflow
{ "language": "en", "length": 119, "provenance": "stackexchange_0000F.jsonl.gz:886619", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610003" }
22816c59a5e7ea634216c407f7b9795085cba269
Stackoverflow Stackexchange Q: Wordpress: On admin pages favicon is not loaded over https As said on the title, whenever I log to my admin page in Wordpress I get this notice in console: Mixed Content: The page at 'https://site-url' was loaded over HTTPS, but requested an insecure favicon 'http://site-url/wp-content/uploads/2017/06/cropped-cropped-logo-square-192x192.png'. This content should also be served over HTTPS. Also, I tried to load another favicon using Appearance->Customize, but it is still loaded over HTTP. Is this a Wordpress bug? or how can I solve this so this warning does not appear? A: For everyone still searching: Go to: Settings - General and change http to https in both URLs
Q: Wordpress: On admin pages favicon is not loaded over https As said on the title, whenever I log to my admin page in Wordpress I get this notice in console: Mixed Content: The page at 'https://site-url' was loaded over HTTPS, but requested an insecure favicon 'http://site-url/wp-content/uploads/2017/06/cropped-cropped-logo-square-192x192.png'. This content should also be served over HTTPS. Also, I tried to load another favicon using Appearance->Customize, but it is still loaded over HTTP. Is this a Wordpress bug? or how can I solve this so this warning does not appear? A: For everyone still searching: Go to: Settings - General and change http to https in both URLs
stackoverflow
{ "language": "en", "length": 106, "provenance": "stackexchange_0000F.jsonl.gz:886646", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610078" }
3fdb538f5925cb64c0a77e32b189c16d11bc943e
Stackoverflow Stackexchange Q: Scroll up and scroll down using AccessibilityNodeInfo in Accessibility Service I want to perform scroll using Accessibility service and i am doing this public boolean scrollView(AccessibilityNodeInfo nodeInfo) { if (nodeInfo == null) return false; if (nodeInfo.isScrollable()) { return nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } for (int i = 0; i < nodeInfo.getChildCount(); i++) { if (scrollView(nodeInfo.getChild(i)) { return true; } } return false; } But problem is when there are four option to perform up,down left and right it performs left and right but i want to perform up and down there also. like in facebook app it scroll on top section where notifications and news feed are.But not on page. is there any way to scroll where is focus of user. A: You're probably scrolling the wrong container. There are likely multiple views in your heirarchy that are "scrollable". Try finding different scrollable views within your heirarchy. Also, in Android M they added APIs to do things like specifically scroll different directions. So, if you are in fact on the correct View, you can scroll in different directions using these actions instead: ACTION_SCROLL_FORWARD ACTION_SCROLL_LEFT ACTION_SCROLL_RIGHT etc. https://developer.android.com/reference/android/view/accessibility/AccessibilityNodeInfo.AccessibilityAction.html
Q: Scroll up and scroll down using AccessibilityNodeInfo in Accessibility Service I want to perform scroll using Accessibility service and i am doing this public boolean scrollView(AccessibilityNodeInfo nodeInfo) { if (nodeInfo == null) return false; if (nodeInfo.isScrollable()) { return nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } for (int i = 0; i < nodeInfo.getChildCount(); i++) { if (scrollView(nodeInfo.getChild(i)) { return true; } } return false; } But problem is when there are four option to perform up,down left and right it performs left and right but i want to perform up and down there also. like in facebook app it scroll on top section where notifications and news feed are.But not on page. is there any way to scroll where is focus of user. A: You're probably scrolling the wrong container. There are likely multiple views in your heirarchy that are "scrollable". Try finding different scrollable views within your heirarchy. Also, in Android M they added APIs to do things like specifically scroll different directions. So, if you are in fact on the correct View, you can scroll in different directions using these actions instead: ACTION_SCROLL_FORWARD ACTION_SCROLL_LEFT ACTION_SCROLL_RIGHT etc. https://developer.android.com/reference/android/view/accessibility/AccessibilityNodeInfo.AccessibilityAction.html
stackoverflow
{ "language": "en", "length": 185, "provenance": "stackexchange_0000F.jsonl.gz:886656", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610107" }
9d048b115b6d03c3071958d6b4eba7c39d0a88b8
Stackoverflow Stackexchange Q: Heroku: Login system - authentication loop failure I am trying to login to my heroku account. I keep getting an error message that says "There was a problem with your login". There are no details of what the problem is. I tried changing my password through the forgot password action and I still get directed back around to the above error message. I can't contact Heroku's support team because I can't login. Has anyone found this problem and found a way around it - or even a way to contact Heroku? A: I reset my password and it helped.
Q: Heroku: Login system - authentication loop failure I am trying to login to my heroku account. I keep getting an error message that says "There was a problem with your login". There are no details of what the problem is. I tried changing my password through the forgot password action and I still get directed back around to the above error message. I can't contact Heroku's support team because I can't login. Has anyone found this problem and found a way around it - or even a way to contact Heroku? A: I reset my password and it helped. A: After a research I found that Last Pass auto generated password was not strong enough as per Heroku password reset requirement. I solved it by opening password reset link on different browser (in my case safari). enter strong password (ex: 51lxgpf2F52PgOBAPdAM@) A: I had the same problem, couldn't login even after resetting my password. I use the Last Pass chrome extension to fill in forms. When I entered the (same) credentials in manually I was able to login. A: I started getting this error very recently. I believe it's linked to a recent email that I got regarding password requirement changes: Heroku will start resetting user account passwords today, May 4, 2022, as mentioned in our previous notification. We recommend that you reset your user account password in advance here and follow the best practices below: * *Minimum of 16 characters *Minimum complexity of 3 out of 4: Uppercase, Lowercase, Numeric, Symbol *Don't just add a letter or a 1 digit number to the existing password while changing *Passwords may not be duplicated across accounts As mentioned elsewhere, resetting my password and ensuring LastPass included symbols resolved it. A: I had this problem on "Opera", then I went to "Chrome", and still the error, but in the end it worked on "Microsoft Edge". So try changing your browser to this one)
stackoverflow
{ "language": "en", "length": 322, "provenance": "stackexchange_0000F.jsonl.gz:886669", "question_score": "39", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610158" }
13ce2989fda5a03c401dd4b7dfd674549bf22c43
Stackoverflow Stackexchange Q: Exchange telephone number for user id in Telegram I wrote a Telegram Bot in groovy and it was a piece of cake. Now in order to register propper webhooks I need to get a hold of user's id. I read, that I should call auth.sendCode method to start that process. Are there any simpler alternatives to that? If not, how can I invoke the sendCode with the smallest effort and possibly w/o any additional dependencies? Any examples or pointers using plain java or curl would be good. A: After some research I ended up with a simple solution. Instead of authenticating against the Telegram API over MTProto, I reversed the process. I implemented a new bot-command: /login {my-user-id} so that the user sends his id (can be some generated token later) in Telegram bot chat and the bot sends this message - along with Telegram user id! - over webhook to my server, where I do the matching and saving. The implementation looks like this: switch( json.message.text ){ case ~/\/login \w+/: String userId text.toLowerCase().eachMatch( /\/login (\w+)/ ){ userId = it[ 1 ] } String telegramUserId = json.message.from.id saveJoin userId, telegramUserId break }
Q: Exchange telephone number for user id in Telegram I wrote a Telegram Bot in groovy and it was a piece of cake. Now in order to register propper webhooks I need to get a hold of user's id. I read, that I should call auth.sendCode method to start that process. Are there any simpler alternatives to that? If not, how can I invoke the sendCode with the smallest effort and possibly w/o any additional dependencies? Any examples or pointers using plain java or curl would be good. A: After some research I ended up with a simple solution. Instead of authenticating against the Telegram API over MTProto, I reversed the process. I implemented a new bot-command: /login {my-user-id} so that the user sends his id (can be some generated token later) in Telegram bot chat and the bot sends this message - along with Telegram user id! - over webhook to my server, where I do the matching and saving. The implementation looks like this: switch( json.message.text ){ case ~/\/login \w+/: String userId text.toLowerCase().eachMatch( /\/login (\w+)/ ){ userId = it[ 1 ] } String telegramUserId = json.message.from.id saveJoin userId, telegramUserId break }
stackoverflow
{ "language": "en", "length": 193, "provenance": "stackexchange_0000F.jsonl.gz:886681", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610194" }
f719f71c4467f769429bf2a7c2ee9714fc080224
Stackoverflow Stackexchange Q: How to use Google’s postmessage redirect uri scheme? Some Google site like api exploer use a mixed scheme instead of redirecting to an uri where a postmessage event is triggered by a callback function from the opener window which is received by the opener window (so window.location.origin is different from window.origin but I don’t understand how). I couldn’t find documentation about it, but maybe I searched incorrectly. The main advantage seems there’s no need for server side token registering as everything happens through JavaScript. Here’s <a href='javascript:window.open("https://accounts.google.com/o/oauth2/auth?client_id=292824132082.apps.googleusercontent.com&immediate=false&scope=https://www.googleapis.com/auth/userinfo.email&include_granted_scopes=false&proxy=oauth2relay604084667&redirect_uri=postmessage&origin=https://apis-explorer.appspot.com&response_type=token&gsiwebsdk=1&state=657454173|0.195379257&authuser=0&jsh=m;/_/scs/apps-static/_/js/k");'>an example script link</a> that will trigger a Domexception if not opened from https://apis-explorer.appspot.com/ Additionally, http://accounts.google.com/o/oauth2/auth access window.opener child’s elements if window.opener.origin match the origin parameter given in the url and thus bypassing sop (but I don’t understand how since no Acess-control-Allow-* headers are used). Otherwise an exception is triggered. So what is the JavaScript api for performing oauth2 authentification with postmessage ? what is the purpose of the proxy= url parameter ? A: Two options: * *You can use the Google sign-in api for javascript to request extra scopes. See the reference docs *You can use OAuth2 for javascript
Q: How to use Google’s postmessage redirect uri scheme? Some Google site like api exploer use a mixed scheme instead of redirecting to an uri where a postmessage event is triggered by a callback function from the opener window which is received by the opener window (so window.location.origin is different from window.origin but I don’t understand how). I couldn’t find documentation about it, but maybe I searched incorrectly. The main advantage seems there’s no need for server side token registering as everything happens through JavaScript. Here’s <a href='javascript:window.open("https://accounts.google.com/o/oauth2/auth?client_id=292824132082.apps.googleusercontent.com&immediate=false&scope=https://www.googleapis.com/auth/userinfo.email&include_granted_scopes=false&proxy=oauth2relay604084667&redirect_uri=postmessage&origin=https://apis-explorer.appspot.com&response_type=token&gsiwebsdk=1&state=657454173|0.195379257&authuser=0&jsh=m;/_/scs/apps-static/_/js/k");'>an example script link</a> that will trigger a Domexception if not opened from https://apis-explorer.appspot.com/ Additionally, http://accounts.google.com/o/oauth2/auth access window.opener child’s elements if window.opener.origin match the origin parameter given in the url and thus bypassing sop (but I don’t understand how since no Acess-control-Allow-* headers are used). Otherwise an exception is triggered. So what is the JavaScript api for performing oauth2 authentification with postmessage ? what is the purpose of the proxy= url parameter ? A: Two options: * *You can use the Google sign-in api for javascript to request extra scopes. See the reference docs *You can use OAuth2 for javascript
stackoverflow
{ "language": "en", "length": 187, "provenance": "stackexchange_0000F.jsonl.gz:886724", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610309" }
68d22f8bf7dcfd661eedaf44e3782114febd57a6
Stackoverflow Stackexchange Q: How to create horizontal line in Markdown (using hexo framework) I'm using the hexo framework and tried adding "---" or "***" in my .md file to get a horizontal line to show up, but it's not working. Also tried enabling gfm markdown in my _config.yml file: marked: gfm: true pedantic: false sanitize: false tables: true breaks: true smartLists: true smartypants: true modifyAnchors: '' autolink: true Any clues? Or is there a way to embed HTML tags to posts? A: --- on a line by itself works for me. I'm using the Icarus theme, which displays the separator as a dashed line: As @Waylan commented, your CSS rules are probably preventing your horizonal line to display. I've also found that preceding the --- line with a <br> line prevents the horizontal line from displaying.
Q: How to create horizontal line in Markdown (using hexo framework) I'm using the hexo framework and tried adding "---" or "***" in my .md file to get a horizontal line to show up, but it's not working. Also tried enabling gfm markdown in my _config.yml file: marked: gfm: true pedantic: false sanitize: false tables: true breaks: true smartLists: true smartypants: true modifyAnchors: '' autolink: true Any clues? Or is there a way to embed HTML tags to posts? A: --- on a line by itself works for me. I'm using the Icarus theme, which displays the separator as a dashed line: As @Waylan commented, your CSS rules are probably preventing your horizonal line to display. I've also found that preceding the --- line with a <br> line prevents the horizontal line from displaying. A: I know this is old, but for anyone else that runs into this problem what worked for me was to use three underscores instead of three dashes. ___ vs. --- A: tripledash --- has to precede and follow with empty lines to take effect like so --- thus results in solid line in Markdown A: I know this is old, but I would like to add one thing with markdown. If you put a horizontal line with no new line right after a paragraph like this: This is text! <!--No new line after paragraph--> --- The output will be: This is text! with the text bolded. In order to create a horizontal line, you need to put a new line between the paragraph and the ---, like this: This text is also text! <!-- New line here... --> --- This is separated text! <!-- ... and new line here. --> which in markdown makes: This text is also text! This is separated text!
stackoverflow
{ "language": "en", "length": 298, "provenance": "stackexchange_0000F.jsonl.gz:886738", "question_score": "53", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610355" }
66fda07527752a70b9007265a0ab03ae1e7728b7
Stackoverflow Stackexchange Q: How to use youtube-dl script to download starting from some index in a playlist? How to download playlist using youtube-dl from start certain number to an upper limit? I tried to use in the code: youtube-dl -o '~/Documents/%(playlist)s/%(chapter_number)s - %(chapter)s/%(playlist_index)s - %(title)s.%(ext)s' URL and it stopped in the middle. I want to restart the process from the index ith numbered video, and not have it start over from the beginning. A: youtube-dl --help, contains: Video Selection: --playlist-start NUMBER Playlist video to start at (default is 1) --playlist-end NUMBER Playlist video to end at (default is last) --playlist-items ITEM_SPEC Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: "--playlist-items 1,2,5,8" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: "--playlist-items 1-3,7,10-13", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13. Thus, the option --playlist-start NUMBER should help you to start the playlist in the middle, specified by NUMBER.
Q: How to use youtube-dl script to download starting from some index in a playlist? How to download playlist using youtube-dl from start certain number to an upper limit? I tried to use in the code: youtube-dl -o '~/Documents/%(playlist)s/%(chapter_number)s - %(chapter)s/%(playlist_index)s - %(title)s.%(ext)s' URL and it stopped in the middle. I want to restart the process from the index ith numbered video, and not have it start over from the beginning. A: youtube-dl --help, contains: Video Selection: --playlist-start NUMBER Playlist video to start at (default is 1) --playlist-end NUMBER Playlist video to end at (default is last) --playlist-items ITEM_SPEC Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: "--playlist-items 1,2,5,8" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: "--playlist-items 1-3,7,10-13", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13. Thus, the option --playlist-start NUMBER should help you to start the playlist in the middle, specified by NUMBER. A: I have total 135 videos in my playlist. I have successfully downloaded 38 of them. So I manually used this command. youtube-dl --playlist-start 39 -u uname@gmail.com -p mypassword https://www.udemy.com/learn-ethical-hacking-from-scratch/learn/v4/content Its downloading my remaining 97 videos. A: This helped: youtube-dl -f best <playlist link> --playlist-start 15 -f best selects the best video formats. use youtube-dl --help for more options
stackoverflow
{ "language": "en", "length": 231, "provenance": "stackexchange_0000F.jsonl.gz:886742", "question_score": "58", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610370" }
a7f6516c8f284cfca1fe0eef8c58aa3b8c9cc6da
Stackoverflow Stackexchange Q: Audio duration returns NaN Accessing an HTML5 audio element (a .ogg file) with JavaScript in Chrome. The file does play properly, yet somehow it will not recognize the duration. I just cribbed this code: https://www.w3schools.com/jsref/prop_audio_duration.asp (I know w3schools isn't great, but it seems like something else is the problem...) var x = document.getElementById("testTone").duration; console.log("duration:"+x); // duration:NaN var y = document.getElementById("testTone"); y.play(); // works! the element... <audio controls id="testTone"> <source src="autoharp/tone0.ogg" type="audio/ogg"> </audio> A: Add preload="metadata" to your tag to have it request the metadata for your audio object: <audio controls id="testTone" preload="metadata"> <source src="autoharp/tone0.ogg" type="audio/ogg"> </audio> In your code, attach an event handler, to set the duration when the metadata has been loaded: var au = document.getElementById("testTone"); au.onloadedmetadata = function() { console.log(au.duration) };
Q: Audio duration returns NaN Accessing an HTML5 audio element (a .ogg file) with JavaScript in Chrome. The file does play properly, yet somehow it will not recognize the duration. I just cribbed this code: https://www.w3schools.com/jsref/prop_audio_duration.asp (I know w3schools isn't great, but it seems like something else is the problem...) var x = document.getElementById("testTone").duration; console.log("duration:"+x); // duration:NaN var y = document.getElementById("testTone"); y.play(); // works! the element... <audio controls id="testTone"> <source src="autoharp/tone0.ogg" type="audio/ogg"> </audio> A: Add preload="metadata" to your tag to have it request the metadata for your audio object: <audio controls id="testTone" preload="metadata"> <source src="autoharp/tone0.ogg" type="audio/ogg"> </audio> In your code, attach an event handler, to set the duration when the metadata has been loaded: var au = document.getElementById("testTone"); au.onloadedmetadata = function() { console.log(au.duration) }; A: Beside @FrankerZ's solution, you could also do the following: <audio controls id="testTone"> <source src="https://www.w3schools.com/jsref/horse.ogg" type="audio/ogg"> <source src="https://www.w3schools.com/jsref/horse.mp3" type="audio/mpeg"> </audio> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var x = document.getElementById("testTone").duration; console.log("duration:" + x); // duration:NaN var y = document.getElementById("testTone"); y.play(); // works! } </script> A: you can try this..hope it will work i used this in 'timeupdate' event as i was getting same NaN error. var x = document.getElementById("testTone").duration; if(x){ console.log("duration:"+x); }
stackoverflow
{ "language": "en", "length": 197, "provenance": "stackexchange_0000F.jsonl.gz:886754", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610417" }
54edb9793b117b6b3b57778040d098ed40341e17
Stackoverflow Stackexchange Q: How to determine which port aiohttp selects when given port=0 When I use aiohttp.web.run_app(. . ., port=0), I assume that it selects an arbitrary available port on which to serve. Is this correct? And if so, is there some way to figure out what port it's selected? A: You use server.sockets as in the following code: @asyncio.coroutine def status(request): """Check that the app is properly working""" return web.json_response('OK') app = web.Application() # pylint: disable=invalid-name app.router.add_get('/api/status', status) def main(): """Starts the aiohttp process to serve the REST API""" loop = asyncio.get_event_loop() # continue server bootstraping handler = app.make_handler() coroutine = loop.create_server(handler, '0.0.0.0', 0) server = loop.run_until_complete(coroutine) print('Serving on http://%s:%s' % server.sockets[0].getsockname()) # HERE! try: loop.run_forever() except KeyboardInterrupt: pass finally: server.close() loop.run_until_complete(server.wait_closed()) loop.run_until_complete(handler.finish_connections(1.0)) loop.close()
Q: How to determine which port aiohttp selects when given port=0 When I use aiohttp.web.run_app(. . ., port=0), I assume that it selects an arbitrary available port on which to serve. Is this correct? And if so, is there some way to figure out what port it's selected? A: You use server.sockets as in the following code: @asyncio.coroutine def status(request): """Check that the app is properly working""" return web.json_response('OK') app = web.Application() # pylint: disable=invalid-name app.router.add_get('/api/status', status) def main(): """Starts the aiohttp process to serve the REST API""" loop = asyncio.get_event_loop() # continue server bootstraping handler = app.make_handler() coroutine = loop.create_server(handler, '0.0.0.0', 0) server = loop.run_until_complete(coroutine) print('Serving on http://%s:%s' % server.sockets[0].getsockname()) # HERE! try: loop.run_forever() except KeyboardInterrupt: pass finally: server.close() loop.run_until_complete(server.wait_closed()) loop.run_until_complete(handler.finish_connections(1.0)) loop.close() A: When using application runners, you can pass in port 0 and access the selected port via the site object: runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, 'localhost', 0) await site.start() print('Serving on http://%s:%s' % site._server.sockets[0].getsockname())
stackoverflow
{ "language": "en", "length": 160, "provenance": "stackexchange_0000F.jsonl.gz:886765", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610441" }
a40d35137371a014077b444639d59cb7f85daa4f
Stackoverflow Stackexchange Q: Google finance 200 day moving average is getting as #NA in Apps Script I'm calculating Google finance 200 day moving average formula in google sheet using formula =average(query(sort(GoogleFinance("GOOG","price", TODAY()-320, TODAY()),1,0),"select Col2 limit 200")) Then in google app script I'm getting the above cell value in variable as below var val = sheet.getRange("T101").getValue(); but in google script I'm getting that variable value as #NA. Can anyone please advise what is causing the issue? A: To expand on @Ric ky's answer, the trick here is to get to a range so the average math can be performed on it. For this working answer: =AVERAGE(INDEX(GoogleFinance("GOOG","all",WORKDAY(TODAY(),-200),TODAY()),,3)) Here's why it works: =AVERAGE( INDEX( // used to get 1 value or a range of values from a reference GoogleFinance("GOOG","all",WORKDAY(TODAY(),-200),TODAY()), // returns an expanded array with column headers, used by INDEX as the reference , // bypass INDEX's row argument to return an entire column to be AVERAGE'd 3 // we want the High column with an index of 3; index is 1-based ) ) A visual:
Q: Google finance 200 day moving average is getting as #NA in Apps Script I'm calculating Google finance 200 day moving average formula in google sheet using formula =average(query(sort(GoogleFinance("GOOG","price", TODAY()-320, TODAY()),1,0),"select Col2 limit 200")) Then in google app script I'm getting the above cell value in variable as below var val = sheet.getRange("T101").getValue(); but in google script I'm getting that variable value as #NA. Can anyone please advise what is causing the issue? A: To expand on @Ric ky's answer, the trick here is to get to a range so the average math can be performed on it. For this working answer: =AVERAGE(INDEX(GoogleFinance("GOOG","all",WORKDAY(TODAY(),-200),TODAY()),,3)) Here's why it works: =AVERAGE( INDEX( // used to get 1 value or a range of values from a reference GoogleFinance("GOOG","all",WORKDAY(TODAY(),-200),TODAY()), // returns an expanded array with column headers, used by INDEX as the reference , // bypass INDEX's row argument to return an entire column to be AVERAGE'd 3 // we want the High column with an index of 3; index is 1-based ) ) A visual: A: =AVERAGE(INDEX( GoogleFinance( "GOOG", "all" , WORKDAY( TODAY(), -200 ) , TODAY() ) , , 3))
stackoverflow
{ "language": "en", "length": 187, "provenance": "stackexchange_0000F.jsonl.gz:886787", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610508" }
c418c3daba9e306dddf56efa4eafb0b3d5014bae
Stackoverflow Stackexchange Q: How can I deserialize JSON with a top-level array using Serde? I have a some JSON data that is returned from a web service. The JSON is a top-level array: [ { "data": "value1" }, { "data": "value2" }, { "data": "value3" } ] Using serde_derive to make structs I can can deserialize the data contained within the array, however, I am unable to get Serde to deserialize the top-level array. Am I missing something, or can Serde not deserialize top level-arrays? A: You can simply use a Vec: use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct Foo { data: String, } fn main() -> Result<(), serde_json::Error> { let data = r#"[ { "data": "value1" }, { "data": "value2" }, { "data": "value3" } ]"#; let datas: Vec<Foo> = serde_json::from_str(data)?; for data in datas.iter() { println!("{:#?}", data); } Ok(()) } If you wish, you could also use transparent: #[derive(Serialize, Deserialize, Debug)] #[serde(transparent)] struct Foos { foos: Vec<Foo>, } let foos: Foos = serde_json::from_str(data)?; This allows to encapsulate your data with your type.
Q: How can I deserialize JSON with a top-level array using Serde? I have a some JSON data that is returned from a web service. The JSON is a top-level array: [ { "data": "value1" }, { "data": "value2" }, { "data": "value3" } ] Using serde_derive to make structs I can can deserialize the data contained within the array, however, I am unable to get Serde to deserialize the top-level array. Am I missing something, or can Serde not deserialize top level-arrays? A: You can simply use a Vec: use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct Foo { data: String, } fn main() -> Result<(), serde_json::Error> { let data = r#"[ { "data": "value1" }, { "data": "value2" }, { "data": "value3" } ]"#; let datas: Vec<Foo> = serde_json::from_str(data)?; for data in datas.iter() { println!("{:#?}", data); } Ok(()) } If you wish, you could also use transparent: #[derive(Serialize, Deserialize, Debug)] #[serde(transparent)] struct Foos { foos: Vec<Foo>, } let foos: Foos = serde_json::from_str(data)?; This allows to encapsulate your data with your type.
stackoverflow
{ "language": "en", "length": 172, "provenance": "stackexchange_0000F.jsonl.gz:886809", "question_score": "33", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610594" }
2d619162ab54ba09a0542fdadbe06051a95ce191
Stackoverflow Stackexchange Q: Node JS mysql deleting multiple rows with an array of arrays I need to make a query which would be able to delete multiple rows from my table. In order to do that I've created an arrays within array with values which need to be passed to that query. Here is my code: var deleteRooms = [ [ 3, 23 ], [ 4, 23 ], [ 5, 23 ], [ 2, 23 ]]; connection.query("DELETE FROM rate_plans_rooms WHERE room_id = ? AND rate_plan_id = ? ", [deleteRooms],function(err,results){ if(err){return console.log(err)} else { console.log('sended'); } }); But every time I receive an error like this: { Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' (4, 23), (5, 23), (2, 23) AND rate_plan_id = ?' at line 1 How can I fix that and send my query properly? A: A solution for your problem is to use 'IN' inside your query: var deleteRooms = [[3,23],[4,23],[5,23], [2,23]]; connection.query("DELETE FROM rate_plans_rooms WHERE (room_id, rate_plan_id) IN (?)", [deleteRooms],function(err,results){ if(err) return console.log(err) else console.log('sended'); });
Q: Node JS mysql deleting multiple rows with an array of arrays I need to make a query which would be able to delete multiple rows from my table. In order to do that I've created an arrays within array with values which need to be passed to that query. Here is my code: var deleteRooms = [ [ 3, 23 ], [ 4, 23 ], [ 5, 23 ], [ 2, 23 ]]; connection.query("DELETE FROM rate_plans_rooms WHERE room_id = ? AND rate_plan_id = ? ", [deleteRooms],function(err,results){ if(err){return console.log(err)} else { console.log('sended'); } }); But every time I receive an error like this: { Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' (4, 23), (5, 23), (2, 23) AND rate_plan_id = ?' at line 1 How can I fix that and send my query properly? A: A solution for your problem is to use 'IN' inside your query: var deleteRooms = [[3,23],[4,23],[5,23], [2,23]]; connection.query("DELETE FROM rate_plans_rooms WHERE (room_id, rate_plan_id) IN (?)", [deleteRooms],function(err,results){ if(err) return console.log(err) else console.log('sended'); }); A: The accepted solution did not work for me as it would give an Error: ER_OPERAND_COLUMNS: Operand should contain 2 column(s) error. Instead, this worked for me: var deleteRooms = [[3,23],[4,23],[5,23], [2,23]]; queryArray = Array(deleteRooms.length).fill('(?)')); connection.query("DELETE FROM rate_plans_rooms WHERE (room_id, rate_plan_id) IN ("+queryArray.join(',')+")", [deleteRooms],function(err,results){ if(err) return console.log(err) else console.log('sended'); });
stackoverflow
{ "language": "en", "length": 238, "provenance": "stackexchange_0000F.jsonl.gz:886815", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610613" }
c76fb54f47acc678513e3991e4c0077c36e1007f
Stackoverflow Stackexchange Q: How to minify multiple HTML / CSS files at once? I know I can minify files and concatenate them one by one before production, but that sounds like a tedious way to do it. Is there some way to minify all my files before pushing it to production? I am using NodeJS, with JS, CSS, and html. I found this not sure if there is a better way or the answer: https://github.com/srod/node-minify Thanks A: You'll need to setup a build-tool or task-runner / or both. If you are using Node (you know JavaScript) - but you are new to build tools, you may want to start with Gulp. The website should walk you through it. Webpack is pretty complex. I use Brunch and Broccoli and sometimes - when I need an easy to use GUI, CodeKit. There are lots of options. Learn Gulp and then you'll be in a good spot to think about other ways and their positives and negatives. Good Luck! : )
Q: How to minify multiple HTML / CSS files at once? I know I can minify files and concatenate them one by one before production, but that sounds like a tedious way to do it. Is there some way to minify all my files before pushing it to production? I am using NodeJS, with JS, CSS, and html. I found this not sure if there is a better way or the answer: https://github.com/srod/node-minify Thanks A: You'll need to setup a build-tool or task-runner / or both. If you are using Node (you know JavaScript) - but you are new to build tools, you may want to start with Gulp. The website should walk you through it. Webpack is pretty complex. I use Brunch and Broccoli and sometimes - when I need an easy to use GUI, CodeKit. There are lots of options. Learn Gulp and then you'll be in a good spot to think about other ways and their positives and negatives. Good Luck! : )
stackoverflow
{ "language": "en", "length": 166, "provenance": "stackexchange_0000F.jsonl.gz:886825", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610631" }
d67a2192a7ed958c8897b27113bd55958a8a1607
Stackoverflow Stackexchange Q: How to link css files to my html in Lumen I have just begun learning lumen and can't seem to find the answer to this simple question. This is my current <head>: <head> <title>Sharp notes!</title> <link rel="stylesheet" type="text/css" href="/assets/css/main.css"> <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"> </head> This causes the following error: [Sat Jun 17 20:13:09 2017] 127.0.0.1:56950 [200]: / [Sat Jun 17 20:13:09 2017] 127.0.0.1:56952 [404]: /assets/css/main.css - No such file or directory Please help! A: You should put the css files in your public directory. myApp/public/css/main.css Then the asset helper should resolve the path correctly {{ asset('/css/main.css') }} Further explanation here: https://laracasts.com/discuss/channels/general-discussion/asset-vs-url Your assets (css, js, images, etc.) need to be placed in the application's public directory.
Q: How to link css files to my html in Lumen I have just begun learning lumen and can't seem to find the answer to this simple question. This is my current <head>: <head> <title>Sharp notes!</title> <link rel="stylesheet" type="text/css" href="/assets/css/main.css"> <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"> </head> This causes the following error: [Sat Jun 17 20:13:09 2017] 127.0.0.1:56950 [200]: / [Sat Jun 17 20:13:09 2017] 127.0.0.1:56952 [404]: /assets/css/main.css - No such file or directory Please help! A: You should put the css files in your public directory. myApp/public/css/main.css Then the asset helper should resolve the path correctly {{ asset('/css/main.css') }} Further explanation here: https://laracasts.com/discuss/channels/general-discussion/asset-vs-url Your assets (css, js, images, etc.) need to be placed in the application's public directory. A: The solution : you need to use url('') , Because Lumen does not provide the asset helper function you may want to use url e.g. The url function generates a fully qualified URL to the given path: Blade. More informations ir : Laravel Helpers url() HOW TO : With Blade : <link rel="stylesheet" href="{{ url('/assets/css/main.css') }}"> With PHP : <link rel="stylesheet" href="<?php url('/assets/css/main.css') ?>"> if you want you can create your own asset helper function of course, have a look here: https://laracasts.com/discuss/channels/lumen/extend-helper-functions-to-lumen?page=0 or How to do {{ asset('/css/app.css') }} in Lumen? A: maybe it helps you try this <link rel="stylesheet" type="text/css" href="{{ URL::asset('resources/assets/css/main.css') }}"> A: You can simply put your assets folder (containing img, libs, js and styles) into public folder & do the needful like like this. <img src="assets/img/visa.PNG"> A: In laravel lumen you don't have to define the public path . Put your assets into public folder and rest will automatically tracked. For more information visit https://lumen.laravel.com
stackoverflow
{ "language": "en", "length": 276, "provenance": "stackexchange_0000F.jsonl.gz:886843", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610686" }
9b3a66f1aa85d94262d18c05b4c2b673857c52e5
Stackoverflow Stackexchange Q: How to get Google Spreadsheet cell link with gspread There is a single Google spreadsheet document. After selecting the very first A1 cell from a right-click pull-down menu I choose: Get Link to this Cell command. The URL link is now stored in a memory and it can be pasted into any text editor. The copied cell's URL link would look like this: https://docs.google.com/spreadsheets/d/f8s9HO0sidw9qIGwuqYq1wFFb9QWWpuFIXE3flYcgBG1/edit?ts=7559594f#gid=2879414198&range=A1 Question: How to get the the same cell's link using gspread in Python? A: First you'll need to generate OAuth2 credentials: http://gspread.readthedocs.io/en/latest/oauth2.html You'll need to create a new authorization object in your Python using the OAuth2 credentials: gc = gspread.authorize(credentials) Then you need to create a connection to the worksheet: # If you want to be specific, use a key (which can be extracted from # the spreadsheet's url) yoursheet = gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE') # Or, if you feel really lazy to extract that key, paste the entire url yoursheet = gc.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm...FE&hl') Then you can grab the cell you want val = yoursheet.acell('B1').value All code was pulled from the gspread Github basic usage with minor tweaks https://github.com/burnash/gspread Cheers!
Q: How to get Google Spreadsheet cell link with gspread There is a single Google spreadsheet document. After selecting the very first A1 cell from a right-click pull-down menu I choose: Get Link to this Cell command. The URL link is now stored in a memory and it can be pasted into any text editor. The copied cell's URL link would look like this: https://docs.google.com/spreadsheets/d/f8s9HO0sidw9qIGwuqYq1wFFb9QWWpuFIXE3flYcgBG1/edit?ts=7559594f#gid=2879414198&range=A1 Question: How to get the the same cell's link using gspread in Python? A: First you'll need to generate OAuth2 credentials: http://gspread.readthedocs.io/en/latest/oauth2.html You'll need to create a new authorization object in your Python using the OAuth2 credentials: gc = gspread.authorize(credentials) Then you need to create a connection to the worksheet: # If you want to be specific, use a key (which can be extracted from # the spreadsheet's url) yoursheet = gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE') # Or, if you feel really lazy to extract that key, paste the entire url yoursheet = gc.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm...FE&hl') Then you can grab the cell you want val = yoursheet.acell('B1').value All code was pulled from the gspread Github basic usage with minor tweaks https://github.com/burnash/gspread Cheers!
stackoverflow
{ "language": "en", "length": 181, "provenance": "stackexchange_0000F.jsonl.gz:886851", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610712" }
12ecddd65f83c889965cf2974f76fcb26f5d24b3
Stackoverflow Stackexchange Q: How to reformat HTML code in JavaScript file in PhpStorm I'm using PhpStorm 2016.2 and developing a web application with VueJS. In PhpStorm I would like reformat HTML code in my JavaScript file. But when I click Code | Reformat only JavaScript is reformatted. How to reformat both JavaScript and HTML? A: I found another solution to my problem with PhpStorm 2016. Use the Fragment Editor. * *Place the cursor on your HTML code fragment. *Press the ALT + ENTER key and click on "Edit HTML Fragment" *Reformat your html code in the fragment editor. *Your Javascript file is updated directly.
Q: How to reformat HTML code in JavaScript file in PhpStorm I'm using PhpStorm 2016.2 and developing a web application with VueJS. In PhpStorm I would like reformat HTML code in my JavaScript file. But when I click Code | Reformat only JavaScript is reformatted. How to reformat both JavaScript and HTML? A: I found another solution to my problem with PhpStorm 2016. Use the Fragment Editor. * *Place the cursor on your HTML code fragment. *Press the ALT + ENTER key and click on "Edit HTML Fragment" *Reformat your html code in the fragment editor. *Your Javascript file is updated directly. A: 2016.2 doesn't support formatting HTML injected in Typescript/ECMAScript 6. This feature (WEB-18307) is available since 2017.1, see https://www.jetbrains.com/help/webstorm/2017.1/using-language-injections.html#d240474e440 A: Have a look at the Code Style options: These are my settings and my mixed HTML/JavaScript gets formatted nicely Also, make sure you are using the necessary escape tags on quotations when needed and that closing braces/semicolons are placed properly before running reformat. Your JavaScript object's "template" uses a ' (single quote) to open what looks like a multi-line string. There appears to be another single quote on line 49 that may be messing up the inspector. In the situation that your HTML is in a JavaScript string, it will (correctly) not be formatted. I would recommend doing the following: * *Copy the HTML into a separate .HTML file *Reformat the HTML in there *Copy the reformatted HTML *Go back to your object's string value (template) *write: template: ' ' <-- place your insertion point in between the quotations *Paste. PHPStorm should automatically escape the quotations for you
stackoverflow
{ "language": "en", "length": 270, "provenance": "stackexchange_0000F.jsonl.gz:886893", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610850" }
cfd7f7f14bdd475a1c3ae50420ca3e662b04cf6e
Stackoverflow Stackexchange Q: Can't verify CSRF token authenticity when calling Rails from Android I'm getting an "Can't verify CSRF token authenticity" when I try to use my android app to call the create action on one of the controllers in my rails service. Also says "Completed 422 Unprocessable Entity" after that. Any ideas what would cause that? Thanks. A: You can disable the built-in CSRF protection Rails uses by default by adding in your controller (ApplicationController or the one being used) the protect_from_forgery method: protect_from_forgery with: :null_session Or also by using the skip_before_action to "skip" the verify_authenticity_token implementation.
Q: Can't verify CSRF token authenticity when calling Rails from Android I'm getting an "Can't verify CSRF token authenticity" when I try to use my android app to call the create action on one of the controllers in my rails service. Also says "Completed 422 Unprocessable Entity" after that. Any ideas what would cause that? Thanks. A: You can disable the built-in CSRF protection Rails uses by default by adding in your controller (ApplicationController or the one being used) the protect_from_forgery method: protect_from_forgery with: :null_session Or also by using the skip_before_action to "skip" the verify_authenticity_token implementation.
stackoverflow
{ "language": "en", "length": 96, "provenance": "stackexchange_0000F.jsonl.gz:886902", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610869" }
76ad4dce7896ffe2aca656a5f37765f6349cded2
Stackoverflow Stackexchange Q: Why am I getting unsupportedoperation: read I am new to python and I am having an issue with the following syntax test_file = open("test.txt", "wb") test_file.write(bytes("Write me to the file\n", 'UTF-8')) test_file.close() text_file = open("test.txt","r+") text_in_file = test_file.read() # this is where the error emerges # more code goes here On this syntax, I am getting io.UnsupportedOperation: read I got it from an online tutorial and I am using python 3. do you know what could lead to such kind of error message? A: It's a typo. You have opened text_file, but the line text_in_file = test_file.read() wants to read from the closed test_file. Change the line to: text_in_file = text_file.read()
Q: Why am I getting unsupportedoperation: read I am new to python and I am having an issue with the following syntax test_file = open("test.txt", "wb") test_file.write(bytes("Write me to the file\n", 'UTF-8')) test_file.close() text_file = open("test.txt","r+") text_in_file = test_file.read() # this is where the error emerges # more code goes here On this syntax, I am getting io.UnsupportedOperation: read I got it from an online tutorial and I am using python 3. do you know what could lead to such kind of error message? A: It's a typo. You have opened text_file, but the line text_in_file = test_file.read() wants to read from the closed test_file. Change the line to: text_in_file = text_file.read()
stackoverflow
{ "language": "en", "length": 112, "provenance": "stackexchange_0000F.jsonl.gz:886905", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44610881" }
2717aec49986b23d584f4fef333fc42903096466
Stackoverflow Stackexchange Q: Get image from server and preview it on client So i'm trying to get an image from a server and previewing it on the client, i can retrieve the image for now, but i don't know how to preview it on a web page asynchronously. axios.get(link,{responseType:'stream'}).then(img=>{ // What i have to do here ? }); Thank you. A: First, you need to fetch your image with the response type arraybuffer. Then you can convert the result to a base64 string and assign it as src of an image tag. Here is a small example with React. import React, { Component } from 'react'; import axios from 'axios'; class Image extends Component { state = { source: null }; componentDidMount() { axios .get( 'https://www.example.com/image.png', { responseType: 'arraybuffer' }, ) .then(response => { const base64 = btoa( new Uint8Array(response.data).reduce( (data, byte) => data + String.fromCharCode(byte), '', ), ); this.setState({ source: "data:;base64," + base64 }); }); } render() { return <img src={this.state.source} />; } } export default Image;
Q: Get image from server and preview it on client So i'm trying to get an image from a server and previewing it on the client, i can retrieve the image for now, but i don't know how to preview it on a web page asynchronously. axios.get(link,{responseType:'stream'}).then(img=>{ // What i have to do here ? }); Thank you. A: First, you need to fetch your image with the response type arraybuffer. Then you can convert the result to a base64 string and assign it as src of an image tag. Here is a small example with React. import React, { Component } from 'react'; import axios from 'axios'; class Image extends Component { state = { source: null }; componentDidMount() { axios .get( 'https://www.example.com/image.png', { responseType: 'arraybuffer' }, ) .then(response => { const base64 = btoa( new Uint8Array(response.data).reduce( (data, byte) => data + String.fromCharCode(byte), '', ), ); this.setState({ source: "data:;base64," + base64 }); }); } render() { return <img src={this.state.source} />; } } export default Image;
stackoverflow
{ "language": "en", "length": 166, "provenance": "stackexchange_0000F.jsonl.gz:886959", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44611047" }
048968d92f7e94b5924241965356d81ecd2e436f
Stackoverflow Stackexchange Q: binding virtualenv to project using setvirtualenvproject command doesn't work (windows) I'm trying to bind my virtualenv to django project. So when I type the command workon my_project it should cd to my django project. (my_project) C:\User\User\Desktop\Project> (my_project) C:\User\User\Desktop\Project>setvirtualenvproject 'setvirtualenvproject' is not recognized as an internal or external command, operable program or batch file. Why the command doesn't work? Is there another way of binding virtualenv to my django project? RESOLVED I've managed to bind my virtualenv to my django project using this command setprojectdir [path to the project folder] A: I've managed to bind my virtualenv to my django project using this command setprojectdir [path to the project folder]
Q: binding virtualenv to project using setvirtualenvproject command doesn't work (windows) I'm trying to bind my virtualenv to django project. So when I type the command workon my_project it should cd to my django project. (my_project) C:\User\User\Desktop\Project> (my_project) C:\User\User\Desktop\Project>setvirtualenvproject 'setvirtualenvproject' is not recognized as an internal or external command, operable program or batch file. Why the command doesn't work? Is there another way of binding virtualenv to my django project? RESOLVED I've managed to bind my virtualenv to my django project using this command setprojectdir [path to the project folder] A: I've managed to bind my virtualenv to my django project using this command setprojectdir [path to the project folder] A: setvirtualenvproject is a command from virtualenvwrapper. Do you have virtualenvwrapper-win installed?
stackoverflow
{ "language": "en", "length": 122, "provenance": "stackexchange_0000F.jsonl.gz:886990", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44611146" }
628cebc5fcf401d94a268d8ad724ddae4af3fcaf
Stackoverflow Stackexchange Q: How can I create a .txt file on CMD? Does someone knows how to create a file .txt on CMD?, I need like an order or steps to create it; I see that i need to write {echo "text"> "name".txt} but, i mean the content has not order and sometimes it doesn´t respond correctly. Thank you guys Well, I know that I was not so clearly 'bout what I wanted to do, and I'm sorry, but, your advices also help me alot, so, Thank u. A: Easy way to do this echo "abcdef" > a.txt echo "12345" >> a.txt the a.txt content will be "abcdef" "12345"
Q: How can I create a .txt file on CMD? Does someone knows how to create a file .txt on CMD?, I need like an order or steps to create it; I see that i need to write {echo "text"> "name".txt} but, i mean the content has not order and sometimes it doesn´t respond correctly. Thank you guys Well, I know that I was not so clearly 'bout what I wanted to do, and I'm sorry, but, your advices also help me alot, so, Thank u. A: Easy way to do this echo "abcdef" > a.txt echo "12345" >> a.txt the a.txt content will be "abcdef" "12345" A: Try creating a variable with the text first like as follows: set /p txt=Your Text Content; echo %txt% > "Location\textfile.txt" EDIT: If you are meaning that the newline doesnt appear all you have to do is the following: echo "FirstLine" > "Location\textfile.txt" echo. "SecondLine" > "Location\textfile.txt" echo. instead of echo will start a new line. A: echo your_text_here > filename.extension A: If you want to create a binary file: C:\>type nul > Diff1.vhd
stackoverflow
{ "language": "en", "length": 181, "provenance": "stackexchange_0000F.jsonl.gz:886993", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44611151" }
efd1661f70a890e375ad10444306890e6ab713d1
Stackoverflow Stackexchange Q: Using jest in my react app, describe is not defined I am new to jest and trying to figure out some basic stuff in my following code import * as actions from './IncrementalSearchActions'; describe('Incremental Search Actions', () => { it('Should create an incremental search action') }); The questions/confusions I have around this are * *I get an error saying describe is not defined, how do I import the reuqired module? *Is this supposed to be used with Karma/Jasmine? A: I believe the answer here is the answer to your question. TL;DR;: add the following to your .eslintrc file: "env": { "jest": true }
Q: Using jest in my react app, describe is not defined I am new to jest and trying to figure out some basic stuff in my following code import * as actions from './IncrementalSearchActions'; describe('Incremental Search Actions', () => { it('Should create an incremental search action') }); The questions/confusions I have around this are * *I get an error saying describe is not defined, how do I import the reuqired module? *Is this supposed to be used with Karma/Jasmine? A: I believe the answer here is the answer to your question. TL;DR;: add the following to your .eslintrc file: "env": { "jest": true } A: Are your test files under a the "test" folder? make sure jest is install properly and listed on your package.json and under scripts have: "test": "jest --coverage", you can run the script with npm test
stackoverflow
{ "language": "en", "length": 140, "provenance": "stackexchange_0000F.jsonl.gz:887000", "question_score": "77", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44611190" }
9a46b0eef2bb385d42a57163dc5c3407edcae815
Stackoverflow Stackexchange Q: getting content from CSS3 pseudo element using BeautifulSoup4 I am currently learning web scraping using Python and Beautiful Soup. I am given a task in which the web page is having star rating inside css pseudo element <span class="bb_rating bble_50"> ::before ::after </span> bble_50::after { content: "\e00b\e00b\e00b\e00b\e00b"; } I want to know how can I get the content from css psuedo element? Need help. Thanks A: I don't think you should actually go to parsing CSS here. Just map out the class names to ratings: class_to_rating = { "bble_45": 4.5, "bble_50": 5 } elm = soup.select_one(".bb_rating") rating_class = next(value for value in elm["class"] if value.startswith("bble_")) print(class_to_rating.get(rating_class, "Unknown rating"))
Q: getting content from CSS3 pseudo element using BeautifulSoup4 I am currently learning web scraping using Python and Beautiful Soup. I am given a task in which the web page is having star rating inside css pseudo element <span class="bb_rating bble_50"> ::before ::after </span> bble_50::after { content: "\e00b\e00b\e00b\e00b\e00b"; } I want to know how can I get the content from css psuedo element? Need help. Thanks A: I don't think you should actually go to parsing CSS here. Just map out the class names to ratings: class_to_rating = { "bble_45": 4.5, "bble_50": 5 } elm = soup.select_one(".bb_rating") rating_class = next(value for value in elm["class"] if value.startswith("bble_")) print(class_to_rating.get(rating_class, "Unknown rating"))
stackoverflow
{ "language": "en", "length": 109, "provenance": "stackexchange_0000F.jsonl.gz:887004", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44611200" }
1dc7af0a1bd9c4a5c9ce9f9cceafff600366ba42
Stackoverflow Stackexchange Q: Excel Formula to count first occurrence of '/' from right side of the string I looking for a excel function that can extract all the string before last occurrence of '/' sample: http://teamspace.abb.com/sites/Product/NAM_MASTERDATA Expected output: http://teamspace.abb.com/sites/Product I able to achieved this by using below excel formula. But this logic was assumed '/' occurrence was at position 5. I looking a more flexible formula where the formula should count first occurrence of '/' from right side of the string. Appreciate any help on this =MID(A1,1,FIND("~",SUBSTITUTE(A1,"/","~",5))-1) A: Use this: =LEFT(A1,FIND("~",SUBSTITUTE(A1,"/","~",LEN(A1)-LEN(SUBSTITUTE(A1,"/",""))))-1) It will find the last "/" by comparing the length of the string with and without the "/".
Q: Excel Formula to count first occurrence of '/' from right side of the string I looking for a excel function that can extract all the string before last occurrence of '/' sample: http://teamspace.abb.com/sites/Product/NAM_MASTERDATA Expected output: http://teamspace.abb.com/sites/Product I able to achieved this by using below excel formula. But this logic was assumed '/' occurrence was at position 5. I looking a more flexible formula where the formula should count first occurrence of '/' from right side of the string. Appreciate any help on this =MID(A1,1,FIND("~",SUBSTITUTE(A1,"/","~",5))-1) A: Use this: =LEFT(A1,FIND("~",SUBSTITUTE(A1,"/","~",LEN(A1)-LEN(SUBSTITUTE(A1,"/",""))))-1) It will find the last "/" by comparing the length of the string with and without the "/". A: A solution using AGGREGATE; first finds the position of the last "/" then truncates left: =LEFT(A1, AGGREGATE(14,6,ROW($1:$200)/(MID(A1,ROW($1:$200),1)="/"),1)-1) 200 stands for any upperbound on the position of the last "/". To make the array's size adapt automatically to the length of the string in A1, it's a bit longer formula but very fast: =LEFT(A1, AGGREGATE(14,6,ROW(OFFSET($A1,0,0,LEN(A1)))/ (MID(A1,ROW(OFFSET($A1,0,0,LEN(A1))),1)="/"),1)-1)
stackoverflow
{ "language": "en", "length": 163, "provenance": "stackexchange_0000F.jsonl.gz:887013", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44611223" }